Posts arquivos para maio, 2009

31mai2009

TGWOH² 2009-05-31 15:04:00

(0) comentários

Classic Gaming Shelf : Phantasy Star II

Back in the early 90′s, the last-gen video game console i asked my parents to have was the Super Nintendo. Although i consider myself a SNES fanboy, it ‘s undeniable that Sega done some awesome work with Genesis. Now with Wii’s Virtual console, i’m taking the time to play the classics i always was curious about but never managed to play back at the time of their respective releases.

My previous system was a Master System II and one of the best games i’ve ever played in life was Phantasy Star. My history with PS is a funny one for another post, but now i’ll comment my impressions on its successor.
The game mechanics are very similar to PS1. The most noticeable differences are 3rd person perspective in battles (you actually see the characers striking the enemies) and the lack of first person dungeon navigation(this style could have been explored more).

The gameplay starts out fine at first, but gets boring over time because of playability issues:

  • Lots of random battles, moving between cities is a test for patience since the pace speed of the characters in the world map is way too slow with battles popping out of every couple of steps.
  • Dungeons are big, hard to navigate and memorize (the spaces are hard to distinguish). For a regular player its virtually impossible to explore them without a map, and even with the map it’s hard to locate yourself in it. It explains a lot why the cartridge had a “110-page hint book included”(as written on the cover).

I’m saying this because i’ve gone through ~4 dungeons till now (just finished the Bio Systems Lab) and each dungeon (in average) can steal you around a couple of hours easily(not counting the ultra-boring powering up needed to cross them without being annihilated).

IMHO, Phantasy Star 1 had a more balanced gameplay. Of course, it had its load of ultra complex dungeons (like Baya Malay/Medusa Towers) and leveling up moments, but at acceptable doses. It seems that Sega in PS2, instead of enhancing the fine balance of these ingredients, decided to overdose them.

But apart the game mechanics issues , i see it as a landmarker game in the time it was released (1989-1990). The universe surrounding the Algol system is amazingly interesting and full of untold secrets.
I surely bet that PS2 was an everlasting gobstopper for a kid with a full summer vacation to play games.

My curiosity concerning what happened after Lassic’s fall was the main motivator for getting this game on Virtual console, but i don’t think i’ll have the time and patience to finish it now. I wonder if these gameplay issues were improved on the Sega Ages remake. I wanna play it once i learn some japanese :)

Ps : I think i’m getting old

28mai2009

setting app.config for different environments

(0) comentários

Imagine the following scenario: You have a project that you just developed in your local machine and want to deploy it into the CI (Continuous Integration) and approval environments. In this project, there is a configuration file (app.config) that contains a few settings, for instance, connection strings and log file directory.

Quite common isn’t it? So, how do you handle with the annoying issue of changing your app.config file for all these environments?

Editing the configuration file in each environment doesn’t seem to be a smart solution. During the development, we can add further settings into the app.config. Updating the config file later (during the deployment) for every environment is a hard and unreliable manner to do this because we can miss some changes.

Another choice that I’ve seen consists in having a copy in your project for each environment. Well, this is much better. We will have app.config, app.config.ci, app.config.approval and app.config.production to satisfy our environments. So, whenever we need to add or change any settings, we can edit all these config files during the development phase. To deploy, just rename the correct file to app.config and that’s it. But the problem that I see in this solution is that our SCM will run crazy with all the renamings.

For example: rename app.config to app.config.local and app.config.ci to app.config. SCM will tell you that app.config has been modified, app.config.local has been created and app.config.ci has been deleted. What a mess!

Another issue of this solution is that it doesn’t help us when we want automatated deployment. It depends on manual editing of the config files or a dependency on a script to do the job.

To avoid these painful processes, we can use the project’s configurations and after build tasks set in .csproj file. I will explain in the following steps:

1st Step

1st Step

As default, Visual Studio creates two project configurations: Debug and Release. We’re going to add a configuration for each environment, assuming that both default configurations applies to our local environment. So, let’s create CI, Approval and Production configurations.

  1. In your Visual Studio, go to the “Solution Configurations” combobox and click “Configuration Manager…”
  2. In “Active solution configuration” combo box select “<New…>”
  3. In the popup window, fill the “Name” field with your environment name and select Release in “Copy settings from” combobox. Check “Create new project configurations” if it is not checked.
  4. Repeat this process for all environments.

At the end, you should have something like this:

Set of solution configurations

2nd Step

2nd Step

Next, let’s create the copies of our App.config files. For this, we will name all the copies as {Configuration}.config. So, in my example, I’ll have Approval.config, CI.config, Production.config.

App.config copies

Let’s change the connection string values from the files.

App.config settings:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="applicationConnection" connectionString="Data Source=localServer..." />
  </connectionStrings>
</configuration>

Approval.config settings:

<configuration>
  <connectionStrings>
    <add name="applicationConnection" connectionString="Data Source=approvalServer..." />
  </connectionStrings>
</configuration>

CI.config settings:

<configuration>
  <connectionStrings>
    <add name="applicationConnection" connectionString="Data Source=ciServer..." />
  </connectionStrings>
</configuration>

Production.config settings:

<configuration>
  <connectionStrings>
    <add name="applicationConnection" connectionString="Data Source=productionServer..." />
  </connectionStrings>
</configuration>

3rd Step

3rd Step

Finally, we will edit the .csproj file to add the AfterBuild task to replace the App.config file according to the configuration set on the build.

  1. Right click in your project and select “Unload Project”
  2. Right click “ProjectName(unavailable)” and select “Edit ProjectName.csproj”
  3. In the end of the file, add the next lines:

    <Target Name="AfterBuild" Condition="'$(Configuration)' == 'CI' or '$(Configuration)' == 'Production' or '$(Configuration)' == 'Approval' ">
        <Delete Files="$(TargetDir)$(TargetFileName).config" />
        <Copy SourceFiles="$(ProjectDir)$(Configuration).config" DestinationFiles="$(TargetDir)$(TargetFileName).config" />
    </Target>

Observe that these lines says: “After build, if configuration is ‘CI’ or ‘Production’ or ‘Approval’, delete output config file and copy {configuration}.config file into output file.”

After building using all configurations, you should have an output directory for each configuration in your bin folder. Check the config files and you should see the differences among them.

And that’s all! I hope you enjoyed this guide and starts to use it to build and deploy your projects with no worries regarding configuration files. C ya soon!

23mai2009

Posting and Getting files in ruby/rails

(0) comentários

Today I’m going to show some very short snippet about posting files with ruby, and receiving them in a rails controller.

For all examples I’ll be using the rest-client gem (”sudo gem install rest-client”).

The fist thing we’re going to do is to implement a very basic file post in ruby - there is basically two methods:

  1. You can post the contents of the file straight to the request body (I’m going to call it the “raw way”);
  2. You can pass the file contents as a parameter inside your request, like any other (I’m going to call it the “pretty way”).

One method is not necessarily better than the other, how you should do it depends a lot more on how your target service is implemented.

Posting a file, the “pretty way”:

PRETTY_UPLOAD = "http://localhost:3000/files/upload_pretty/pretty_file.txt"

def self.post
    pretty_resource = RestClient::Resource.new PRETTY_UPLOAD

    pretty_file = "./pretty_file.txt"

    File.open pretty_file, "wb" do |file|
      file.write "some random pretty content"
    end

    pretty_resource.post :file => File.read(pretty_file)
end

Posting a file, the “raw way”:

RAW_UPLOAD = "http://localhost:3000/files/upload_raw/raw_file.txt"

def self.post
    raw_resource = RestClient::Resource.new RAW_UPLOAD

    raw_file = "./raw_file.txt"

    File.open raw_file, "wb" do |file|
      file.write "some random raw content"
    end

    raw_resource.post File.read(raw_file)
end

Now, getting a file - since there is basically just one way to get it, I’ve made just one method - getting a file on ruby:

DOWNLOAD = "http://localhost:3000/files/download/raw_file.txt"

def self.get
    resource = RestClient::Resource.new DOWNLOAD

    downloaded_file = "./downloaded_file.txt"

    response = resource.get
    # you can access the headers (response.headers) or the
    # http response (response.net_http_res) if you need to

    File.open downloaded_file, "wb" do |file|
      file.write response.to_s
    end
end

That’s pretty much all you need on the client side (reading the contents of a regular http request should be no different at all than reading an attached file).

Time to go to the server side, shall we? Here good old rails kicks ass per se.

All I needed to do was to set up a custom route (just to make things more clear):

map.files ':controller/:action/:name.:extension'

Then, for the controller, I’ve set up two methods to receive the posted file - pay attention to the slightly different approach for the “pretty way” and the “raw way” of posting a file.

Receiving a file, the “pretty way”:

def upload_pretty
    file_name = "#{params[:name]}.#{params[:extension]}"
    file_contents = params[:file]
    File.open "tmp/#{file_name}", "wb" do |file|
      file.write file_contents
    end

    render :text => "ok"
end

Receiving a file, the “raw way”:

def upload_raw
    file_name = "#{params[:name]}.#{params[:extension]}"
    file_contents = request.raw_post
    File.open "tmp/#{file_name}", "wb" do |file|
      file.write file_contents
    end

    render :text => "ok"
end

I also provided a method for the client to download back the files, so that you can check on the contents to see that it went through flawlessly:

def download
    file_name = "#{params[:name]}.#{params[:extension]}"
    send_file "tmp/#{file_name}"
    # you can also use: send_data File.read("tmp/#{file_name}")
end

And that’s basically it, as simple as it can be.

As usual, you can download the sample code clicking here.

That’s a very quickly put together piece of code which, most likely, can be greatly improved - but I think it is just good enough to show the basics of how to get and post files on ruby and rails.

Criticism is always welcome.

23mai2009

Sem repetições

(0) comentários

Há uns 2 meses, meu amigo Saroka e eu preparamos uma apresentação para falar de automatização de tarefas. Falamos para um público técnico da Locaweb sobre algumas melhorias que estamos realizando no nosso processo de deploy.

Achei legal registrar aqui pra me lembrar que sempre dá pra automatizar alguma coisa. Toda vez que rodo uma task e economizo meu tempo e paciência, lembro de que é muito bom deixar de fazer tarefas repetitivas. Um ótimo post sobre o assunto foi escrito pelo ‘louco por automatização‘ Guilherme Chapiewski.

Pra quem quiser ver a nossa apresentação no 3o. Locaweb Tech Day, segue um link para o vídeo.

Locaweb - Automatizando suas tarefas usando Capistrano from Locaweb on Vimeo.

19mai2009

E o manifesto ágil, meu caro CSP

(0) comentários

Já faz algum tempo que não tenho tanta paciência para ficar discutindo metodologias ágeis para desenvolvimento de software. A minha cabeça de alguma forma passou a pensar que tudo se resume a aplicar bem o manifesto ágil. E isto, por si só, não é nada fácil. Exige muita disciplina, capacidade, atenção e profissionalismo. Nenhuma metodologia, ferramenta ou gerente vai resolver o real problema do nosso mercado: escrever software útil e de qualidade.

Danem-se os selos CMMI, as certificações do PMI e da Scrum Alliance, os programadores que enchem currículos de siglas e código de sujeira. O que vai resolver o nosso problema é gente competente, disciplinada (no sentido dado pelo Uncle Bob no seu keynote da RailsConf), capaz de ouvir o cliente e criar uma relação verdadeira de parceria com ele, com características para evoluir constantemente. Se você ou a sua empresa são capazes de fazer isso bem, não se preocupe em dar um nome para os métodos que você usa para fazer o seu trabalho. É feio sair por aí dizendo que aplica scrum (ou qualquer outra coisa da moda), encher o bolso de dinheiro e se esquecer os princípios básicos do manifesto ágil.

Esta introdução longa é para desabafar a raiva acumulada pelo monte de besteiras que eu ouvi em algumas palestras no Scrum Gathering 2009. Muita gente já escreveu e/ou tocou em pontos polêmicos sobre o evento. Quero dar os meus pitacos, então vamos ao que mais me irritou naqueles dois dias:

  • Times auto-gerenciáveis - pelo menos 2 palestrantes (Ricardo Vargas e Fábio Câmara) afirmaram categoricamente que nunca viram um time capaz de se gerenciar. E somente isso. Não contaram alguma experiência ou analisaram o motivo pelo qual isso é impossível no ambiente deles. Este é um assunto muito interessante e qualquer discussão é válida.
  • Ken Schwaber - imagine que você vai ter uma aula de futebol com o Ronaldinho Gaúcho e o cara gasta o tempo falando que no futebol a bola é redonda, os times têm 11 jogadores, o objetivo é fazer o maior número de gols, etc, etc, etc. Pois é, assim foi a palestra de um dos criadores do scrum. O sujeito ficou quase uma hora falando o básico e o óbvio, fez uma brincadeira mais do que manjada para falar de “comando e controle” versus “times auto-gerenciáveis” e finalizou anunciando que a Scrum Alliance vai lançar o treinamento para CSD (Certified Scrum Developer) e que este vai ser baseado em ferramentas da Microsoft. Precisa falar mais alguma coisa?
  • Fábio Câmara - a palestra do Fábio foi a mais polêmica, ainda mais sabendo que ele é um CSP (Certified Scrum Practitioner). Li o título “Usando scrum com o Visual Studio Team System” e fiquei curioso para saber o que faz alguém precisar tanto de uma ferramenta para usar scrum. No meio da palestra o Fábio algumas afirmações, dentre elas: “eu questiono o uso de testes, principalmente os unitários, em projetos time-driven”; “eu tinha um estagiário que eu chamava de controller porque ele ia todo dia de manhã de mesa em mesa perguntando para o desenvolvedor se ele estava fazendo a tarefa que ele deveria estar fazendo. O VSTS me diz isso, uma vez que ele cria um link entre o requisito e o pedaço de código que foi escrito para atender aquele requisito. Eu também consigo saber quem escreveu cada linha, porque quando você pergunta numa sala ‘quem escreveu essa linha aqui?’ fica todo mundo assobiando”; “é incrível como o princípio de pareto se aplica em quase todos os projetos de software. 20% das pessoas fazem 80% do trabalho”; “os desenvolvedores, no final do dia de trabalho, fazem check-in do que eles produziram. No VSTS eu consigo ver cada check-in e passar a mão no telefone pra perguntar por cara lá em Recife porque ele subiu só 25 linhas de código quando a média dele era de umas 200″; “o scrum master e responsável por distribuir as tarefas para o time”. Logicamente algumas pessoas começaram a questionar tudo isso e ele descreveu um cenário para ‘justificar’ tudo isso: “imagine uma equipe grande. Eu já gerenciei equipes com 60 pessoas, algumas trabalhando em outros estados, etc …”. As minhas sugestões para o Fábio são as seguintes: 1) demita umas 50 pessoas da sua equipe (olha o problema do princípio de pareto sendo resolvido) e forme um time com os 20% que fazem 80% do trabalho e no qual você possa confiar e não controlar (opa, pode mandar o controller embora também). Pare de procurar culpados, isso não resolve nada, é desperdício. Se alguém fez alguma coisa errada no código, esse alguém foi o time e ele mesmo resolve (você já deve ter ouvido falar de propriedade coletiva do código e programação em par). Você não vai precisar ficar bancando o detetive pra descobrir quem foi o infeliz que escreveu a linha 1567 da classe XXXX ou bancando o leão-de-chácara do repositório. Deixe os seus programadores escreverem muitos testes e automatizá-los. 2) se vocês estão sem tempo para escrever os testes, peça a colaboração do seu cliente; explique que o time precisa escrever testes para entregar um produto de qualidade, trabalhem com ele na priorização das histórias, mostre as vantagens de desenvolver um produto iterativamente, melhorando continuamente, respondendo às mudanças. 3) pare de valorizar mais o Visual Studio do que a sua equipe. 4) nunca, jamais, de forma alguma, esqueça do manifesto ágil 5) e, POR FAVOR, pare de falar que o que você está fazendo é scrum.

Na minha opinião, o evento contou com palestras muito boas (Juan Bernabó, Alexandre Magno e Luiz Cláudio Parzianello), mas estes 3 fatos citados bastaram para fazer do Scrum Gathering 2009 - Brazil e da Scrum Alliance um baita fiasco.

15mai2009

Catalyst::Plugin::Captcha

(0) comentários
Simples “como fazer” para usar o Catalyst::Plugin::Captcha. Criando um projeto: catalyst.pl MyApp cd MyApp Inserindo o plugin no projeto: No Arquivo, altere: vim lib/MyApp.pm use Catalyst qw/-Debug ConfigLoader Static::Simple/; para: use Catalyst qw/-Debug ConfigLoader Static::Simple Captcha Session Session::Store::FastMmap Session::State::Cookie/; Acrescente a configuração de como será a imagem de Captcha: MyApp->config->{captcha} = { session_name => ‘captcha_string’, [...]
11mai2009

CouchDB – Quick Tip

(0) comentários

A quick tip for those who want to get a grasp on what CouchDB actually is before actually going to the trouble of setting up the whole environment (Erlang + CouchDB installation process seems to be a pain on Windows).

A friend of mine, who got all hyped about it when I told him about CouchDB sent me a link with an online interactive interpreter for people to toy with it. You can access it here.

To be able to actually do anything with it though, you’re going to need some knowledge of functional programming, specially map and reduce concepts.

10mai2009

TGWOH² 2009-05-10 20:51:00

(0) comentários

Uncle Bob just wanna have fun!

Uncle Bob Martin’s keynote @ RailsConf’09 is definitely a very remarkable one. What keynote to expect from a General Yamamoto-class of software developer with great communication skills? At least some good advices and food for thought.

The title was “What killed Smalltalk Could Kill Ruby”, but don’t hang too much on it as much some people did. The majority of the keynote was focused on exposing how decent test suites and TDD adoption generates a positive-clean-code-feedback.

Few points of the presentation pissed Smalltalkers for obvious reasons. Usually “Z language is dead” statements immediately pisses the Z-language hackers. Before spitting flames try to take a deep breath and see the thing on a different perspective(and with a bit of humor, of course).

It’s fairly known that “No existing language will die in a long time. An interpretation for “Killed” in the context of programming languages can be: “a language that had lost its lift-off momentum to occupy the front row of IT industry technologies”. I believe that Smalltalk and Common Lisp are two examples of it.

Sincerely , i didn’t read any tone of “Smalltalk was killed because of the lack of testing” on the presentation as some people did. What i understood is that testing provides you the control mechanism to properly harness the power of languages like Ruby and Smalltalk. On such languages with high degree of expressive freedom it becomes “too easy to make a mess”. In other words: you can fly high if you don’t have proper discipline.

Fabio Kung published an interesting analogy that came to me a while ago when reading a chapter of The Ruby Programming Language. “With great power comes great responsibility” said Uncle Ben and so did Uncle Bob.

[...] Professionalism is honor, Professionalism is being honest with yourself and Disciplined in the way you work [...]

Bob just nailed it. These are the main attitudes i have been working hard to improve right now. A couple of years ago, when i started to code a solution, my mind entered in a turmoil state trying to unroll the entire thing at once, much like a hungry beast attacking its prey. The final result was that i often got lost in the ideas entering an analysis-paralysis state. Today, i have far better control of the beast(sometimes it leaves the cage.. lol). I’m lucky enough to pair program with great people that gives me feedback when that happens.

I see TDD as a software development equivalent to Ritalin. A way of achieving discipline and delivering quality software with one shot. It’s no silver bullet, but surely helps a lot.

Take Bob’s words seriously , but not too much. Allow the guy to be a little ironic and humorous sometimes (e.g when he was speaking on Academic Smalltalk adoption).

Uncle Bob just wanna have fun and watch his nephews writing clean code :)

9mai2009

Spider Man’s professionalism at RailsConf 09

(0) comentários

Professionalism definition from Uncle Bob in his recent talk at RailsConf 2009:

“Discipline to wielding of power.”

– Robert Martin (aka Uncle Bob)

To me, it looks pretty much similar to the “Ruby” definition from Chad Fowler in the last Rails Summit Brasil:

“Ruby is a dangerous tool.”

– Chad Fowler

Wich makes me remember Uncle Ben’s advice to Spider Man:

“With great power comes great responsibility.”

– Uncle Ben

Would be Uncle Bob inspired by Uncle Ben? What if they are the same person? :D


Posted in Uncategorized

Switch to our mobile site