quinta-feira, janeiro 28, 2010

MVC or WebForms: It's more about client side vs server side - Ian Cooper - CodeBetter.Com

MVC or WebForms: It's more about client side vs server side

Scott Guthrie has posted on the growing debate over Webforms vs. MVC, a debate that seems to be raging everywhere (although there is more that one MVC framework out there too). I agree with Scott's point about the nature of technical debates, and the acceptance that there are different schools of thought. However, that does not always imply that all schools are equally good solutions to a given problem.

The issue has been though I think not solely about the MVC pattern, it is also about the shift from providing rich client behavior server-side or client-side. In this area the renewed interest in AJAX and the emergence of Javascript libraries like Prototype, script.aculo.us and JQuery have been game changers. And for me those RIA paradigms dovetail better with MVC apps than with Webforms applications. At the same time the growth of REST has meant many have re-engaged with the HTTP protocol and its resource oriented model, have turned attention away from page based approaches to web development toward resource oriented ones. There is a correspondence here, because as the use of client side scripting grows so does the perspective of the server as a resource provider used by the client.

It is in many ways this shift of paradigm that MVC supports better and why using MVP approaches with WebForms is not a 'seperate but equal' answer to modern web development. Its not simply about better conformance to Single Responsibility Principle.

What our frameworks do for us

Our average web framework has some pretty basic requirements - handle requests for resources from the server by returning an appropriate response. In our case this is HTML. The simple nature of this model underlies the success of the web.

To support this model our framework needs to route to an appropriate handler in our code that can read the request. Now we could just interrogate that request to pull out post data or query strings, but writing a lot of that code would get old fast, so it helps if our framework can map between form, params and query string values and part of our object model. That way we can manipulate the variables of the request more easily. Now we have to take an appropriate action in response to the request. Generally this is where most of our code plugs in. We get some data and compose a response, in HTML to return in the response. Now just using Response.Write() to output our HTML becomes hard to maintain, so most of us expect our framework to give us  some sort of template so that we can separate the static and dynamic portions of our response.

The MVC pattern enters the fray here when frameworks separate the responsibilities of template to provide view, model to provide response to action, and co-ordination between the two for a request. Criticism of Webforms as lacking effective separation cf concerns is because the aspx file is both responsible for rendering the HTML used as a response and providing the controller for the request. It thus has two reasons to change, because the template changes or because the co-ordination of handling a request changes. These may be orthogonal concerns and make maintenance harder. Some patterns such as MVP try to alleviate this by enforcing separation of these two responsibilities within the framework. this criticism is valid but not complete issue; the significance of 'MVC' frameworks is not solely their better separation of concerns.

Now for sure the devil is in the details, but that's pretty much it.

Bare Bones

'MVC' frameworks such as ASP.NET MVC or Monorail ttend to have a bare bones approach to meeting these requirements. The framework takes requests and calls an action to service them, mapping request to action parameters. We then carry out the appropriate task and render html through a view engine. MVC frameworks add little on top of this paradigm. The big win here is that this makes them simple to learn and easy to use, because the surface area of the API is small. The surface area for ASP.NET MVC is smaller than that for Webforms and is easier for new developers to learn. It also works in harmony with http and thus expectations. The principle of least surprise is important to APIs because it makes them easier to discover. Understand the problem and you are likely led in search of the solution.

Rich Internet Applications

Now ASP.NET MVC etc. allow you to return an HTML response, but HTML has its limitations in that it is static. You need to post a request to the server each time you want some new action to occur. In some cases this 'complete form and submit' model works, but we have become used, from smart clients, to a more dynamic model that provides feedback as we make selections. We expect choosing from one dropdown such as country to restrict choices such as US State vs. UK county or Post Code vs. Zip Code.

Out-of-the-box support in web browsers for dynamic behaviour came in the form of Javascript and manipulation of the DOM. The browser is the smart client in this approach. The issue here is that Javascript development was a challenge for many developers and consequently many development shops. Why? Because folks found client side behaviour did not just require switching to another language, but also learning the DOM, which was also sometimes uncomfortably close to metal for developers weaned on smart client Forms frameworks like Windows Forms, VB, or PowerBuilder. In addition the browser wars meant that the model for programming against the DOM was not the same from browser to browser, further complicating the code that was needed to implement a rich client in the browser. In truth it was expensive. Finally the debugging experience was poor. We were back to tracing the state of variables in order to isolate and fix problems in the browser. For many MIS departments writing sites with a rich client, heavy on javascript, was out-of-reach in other cost or skills.

To solve this problem WebForms introduces the concept of server side controls - essentially shifting the rich interaction to the server. The server side control abstracts the html control from the client side. The benefit is that it allows you a development approach familiar to forms based programmers. You set and get control properties and write handlers to react to events. But as the events are raised client-side you need effectively mirror all of the control state from the client side to the server. The problem here is that html does not share this with you on a post. You also need to record the event raised for the server side too, as a post is all you know about from http. This brings in ViewState, which captures all the state which a post is not giving you. But once it is implemented I can provide all that dynamic behaviour on the server, skipping and jumping over issues like knowledge of Javascipt and the DOM, as well as browser compatibility issues.

Of course we can quickly see that with any complex enough page ViewState will grow. As it is embedded in a page it increases the page weight which can hamper performance In addition because we must do an http post to transfer the state of our application back to the server, and then display the response, events are handled by a page refresh. This has the consequence of making the system slower than one which handles the event locally, giving rise to user complaints of flicker or slow response. In addition if you try to cope by adding some AJAX callbacks from your client  the question quickly becomes 'who owns this state' as you may have copies of the state both on the client and in ViewData being marshalled back and forth to the server.

Webforms is also a more complex API than MVC and thus harder for developers to learn. Most of us have been at an interview where we have asked, or been asked the question - what is the Webforms lifecycle? Understanding the stages, where viewdata is available and modifiable is not an insignificant learning challenge.

Given that, for some time I used to recommend building applications using WebForms server-side control model over building applications with client side behaviour. Why? Because of the cost and difficulty of building rich client behaviour in Javascript with the DOM outweighed the cost of learning Webforms.

What Changed?

MVC trades the complexity of server side controls for a simpler programming model, supported by client side controls. The emergence of the new breed of Javascript frameworks like Prototype, JQuery, and script.aculo.us, made it far cheaper to code the client behaviour on the client. The elegance and simplicity of these frameworks, their abstraction of browser API differences, and their rich ecosystem of control providers, lowered the barrier to entry for client-side development providing solutions to common needs such as  grids . The availability of many free controls lowers the cost of common UI widgets that have often been the preserve of expensive vendor solutions.

In addition the debugging experience for Javascript has significantly improved from the old trace and dump model with browser plugins such as Firebug and Visual Studio.

With a lower cost it has become commercially viable for more development shops to build rich client applications. Best of breed applications do not suffer from the postback flicker issue because they manipulate state locally on the browser and use AJAX calls to the server. With effective client side development, the user experience is akin to smart clients of yesterday, with none of the distribution problems for central IT departments. This rich experience available for the web lies at the heart of the SaaS revolution.

The MVC model truly shines with AJAX where the target for an AJAX call is just an action on a controller. The affinity to http’s resource based model allows for easy definition of the server side support for rich clients. The advatange of MVC frameworks is the ease with which they dovetail to client-code using frameworks like JQuery. Client-side programming is back, using modern Javascript libraries!

It is this, IMO, which has shifted the balance in favour of MVC. I do not think it any accident that the ASP.NET team shipped JQuery with ASP.NET MVC. I think it was essential to shipping an ASP.NET MVC application that a modern Javascript client library was included to support rich client behaviour on the browser instead of server side.

From my cold dead hands

The attitude of many developers may be ‘you will pry Weforms from my cold dead hands’. The march of progress is threatening to do just that. Much of theresistance is based on prior experiences with the cost of client-side development using Javascript, without understanding that the new frameworks available have significantly lowered the barrier to entry there. In addition, Silverlight opens a second front against Webforms by offering rich client development using XAML. If Javascript does not replace Webforms, then XAML will. Server-side controls had their day. They built careers, companies, and fortunes but they are legacy applications now. Client-side controls have returned with fresh offensives that will see their end. If you are building a new web project today you should be looking at an MVC framework.

For my part the question of Webforms vs. MVC is already an irrelevance. That is yesterday’s fight and victory has been declared despite a few units continuing to fight on. The next war is likely to be between Silverlight and Javascript for ownership of the smart client…


Posted 01-27-2010 3:34 AM by Ian Cooper

Best and most complete article I have ever read about this subject.
Let me underline these two citations, that I subscribe:
"If Javascript does not replace Webforms, then XAML will."
"The next war is likely to be between Silverlight and Javascript for ownership of the smart client…"

Posted via web from paulocunha's posterous

quarta-feira, janeiro 27, 2010

8 Things That Suck About the iPad [Apple]

8 Things That Suck About the iPad

A lot of people are psyched about the iPad. Not me! My god, am I underwhelmed by it. It has some absolutely backbreaking failures that will make buying one the last thing I would want to do. Updated
Big, Ugly Bezel
Have you seen the bezel on this thing?! It's huge! I know you don't want to accidentally input a command when your thumb is holding it, but come on.
No Multitasking
This is a backbreaker. If this is supposed to be a replacement for netbooks, how can it possibly not have multitasking? Are you saying I can't listen to Pandora while writing a document? I can't have my Twitter app open at the same time as my browser? I can't have AIM open at the same time as my email? Are you kidding me? This alone guarantees that I will not buy this product.
No Cameras
No front facing camera is one thing. But no back facing camera either? Why the hell not? I can't imagine what the downside was for including at least one camera. Could this thing not handle video iChat?
Touch Keyboard
So much for Apple revolutionizing tablet inputs; this is the same big, ugly touchscreen keyboard we've seen on other tablets, and unless you're lying on the couch with your knees propping it up, it'll be awkward to use.
Want to watch those nice HD videos you downloaded from iTunes on your TV? Too damned bad! If you were truly loyal, you'd just buy an AppleTV already.
The Name iPad
Get ready for Maxi pad jokes, and lots of 'em!
No Flash
No Flash is annoying but not a dealbreaker on the iPhone and iPod Touch. On something that's supposed to be closer to a netbook or laptop? It will leave huge, gaping holes in websites. I hope you don't care about streaming video! God knows not many casual internet users do. Oh wait, nevermind, they all do.
Adapters, Adapters, Adapters
So much for those smooth lines. If you want to plug anything into this, such as a digital camera, you need all sorts of ugly adapters. You need an adapter for USB for god's sake.
Update: Why stop at 8? Here are more things we are discovering that suck about the iPad.
It's Not Widescreen
Widescreen movies look lousy on this thing thanks to its 4:3 screen, according to Blam, who checked out some of Star Trek on one. It's like owning a 4:3 TV all over again!
Doesn't Support T-Mobile 3G
Sure, it's "unlocked." But it won't work on T-Mobile, and it uses microSIMs that literally no one else uses.

Send an email to Adam Frucci, the author of this post, at adam@gizmodo.com.

One more proof of what I'm getting tired to say: Apple is very good doing pretty things, but not practical ones...
Event the god damn name is a practical joke and an utterly big fail: maxi pad is a synonym to tampon (see http://www.stayfree.com

sábado, janeiro 23, 2010

Air Race: António Costa admite que exclusivo publicitário da Red Bull pode inviabilizar prova no Tejo - Local - PUBLICO.PT

O autarca falava no final de uma reunião de câmara em que todos os vereadores da oposição criticaram, com veemência, o contrato “leonino” firmado entre a Associação Turismo de Lisboa (ATL) – de que o município faz parte – e a Red Bull, com vista à realização do espectáculo aéreo.

Diz o documento que as Câmaras de Lisboa e de Oeiras terão, juntamente com a ATL, de pagar à Red Bull 3,5 milhões de euros pela corrida, assegurando também todas as suas necessidades logísticas. O acordo é bastante diferente daquele que vigorou nas anteriores edições, que tiveram lugar no Douro. As Câmaras de Gaia e do Porto nunca pagaram mais de 400 mil euros cada uma aos organizadores da prova, cujo risco comercial esteve sempre do lado de uma empresa privada, a Extreme, que intermediava o negócio.

Já as autarquias de Lisboa e de Oeiras, que se preparam para acolher a edição deste ano, vão ficar dependentes do apoio de patrocinadores para conseguirem reunir pelo menos parte significativa dos 3,5 milhões. Só que o contrato assinado pela Associação de Turismo de Lisboa estabelece que o exclusivo publicitário da área onde se realiza a prova, entre Alcântara e Algés, pertence à Red Bull – tal como os direitos de transmissão televisiva. Toda a área ou apenas uma parte? Redigido em inglês, o documento levantou ontem grandes dúvidas quer aos vereadores quer a António Costa, que vai pedir esclarecimentos à ATL.

Alugar espaços

A Câmara de Lisboa contava obter receitas alugando espaços nesta zona – a restaurantes, por exemplo – ou cedendo-os a patrocinadores. “A clarificação desta cláusula é crucial”, observou ontem o presidente da autarquia. “Se a Red Bull tiver o exclusivo de toda a área, isso implicará um custo para a câmara que não podemos considerar”. E tal inviabilizaria a realização do evento em Lisboa? António Costa respondeu que sim.

Para o vereador do CDS-PP, António Carlos Monteiro, todo o processo tem sido conduzido de forma “pouco transparente e absolutamente leviana”, com consequências gravosas para o erário: “Este contrato estabelece que a carne fica do lado da Red Bull e os ossos do lado da câmara”.

O seu colega do PCP, Ruben de Carvalho, mostrou-se também preocupado: “O contrato entre o Turismo de Lisboa e a Red Bull é inaceitável”. Já o vereador social-democrata Victor Gonçalves exigiu um estudo de viabilidade financeira do evento.

As objecções fizeram com que a votação do assunto na câmara tivesse sido adiada para a próxima semana. Quanto à Red Bull, continua a manter-se em silêncio, invocando a confidencialidade prevista no contrato.

Escrito em inglês

Um pormenor que espantou os vereadores da Câmara de Lisboa foi o facto de o acordo assinado entre a Associação Turismo de Lisboa e a Red Bull Air Race estar redigido em língua inglesa. Daí também as dúvidas da sua quinta cláusula, que diz que a Red Bull será a única detentora dos direitos publicitários “on the entire event venue”, isto é, em todo o local do evento, excepto se forem propriedade privada.

Os autarcas ficaram também surpreendidos por o documento remeter a resolução de eventuais diferendos para os tribunais de Viena

Não sei se ria ou chore! Espero que sirva de lição para, numa eventual próxima, se dignem ler primeiro o contrato!!!

Posted via web from paulocunha's posterous

quinta-feira, janeiro 21, 2010

O Porto não é pequeno nem é segundo | Nuno Gomes Lopes

By Nuno Gomes Lopes, 19 de Janeiro de 2010 0:25

(aqui grande)

Espero que depois desta imagem deixem de se referir a Lisboa como o centro. Aliás, peço-o encarecidamente. Se há um centro no oeste peninsular, este é o Porto. E se havia dúvidas, não há nada como o visual para as eliminar. Espero que deixem de falar de TGVs para Madrid, de pontes sobre o Tejo ou de ‘aeroportos nacionais’. Não é do ‘interesse nacional’ investir desmesuradamente em Lisboa, mas apenas do ‘interesse’ de quem lá mora. Já é tempo de exigir o que nunca devia ter deixado de ser nosso.

Estou surpreendido!

Posted via web from paulocunha's posterous

domingo, janeiro 17, 2010

Que bons jornalistas temos...

Até os meus pais, com 4 anos de escolaridade feitos à dezenas de anos, reconheceram de imediato o erro…

Reparem no comentário do final J

In http://tsf.sapo.pt/PaginaInicial/Vida/Interior.aspx?content_id=1472155 (provavelmente, vão corrigir, entretanto)

Posted via email from paulocunha's posterous

O palhaço, por Mário Crespo

Um bocado mordaz demais para o meu gosto, mas não deixa de ser corajoso:

Saltar links iniciais


  • Serviços SAPO

O palhaço

O palhaço compra empresas de alta tecnologia em Puerto Rico por milhões, vende-as em Marrocos por uma caixa de robalos e fica com o troco. E diz que não fez nada. O palhaço compra acções não cotadas e num ano consegue que rendam 147,5 por cento. E acha bem.

O palhaço escuta as conversas dos outros e diz que está a ser escutado. O palhaço é um mentiroso. O palhaço quer sempre maiorias. Absolutas. O palhaço é absoluto. O palhaço é quem nos faz abster. Ou votar em branco. Ou escrever no boletim de voto que não gostamos de palhaços. O palhaço coloca notícias nos jornais. O palhaço torna-nos descrentes. Um palhaço é igual a outro palhaço. E a outro. E são iguais entre si. O palhaço mete medo. Porque está em todo o lado. E ataca sempre que pode. E ataca sempre que o mandam. Sempre às escondidas. Seja a dar pontapés nas costas de agricultores de milho transgénico seja a desviar as atenções para os ruídos de fundo. Seja a instaurar processos. Seja a arquivar processos. Porque o palhaço é só ruído de fundo. Pagam-lhe para ser isso com fundos públicos. E ele vende-se por isso. Por qualquer preço. O palhaço é cobarde. É um cobarde impiedoso. É sempre desalmado quando espuma ofensas ou quando tapa a cara e ataca agricultores. Depois diz que não fez nada. Ou pede desculpa. O palhaço não tem vergonha. O palhaço está em comissões que tiram conclusões. Depois diz que não concluiu. E esconde-se atrás dos outros vociferando insultos. O palhaço porta-se como um labrego no Parlamento, como um boçal nos conselhos de administração e é grosseiro nas entrevistas. O palhaço está nas escolas a ensinar palhaçadas. E nos tribunais. Também. O palhaço não tem género. Por isso, para ele, o género não conta. Tem o género que o mandam ter. Ou que lhe convém. Por isso pode casar com qualquer género. E fingir que tem género. Ou que não o tem. O palhaço faz mal orçamentos. E depois rectifica-os. E diz que não dá dinheiro para desvarios. E depois dá. Porque o mandaram dar. E o palhaço cumpre. E o palhaço nacionaliza bancos e fica com o dinheiro dos depositantes. Mas deixa depositantes na rua. Sem dinheiro. A fazerem figura de palhaços pobres. O palhaço rouba. Dinheiro público. E quando se vê que roubou, quer que se diga que não roubou. Quer que se finja que não se viu nada.

Depois diz que quem viu o insulta. Porque viu o que não devia ver.

O palhaço é ruído de fundo que há-de acabar como todo o mal. Mas antes ainda vai viabilizar orçamentos e centros comerciais em cima de reservas da natureza, ocupar bancos e construir comboios que ninguém quer. Vai destruir estádios que construiu e que afinal ninguém queria. E vai fazer muito barulho com as suas pandeiretas digitais saracoteando-se em palhaçadas por comissões parlamentares, comarcas, ordens, jornais, gabinetes e presidências, conselhos e igrejas, escolas e asilos, roubando e violando porque acha que o pode fazer. Porque acha que é regimental e normal agredir violar e roubar.

E com isto o palhaço tem vindo a crescer e a ocupar espaço e a perder cada vez mais vergonha. O palhaço é inimputável. Porque não lhe tem acontecido nada desde que conseguiu uma passagem administrativa ou aprendeu o inglês dos técnicos e se tornou político. Este é o país do palhaço. Nós é que estamos a mais. E continuaremos a mais enquanto o deixarmos cá estar. A escolha é simples.

Ou nós, ou o palhaço.


publicado a 2009-12-14 às 00:30

Posted via email from paulocunha's posterous

quarta-feira, janeiro 13, 2010

A new approach to China

Citation: "we have evidence to suggest that a primary goal of the attackers was accessing the Gmail accounts of Chinese human rights activists".

My respects to Google on this subject.

Posted via web from paulocunha's posterous

domingo, janeiro 10, 2010

Câmaras pagam 13 milhões por ano aos bancos pelos estádios do Euro 2004

Lembro-me perfeitamente de, em 2003/2004, argumentar, com amigos adeptos de futebol, acerca da não viabilidade económica dos gastos públicos na construção destes estádios, com pouco ou nenhum sucesso.

Vejamos agora:

Câmaras pagam 13 milhões por ano aos bancos pelos estádios do Euro 2004

Em tempo de crise, as autarquias de Braga, Aveiro, Coimbra, Leiria, Faro e Loulé têm mais um problema: a factura dos estádios construídos a pensar no Euro 2004. Só em encargos com a banca, as seis câmaras pagam, por ano, mais de 13 milhões de euros.

Artigo completo em: http://jn.sapo.pt/paginainicial/economia/interior.aspx?content_id=1466000#

Posted via email from paulocunha's posterous

quarta-feira, janeiro 06, 2010

Windows 7 God Mode Easter Egg

I did not discover this, I got it from a tweet that Rob Conery put out there. Thank you, Rob!

I don’t know if this is a Windows 7 hack or if this is available in other operating systems.

  1. Create a new folder on your desktop
  2. Name the new folder:

The new folder will change into this icon.


Clicking your shiny new icon will result in a new window that gives shortcut access to the myriad of configuration and administration utilities in Windows that I always seem to need to hunt down.


Opening one of these nodes will provide direct access to the associated utils.


Weird and beautiful, isn’t it?

It makes me wonder what other Easter eggs are in there.

David Starr Tools and Utilities

Very useful! :)

Posted via web from paulocunha's posterous

gcontactsynch – Sincronize-se!

IN pplware

Mais uma vez venho falar maravilhas dos produtos Google, mas desta vez graças a uma ferramenta externa. Cada vez mais estamos a fazer da Google o ponto central da nossa vida informática. Entregámos-lhe a gestão das nossas contas de email, a gestão dos nossos contactos, o nosso calendário e por ai fora… Mas até agora não tenho tido razões de queixa. Ainda não se tornaram demasiado intrusivos e controladores.
Falemos agora menos bem! Quem concebeu a gestão dos nossos contactos devia ter-se lembrado que por vezes podemos ter de nos sincronizar com outros software ou com equipamentos externos. E ter de fazer esse trabalho à mão é no mínimo enfadonho. Mas felizmente temos o gcontactsynch.

Passamos portanto a ter a possibilidade de sincronizar o nosso Outlook com o Google Contacts e fazer esse sincronismo de forma periódica e sem qualquer intervenção manual.
Basta inserirmos os dados da nossa conta de Gmail (ou Google Apps) e ele trata de tudo o resto. Indiquem apenas a periodicidade do sincronismo e quem pretendem que seja o original em caso de conflito e está pronto a sincronizar.
Podemos controlar o processo através de uma janela de log que nos vai mostrando o número de contactos sincronizados e eventuais erros que surjam.

Apesar de estar ainda numa fase muito beta esta ferramenta cumpre já um objectivo por mim muito esperado e que era a sincronização dos contactos entre o Gmail e o Outlook.
Caso não consigam fazer essa sincronização verifiquem se estão a colocar a palavra chave correcta. Foi um dos bugs que descobri! Tinha a palavra chave errada e o programa não se queixava, apesar de não conseguir fazer a sincronização.
Para todos aqueles que esperaram e desesperaram eis uma luz ao fundo do túnel!
Licença: Freeware
Sistemas Operativos: Windows XP / Vista / 7
Download: gcontactsynch [377KB]
Homepage: gcontactsynch
Aleluia!!! It's a shame that Google itself doesn't promote integration with Office :(