Posts de June, 2008

[Claudio Figueiredo] ASP.NET MVC Experiences 2, Overview

Monday, June 30th, 2008

Setting expectations clear

What I’m trying to achieve here is not a "how to use" ASP.NET MVC or a Tutorial. For those I really recommend Scott Hanselman’s videos which were my first source on the subject.

It’s a hands on experience, a spike if you will, with the most prominent features of the framework.
It’s a evaluation on how it works checking it advantages and disadvantages, from my point of view, and trying reducing some friction that I’m encountering on using MonoRail in my new project. Don’t get me wrong, I have nothing against MonoRail, it is still the most mature, featured MVC implementation on .Net world and I would not find any friction on it if not checking on .Net MVC features.

Evaluation procedure

The criterias that I’ll use in my evaluation will be, in the following order of importance:

  • Testability
  • SoC
  • Extensibility
  • Manageability

This analysis might not be linear, but these will be the focused points.

Overview

First time I heard about .Net MVC and checked out it’s features, it looked to me a badly built copy of MonoRail. But I soon realized some very nice differences. Not on the project itself, but the behaviour of P&P conducting it’s development. The way they positioned themselves eager to hear the community feedback led to great improvements over the three released iterations. That made me realize the fact that the similarities between them were not coincidental. Maybe the coincidences lie in the fact that they are both implementations of the same pattern, or more likely intentional (unless Filters and ActionFilters are both Design Patterns affiliated to MVC and I don’t know ).

Anyway, this is good because the transition between them is almost seamless, but that’s another topic.

Application Model

Almost everyone I talked about it, thinks that .Net MVC is sitting onto an Application Model of it’s own. But the fact is that it’s standing over the ASP.NET 2.0 Application model. Just as any other ASP.NET 2.0 application, it inherits from HttpApplication and has it’s events and life cycle. In fact, the new cool routing system is registered just in Application_Start as any global register.

This allows some interesting (and freaking) options as running both WebForm and MVC simultaneously.

Even though I didn’t expect a whole new web platform, I kinda hoped the separation would be a little more clear, not that this clouds the benefits that it provides. What really bother me is finding out that the standard ViewEngine, implemented by the ViewPage, inherits directly from our dear old friend System.Web.UI.Page. This open up even freakier possibilities. The fact that you can do the same funky thing that you do with a WebForm on a MVC View really scares the hell out of me.

First thing a tried when I find that out, was: add a Server form, an asp:button, an event handler and, Voilá: - Back to the same beach we’ve been swimming the past few years. I know that the fact the you could do something doesn’t mean you should or would do it, but it gave me shivers anyway.

This also showed me that you could add any WebControl you like on the Page, and work with it freely as you would on WebForms but in fact you wouldn’t like, more on that later.

Views

As said before, the default ViewEngine is basically a HttpHandler inheriting from the standard Page model. That said, one may conclude that anything you can do on a Page could be done on a ViewPage and most can actually be done. Here a some observations about this cross model that I checked:

  • The layout scheme, as expected is the same MasterPage mechanism used in WebForms.
  • Custom controls can be used the same way if you add a server form to the View.
  • Yes YOU HAVE VIEWSTATE, but only when adding a server form to the View, otherwise you get a nice clean html to work with.
  • You can use UserControls inside a ViewPage, but you’ll end up with the whole ViewState/ServerForm stack polluting to your code.
  • You’ve got tracing enabled just as a WebForm.

The above issues worried me a little. … mixed up model but spaghetti code?

Then again I remembered that’s it’s a Microsoft Product anyway. No rants here, just saying that Microsoft is not a charity and as such can’t avoid cathering for the main customers in their current business model. This is just something I (and you reader) should bear in mind while reading this.

The good thing here, is that the View layer was nicely built. Although they allow more than I would like, what is done here is done in a beautiful way. View testing has been somewhat neglected on implementing MVC applications, but here we get a stronger model which we can test and extend in a natural way.

Some key points on Views:

Convention over Configuration

The first thing I noticed, and one that made very happy is that ASP.Net MVC Views and setting approach follow strictly the CoC principle. It’s is such on MR and should not be changed, so common sense prevailed here for the good.

The rule here is putting your views on /Views/{controller}/{action} and nothing more needs to be done. It can be changed setting a new ViewLocator, which is a resolver for View’s paths.

Even though everything seems the same, one addition that I really liked is the Shared Views concept, which is so obvious that I’ll refrain from explaining.

The introduction of the concept of Typed Views.

Binding a View to a model seems very natural on MVC. And every view is bound to a model indirectly. The introduced change allows you to strongly-type your View’s Data to it’s own Model, thus making it more intuitive than generic views, that most of the time aren’t really generic. Let’s check how’s that works.

That’s the code for a view called List that’ll be rendered by the List Action of the Home Controller.

   1: namespace Stormwind.MVC.Template.Views.Home {
   2:     #region usings
   3:  
   4:     using System.Web.Mvc;
   5:  
   6:     #endregion
   7:  
   8:     public partial class List : Viewpage {
   9:     }
  10: }

And that’s the Template:

   1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="List.aspx.cs"           Inherits="Stormwind.MVC.Template.Views.Home.List" %>
   2: <ul>
   3:     <%
   4:         foreach (var pair in (IList<string>)ViewData["listItem"]) {
   5:     %><li>
   6:         <%= pair %></li>
   7:     <% } 
   8:     %>
   9: </ul>

There’s two important points here:

  1. The first is ‘public partial class List : ViewUserControl‘, notice that the view inherits from a specific base class. Among other things, this base class contain a property call ViewData. ViewData is nothing more than a KeyValuePair collection that is used to interchange data between the controller and the View. It’s almost exactly the same as a MonoRail property bag.
  2. The second is ‘ var pair in (IList<string>)ViewData["listItem"]‘. Notice the cast here. As an untyped collection, ViewData items should be casted before used in a not so intuitive way. Worst of all making refactoring harder and the view error prone.

The concept of Typed Views, come to solve these issues. Check it out.

   1: public partial class ListTyped : ViewPage<List<string>> {
   2: }

Notice that the view now inherits ‘ViewUserControl<List<string>>‘ allowing us to:

   1: <ul>
   2:     <%
   3:         foreach (var pair in ViewData.Model) {
   4:     %><li>
   5:         <%= pair %></li>
   6:     <% } 
   7:     %>
   8: </ul>

The inherited View sets the Model allowing us working more naturally and refactoring friendly now.

The ability to easily create and change a ViewEngine.

Creating and changing View Engines in MonoRail is not too difficult, but changing them in runtime is a little painful and doing that through Windsor makes it feels makes it feel unnatural and definitely not the expected behaviour, or at least one that requires more configuration than expected.

Creating a new view engine is incredibly easy, since the IViewEngine contract only has one method to implement - The RenderView method.

Of course, this post does not sums everything that the MVC Framework has to offer, but believe me, there’s not much more either. You’ll see soon in another post.

Well, Views are not that different from MonoRail or other MVC implementations, and given you have the ability to implement your own, it’s a very flexible structure.

Next post: Controllers.

Stay tuned.

[Gabriel Falcão] New blog!

Sunday, June 29th, 2008

i’m proud to present my brand new blog!

It’s awesome to be able to publish hackerish stuff like GObject, Python, GNOME, and anything else related to coding and freedom.

For now that is all!

[Claudio Figueiredo] ASP.NET MVC Experiences - Part 1, The Setup

Thursday, June 26th, 2008

First of all I did what as every developer experienced in the RTFM methodology should do I went to it’s Site and download the installer.

As I didn’t found the binaries and was not in the mood of build the source (oh yeah, there is a source available for a change) I’ve downloaded the Installer just to check it out.

As a I installed the package, the usual NNF*, I was currently happily surprised to find no reference in the GAC. Only changes noticed so far were a new Visual Studio Template called ASP.NET MVC Web Application and a Start Menu Item Microsoft ASP.NET MVC Preview 3 which leads you the a folder containing the set of assemblies needed to run a ASP.NET MVC Application. (Duh!)

Normally I would go my usual way, creating a new structure using a Stormwind Project template and setting the references, but as I’ve been having a nice user experience so far I’ve decided to take the full trip MS induced experience.

Open up Visual Studio, selected New Project, Visual C# / Web and ASP.NET MVC Web Application named my Project , and then the first surprise:

asp_mvn_unit_test_setup

 

 

 

 

 

 

 

 

 

Yes, it’s a nice change see anyone at MS thinking in Test First, but the only test framework supplied is the MS Test. First I got a little angry, but then I realized that it’s a MS product after all. :)

Well I’m a NUnit guy and as such I started digging how to make ASP.NET MVC works with another test framework.

After taking a look at it, and checked out it really works, I decided it was not worth it.

The main issue is exactly the wizard that, for some arcane reason, only is setup to show the Test Framework of your choice, changing a registry key.

Hope you now I didn’t like it a bit, so I decided to make my own template with the basic structure settled.

Thanks to my friend Bernardo cant-wait-till-you-get -home-so-I-did-it Heynemann, we already got Windsor container up and running.

Next Post, working with ASP.MVC and overall feeling so far.

*NNF:Next, Next, Finish.

[Claudio Figueiredo] ASP.NET MVC Experiences

Thursday, June 26th, 2008

There´s sometime now there I´ve been wondering toying with the new ASP.NET MVC. I´ve been really impressed with what I´ve been hearing about it, and specially what I´ve been reading in Scott Guthrie´s blog, but only after the RC3 it got me really impressed.

So I decided to move my fat a$$ a little and do some constructive blogging for a change and create a series of introcdutories and eventually more advanced posts about my experinces with this new toy.

Stay tuned.

[Bruno F. M. Souza] HDTV é o que há

Tuesday, June 24th, 2008

Finalmente entramos na era da TV Digital aqui na Globo.com… Não! Não estamos transmitindo nenhum canal de TV Digital, e também não temos um decodificador recebendo o sinal digital do broadcast… É que essa semana foi instalado em nosso laboratório o Net DIGITAL HD MAX. Sua principal função é prover imagens com uma maior definição - HDTV, além de servir como um gravador digital integrado - DVR (mediante o pagamento de uma taxa “simbólica”). Dentre suas principais características técnicas, temos:

  • Resolução: 480i, 480p, 720p, 1080i;
  • Compressão: H.264;
  • Saídas de vídeo: Composto, S-Vídeo, Componente e HDMI;
  • Saídas de áudio: HDMI, S/PDIF e Stereo RCA;
  • Interfaces RJ-45 (Ethernet) e USB - desabilitadas, obviamente;
  • 2 tuners DVB.

Os canais produzidos em HDTV dão um show, mas ainda deixam algo a desejar para olhos mais clínicos - percebem-se artefatos de borda facilmente, em função dos parâmetros de compressão utilizados. Com 2 tuners, é possível assistir ao conteúdo ao vivo de um canal, ou até mesmo gravado, enquanto se grava o ao vivo de outro canal. A decepção ficou por conta da ausência do padrão Full HD (resolução 1080p).

São boas as perspectivas para os padrões de captura atuais, visto que, além de não precisarmos mais gastar rios de dinheiro com placas de capturas capazes de fazer o deinterlace - temos a opção de receber sinais SD progressivos - também poderemos receber vídeos 100% digitais pela interface HDMI - sem ruídos e sem necessidades de conversão A/D - com placas de “baixo” custo como a Intensity Pro da BlackMagic Design. Isso, se conseguirmos algum workaround para o HDCP

Além disso, começa a ficar mais fácil pensar em oferecer conteúdo “HD - widescreen - 16:9″ com fontes originalmente em alta resoução.

[Rafael Silva Pereira] TV Digital e a Interatividade, Portabilidade e Mobilidade

Sunday, June 15th, 2008

Para quem ainda não sabe, amanhã, dia 16/06, a TV Globo inicia sua transmissão de TV Digital para o Rio de Janeiro, durante a exibição do Jornal Nacional. Depois de mais de 5 anos de muita burocracia governamental finalmente estamos implantando o novo sistema, processo que deve demorar, pelo menos, mais uns dois anos para ter toda a cobertura que a TV analógica possui hoje (99% do território nacional). A pergunta que me faço neste momento é quais serão as reais vantagens do SBTVD, além do ganho de qualidade é claro, considerando o grande atraso no processo de definição/implantação.

O comitê para definição do SBTVD foi criado em 2003 com o objetivo de pesquisar os padrões existentes e escolher um para utilização no Brasil. Depois de muita pesquisa e discussão, chegou-se a conclusão de que o ISDB-T (padrão de TV Digital Terrestre do Japão) era o que oferecia as melhores condições, já que possuía características que permitiam a recepção por dispositivos móveis e portáteis. Porém, o ISDB-T utilizava o MPEG-2 como codec de vídeo, e, devido a demora na definição do padrão brasileiro, já existia uma corrente muito forte em prol da utilização do H.264 como codec de vídeo, devido a melhor eficiência em relação ao MPEG-2. Foi então que decidiu-se pela criação de um sistema híbrido, utilizando a modulação ISDB-T com o H.264 como algoritmo de compressão de vídeo. Esta, no meu ponto de vista, foi a única vantagem de termos demorado tanto em definir um padrão de TVD.

Entretanto, a interatividade, uma das grandes vantagens da TVD além da qualidade, está praticamente esquecida, e, pelo ritmo que as coisas caminham, ainda vai demorar muito para que funcionalidades descentes sejam implementadas. A ausência de um processo interativo mais estruturado na TV acaba abrindo caminho para a expansão da distribuição de vídeo na internet, que já lida com este processo de interação desde seu nascimento, e que ainda pode evoluir bastante.

O problema é que quando a interatividade finalmente chegar à TV pode ser tarde demais. Dizer que a TV vai acabar e que o consumo de conteúdo em vídeo será realizado via internet é ser um tanto quanto radical. Na verdade, acredito em um processo de convergência, onde os grandes broadcasters continuarão gerando conteúdo, que será consumido e distribuído de diversas formas. A única certeza que eu tenho é que o modelo comercial que temos hoje será completamente substituído, já que o processo de consumo de conteúdo será alterado.

Com relação à mobilidade e portabilidade, acredito que a distribuição de vídeos via redes de dados 3G irá predominar sobre a TVD por dois motivos: primeiro, porque as redes 3G já estão sendo implantadas, e existe uma demanda forte que impulsiona a expansão; segundo, pelo processo de consumo “on demand” que já existe na internet e que esta sendo expandido para experiências mobile, e que faz muito mais sentido em relação ao modelo de distribuição da TV, do ponto de vista de consumo de conteúdo em celulares.

Resumindo, é necessário uma mudança de mentalidade daqueles que hoje lidam com TV para que seja possível aproveitar de forma ampla os benefícios que a TV Digital nos oferece, atendendo assim as expectativas de consumo do mercado. Caso contrário, a TV irá perder cada vez mais sua força, abrindo caminho para novas possibilidades e experiências que ela não é capaz de suprir.

[Rafael Silva Pereira] [WWDC] iPhone 3G e Lançamento no Brasil

Monday, June 9th, 2008

Hoje, precisamente às 11:32am horário de San Francisco, o iPhone 3G foi anunciado no keynote do Steve Jobs na WWDC, notícia já bastante esperada por todos aqueles fanáticos por tecnologia, porém mais comemorada que um gol do Brasil pelos geeks de plantão aqui da Globo.com, que acompanharam o keynote ao vivo pela internet (inclusive eu). Para alegria de todos, o iPhone 3G já vem com suporte Tri-Band, o que significa que ele irá funcionar na rede 3G do Brasil sem problemas. Além disso, o iPhone 3G também conta com um GPS integrado, é um pouco mais fino que o iPhone atual e vem em duas cores básicas (preto ou branco). Especificações

A melhor de todas as novidades, ou pelo menos, a que ninguém esperava, foi o preço: $199 para o de 8GB e $299 para o de 16GB!!!!! Realmente é para destruir a concorrência. A notícia triste ficou por conta das datas. O iPhone 3G já pode ser comprado agora na Apple Store dos US, porém o shipping será apenas no dia 11 de julho. Nesta data, o novo iPhone estará disponível em 25 países, porém, no Brasil, ainda não existe uma data definida. A única certeza, neste caso, é que a Claro será a distribuidora “oficial” do iPhone no Brasil.

Quem quiser saber mais sobre o iPhone 3G e sobre o keynote de abertura da WWDC pode conferir os detalhes aqui.

Fugindo um pouco do assunto iPhone 3G, também foi anunciado hoje o Samsung Omnia, um clone do iPhone, porém com o terrível Windows Mobile instalado. O único ponto positivo deste lançamento, fato pelo qual eu estou mencionando ele aqui no blog, é o suporte nativo ao H.264, consolidando o novo padrão de vídeos para celulares, em convergência com os padrões de TV, e também Web.

[Bruno F. M. Souza] Novo iPhone 3G na pista…

Monday, June 9th, 2008

Como muitos já devem saber, Steve Jobs, CEO e co-fundador da Apple, anunciou hoje o novo iPhone no keynote de abertura da WWDC (Worldwide Developers Conference). Todos aqui na Globo.com ficaram muito eufóricos e puderam acompanhar “ao NEXTEL” e “ao Twitter” de nosso “enviado especial” Guilherme Chapiewski.

Dentre as principais novidades do meu futuro novo gadget, temos:

  • Compatibilidade com a rede de telefonia 3G (UMTS/HSPDA), possibilitando um tráfego de dados em taxas mais altas que o EDGE;
  • Suporte ao sistema de localização GPS;
  • Firmware 2.0;
  • Maior durabilidade da bateria;
  • Entrada para fones de ouvido convencionais;
  • Capa externa nas cores preta e branca (apenas o de 16GB);
  • Design mais compacto;
  • Ferramenta para remoção do SIM Card;
  • Preço de lançamento: $199 (8GB) e $299 (16GB);
  • Disponibilidade nos EUA e mais 21 países no dia 11 de julho;
  • Disponibilidade no Brasil pela Claro, sem data definida, e mais outros 69 países.

Isso, sem falar na possibilidade de se fazer download de aplicações “legítimas de terceiros” pelo novo App Store e do serviço MobileMe (me.com), um conjunto de aplicações web (Ajax) que permite sincronização online de contatos, calendário, e-mail, fotos, etc. nas plataformas Mac e PC. Este último a um custo anual de $99 com 20GB de storage disponíveis.

Reitero as palavras do chefe do chefe do chefe referentes ao magnífico acontecimento: “… marketing é isso, você amplia as funcionalidades de um produto, reduz o preço, e a galera, ao invés de ficar puta, só pensa em comprar o novo…”.

Enfim, informações mais detalhadas podem ser encontradas nos links abaixo:

A propósito: aceito ofertas para compra de meu futuro ex-iPhone 2.5G… ;)

[Anselmo Alves] Aplicações web nativas - por que não?

Friday, June 6th, 2008

Recentes discussões sobre desempenho e escalabilidade de sistemas me levaram a seguinte questão: por que não se fala em frameworks e sistemas web server-side compilados diretamente para assembly nativo?

Este é um fenômeno curioso para mim, já que aplicações interpretadas (e até as compiladas para uma virtual machine), são menos performáticas. Quero que fique claro que não acredito que o uso de aplicações compiladas seja a solução para problemas de performance. Estas questões precisam ser primariamente endereçadas a melhorias arquiteturais e infraestruturais desenhadas para cada aplicação particular. Apenas questiono o fato de nós desenvolvedores, na grande maioria dos casos, não considerarmos essa hipótese ao desenvolver uma aplicação web, ou mesmo como meio de otimizar sistemas específicos cuja performance é crítica.

Por exemplo, ainda que soluções Java tenham desempenho excelente em muitos casos, seria muito interessante e perfeitamente justificável, do meu ponto de vista, o desenvolvimento de um framework para C++ que suportasse um esquema semelhante à tecnologia Servlet do Java - sem as limitações de performance de programas CGI - entre outras soluções web consagradas, além de bibliotecas que facilitassem o desenvolvimento de aplicações C++ para web.

É claro que não podemos negar que existem vantagens interessantes oferecidas pelas linguagens interpretadas neste campo. Mas, honestamente, não entendo porque o simples ganho de performance oferecido por aplicações nativas ainda não resultou no surgimento de pelo menos um framework desse gênero consolidado e de uma comunidade de desenvolvedores que, assim como eu, são aficionados por desempenho. :)

[Danilo Bardusco] Certified Scrum Trainer

Tuesday, June 3rd, 2008

Como eu disse no meu ultimo post, na semana passada estive em Recife para apresentar a experiência da Globo.com com Scrum. No final do evento, tive a grata surpresa de ser convidado pelo Boris para fazer parte do seu programa de mentoring com o objetivo de me tornar um Certified Scrum Trainer.

O programa tem um ano de duração, durante o qual eu acompanharei o Boris, ajudando nos seus treinamentos com uma participação cada vez maior, até estar apto a realizar todo o treinamento.

O primeiro passo foi dado nesse fim de semana quando fui à São Paulo, para ajudar o Boris num treinamento CSM aberto. A idéia era chegar na sexta-feira pela tarde para poder fazer a programação do sábado com o Boris no fim do dia, mas devido ao tempo ruim no Rio de Janeiro, o Galeão ficou um bom tempo fechado e acabei chegando em São Paulo muito tarde. Por conta disso tive que fazer a minha parte de improviso.

Durante o treinamento, Boris me pediu para explicar a dinâmica do Wall-Board e no final, quando ele falou sobre como escalar Scrum, tive a chance de mostrar como estamos tratando esse asunto na globo.com com 17 times atualmente.

Foi muito gratificante ver como o Scrum está se difundindo rapidamente no Brasil além de poder trocar ideias com o pessoal da Abril Digital, Instituto Nokia de Tecnologia, Weg e Motorola. Sorte a todos!

PS: ao pessoal que assistiu o treinamento, gostaria muito de ter um feedback sobre minha apresentação e como posso fazer para melhorar. Fiquem a vontade para escrever nos comentários.