December 3, 2009

Erlang On Nitro – Erlang Web Development Tutorial – Part 3/3

So now you that know already how to start developing your web projects using erlang, i want to present to you a resume of tools, tips, applications and some erlang resources that will make your life easier.

Tools & Tips

Toolbar : a very simple visual toolbar for the most used tools in erlang. Type on your erlang shell toolbar:start(). You should see 4 icons representing this tools:

  • Table Viewer: An ETS and MNESIA graphical table visualizer. With this you can view and change data inside a ets or mnesia table. On shell you can call it using tv:start().

  • Process Manager : A process manager used to inspect the state of an Erlang system. Call on erlang shell : pman:start(). X11 window will open showing the running processes for this node.

  • Debugger : A debugger for debugging and testing of Erlang programs. Call on erlang shell : debugger:start(). A window will open like this one

  • Application Monitor : A utility used to supervise Applications executing on several Erlang nodes. Very useful when you start deploying cluster of application in different nodes :) On shell use appmon:start().

Some other useful tips:

Tip1 : if you have no internet to search, you can use erlang manual. Just type this in your terminal

erl -man lists

Tip2 : in order to let an application running in background, all you need is to add this to your start script

-detached \

Tip3 : you probably have notice that we are using error_logger module. This is the best way to deal with errors, and for example get warned by email each time your application is in trouble. Please read more here

Applications

As you probably noticed i did not talk about any data-store mechanisms, in order to avoid to much detail. In erlang there are many options to store data. Erlang has two system modules ets and dets that are used for efficient storage of large numbers of Erlang terms. ETS is short for Erlang term storage,
and DETS is short for disk ets. ETS and DETS perform basically the same task: they provide large key-value lookup tables. ETS is memory resident, while DETS is disk resident. You can use ETS or DETS directly or you can use erlang database : MNESIA, a distributed DataBase Management System, with a relational/object hybrid data model. Mnesia is really cool because it maps directly to records, and you have a nice query language to it.

Another great way to store info in erlang is using one of the coolest erlang projects: couchdb is a document-oriented database that can be queried and indexed in a MapReduce fashion using JavaScript. In other words you don’t need a schema to your data, and since its json its very easy to write/read. This is very useful for example when you are saving 3rd party data that you don’t control, like tweets. In order to make the interaction between erlang and couchdb or any other service, before you start coding, look first at github (another great project using erlang), where you can find a lot erlang code, that will make you life even easier.

Some useful Erlang Resources

You can find a lot of stuff on the web about erlang, but here are some of our favorite bookmarks about erlang :

Resume

Erlang it has been around for a long time now, but the buzz around erlang started around 2007 with the publication of Programming Erlang: Software for a Concurrent World by Joe Armstrong, erlang creator and the use of erlang in really projects, like ejabberd, couchdb or facebook chat system. With this buzz erlang community start to grow outside the Telecom world specially in the web world.

Erlang is not just another programming language,  for me that have been programming more then 5 years with OO, its new paradigm, a new way to think, a new form of coding. And we are deeply in love with it… we hope you come to.

If you are not yet sold, just watch erlang demo video from the 80’s and you will for sure :)

Erlang On Nitro – Erlang Web Development Tutorial – Part 2/3

So now that you have already know nitrogen basics in part 1 of this tutorial, lets see what he can real do with it. So lets see a real simple web application that will track a keyword and wait for twitter to push “tweets” that contains this keyword, and stream them in a never ending stream. So lets grab our code :

Clone this git repositorium :

darkua:~ sergioveiga$ git clone git://github.com/darkua/ErlanOnNitro_TwitterStream.git
Initialized empty Git repository in /Users/sergioveiga/ErlanOnNitro_TwitterStream/.git/
remote: Counting objects: 72, done.
remote: Compressing objects: 100% (68/68), done.
remote: Total 72 (delta 4), reused 0 (delta 0)
Receiving objects: 100% (72/72), 144.83 KiB | 182 KiB/s, done.
Resolving deltas: 100% (4/4), done.
darkua:~ sergioveiga$ cd ErlanOnNitro_TwitterStream
darkua:ErlanOnNitro_TwitterStream sergioveiga$ ./start.sh

NOTE : in this project we will be use a lib packed with mochiweb project, so please check if already you have mochiweb intalled. (say thanks to @bpedro, for pointing this out :) )

twitter_stream@localhost)4> mochijson2:encode(<<"hello">>).
[34,<<"hello">>,34]

if you don’t see this, you need to install mochiweb first. Its very easy:

darkua:twitterstream sergioveiga$ echo $ERL_LIBS
/opt/local/lib/erlang/lib/:/usr/lib/erlang/lib/:/Users/sergioveiga/erlangProjects/tedi
darkua:twitterstream sergioveiga$ cd /opt/local/lib/erlang/lib/
darkua:lib sergioveiga$ sudo svn checkout http://mochiweb.googlecode.com/svn/trunk/ mochiweb-read-only
darkua:lib sergioveiga$ cd mochiweb-read-only/
darkua:mochiweb-read-only sergioveiga$ make

Now you probably need to kill erlang shell, just hit ctr-c twice. Start it again and now mochijson should already be available.

Before you go and check your browser you need to enter your twitter credentials, needed for twitter stream. So please go to include/include.hrl and add your own credentials, and compile the project.

Make sure you dont any other server running on port 8000, and go to your browser http://localhost:8000/. Here you will find some descriptions and links to both examples we will follow in this part.

Now choose you favorite IDE, we are using textmate, and open the project dir.

So this is ver similar with your previous nitrogen project, with some little changes. Open your project app file inside ebin dir. Here we have added templateroot so we can put all templates inside a different directory.

We have created an include dir, where we will put all our include files, and on src, we divide the pages, from the libs, that will hold “hard-core” code.

Example 1 – Twitter Stream

A screenshot of how twitter stream looks like :

Now open /src/pages/web_index.erl. You can see that we almost don’t do nothing here, because this is a static file, so we are only are adding the page title, and saying witch template will be used to render the page. All the code you can see its on index.html template file.

Now open web_stream page.

Lets check body function

body() ->

 %%builds the stream
 Stream = start_stream(),

 %% the html to render
 Body= [
 #panel{class="header", body=[
 #h1{text="Erlang on Nitro - Twitter Stream"},
 #panel{id=feedback,class="feedback", body=[
 "Calling Twitter...pls wait..."
 ]},
 #panel{id=control,body=[#button{text="Stop", postback={stop,Stream}}]}
 ]},
 #panel{id=stream,body=[]}
 ],

 wf:render(Body).

Here we are calling stream_start() to open stream connections and building the page html structure. Now check the start_stream() to see where is the magic.

start_stream()->
 Pid = wf:comet(fun()-> ?MODULE:loop() end),
%%check for track
 case wf:get_path_info() of
 []->
 twitter_stream:sample(Pid);
 Track->
 twitter_stream:track(Track,Pid)
 end.

When calling wf:comet, we are building a comet connection to this page, and passing what function will be used to “comunicate” with the browser. Then we use wf:get_path_info() to get extra info on path, that we will use to call twitter, for example the twitter or hello keyword from the examples. All the connection to twitter stream api happens inside twitter_stream, and for now you can look at it as a black box that streams tweets for you, later you can check it out and try to understand what is happening.

Now before checking loop function, its time to better undersand one of erlang top features, creating and communicating with processes. When we did wf:comet, what is happening in resume, is that we have spawned loop function into a new process, and now we can comunicate with it by sending to the Process Id messages. And to do that we just need to do this :

Pid ! message

In order to put a process waiting for messages is also very simple, just do this :

receive
 Message->
 ...
 end.

When creating a receive block, you are telling erlang to wait there until he receives a new message, that he will try to match to execute the respective code.

Now lets check a very simple example in order to better understand this. Open file spawn_example inside libs. You can see that we just have 2 functions, start and loop. On start we are spawning function loop, and registering the process with a name to be easier to call them after, like your fathers did with you :)

Now go to erlang shell and call this:

(twitter_stream@localhost)2> spawn_example:start().
true
(twitter_stream@localhost)3> bot ! hello.
Hello. How are you?
hello
(twitter_stream@localhost)4>

Very simple and cool, but now try to call it again

(twitter_stream@localhost)15> bot ! hello.
** exception error: bad argument
 in operator  !/2
 called as bot ! hello
(twitter_stream@localhost)16>

Humm… the reason it failed its very simple. After the process received the first message he executed the code matched to hello and it ended. So when you try to send a new message to it, it no longer exists, and it fails. So if you want to create process that after processing a message continues waiting for other you need to recall the function. So in the end of the loop add a call to loop.

loop()->
 receive
 hello ->
 io:format("Hello. How are you?~n",[]);
 _->
 void
 end,
 loop().

Now lets try again

(twitter_stream@localhost)16> sync:go().
Recompile: ./src/libs/spawn_example
ok
(twitter_stream@localhost)17> spawn_example:start().
true
(twitter_stream@localhost)18> bot ! hello.
Hello. How are you?
hello
(twitter_stream@localhost)19> bot ! hello.
Hello. How are you?
hello

As you can see now the process no longer dies. Now lets see another great feature of erlang: hot code swapping, the ability to change the code without stopping the system. Try to change the text on the message, for example to:

io:format("Hot swapping rocks!~n",[])

sync:go and lets see what happens:

(twitter_stream@localhost)24> sync:go().
Recompile: ./src/libs/spawn_example
ok
(twitter_stream@localhost)25> bot ! hello.
Hello. How are you?
hello

Humm… the old message is still there. The reason this happens is very simple. If we dont call “externally” by  prefixing the module name we are saying to erlang to “use this version of this method” and not the current version. So all we need to do is add the ?MODULE to the loop call, in the start function and also in the end of the loop. Now sync your code, and start your bot again.

(twitter_stream@localhost)38> sync:go().
Recompile: ./src/libs/spawn_example
ok
(twitter_stream@localhost)39> spawn_example:start().
true
(twitter_stream@localhost)40> bot ! hello.
Hot swapping rocks!
hello

Now lets change the message again, to “Hot swapping really rocks”. Sync your code again and send him a message.

(twitter_stream@localhost)41> sync:go().
Recompile: ./src/libs/spawn_example
ok
(twitter_stream@localhost)42> bot ! hello.
Hot swapping rocks!
hello
(twitter_stream@localhost)43> bot ! hello.
Hot swapping really rocks!
hello

As you can see the first message the bot receives the old code will be executed, because the process was already blocked waiting for a message, but when it run again it will already be using the current version of the code. You can see final version of spawn_example here.

Now back to our example, you can see exactly this happening with the loop function inside web_stream module. As you can see the loop function will be waiting for a subset of messages that twitter stream will send to him, and according to each we will be doing something different. Now what is important to understand is how nitrogen communicates with the client browser.

We are using 2 nitrogen functions  wf:update(id, content) and wf:insert_top(id, content) that will update and insert on the top of a DOM element. Nitrogen will translate this to the corresponding javascript, using jquery lib, and send it to the browser when we call wf:comet_flush(). So only when call this function inside a comet loop, we will be sending all previous javascript code built with wf:update/wf:insert_top” as a response to the comet connection.

loop()->
 receive
 {unauthorized,Message}->
 io:format("~p~n",[Message]),
 wf:update(feedback,"Your twitter credentials are wrong, check include.htr file!");
 {start,_Message}->
 wf:update(feedback,"Stream Running...");
 {stream,Message}->
 get_tweet_info(Message);
 {stream_end,_Message}->
 restart_button(),
 wf:update(feedback,"Stream Ended...");
 {stop,_Reason}->
 restart_button(),
 wf:update(feedback,"Stream Stoped...");
 {error,Reason}->
 error_logger:error_msg("Error : ~p~n",[Reason]),
 restart_button(),
 wf:update(feedback,#panel{class="error",body=wf:f("Error : ~s !",[Reason])});
 Any->
 error_logger:info_msg("ANY : ~p~n",[Any])
 after 55000 ->
 wf:update(feedback,"to quiet for me...")
 end,
 wf:comet_flush(),
 ?MODULE:loop().

With this simple code you have learn the basic blocks to create parallel computing, and the possibility to push content to users without the need to be constantly polling a service. And this is really cool because is all you need to create cool real-time / multi-user applications.

Example 2 – Twitter Cloud

Twitter Cloud Screenshot :

Nitrogen does already lot of work for us on erlang/javascript interaction, making easier  the creation of appealing  and rich web applications. Check web_cloud example where we have created another visualization for twitter stream, but now its a cloud of twitter users, where the size of the pictures is related to the ratio following/followers, where you can click to see the status update.

if you open web_cloud.erl, you can see that its very closed to web_stream, but now instead of building the html on the server we are passing the info to the the browser and will will build the dom with javascript. This can be achieved very easily with nitrogen using wf:wire constructor. As you can check on line 126 of web_cloud

wf:wire(wf:f("buildTweet({id:'~s',screen_name:'~s',picture:'~s',text:\"~s\",size:'~p'})",
[Tweet#tweet.id,
Tweet#tweet.screen_name,
Tweet#tweet.picture,
wf_utils:js_escape(Tweet#tweet.text),
Tweet#tweet.size])
).

Mainly we are calling the js function buildTweet that you can find on /js/main.js a js object with all the tweet function. We also use another great nitrogen function wf:f, that helps you build complex strings.

Another thing really useful is giving to an event different actions, like you can see in line 27.

#panel{id=control,body=[#button{text="Stop", actions=#event{actions="$.growl('','Stream is Stoping...');"}, postback={stop,Stream}}]}

Inside each event you can define your postback, and you can also use actions parameters to execute javascript. So if you click on the stop button, we will be calling event({stop,Stream}) and also calling jquery-growl plugin that will show a message to the user.  We can even define more than one event type to the same element. For example change control panel this on body function

#panel{id=control,body=[#button{text="Stop", actions=[
#event{actions="$.growl('','Stream is Stoping...');", postback={stop,Stream}},
#event{type=mouseover,actions="$.growl('','Click if you are a mouse!...');"}]
}]}

sync:go, and check your example. You should be seeing a message appear when you put your mouse over stop button and other when you click it.
As you can imagine this is a very simple example of all you can do with nitrogen . So please check nitrogen project where will have a lot of cool examplesnitrogen api with all functions available, and you can check some more documentation on on github wiki.

So now you know already enough to start coding your own ideas and projects, but before read last part of this tutorial, where we will resume some of the tools erlang has to help on your adventure.

December 2, 2009

Erlang On Nitro – Erlang Web Development Tutorial – Part 1/3

After learning erlang basics, and fell in love with it, one question pop up on my mind: Erlang is with no doubt a great language, but i make my living building web applications, so how i can use erlang to build web applications?

After some searching i discover 3 Erlang Web Frameworks : Nitrogen Project, ErlyWeb and ErlangWeb.  I tested the 3, and i decided to go with Nitrogen, because it had some cool examples and documentation, and it looked simple. I have spend the last 6 months building web applications using nitrogen and i could not be more pleased.

This tutorial is divided into 3 parts, in part 1 we will assume that you are a newbie to erlang also, so i will try to explain some basic stuff about erlang as we go, but i recommend you to read this hello world tutorials to better understand this one #link , #link …

In part 2 we will show in a step by step explanation how to build a simple and powerful app with erlang and nitrogen, using twitter stream api.

In part 3 i will present you some erlang tools that will help you mastering erlang.

Get Started with Erlang & Nitrogen

Nitrogen is open source project, started in November 2008 by @rklophausunder MIT-LICENSE. Although its pretty stable, you should be ready to assume your risk using it on production environments.

All the following examples were made on Mac OS X but they should be valid to Linux and windows as well.

First lets check if you have erlang installed. Open a terminal and type erl, if you have an error you need to install erlang.

apt-get install erlang

or go here to download source. If you are seeing something like this, congratulations you have already erlang installed.

darkua:~ sergioveiga$ erl
Erlang R13B (erts-5.7.1) [source] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.7.1  (abort with ^G)
1>

Now its time to install Nitrogen, what is very easy, just follow this instructions, In resume you just need to clone nitrogen project into a directory that is included in erlang path($ERL_LIBS).

darkua:~ sergioveiga$ echo $ERL_LIBS
/opt/local/lib/erlang/lib/:/usr/lib/erlang/lib/:/Users/sergioveiga/erlangProjects/tedi
darkua:~ sergioveiga$ cd /opt/local/lib/erlang/lib/
darkua:lib sergioveiga$ git clone git://github.com/rklophaus/nitrogen.git

Now lets see if everthink is ok. Enter Nitrogen directory and run this command

./Quickstart/quickstart.sh

Now try open your browser on http://localhost:8000/web/index , you should see a copy of nitrogen website running on local.

Erlang Project Structure

More or less but all erlang project have a defined structure:

– ebin ()
– *.beam (code compiled)
–  name_of_the_application.app (application resource file)
– include
– *.hrl (structure descriptions to include)
– src
– *.erl (source code)

application resource file is very important because it defines your application:

{application, name_of_the_application, [
 {description,  "App descritpion"},
 { vsn, "0.0.1" },
 {mod, {name_of_the_application_app, []}},
 { applications, [ kernel, stdlib] },
 {env, [
 {platform, inets},
 {port, 8000},
 {session_timeout, 3600},
 {sign_key, randomized},
 {www_root, "./wwwroot"},
 {templateroot,"./wwwroot/templates"},
 {scratch_directory,'./wwwroot/scratch'}]},
]}.

This is an example of the app file, and you can read more about application behaviour here In resume its the file that describes you app to erlang vm, where you define its version, its environment vars, the modules, and the applications that your app will use.

Nitrogen as an extra dir called wwwroot, where we will store all our static files (js, html templates, css, images,etc…)

Now lets create your first project, using a nitrogen script that will do most of the work for you. Check if you have already nitrogen symbolic link created.

darkua:~ sergioveiga$ nitrogen
Nitrogen Web Framework.

Usage:
nitrogen create [PROJECT_NAME]  - Creates a project in a subdirectory
nitrogen page [URL]             - Create a page for URL (EXAMPLE: 'nitrogen page web/blog/post')
darkua:~ sergioveiga$

if you get an error you need to create a symbolic link to the path you have previous clone nitrogen

sudo ln -s $ERL_LIBS/nitrogen/support/nitrogen \ /usr/local/bin/nitrogen

So now its time to create our first nitrogen project

 nitrogen create twitter_stream

A twitter_stream directory has been created and you should see a directory structure close to the one, i described before. Now in order to see that everything is ok, just run in your shell the start script

 ./start.sh

Now you should be able to go to http://localhost:8000/ and see you project running. If you get this error

=ERROR REPORT==== 18-Nov-2009::19:25:31 ===
Failed initiating web server:
(...)
{listen,eaddrinuse}
(...)

This happens because you have already a server running on the same port. You need to shut down the other service, or change port on the .app file.

Now that we have our infrastructure ready lets get deep into real code :)

Nitrogen Workflow

Open twitter_stream.erl in the source directory

The most important in this page is understand the erlang behaviour concept. In resume Behaviours are formalizations of common patterns. So when we say -behavior(application), erlang expects this module to behave like an application. You can read more about it here. In this case the application behaviour just needs a start and a stop function. Now open start.sh script.

echo Starting TwitterStream.
erl \
-name twitter_stream@localhost\
-pa ./ebin -pa ./include \
-s make all \
-eval "application:start(twitter_stream)"

In resume we are starting erlang vm, giving it a name, include and binary path, compiling the code, and start our application, that will execute the start method we saw on twitter_stream.erl. The rest for now its not important. So what happens when you go to http:localhost:8000/ ? If you check you twitter_stream.app file you will see this entries

{platform, inets}
{port, 8000}

This is very important because this defines what http server you are going to use, and in witch port is going to run. So nitrogen is not a web server, but it starts for you one of 3 possible web servers (inets, mochiweb, and yaws), you can read more about all of them, but for now we can use any. This also means that you dont need any other webserver (apache,etc…) to run your application :)

So when you enter the address the web server will receive the request and match it to a page. By default if you just call http://localhost:8000/ the request will be mapped to http://localhost:8000/web/index/ and this will run the web_index module inside /src/pages. So if you request /web/home it will execute the module web_home.erl inside the pages dir.
In order to avid to much detail, now lets assume that this mapping /web/xpto -> web_xpto.erl happens by magic :)

So now open the file web_index file.

-module (web_index).
-include_lib ("nitrogen/include/wf.inc").
-compile(export_all).

main() ->
#template { file="./wwwroot/template.html"}.

title() ->
"web_index".

body() ->
#label{text="web_index body."}.

event(_) -> ok.

-module (web_index).
The module definition is always required, and it defines your module name. Very important Reminder : erlang does not have namespaces, so try to use always prefixes on your own modules to avoid conflicts. For example dont call your module lists.erl… use for example my_lists.erl.. don’t laugh this happens to the best :)

-include_lib (”nitrogen/include/wf.inc”).
The way you can include a lib, in this case nitrogen lib, so you can use nitrogen stuff. Just keep it :)

-compile(export_all)
In order to call a function from module, you need to export it. To avoid that you can use this directive, but use it with caution, its best to export each one, like this:
-export([ main/0, body/0, title/0, event/0]).

So module, include, and exports is what we can call the “header” of the module. Bellow is where the code really begins :)

main() ->
#template { file="./wwwroot/template.html"}.

This function is needed in all your pages because its the one that will be executed when you request this page. This function needs to return (in erlang return is always the last line of execution) a #template element. In erlang we have a structure called record, read more here, and its similar to a struct in C. This records are used by nitrogen to create elements that will help you build web applications with erlang. The template element will define the html template for this page, and the file attribute is the location of your html page that will be used as template.

Open wwwroot/template.html.

As you can see its a perfect normal html page, with some weird stuff [[[page:title()]]] on it. As you probably are imagining right now, nitrogen will parse this page, and will replace the [[[page:title()]]] with the output of the title function inside web_index. The reason to use page, and not web_index is that you can use a template for many pages, and this way it will execute the title of each calling page.

The other important part is the [[[script]]] element. This is where nitrogen will put all javascript he creates. Just don’t remove it or you will get into troubles :)

Now back to web_index page, you can see that title function return a simple string, and body uses another nitrogen element.  So mainly you have an element  for  all html elements (div, li, table,input…). The only problem is that nitrogen does not use always the same tags you find in html, so for example a span is #span element, but a div is #panel element… but don’t worry after a while you get use to it.

So lets try replace the body with this code:

body()->
#textbox{text="some text"},
#button{text="Hello!"}.

now go to erlang shell you have started the project and execute sync:go().

(nitrogen@localhost)2> sync:go().
Recompile: ./src/pages/web_index
./src/pages/web_index.erl:12: Warning: a term is constructed, but never used
ok

sync:go() will turn into one of you best friends because it will compile all the files you have changed :)

You can see a warning, that is mainly telling that you have some code, that in never used, and if you go to the browser, and can see that you only have the button there. So what happen to the textbox? Like i told you before, erlang only returns the last code line, so mainly you are only returning the button. To return all you just need to do this:

body()->
[
#textbox{text="some text"},
#button{text="hello"}
].

Mainly you just need to add your elements to a list. In erlang [] is a list, not an array.  Lists are on of the most used structures so bookmark this link, you will need it for sure.

Now sync again and go to the browser. You should see now a input text element and a button :)

Nitrogen has also a set of built in functions that do a lot of stuff for you. For example the wf:render one.

body()->
Elements = [
#textbox{id=input_id, text="some text"},
#button{text="hello"}
],
wf:render(Elements).

This does exactly the same as before but let you organize the code, the way you like most, what is always great.

So now that you know the alphabet lets start making words :)

Nitrogen Actions

The interaction between user and application, nitrogen calls it actions. So lets add some actions to our previous button.

pre #button{text=”hello”,actions=#event{type=click,postback=hello}} /pre

This will tell the button that on click, will execute the hello event.

So the next thing you need to do is the hello event

event(hello)->
io:format("~p~n",["test message"]);

event(_) -> ok.

sync:go(), and click on hello button and go back to your erlang shell.

You have just created your first client server interaction :) . If you are using firebug you can easily see that this is done using an AJAX Event, where all the page info is send to the server, and matched to the specific event.

Now lets grab some info

event(hello)->
Input = wf:q("input_id"),
io:format("~p~n",[Input]);

sync:go(), and after clicking again go to erlang shell.

 (nitrogen@localhost)1> ["some text"]

As you can see using nitrogen wf:q(id) function you have access to input box value. In resume you can access to all parameters sent in a get or post request. Lets test get parameters. Change your body function to this:

body()->
Input = wf:q("input_id"),
io:format("~p~n",[Input]),

Elements = [
#textbox{id=input_id, text="some text"},
#button{text="hello",actions=#event{type=click,postback=hello}}
],
wf:render(Elements).

sync:go(), and change url to http://localhost:8000/?input_id=hello

As you can see it work exactly the same, the important thing to remember is that wf:q can only read the header parameters of the request, so for example if now you click on the button, you are creating another request, and input_id=hello from the previous one does not exist.

Now as you can see the output comes inside a list, that we dont really want, so lets remove the element from the list. Replace Input with this:

 hd(wf:q("input_id"))

sync:go(), and call the url again ( http://localhost:8000/?input_id=hello ). You should be able to see only the string with no list.

But now call the url without any parameter http://localhost:8000/

Say hello to your first of many erlang errors! Go back to the shell, and you will see exactly what happened

[{erlang,hd,[[]]},
{web_index,body,0},
{element_template,eval_callbacks,2},
{element_template,eval,2},
{element_template,eval,2},
{element_template,eval,2},
{element_template,eval,2},
{element_template,eval,2}]

Here you have info of witch module and function create the error {web_index,body,0}, and also witch instruction erlang,hd,[[]], and in resume the problem is that you are trying to get the head of an empty list.

In order to solve this we will introduce on of the most common structures in a erlang code, the case statement. As you probably have heard erlang does not have if statement, its false it has, but in the end you never need to use it, because the case really solves all your problems. So lets change again the Input :

Input = case wf:q("input_id") of
 []->
 "Oops, not input!";
 _->
 hd(wf:q("input_id"))
 end,

Case works like it is supposed to be, it will evaluate the return of wf:q and if it evaluates to [], what happens when you dont have the parameter defined, it will associate the string “Oops, not input!” to Input, or if it is something else (_) does not matter what, it will grab the head of the list.

Since erlang lives a lot of pattern matching, _ option is a powerful arm for your arsenal :)

Import reminder, and one of the most annoying stuff around erlang, is that the way you end your instruction (, or ; or .) its not a coincidence.
In resume, the end of a function is indicated by the dot (.), but if your function uses pattern matching with the same number of arguments, like it happens on event, only the last one ends with the (.) all the others end with (;).

event(hello)->
Input = hd(wf:q("input_id")),
io:format("~p~n",[Input]);

event(_) -> ok.

All other instruction always end with comma (,) with exception of case instruction where the different options are ended also with (;) and the last one does not need any, like you have seen in the previous example.

Back to the action itself, we were just sending an Atom (erlang simple structure, any word starting with a lower_case :) ), but we can send info in the postback. Replace postback with this:

 postback={hello,"Hello, i'm string!"}

and adapt your event to receive the new info

event({hello,Item})->
io:format("~p~n",[Item]);

sync:go,  and as should see how easy its to pass info into events.

Now that you have understood the basics around nitrogen its time to check more complex example, and the cool nitrogen elements, like the comet! So lets continue to part 2 of this tutorial, where we will build a twitter visualization using twitter stream api.

October 27, 2009

Wikipedia PT Search Engine for FireFox

Sometimes i have the feeling that even on the internet when i really need something i never find it… i find hard to believe that there isn’t already a firefox search engine for portuguese articles in wikipedia… damm it, i losted 30 minutes and i have build one -> Add Portuguese Wikipedia Search Engine

At least now i have an idea how easy is to create one for my own services :)

To build your own all you need to do is create a file like this one, read more here

Erlang Poker Server + HTML5 Canvas

Hey, today i was walking around git-hub checking some erlang projects, and i found this really great erlang poker server, from the greater Joel Reymont.

Well to be honest i dont really give a damm about poker, i never played it, online or in real world, but i have a lot of friends completely addicted to it, so its a topic that catches my attention.

So i start to wonder how great would be to build a client to this server, and i remember a discussion i had earlier with @telmodiasand @jclopesabout htm5 canvas and flash, and the battle to control rich interface applications. EUREKA! Lets build a client for the openpoker server using canvas, to prove that its possible to build a rich interface like the ones exist today in flash (like this one ) much more lighter and faster.

Since i have tons of other projects to work in, this is going to the “when i get time” department, and then probably to oblivion… so i would be really happy to help anybody that would like to really do it :)

If you are not convinced check 9elements experiment of canvas, just amazing :)

October 23, 2009

Hello World in Erlang

Before you star reading, caution, ERLANG i highly vicious and can cause you to hate any other programming languages you are used to.

Install Erlang

apt-get install erlang

now lets start with the most simple code you can write in erlang

Save it as hello.erl and run erlang shell

erl

Now you can compile hello.erl from the erlang shell. Don’t forget the full-stop (”period” in American English) at the end of each command. After you just need to execute Module:Function().


Erlang R13B01 (erts-5.7.2) [source] [rq:1] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.7.2 (abort with ^G)
1> c(hello).
{ok,hello}
2>hello:start().
Hello, World!ok
3>

Now that that you are not long afraid of erlang, lets show some of the mighty power everybody talks about, and build “hello world elang style” ;)

copy the code above

now compile the code, and execute the following commands


Erlang R13B (erts-5.7.1) [source] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.1 (abort with ^G)
1> c(hello2).
{ok,hello2}
2> Pid = hello2:start().
<0.39.0>
3> Pid ! hello.
Hello, World!
hello
4> Pid ! goodbye.
goodbye
5> Pid ! hello.
hello
6>

In resume what you have just did, was create a new process with a process id = Pid, that will be waiting for messages. When it receives the message hello, it prints Hello World, and it calls itself to continue listening, when you send the message goodbye the process just finishes execution and dye.

All this with just a few lines of code, and a very simple syntax :) , but this is just the beginning, now imagine that this process can be running in any machine in the world, and you still can use exactly the same code! This and much more WOW effects is what makes erlang so amazing.

Now in order to really learn erlang i recommend you to get Joe Armstrong the erlang creator,
Programming Erlang: Software for a Concurrent World book and visit the erlang best documentation repo http://erlang.org/doc/

Please check also the source and inspiration for this post.

October 22, 2009

My first blog post…

Back in 2006 when everybody was creating blogs, i never did it, now that everybody is just tweeting i will start blogging… lol… this need to be different will be my ruin :)