Develop Autodesk Inventor Addin using C# – Part 1

Part 1a

Part 1b

Watch High Resolution video of both above videos on AR-CAD

I hope you have gone through my earlier video tutorial and post, as they provide a good (if not great) foundation for basic concepts of Autodesk Inventor API and how it Inventor can be customized using Visual C#. In the previous posts, we had connected to Inventor as an external exe file, which runs out 0f process with respect to Inventor and hence can be considered slow. To make the addins work faster and to give the end user a better work-flow and experience, we have to make an addin which is internal to Inventor and which runs in-process with respect to Inventor.

In the above videos ( they have been broken into part 1a and 1b as youtube couldn’t upload the whole video, which is 12 mins long), basic introduction is given to “How to develop an addin to Inventor using C#”. Please go through it and I hope the explanation in it is good enough to get you started. In Next versions of this tutorial, I shall try to increase the complexities. If there are any doubts/ clarifications / suggestions, I would love to hear from you as comments to this post. Watch High Resolution video of both above videos on AR-CAD

Customize Autodesk Inventor API using C# – Part 3

In continuation to my previous post on Customizing Inventor using C#, I go a step further and interact with an opened Assembly through API. I have ported the code from VBA to C# for the example explained in Introduction to Inventor API and VBA (Visual Basic for Applications). The attached document is from Autodesk University of 2003.

Start a new C# Windows Application project in Visual Studio 2005, as done in previous tutorial. Design the form as shown in the image to the left. Double clicking on Hide / Show will take you to Form1.cs in the Code Viewer window and add/append the following code into it. Please note that I have changed the Names/Identifiers of form elements to txtSearchName , cmdShow, cmdHide as explained in the above tutorial document.

In this example, when you hit ‘F5’ or Debug, a windows form appears as shown. Type a part name in the Search Field and hit “Hide”. If any part(s) exist in the opened assembly with that name, it/they would be made invisible. If its hidden and you hit on “Show”, the part would be made visible. In our case, we have made Piston part invisible in the engine assembly that ships with Inventor as an example assembly. Save the application by File> Save All in Visual Studio.

You can also use this Windows Application by executing the .exe file that is produced, when you debug/build your application. In my case, its at My DocumentsVisual Studio 2005ProjectsWindowsApplication1WindowsApplication1binDebugWindowsApplication1.exe . Double clicking on the exe file would also popup the Form that was developed.

Form1.cs code

[sourcecode language=’c#’]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
//Instantiate a variable with Inventor.Application object.
//It should have a scope throughout this Class
private Inventor.Application oApp=(Inventor.Application)System.Runtime.
InteropServices.Marshal.GetActiveObject(“Inventor.Application”);

//Declare oAsmDoc to have a scope within this Class
private Inventor.AssemblyDocument oAsmDoc;
public Form1()
{
InitializeComponent();

//Check that a document is open
if (oApp.Documents.Count == 0)
{
MessageBox.Show(“An Assembly must be active”);

}
//Check that an assembly document is active
if (oApp.ActiveDocument.DocumentType !=
Inventor.DocumentTypeEnum.kAssemblyDocumentObject)
{
MessageBox.Show(“As Assembly document must be active”);

}
//First Type Cast ActiveDocument into AssemblyDocument
//Set a reference to the active document
oAsmDoc = (Inventor.AssemblyDocument) oApp.ActiveDocument;
}

private void cmdHide_Click(object sender, EventArgs e)
{
//Call the function that traverses the assembly
// and sets the visibility.
SetVisibility(oAsmDoc.ComponentDefinition.Occurrences,
txtSearchName.Text, false);

//Update the View.
oApp.ActiveView.Update();
}

private void cmdShow_Click(object sender, EventArgs e)
{
//Call the function that traverses the assembly
// and sets the visibility.
SetVisibility(oAsmDoc.ComponentDefinition.Occurrences,
txtSearchName.Text, true);

//Update the View.
oApp.ActiveView.Update();
}

private static void SetVisibility
(Inventor.ComponentOccurrences Occurences, string SearchName,
bool VisibilityOn)
{
//Iterate through each of the occurences
//in the collection provided.
foreach (Inventor.ComponentOccurrence oOccurence in Occurences)
{//Check to see if the occurence name matches the search name
//The strings are converted to lower case
// to remove context sensitivity.
if(oOccurence.Name.ToLower().Contains(SearchName.ToLower()))
{//Check to see if the visibility is different than the specified
if (oOccurence.Visible != VisibilityOn)
{//Set the Visibility of the occurence.
oOccurence.Visible = VisibilityOn;
}
}
}
}
}
}
[/sourcecode]

Customize Autodesk Inventor API using C# – Part 2


Watch High Resolution video on AR-CAD

I hope you have gone through my previous posts on Inventor API a) Introduction to Autodesk Inventor API and Customization and b) Customize Autodesk Inventor using C#. It is also assumed that you have gone through DevTV: Introduction to Inventor Programming Video, which is on Inventor Customization page. In the above video, we connect to Inventor API from Visual C# (Visual Studio 2005). I have just replaced the VB.NET code that was used in DevTV tutorial with the corresponding C# code. You can see the comparison below. Please note how GetObject in VB.NET is replaced by a much more lengthier code. If the above youtube video is not very clear, watch it on AR-CAD.

VB.NET Code
[sourcecode language=’vb’]
Dim oApp As Inventor.Application
oApp = GetObject( , “Inventor.Application”)
MsgBox(“Number of open docs = ” & oApp.Documents.Count)
[/sourcecode]

Visual C# Code
[sourcecode language=’c#’]
Inventor.Application oApp;
//The below initialization is on a single line
oApp =
(Inventor.Application)System.Runtime.InteropServices.Marshall.
GetActiveObject(“Inventor.Application”);

int number_int = oApp.Documents.Count;
string number_string = Convert.ToString(number_int);

MessageBox.Show (“Number of open docs =” + number_string);
[/sourcecode]

Customize Autodesk Inventor API using C#

In continuation of previous post on Introduction to Inventor API and Customization, this blog post will show some insights on how to customize Inventor API using Visual C# and Visual Studio 2005.

It is assumed that you have installed Autodesk Inventor (Version 10 or above) and Visual Studio 2005. As per the discussion over Inventor Customization forum, it is suggested that you have Visual Studio 2003 or 2005 for the Inventor Addin Template to work properly. At present, Addin Template does not get installed in Visual Studio 2008.

To get started with Visual C# and Visual Studio IDE (Integrated Development Environment), watch the following Videos from MSDN Library.

  1. Introduction to Visual C# 2008 Express Edition. Though we would be using Visual Studio 2005 for our development purpose, Visual C# Express Edition has similar functionality as Visual Studio. In this video, basic understanding of how an IDE works could be gained and also how C# programs and projects are developed and built.
  2. Introduction to C# Programming Language. This video shows how to develop C# applications using Visual Studio 2005. It is highly recommended that you download this package installer and upon installation on your system, you have a copy of Video downloaded and also a MS Word Document which is basically a transcript for the Video and also explains Basics of C# in a very good way.

I hope you also have downloaded DevTv: Introduction to Inventor Programming from Inventor Customization Page. In this video, Mr. Wayne Brill of Autodesk has explained API concepts very well, but they are either in VB6 or VB.NET. I would like to highlight to the audience that even in Inventor Programmers Help (Located in Help tab), most of the code examples are given in VB.NET or VBA.

I would try to bridge the gap by giving out equivalent C# code in the blog posts to follow. You may also be interested to check out a free VB.Net to VC# translator I stumbled upon, though I haven’t used it yet.

Introduction to Autodesk Inventor API and Customization

Update: IN-Motion, a Motion and Dynamic Simulation Addin for Autodesk Inventor has been launched by us.

Update: Video tutorials on usage of IN-Motion for Dynamic Simulation of Autodesk Inventor Assemblies.

Autodesk Inventor Logo For those in CAD (Computer Aided Design) field, Autodesk would have been a very common company they would have come across. One of the most famous CAD software, AutoCAD belongs to their stable. Autodesk Inventor is somewhat an extension of AutoCAD, specific for Manufacturing section and deals mainly with 3D CAD, solid modeling of parts and then building assemblies out of them, Rapid Prototyping and many more advanced features. Inventor has been a great success in this field and it is evident from the fact that there are more than 800,000 official licensed users of Inventor across the world.

One of the strong points for the success is the fact that Autodesk has opened its API (Application Program Interface) to developers who can extend the base product to fit into their requirements. This is called Customization of the CAD package. Inventor also has its API exposed to developers through COM (Component Object Model) interface using which developers can customize the base installation of Inventor to tailor made needs such as automating a certain process or developing addins/ addons/ plugins which do specific task.

For those, who want to get started with Inventor API customization using their SDK (Software Development Kit), the following steps can be followed.

  1. Introduction to Inventor API and VBA (Visual Basic for Applications). The attached document is from Autodesk University of 2003. Though it may seem to be old, its a very good starting point and the code works even in latest versions of Inventor.
  2. You may also consider going through the 3 part series of Focused VBA for Inventor, which is a part of AUGI Training Program (2007) : Part 1, Part 2 and Part 3.
  3. Visit Inventor Customization page and get more insight, by watching 1 hour video on Basics of Inventor API and developing addins for Inventor (DevTV: Introduction to Inventor Programming )
  4. Decide upon which .NET technology you would be comfortable in developing Addins and Standalone applications (Either of VB.NET, VC++ or Visual C#)
  5. Browse through Inventor Customization forum to get more insights, code examples and also problems faced by other developers and also an active Autodesk support team which answers those queries
  6. If you happen to progress well, consider joining Autodesk Developers Network (ADN) and also attend AUGI Training Programs (ATP)
  7. Also you can keep a track on my Blog as I would be trying to pen down my learning, developing full fledged Addins for Inventor and also other major CAD software.

Glad am back to CAD World.. Crossroads of my Career

Update: IN-Motion, a Motion and Dynamic Simulation Addin for Autodesk Inventor has been launched by us.

Crossroads in Career Its been quite some time since I blogged. I was pretty much occupied with the Confusion I had in my mind, as I had hit a Cross-Roads of my career. After quitting my job at HeroHonda R&D, I teamed up with my mentor, Aik-Siong Koh in US and we started off with AR-CAD in April 2007. Since he is an expert at CAD (Motion Simulation) and he had used Smalltalk to develop freeCAD, I also had to learn Smalltalk to help him in further development. Our initial plan was to develop Motion Add-ons/Add-ins or Plug-ins for various CAD software such as Autodesk Inventor, SolidWorks, Rhino CAD and others. Somehow in the due course, we thought of exploring Web 2.0 using Seaside, which is a web framework built on Smalltalk. The idea was that I could learn Smalltalk and also explore Web 2.0 as we had plans for integration of Web and CAD.

We started developing Caartz using Seaside. It took us a long time to get it out. During this period, I learnt Smalltalk, Seaside, OOP, Basic Linux Setup and Usage, various Web related configurations such as Apache, load-balancing etc. When Caartz was launched, it was just a lot of things we had learnt and we had no plans to make money out of it. Since I had gathered experience in Web domain, I completely forgot that I had to return to CAD to make Motion Add-ons.

Then I helped a friend to develop a couple of websites and took a Web Developer Job in a Bangalore based Services Startup. Though the work there involved me in whole life cycle of a project and was very challenging, I thought I was missing something there. Being a Mechanical Engineer from a reputed Engineering College with a lot of interest in CAD, I had a feeling that I was not doing what I was supposed to do. After a couple of months in that Web Startup, I quit it and again I have teamed up with my mentor in US to develop CAD Add-ons.

This time, we are very serious about our path we are going to follow to become a very known name in Motion Simulation Domain. We have completely revamped AR-CAD website as the first step. My mentor already has Motion Simulation code in Smalltalk. I am learning VBA and .NET C# to develop an Add-in which talks to both Autodesk Inventor COM API and our Smalltalk code. As of today, I am able to make simple VBA Add-ons for Inventor and hopefully within next 6 months, we would be ready to sell our Motion Add-ons for Inventor. Once it is done, we would then develop Motion Add-ons for other CAD software.

Jist of my post is that I had come across a Crossroads a year ago and chose a road which took me to Web 2.0 domain. Somewhere down the line, I realized that I wasn’t enjoying it and came back to the crossroads and now I have chosen the road which takes me into CAD world and I am glad that I am finding it interesting and challenging.

Rails Video Tutorial 4 – Installation

In this post, the videos explain the Installation of Ruby, Rails, MySQL etc for you to get started with Rails Development on your local system. Since I am on Windows, I dont have any summary to offer on Installation on Mac 🙂 , but still its worth watching all the videos irrespective of the OS you are on.

The following videos constitute this post.

  1. Installation on Mac Part 1
  2. Installation on Mac Part 2
  3. MySQL Install on Mac
  4. Troubleshooting Mac Install
  5. Installation on Windows
  6. MySQL install on Windows
  7. One-stop-shop on Mac
  8. Keeping Rails up to Date

Installation on Mac Part 1

Summary:

Not much, I am on Windows 🙂


Installation on Mac Part 2

Summary:

Not much, I am on Windows 🙂


MySQL Install on Mac

Summary:

Not much, I am on Windows 🙂


Troubleshooting Mac Install

Summary:

Not much, I am on Windows 🙂


Installation on Windows

Summary:

For Installation of Ruby on Rails on Windows OS (Windows XP in my case), we need to install 3 things. Two of which can be downloaded directly from RubyonRails website i.e Ruby language from http://rubyforge.org/frs/?group_id=167 and RubyGems(standard Ruby Package Manager) from http://rubyforge.org/frs/?group_id=126 . The third(RubyonRails) can be installed from Command Line as shown in the videos.

  1. First installation file which was Ruby language is an .exe file. I just double click on it and it gets installed like any other Windows Application.
  2. Second installation file which was RubyGems is a .zip file. I unzip it and then inside it, there is a ‘Setup’ executable file. Double clicking on it will run a Ruby Script and it gets installed.
  3. Third installation is RubyonRails. Once the above 2 steps are followed, go to command prompt (Start->Run->type cmd), and type gem install rails –include-dependencies and hit enter. Please make sure that your computer is connected to the internet as it needs Gems installed concerned to Rails. In my case, it took close to 4-5 minutes.(I actually closed the Command line window twice without knowing that it takes time).

Once the installation is complete, in the command line, navigate to the directory where you want to have your First Rails app setup. I chose f:>RoR by using cd command(Change Directory). Type rails firstRailsApp and hit enter. This creates/generates a Rails application in that directory. Now navigate into firstRailsApp directory (again using cd) and type ruby scriptabout and hit enter, you will see the versions of Ruby, Rails and other packages. Now, lets start Rails(firstRailsApp) by typing ruby scriptserver and hit enter. Now WEBrick webserver is started on port 3000 on your localhost(system). Without closing the Command Prompt(Console), point your web-browser (Firefox or Internet Explorer) to http://localhost:3000 and your first Rails app is up and running. You shall be greeted by Rails Welcome Page.(btw you could also reach this page by pointing to http://127.0.0.1:3000). If you close the Command prompt(console), your WEBrick server which was started on port 3000 would no longer work and you will be greeted by a 404 Page not Found error.

In the next video, installation of MySQL database on Windows is explained

Pre-Packaged Rails Installer

If you don’t have the patience to get Ruby on Rails running manually, you can also try one of the pre-packaged solutions. These include everything in one bundle: Web server, database, Ruby, Rails, the works.

For OS X, there’s Locomotive.
For Windows, there’s Instant Rails.


MySQL install on Windows

Summary:

To install MySQL database on your Windows system, download(Windows Essential version ) installer from MySQL website http://dev.mysql.com/downloads/mysql/5.1.html#win32 , after download, double click on it and follow the instruction in the Video. Make some server configuration and the installation is done.

Actually I already have MySQL installed as a part of WAMP(Windows-Apache-MySQL-PHP), which I use to develop PHP websites. I am assuming that it would work if I start my WAMP server and have WEBrick(Rails) server running together.


One-stop-shop on Mac

Summary:

Its related to Locomotive ( A one stop installer for Ruby, Rails on Mac), similar to what Instant Rails is for Windows. It is recommended for newbies but it becomes difficult to port this to a Development web server. So, developers looking to deploy their applications on Remotely hosted webservers, it is worth following the traditional installation of building block by block.


Keeping Rails up to Date

Summary:

In this video, the author explains how to Keep our Rails version updated. We use the same command from Command Line as we did to install Rails i.e gem install rails –include-dependencies . This will ask for files to be overwritten. You can say no to database.yaml file to be not-over written and/or for other files as well. Once update is completed, you can again start WEBrick server by command ruby scriptserver .

If you want to update to the latest version(edge) which the Rails core developers are developing and working on, use command rake freeze_edge in the directory of your Rails application. Once you do that, latest Edge version of Rails is downloaded from internet and put into the vendors directory inside your Rails application directory. Since I am a newbie myself, I shall try this feature some other time 🙂

Hopefully, you must have been successful in installing Ruby, Rails and MySQL onto your local system. Lets explore more in the following posts


Disclaimer: The Screencasts are not recorded by me. I have just embedded them from Youtube. The original Videos area a part of Virtual Training Company, who give Online Training and the author for Ruby on Rails Series is Mr. Al Anderson. If you are benefited from these, you may register there by paying certain amount or order a CD from them.

Rails Video Tutorial 3- Tools

In our previous set of Videos, we have covered basics of a Web Application, MVC architecture and also basic introduction to Ruby and Rails.

In this post, we have videos which explain certain tools which can be used to speed up our development process. They are:

  1. Command Line
  2. Text Editor
  3. Rails & Ruby Overview

Command Line


Summary:

We use Terminal in Mac, Command prompt in Windows and X-terminal in Unix/Linux. In windows, we can access this by going to ‘Start’ button, then ‘Run’ and then type ‘cmd’. The author explains how to use Command Line to navigate between files and Rails files in particular and also to check the version of Rails installed and some commands to operate Rails from command line. It would be dealt with detail in the coming videos.


Text Editor


Summary:

The author explains the working of Text-Mate, a text editor used extensively by Programmers on Mac OS. Since I don’t use Text-Mate, I have no summary to offer 🙂 . Windows text-editors are explained in Installation of Rails on Windows videos.


Overview of Ruby and Rails


Summary:

For development on Ruby on Rails, we need Ruby Language and Rails Framework.

Ruby language is a scripting language developed by a Japanese in 1990’s. Installation of Ruby on Windows is a simple Double-click which will be dealt in detail in coming videos.

Rails framework installation is also discussed in coming videos. After its installation, Rails framework is saved in a particular file format which will also be discussed later.


Disclaimer: The Screencasts are not recorded by me. I have just embedded them from Youtube. The original Videos area a part of Virtual Training Company, who give Online Training and the author for Ruby on Rails Series is Mr. Al Anderson. If you are benefited from these, you may register there by paying certain amount or order a CD from them.

Rails Video Tutorial 2 – What Rails is

In this post, the following Concepts are explained

  1. Web Applications and Rails
  2. What Rails can Do
  3. Where Rails Came From
  4. Rails Philosophies
  5. More Rails Philosophies
  6. MVC
  7. Model
  8. View Part 1
  9. View Part 2
  10. Controller

Web Applications and Rails

Summary:

Basic introduction to Web applications in general. The architecture of Web browser(Cleint) and Server(which also includes a Database) is explained. Model-View-Controller architecture of Rails is also explained very well. A must see for newbies.


What Rails can Do

Summary:

Examples of usages of Ruby on Rails in some of the Deployed and running web applications. The author also explains a web app he had developed with Rails (Please dont be upset with the layout of this app, the functionality matters ). The app developed by him shows the power of Rails prototyping at a much faster rate compared to other frameworks. He also goes on to explain different Rails website showcased on Rubyonrails official website.


Where Rails Came From

Summary:

This explains the background for the development for Ruby on Rails. A company based out of Chicago by name 37Signals hired a smart developer from Denmark by name David Heinemeier Hansson to work on a Collaborating Web-app Basecamp . Because of the Geographical distance between them, an interesting Design pattern and philosophy was developed which has crept its way into Ruby on Rails. Rails has been extracted into a framework from a product (BaseCamp), which is not quite the usual case. The author also recommends to watch the Video presentation by David on Rails and its background.


Rails Philosophies

Summary:

This covers the Philosophies behind Rails

DRY (Dont Repeat Yourselves)

One piece of information should be present only at a single place. Most of the code should be placed only once in specific places based on MVC paradigm. This makes the code highly efficient and easy to maintain.

Convention over Configuration

Rails follows certain Conventions, that is it has defaults for most aspects of putting together a web application. If you follow these conventions, you can develop Web apps rapidly not bothering about a lot of Configurations which you would otherwise do in Java or normal PHP. This also makes your code base very minimal


More Rails Philosophies

Summary:

Another philosophy behind Rails is Agile Development. It emphasizes more on important things rather than conventional standards. In the following list, the items in bold text have emphasis over the normal text.

  • Individuals and interactions over processes and tools
  • Working software over comprehensive documentation
  • Customer collaboration over contract negotiation
  • Responding to change over following a plan

MVC

Summary:

A brief history and introduction to MVC architecture. The pattern was first described in 1979 by Trygve Reenskaug, then working on Smalltalk at Xerox PARC

The components of MVC are Model-View and Controller.

  1. Model maintains the state of your application.
  2. View is responsible for generating User Interface through which a website user interacts with it
  3. Controller can be perceived as the part which controls and co-ordinates the View and Model.

In Rails, M-V-C files are under separate folders and Model and Controller files have .rb extension whereas View files have a .rhtml(html with Ruby Code embedded) or .rjs (JavaScript embedded with Ruby Code).In Rails, the MVC works as follows.

A URL from Web-browser interacts with a Controller (not a View directly). Controller then interacts with Model which makes queries into the Database. The Database replies with the output to Model which will return to Controller in the form of Object Oriented array, which can be manipulated and then sent to the View which renders the html and Javascript on the Web-browser.


Model

Summary:

Model interacts with database and maintains state of the database in a Rails Application. In Rails, we extensively use Active Record which is a ORM (Object-Relational Mapping ) mechanism. Every model-class in Rails app corresponds to a Table in our Database. Every attribute in a model-class is mapped to a column in the corresponding database table. All these are done automatically once you instantiate a Model (Thanks to Rails, which takes care of this headache ). Author also shows and explains some Code of a model class. The ActiveRecord is intelligent enough to update itself with any Database changes you make. So it truly uses DRY i.e you dont have to make any changes in the Model file after you make changes in the Database. He also explains the syntax of a Model file(tech.rb), which is

[sourcecode language=’ruby’]
class Tech < ActiveRecord::Base #Tech as a subclass of ActiveRecord Class has_many: work_requests # one to many mapping, work_requests is another model-class has_many: assigned_teches has_many: work_requests_notes def self.login(name,password) find(:first, :condtions => [“name = ? and password = ?”, name, password])
end

def try_to_login
Tech.login(self.name, self.password)
end
end
[/sourcecode]


View Part 1


Summary:

View is the Part of the MVC architecture which renders or parses the generated html and javascript code to the Browser. Compared to Model and Controller files(.rb) which are Classes and have only Ruby code in them, View files(.rhtml or .rjs) have html and/or javascript code and have Ruby code embedded in them between <% …some ruby code…%>

The author shows and explains a simple Recipe list which has Recipes with add/edit/delete and search functionalities. He goes through the Controller code which will in-turn parse to View to render html to browser. Name of the Controller file and Controller class are related and is generated by Rails. In this example, the controller’s class name is RecipeController and the controller file name is recipe_controller.rb , which is as follows

[sourcecode language=’ruby’]
class RecipeController < ApplicationController # Subclass of ApplicationController def list #function or method. An important convention is that it parses a view file by the same name. i.e list.rhtml and is not explicitly mentioned @all_recipes = Recipe.find(:all) #It finds all the recipes and stores in instance variable 'all_recipes' end def view @a_recipe = Recipe.find(params[:id]) #it finds a recipe with a given id @all_recipes = Recipe.find(:all) #It finds all the recipes end def show_add_recipe end def search title = "%" + @params[:title] + "%" @all_recipes = Recipe.find(:all, :condtions=>[“title like ?”, title])
end

def add_recipe
@a_recipe = Recipe.new(params[:new_recipe])
@a_recipe.save
redirect_to :action => ‘list’
end

def delete_the_recipe
Recipe.find(params[:id]).destroy
redirect_to :action => ‘list’
end

def edit_recipe
@recipe_to_edit = Recipe.find(params[:id])
end

def save_recipe
@recipe_to_update = Recipe.find(@params[:a_recipe_id])
@recipe_to_update.update_attributes(@params[:recipe_to_edit])
redirect_to :action => ‘list’
end

end
[/sourcecode]


View Part 2

Summary:

From the previous Video, we look at list.rhtml. It is called by ‘list’ method/function in RecipeController class. The beauty of Rails is that you dont have to specify the name of the View file, its convention is to have the Controller class name itself. In this case it is list.rhtml whose content is as follows

[sourcecode language=’html’]


Recipe List

<%= flash[:notice] %>

<%= render(:partial => ‘the_list”)%>



[/sourcecode]

In the above snippet of code, the major part is normal html. The Ruby code is put between <% …some code … %> if its not printing anything on the browser . If you are outputting or printing something, we use <%= ..some code.. %>.

The line <%= render(:partial => “the_list”) %> renders another view, in this case its a partial view. The partial views can only be called from main views and hence can be used repeatedly at many places. The partial view file is named _the_list.rhtml . There is an underscore before the file name to distinguish it as a partial view. The contents of ‘_the_list.rhtml’ file is as follows

[sourcecode language=’html’]

<% for a_recipe in @all_recipes%>

<% end%>

<%=link_to "View Recipe", :action=> ‘view’, :id=> a_recipe %> <%=a_recipe.title %> <%=a_recipe.description %> <%=link_to "Edit", :action=> ‘edit_recipe’, :id=> a_recipe %> <%=link_to "Delete", :action=> ‘delete_the_recipe’, :id=> a_recipe %>

<%= render(:partial => “search_form”)%>
<%= link_to "Add New Recipe", :action => ‘show_add_recipe’ %>
[/sourcecode]

In the above snippet of code,

  • @all_recipes which is parsed from RecipeController is taken on a Loop.
  • On every iteration, variable ‘a_recipe’ is rendered in a new table-row.
  • To print the title of a recipe, we use a_recipe.title and similarly for description, we use a_recipe.description.
  • In <%= link_to ‘View Recipe”, action=> ‘view’, :id=> a_recipe %> , link_to is a Ruby function which builds an anchor or link with text “View Recipe” and clicking on it will trigger ‘view’ function in RecipeController and parses ‘id’ as an argument.
  • <%= render(:partial => “search_form”) %> will render “_the_search_form.rhtml” file

Controller

Summary:

Controller can be thought of a co-ordinator between a model and a view. A controller is usually called by a URL from the web-browser. Say there is a URL request of http://0.0.0.0:3000/recipe/list , it directly goes to controller recipe, whose filename is recipe_controller.rb and whose class name is RecipeController. All these would seem a bit confusing at first, but once you are familiar with the conventions, it would be a cake walk in future. The next part of the url after the controller name is ‘list’, which is the function name inside ‘recipe’ controller.

Lets explore ‘recipe_controller.rb’ file

[sourcecode language=’ruby’]
class RecipeController < ApplicationController # Subclass of ApplicationController, Class is i def list #function or method. An important convention is that it parses a view file by the same name. i.e list.rhtml and is not explicitly mentioned @all_recipes = Recipe.find(:all) #It finds all the recipes and stores in instance variable 'all_recipes' end def view @a_recipe = Recipe.find(params[:id]) #it finds a recipe with a given id @all_recipes = Recipe.find(:all) #It finds all the recipes end def show_add_recipe end def search title = "%" + @params[:title] + "%" @all_recipes = Recipe.find(:all, :condtions=>[“title like ?”, title])
end

def add_recipe
@a_recipe = Recipe.new(params[:new_recipe])
@a_recipe.save
redirect_to :action => ‘list’
end

def delete_the_recipe
Recipe.find(params[:id]).destroy
redirect_to :action => ‘list’
end

def edit_recipe
@recipe_to_edit = Recipe.find(params[:id])
end

def save_recipe
@recipe_to_update = Recipe.find(@params[:a_recipe_id])
@recipe_to_update.update_attributes(@params[:recipe_to_edit])
redirect_to :action => ‘list’
end

end
[/sourcecode]

In the following snippet of code, RecipeController class is made a sub-class of ApplicationController, meaning it derives all the properties of ApplicationController (Inheritance property of OOP). The class should always be terminated by ‘end’
[sourcecode language=’ruby’]
class RecipeController < ApplicationController ..... ..... end [/sourcecode] In the following snippet of code, 'list' is a function/method. It is defined by keyword 'def' followed by its name. It is terminated by 'end'. Whatever is in between them is executed upon calling the function. In this case, there is a ActiveRecord Model named 'Recipe'. Recipe.find(:all) will interact with recipe corresponding table in database and get all the rows. The relational data from database is converted into Object by ActiveRecord and it is assigned to instance variable @all_recipes in the form of an array. Once this is done, the function will then call the view file with the same name as its, and parse the instance variables. In this case, it would be 'list.rhtml' as we had covered in the previous video summary. [sourcecode language='ruby'] def list @all_recipes = Recipe.find(:all) end [/sourcecode] Since a Controller is the co-ordinator for Views and Models, if we have less code in View and more in Controller, it would become easy to maintain and update the code.


Disclaimer: The Screencasts are not recorded by me. I have just embedded them from Youtube. The original Videos area a part of Virtual Training Company, who give Online Training and the author for Ruby on Rails Series is Mr. Al Anderson. If you are benefited from these, you may register there by paying certain amount or order a CD from them.

Rails Video Tutorial 1 – Introduction

Welcome to Ruby on Rails

Summary :

It is intended for completely novice beginners. There is a brief introduction given to

  1. Web Applications: How exactly any Web Application deployed on a server would function ?
  2. Ruby Language: “Ruby is a dynamic, reflective, general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was initially developed and designed by Yukihiro “Matz” Matsumoto
  3. Rails Framework: Rails framework is a series of Ruby Code written to develop a Web application, making Rapid Web application development very straight forward. “Ruby on Rails was extracted by David Heinemeier Hansson from his work on Basecamp, a project management tool by the web design (now web application) company 37signals

What this Tutorial will Cover ?

Summary:

This is again intended for Novice learners. In this video, a outline or the Things to be covered in Tutorial Set has been given, which is as follows.

  1. What is Ruby on Rails? – A brief intro
  2. Where did it come from ? – A brief history
  3. How and what it does ?
  4. How to install Rails on Windows/ Mac ?
  5. What are different tools used for Development and Deployment ?
  6. What are the programming constructs ?
  7. How to build Database backed Applications ? – Usage of CRUD
  8. What are the resources available ?

Disclaimer: The Screencasts are not recorded by me. I have just embedded them from Youtube. The original Videos area a part of Virtual Training Company, who give Online Training and the author for Ruby on Rails Series is Mr. Al Anderson.  If you are benefited from these, you may register there by paying certain amount or order a CD from them.