"…mais ce serait peut-être l'une des plus grandes opportunités manquées de notre époque si le logiciel libre ne libérait rien d'autre que du code…"

Archive for the ‘ORM’ Category

Compte rendu de la conférence Ruby/Ruby On Rails du mercredi 19 décembre 2007 à Grenoble

Posted by patrick le janvier 7, 2008

Bonjour et bonne année 2008 (1) mais aussi 5768, 1428, 1386, 4405, etc. :)

C’est avec plaisir que j’ai assisté à la conférence sur Ruby et Ruby On Rails. Etant un fan du langage Python, j’apprécie à sa juste valeur le langage Ruby et son framework Web bien connu Ruby On Rails. Cela fait plaisir de voir que je ne suis pas le seul à apprécier ce genre d’environnement (avec Python il y a Django, Grok, Pylons) et qu’il est bien regrettable que les entreprises ne pensent qu’à l’artillerie lourde JEE même pour des applications petites ou moyennes.

La conférence s’est déroulée en 2 parties. D’abord une présentation de Ruby et ensuite une présentation de Ruby On Rails.

Ici, le support de la conférence: http://www.guilde.asso.fr/rencontres/20071219/Ruby_Rails_Introduction_PoR_2007_longue_v2.pdf
Ce que j’ai appris:

- le modèle objet de Ruby est fortement inspiré de Smalltalk

- Ruby applique le principe POLS ( principle of least surprise)

- les blocs sont employés partout dans Ruby

- il n’y a pas d’héritage multiple mais on peut utiliser des mixins (étend les compétences d’une classe en lui rajoutant une série de méthodes)

- les conventions de nommage sont importantes

- il y a un haut niveau de métaprogrammation

- Ruby est bien adapté pour implémenter des langages spécifiques (DSL)

- pour les grosses applications il faut utiliser n instances de mongrel derrière un serveur Apache faisant office de répartisseur de charge. (« One popular configuration is to run Apache 2.2 as a load balancer using mod_proxy_balancer in conjunction with several Mongrel instances, with each Mongrel instance running on a separate port. This is something that can be configured very easily using the mongrel_cluster management utility. Apache can divide the incoming requests among the available Mongrel processes, and, with careful configuration can even serve static content itself without having to delegate to Mongrel. »)

- Sun s’intéresse fortement à Ruby ce qui explique que de plus en plus de développeurs Java s’intéressent à Ruby. La version 6 de Netbeans intègre Ruby et Ruby On Rails (« Since version 6.0, Netbeans allow IDE development with Ruby and JRuby, as well as Rails for these two implementations of Ruby…It is also possible to create directly Ruby projects or Ruby on Rails projects, using the reference Ruby implementation, or using JRuby (the Java implementation of Ruby) . »)
Sites à voir:

- http://www.rubyfrance.org/ (« Site de l’association francophone des utilisateurs du langage de programmation Ruby« )

- http://www.railsfrance.org/ (« Rails est un framework, basé sur le langage Ruby, permettant le développement rapide d’applications web utilisants le modèle MVC (Modèle-Vue-Contrôleur). »)

- Laurent Julliardhttp://paris.onrails.info/conferenciers (« Laurent Julliard est un fervent utilisateur du langage Ruby depuis 2000. Traducteur de l’ouvrage « Agile Web development with Rails » pour Eyrolles, il a en outre participé a plusieurs projets Ruby dont l’environnement de développement FreeRIDE. Il s’est investi de longue date dans le mouvement Open Source en créant le premier groupe d’utilisateur Linux français en Janvier 1995 (La GUILDE). Après avoir occupé des postes de leader techniques et d’architecte logiciel dans les laboratoires de R&D de Hewlett-Packard et de Xerox en France et aux Etats-Unis, il est aujourd’hui Directeur Associé de Nuxos Group. »)

- http://www.journaldunet.com/developpeur/outils/interview/07/1210-paris-on-rails.shtml (« Quels sont les points forts du framework Ruby on Rails ? Après 10 ans de développement d’applications Web avec des logiques métier fortes, on s’est retrouvé avec une véritable cacophonie au niveau des frameworks, les composants partant un peu dans tous les sens. Face à cette problématique, Rails propose un cadre reposant sur le modèle MVC, Modèle Vue Contrôleur. L’idée était d’appliquer ce modèle de développement qui a fait ses preuves à l’univers de la programmation Web... Ecrit en Ruby, Rails a donc proposé de couvrir ces trois couches. D’où sa qualification de full-stack application framework. C’est d’ailleurs pour cette raison que David Heinemeier Hansson, le créateur du framework, a indiqué qu’il n’avait rien inventé de nouveau. Ruby on Rails agrège des bonnes pratiques en les intégrant à un outil de façon cohérente…

…Sun sponsorise la conférence Paris on Rails cette année. Comment cet acteur se situe-t-il vis-à-vis du projet ? Le buzz généré par Rails a entraîné l’apparition de clones, notamment PHP (CakePHP, Symphony) et Python (Django, TurboGears, Pylons). Des développeurs ont également travaillé au portage de Ruby sur la machine virtuelle Java. Il s’agit de Charles Oliver Nutter et Thomas Enebo. C’est le projet JRuby. Conscient des potentialités de Rails et des limites de ses propres outils de développement, Sun a décidé de les embaucher. C’est très intéressant, dans la mesure où avec JRuby il devient possible de reprendre des classes Java dans une application Ruby via Rails. Plusieurs grandes entreprises s’intéressent déjà à cette initiative, notamment des banques du Luxembourg. Sun a déjà étendu NetBeans en y ajoutant des greffons pour Ruby on Rails. On note une initiative équivalente chez Microsoft qui a pour but de porter Ruby sur l’infrastructure .Net et la CLR (IronRuby, voir Ironpython). Même démarche du côté d’Apple qui supporte Ruby on Rails dans le système Leopard lorsqu’on installe son kit de développement

…Quel est aujourd’hui le public de Paris on Rails ? Parmi les inscrits, on compte à la fois des start-up qui privilégient des environnements de développement rapide, mais également des grandes entreprises qui s’intéressent de plus en plus à Rails, notamment au travers de cellules de veille et de projets de prototypage. Beaucoup de sites Web reposent sur Rails. C’est le cas du site de vidéos Eyeka, des sites du Figaro Madame et de la partie shopping du Nouvel Obs. Au niveau des grandes entreprises, la banque RBC Dexia a récemment adopté Ruby on Rails. Cette société a réalisé le déploiement d’une vingtaine d’applications depuis le mois de septembre dernier. Un rythme de livraison jamais atteint au sein de cette banque. Il est clair que l’arrivée de JRuby (voir Jython) est très intéressant pour les structures d’une certaine taille. Il permet en effet d’adopter Rails tout en étant capable de reprendre l’existant Java, et de s’y intégrer. Le changement peut ainsi s’effectuer en douceur…Qu’en est-il des développeurs Rails en France ? Ils sont toujours très peu nombreux comparé aux pays voisins où la communauté est plus importante. De ce fait, le coût des profils de développeur Rails est très élevé chez nous. C’est clairement un facteur bloquant l’extension de Rails en France. Nous organisons Paris on Rails notamment dans l’objectif de sensibiliser les développeurs à la technologie Rails et à ses potentialités. Historiquement, les développeurs Web français se sont beaucoup focalisés sur PHP pour les applications Web. Nous voulons les pousser à sortir des sentiers battus« )

- http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 (« The language was created by Yukihiro « Matz » Matsumoto, who started working on Ruby on February 24, 1993, and released it to the public in 1995. « Ruby » was named as a gemstone because of a joke within Matsumoto’s circle of friends alluding to Perl’s name. As of March 2007, the latest stable version is 1.8.6. Ruby 1.9 (with some major changes) is also in development. Poor performance of the current Ruby implementation in comparison to other more entrenched programming languages has led to the development of several virtual machines for Ruby. These include JRuby, a port of Ruby to the Java platform, IronRuby, an implementation for the .NET Framework produced by Microsoft, and Rubinius, an interpreter modeled after self-hosting Smalltalk virtual machines. The main developers have thrown their weight behind the virtual machine provided by the YARV project, which was merged into the Ruby source tree on 31 December 2006, and will be released as Ruby 2.0. »)

Dernières nouvelles:

- http://www.rubyfrance.org/articles/2007/12/25/sortie-de-ruby-1-9-0/ (« Ruby 1.9.0 est disponible ! Joyeux Noël ! Ruby 1.9.0 est la première version publique de Ruby comportant une machine virtuelle, ainsi que le nouveau moteur d’expression rationnelles Oniguruma, la gestion de m17n (multilingualization, notamment une meilleure gestion d’Unicode), les fibres, une présence accrue des énumérateurs (enumerator), des nouvelles constructions syntaxiques (->() {} etc.) RubyGems 1.0.1 (sorti la semaine dernière) et Rake 0.8.0 sont désormais intégrés à Ruby, FasterCSV remplace CSV. Matz n’a pas voulu nommer cette version 1.9.1 comme initialement prévue, car certains tests ne passaient pas, cette version n’était pas assez stable à son goût. En passant, notons que Perl, langage qui a influencé le design de Ruby, fête ses 20 ans, avec la mise à disposition de Perl 5.10″)

- http://www.programmez.com/actualites.php?id_actu=2608 (« Depuis le 6 décembre 2007, la version 2.0 du désormais célèbre Ruby on Rails, est disponible en version finale ! Attendue depuis plusieurs mois, cette version consolide les fonctions et les acquis des versions 1.x. Un important travail a été réalisé sur les ressources, notamment dans tout ce qui est RESTful. Dans le multivue, Rails 2 sépare le format du template du moteur de rendu. Ainsi, on peut donner à son application une interface iPhone… Des améliorations concernent aussi le support de HTML, la sécurité (par exemple : gérer une attaque XSS), la gestion des exceptions mise à niveau, l’apparition d’un nouveau stockage des sessions par un mécanisme de cookies (la session n’est plus gérée dans une base). Un gros travail a été réalisé sur Active Record pour l’alléger et l’optimiser, ainsi la désérialisation XML est supportée. Rails 2 réintroduit le debugger (installable via un simple gem, le format d’installation de Rails). Pour toute migration, il faut d’abord installer la version 1.2.6 avant de passer à la 2.0. Quant à la sortie de la 2.0 de Ruby, rien n’est encore fixé. Une première version devrait apparaître vers la mi-2008. »)

- http://linuxfr.org/2007/12/11/23448.html (« Ruby on Rails, le célèbre framework basé sur le langage Ruby, permettant le développement rapide d’applications web selon le modèle MVC (Modèle, Vue, Contrôleur) sort en version 2.0. Le développement qui a duré une année a permis l’ajout de nombreuses fonctionnalités, la résolution de beaucoup de bugs, une orientation tournée vers le REST, et pas mal d’allégements au niveau du core (externalisation de fonctionnalités en greffons)…

Ressources et webservices Rails a tranché dans le débat REST – SOAP au profit du REST. Le module ActionWebservice a été sorti du core et placé en greffon pour ceux qui veulent continuer à utiliser du SOAP. ActiveResource est le nouveau module qui est similaire à ActiveRecord mais avec une approche ressource. Au passage, l’url des ressources a été modifié, l’utilisation du point virgule ( ; ) pour séparer l’action de la ressource a été remplacé par un slash ( / ), à cause de navigateurs et bibliothèques HTTP qui ne le supportaient pas en tant que séparateur de requêtes...Multi-vues Rails 2.0 sépare le format du template (html, xml, atom, rss, …) du moteur de rendu. Le template show.rhtml devient donc show.html.erb (ERB étant le moteur de rendu par défaut).
D’autres moteurs de rendus existent aussi, builder utilisé pour générer du atom+xml, et HAML principalement utilisé aujourd’hui pour générer des templates adapté à l’iPhone.
..Session basée sur les cookies
Les sessions ne sont plus stockées par défaut sur le système de fichiers du serveur web mais au niveau du client sous une forme qui ne peut pas être forgée. En revanche, le contenu sera visible, donc ce mécanisme de stockage de sessions n’est pas adapté si vous avez besoin d’y stocker une information que ne doit pas voir l’utilisateur.
« )

(1) http://fr.wikipedia.org/wiki/2008 (« L’année 2008 du calendrier grégorien correspondra aux années suivantes :

Posted in 2007, active record, machines virtuelles, ORM, REST, ruby, Web Frameworks | Tagué: , , , , | Leave a Comment »

Les nouveautés dans ASP.NET Extensions: ASP.NET MVC et ASP.NET AJAX

Posted by patrick le décembre 15, 2007

Comme le précise ce billet http://dosimple.ch/articles/MVC-ASP.NET/ écrit le 2 mai 2006 et celui-ci écrit le 13 mars 2007, le framework ASP.NET n’incite pas particulièrement à la séparation stricte de type Modèle, Vue, Contrôleur. On a vu que Monorail, projet open source, implémente le modèle MVC. Microsoft emboite le pas avec un grand retard en introduisant ASP.NET MVC: voir le billet suivant: http://weblogs.asp.net/scottgu/archive/2007/10/14/asp-net-mvc-framework.aspx (« One of the things that many people have asked for over the years with ASP.NET is built-in support for developing web applications using a model-view-controller (MVC) based architecture. Last weekend at the Alt.NET conference in Austin I gave the first public demonstration of a new ASP.NET MVC framework that my team has been working on. You can watch a video of my presentation about it on Scott Hanselman’s blog here.

What is a Model View Controller (MVC) Framework?

MVC is a framework methodology that divides an application’s implementation into three component roles: models, views, and controllers.

  • « Models » in a MVC based application are the components of the application that are responsible for maintaining state. Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).

  • « Views » in a MVC based application are the components responsible for displaying the application’s user interface. Typically this UI is created off of the model data (for example: we might create an Product « Edit » view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).

  • « Controllers » in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information – it is the controller that handles and responds to user input and interaction.

One of the benefits of using a MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application. Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated.

The MVC pattern can also help enable red/green test driven development (TDD) – where you implement automated unit tests, which define and verify the requirements of new code, first before you actually write the code itself.

A few quick details about the ASP.NET MVC Framework

I’ll be doing some in-depth tutorial posts about the new ASP.NET MVC framework in a few weeks once the bits are available for download (in the meantime the best way to learn more is to watch the video of my Alt.net presentation).

A few quick details to share in the meantime about the ASP.NET MVC framework:

  • It enables clean separation of concerns, testability, and TDD by default. All core contracts within the MVC framework are interface based and easily mockable (it includes interface based IHttpRequest/IHttpResponse intrinsics). You can unit test the application without having to run the Controllers within an ASP.NET process (making unit testing fast). You can use any unit testing framework you want to-do this testing (including NUnit, MBUnit, MS Test, etc).

  • It is highly extensible and pluggable. Everything in the MVC framework is designed so that it can be easily replaced/customized (for example: you can optionally plug-in your own view engine, routing policy, parameter serialization, etc). It also supports using existing dependency injection and IOC container models (Windsor, Spring.Net, NHibernate, etc).

  • It includes a very powerful URL mapping component that enables you to build applications with clean URLs. URLs do not need to have extensions within them, and are designed to easily support SEO and REST-friendly naming patterns. For example, I could easily map the /products/edit/4 URL to the « Edit » action of the ProductsController class in my project above, or map the /Blogs/scottgu/10-10-2007/SomeTopic/ URL to a « DisplayPost » action of a BlogEngineController class.

  • The MVC framework supports using the existing ASP.NET .ASPX, .ASCX, and .Master markup files as « view templates » (meaning you can easily use existing ASP.NET features like nested master pages, <%= %> snippets, declarative server controls, templates, data-binding, localization, etc). It does not, however, use the existing post-back model for interactions back to the server. Instead, you’ll route all end-user interactions to a Controller class instead – which helps ensure clean separation of concerns and testability (it also means no viewstate or page lifecycle with MVC based views).

  • The ASP.NET MVC framework fully supports existing ASP.NET features like forms/windows authentication, URL authorization, membership/roles, output and data caching, session/profile state management, health monitoring, configuration system, the provider architecture, etc. »)

A voir:

  • http://pvergain.wordpress.com/2007/03/13/critique-de-larchitecture-aspnet/ (« Le problème avec ASP. Net est qu’il n’y a qu’un objet qui traite les demandes http, c’est l’objet PAGE. C’est lui qui a le contrôle de tout, et donc il mélange le code dit de «contrôle», et le code qui pilote la «visualisation» des éléments en html. Et bien souvent, on mélange aussi le code qui pilote le «Modèle» c’est à dire l’obtention des données directement depuis la base de données avec Ado.Net (c’est ce qu’on obtient lorsqu’on fait du WYSIWYG dans Visual Studio en choisissant les Sql Data Source et les glissant-déposant sur l’ihm). Cet anti-modèle (ou anti–pattern) a été souvent pointé du doigt par les architectes et développeurs, car en plus de faire produire du code spaghetti (bien que orienté objet), il rend impossible les tests systématisés (automatisés).« )
  • http://dosimple.ch/articles/MVC-ASP.NET/ (« Dans le framework ASP.NET la vue est un fichier HTML agrémenté de balises ASP. Le contrôleur et le modèle sont en général mélangés dans un objet qui dérive de la classe System.Web.UI.Page. »)
  • http://www.castleproject.org/monorail/index.html (« MonoRail is a MVC Web Framework inspired by Action Pack. MonoRail differs from the standard WebForms way of development as it enforces separation of concerns; controllers just handle application flow, models represent the data, and the view is just concerned about presentation logic. Consequently, you write less code and end up with a more maintainable application. Although the project name is MonoRail, we do not have any affiliation with the Mono project. MonoRail runs on Microsoft .Net 1.1, 2.0 and Mono.« )
  • http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework (« ASP.NET MVC Framework is a Model-view-controller framework which Microsoft is adding to ASP.NET. It allows an application to be built as a composition of three roles: Model, View and Controller. A Model represents the state of a particular aspect in the application. Frequently, a model maps to a database table, with the entries in the table representing the state of the table. A Controller handles interactions and updates the model to reflect a change in state of the application. A View ASP.NET MVC Framework couples the models, views and controllers using interface-based contracts, thereby allowing each component to be easily tested independently. The view engine in the MVC framework uses regular .aspx pages to design the layout of the UI pages onto which the data is composed; however any interactions are routed to the controllers rather than using the postback mechanism. Views can be mapped to REST-friendly URLs. ASP.NET MVC Framework has been launched as a Community Technology Preview on December 10, 2007 extracts necessary information from a model and renders a UI to display that.. »)
  • http://www.hanselman.com/blog/ScottGuMVCPresentationAndScottHaScreencastFromALTNETConference.aspx ( » I attended the ALT.NET Conference last weekend in Austin, TX. I personally find the name « Alt » as in « Alternative » too polarizing and prefer terms like « Pragmatic.NET » or « Agile.NET. » At the conference I suggested, partially in jest, that we call it « NIH.NET » as in « Not Invented Here.NET. » ;) Ultimately this is a group that believes in:
    • Continuous Learning
    • Being Open to Open Source Solutions
    • Challenging the Status Quo
    • Good Software Practices
    • DRY (Don’t Repeat Yourself)
    • Common Sense when possible.

    ScottGu gave an hour long presentation on the upcoming MVC Framework and I took some guerilla video. ScottGu’s presentation is here in Silverlight and it’s about 60 minutes long. Considering it’s so long, the video squished nicely. This was the first time the MVC Framework was shown publicly. Note that this was a Prototype, not the Production code and both ScottGu and I make that point a number of times to drive home that it’s early. Some of the code was written on a plane, just to give you an idea. After The Gu did his piece on the MVC Framework, I showed some prototype hacking that I’d done over the previous few days along with some work Phil Haack did. My presentation is here as Silverlight and it’s about 30 minutes long. I showed the Model View Controller with Controllers in IronPython and an IronPython view using a WebFormViewEngine. Then I talked about the possibilities of alternate ViewEngines and showed Phil Haack’s prototype RubyViewEngine. »)

  • http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx ( » ASP.NET MVC Framework (Part 1) I’m going to use a simple e-commerce store application to help illustrate how the ASP.NET MVC Framework works. For today’s post I’ll be implementing a product listing/browsing scenario in it. Specifically, we are going to build a store-front that enables end-users to browse a list of product categories when they visit the /Products/Categories URL on the site>>Since it adds a testing project, does this require Team System? No – the good news is that Test Projects with VS 2008 are now supported with the VS 2008 Professional edition – and no longer require team system. You will also be able to use the VS Express and Standard edition products as well, and then use NUnit, MBUnit or some other testing framework with them (we’ll ship project templates for these as well…>> 2. Is it also possible to have this URL mapped: /Products/Beverages/3 instead of /Products/Beverages?page=3 or does it _need_ the parameter name? Yes – this is totally supported. Just set a route rule for /Products/Beverages with the format /Products/<Category>/<Page> – they’ll then get passed in as arguments to the action method:public List(string category, int? page) {}>>Also, some ideas and general remarks: 1. I’d love to see more helper methods for use in the views, I like how Ruby on Rails has many shortcuts for creating forms and formfields etc. Yes – we’ll have a rich library of helper methods for the views. They’ll include helpers to create all the standard forms, formfields and more.

>>2. Migrations! Not a part of MVC but from my experience with Ruby on Rails I would love to see support for this somewhere, anywhere! It would fit perfectly with the more agile way of developing that is possible with ASP.NET MVC. Rob Conery is building .NET Migrations support as part of the SubSonic project, and recently joined Microsoft. You’ll be able to use this with ASP.NET MVC

>>I’m also very keen to get my hands on the CTP. Scott, you mention, using Inversion of Control containers with the MVC framework. I’d be very interested in seeing a blog post on this subject. Also, will there be a sample application (with tests and IoC) available alonside the CTP? We have a IControllerFactory extensiblity point that owns creating Controller instances. You can use this with a IOC container to customize any Controller instance prior to it being called by the MVC framework. We’ll be posting samples of how to use this with ObjectBuilder and Windsor with the first CTP I believe

>> Very cool! One thing I’d like to see guidance on is developing MVC apps with multiple UIs. You say here that it’s best to put your models and controllers in the web app, but say we want a Winforms, WPF, Silverlight, and Web UI all doing similar things. Or a Mobile Web UI and Desktop Web UI… Would these still each need their own Models and Controllers, or does it make sense to have one library that they all share? If so, how is that supported? I’m still new to MVC, so if I’m missing something conceptually here, tell me! That is a good question, and one we’ll need to provide more guidance on in the future. In general it is often hard to share the same controller across both client and web UI, since the way you do data access and the stateful/stateless boundaries end up being very different. It is possible – but some guidance here would ceretainly be useful. My team should hopefully be coming out with this in the future

>>I really appreciate this material. Do you support the MVC pattern over the MVP pattern? Or are there just better scenarios for using each? The above approach I showed uses a MVC based pattern – where the Controller and the View tend to be more separate and more loosly coupled. In a MVP pattern you typically drive the UI via interfaces. This works well with a controls model, and makes a lot of sense with both WinForms and WebForms where you are using a postback model. Both MVC and MVP are perfectly fine approaches to use. We are coming out with the MVC approach for ASP.NET partly because we’ve seen more demand for it recently for web scenarios…

>> When can we expect a similar chapter with SubSonic as the DAL and scaffolding provider? (see http://oakleafblog.blogspot.com/2007/11subsonic-will-be-toolset-for-microsofts.html I’ll be covering scaffolding in a future blog post. LINQ to SQL scaffolding is built-in with ASP.NET MVC and doesn’t require SubSonic. SubSonic will also obviously be adding new ASP.NET MVC features as well.

>> My applications in .NET works with « 3 layers » pattern (business logic and data access in your own dll). How can i use this wonderfull MVC with my Models (data access) and Controllers (B.Logic)?? Because if i’m not reuse this, i’ve repeat code in every layer; then this MVC is not DRY (don’t repeat yourself) and the community don’t accept. There is no need to put your business and data logic in the same assembly as your controllers. You can split them up across multiple class library projects if you prefer

>> Does this mean that with MVC, we no longer use LinqDatasource in the View section? While the LinqDataSource control will technically work in MVC Views, if you are using a MVC model you wouldn’t want to place it there. Instead you want to perform all of your data and application logic in the Controller layer – and then pass the needed data to the view.

>> Perhaps I missed it somehow, but can you explain on which version of asp.net will this ctp run? The MVC framework builds on top of .NET 3.5

>> Scott, this is amazing timing! The URL mapping features inherit in an MVC application are PERFECT for the upgrade to ASP.NET 3.5 I’m making to my spelldamage.com site. Hosting question, will hosts simply need to support the ASP.NET 3.5 framework to allow us to run ASP.NET MVC applications? Your hoster will need to support .NET 3.5 for the MVC support.

>> Is’nt the MVC framework, in fact the Controller, implementation of the Front Controller pattern? Yes – the ASP.NET MVC framework uses a front-controller pattern. »)

  • http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx (« Last month I blogged the first in a series of posts I’m going to write that cover the new ASP.NET MVC Framework we are working on. The first post in this series built a simple e-commerce product listing/browsing scenario. It covered the high-level concepts behind MVC, and demonstrated how to create a new ASP.NET MVC project from scratch to implement and test this e-commerce product listing functionality. In today’s blog post I’m going to drill deeper into the routing architecture of the ASP.NET MVC Framework, and discuss some of the cool ways you can use it for more advanced scenarios in your application… What does the ASP.NET MVC URL Routing System do? The ASP.NET MVC framework includes a flexible URL routing system that enables you to define URL mapping rules within your applications. The routing system has two main purposes:
    • Map incoming URLs to the application and route them so that the right Controller and Action method executes to process them
    • Construct outgoing URLs that can be used to call back to Controllers/Actions (for example: form posts, <a href= » »> links, and AJAX calls)

Having the ability to use URL mapping rules to handle both incoming and outgoing URL scenarios adds a lot of flexibility to application code. It means that if we want to later change the URL structure of our application (for example: rename /Products to /Catalog), we could do so by modifying one set of mapping rules at the application level – and not require changing any code within our Controllers or View templates.

>> BTW, can you explain in short about the Active Record Type support in our MVC.

.NET 3.5 has LINQ to SQL built-in – which is a great ORM. LINQ to Entities will also be built-into .NET 3.5 in the future (it also ships with the MVC setup). The MVC framework doesn’t require LINQ to SQL or LINQ to Entities as the data model – it also works with NHibernate, LLBLGen, SubSonic, DataSets, DataReaders, and/or any other data model with .NET. We will, though, provide out of the box scaffolding support for LINQ to SQL and LINQ to Entities that delivers nice integration with the MVC support.

>> Question : What is this MockHttpContext in the UnitTest class? I mean, i can guess what it is .. but is it new in .NET 3.5 or the MVC framework? The MockHttpContext is an example mock object. It isn’t currently built-in with the MVC framework (with the first preview you’d need to create this yourself). I’m hoping that before the MVC framework ships, though, that there are a built-in set of mock objects and test helpers that you can use out of the box (without having to mock them yourself). Note that all core contracts and types with the MVC framework are mockable (non-sealed and interfaces). So you can also use any existing Mock framework to test it (RhinoMocks, TypeMock, etc).

>> 1) Is it possible to use routes with a file extension if I don’t want to enable wildcard script mappings? For example, /Products/List/Beverages.rails or /Products/Detail/34.rails ? Yes – this is fully supported. We recommend changing your route rule to /[controller].mvc/[action]/[id]. When you install the ASP.NET MVC Framework we automatically register this .mvc extension – although you are free to use any other one you want.

>> Hypothetically, do you think it would be possible to customise the route creation process so that route data could be gathered from attributes on actions? We don’t currently support this built-in, but hypothetically you could load all the controllers at app-startup and use reflection on them to calculate the route rules. This would enable the scenario you are after.

>> Is it possible to use IronRuby as the coding language to target the MVC framework?? Yes – we’ll support both IronRuby and IronPython with the ASP.NET MVC Framework.

>> I am liking this more and more. I can see how the routing configuration code in global.asax.cs could become quite large. In my application, I can see dozens, maybe hundreds of unique routing rules. Is there any way this configuration can be put in a file somewhere? That file would be read on Application start. Seems like that would make deployment of routing changes easier, too. We don’t currently have a pre-built file format for reading in mapping rules. But it should be relatively easy to build (you could even use LINQ to XML to read in and construct the rules).

>> Just out of curiosity where in the HttpApplication cycle are the routing rules evaluated and are they exposed in any way to the rest of the HttpApplication cycle? My current security system grants permissions at what would become the controller-action level so if the route determination is made early enough I’d really like to drive my authorization off of it.
The routing rules are resolved after the OnPostMapRequestRequestHandler event. This means that it will happen *after* your authorization rules evaluate. The good news is that this means you should be able to re-use your existing security system as-is.

>> Will there be any way to use an XML document to create the routing rules outside of the Global.asax code? Yep – this scenario will be supported.

>> I noticed that in Django, you have to repeat yourself kind of often when you have a deep nested hierarchy of pages. Your search & search-results pages seem to be continuing that trend. I’m sure I could come up with some hierarchical data structure which can be serialized into Route objects, but is the ASP.NET team planning anything along those lines that would come stock?

With our first preview the Route type is not extensible (you can’t subclass it) – which means you sometimes need to register multiple routes for a series of things. For the next preview we are looking at enabling Route to be sub-classed – in which case you could easily encapsulate multiple URL mappings into a single registration.

>> Have you thought about being able to define a regular expression for url matching and using backreferences or named captures as the tokenized url? I think this would allow for much more flexibility while keeping the list of routing rules down to a minimum.

Yes – this is something we are looking at. The challange with regular expressions is that only a subset of people really understand them (and importantly – understand how to optimize them). But I agree that having this as an option would be super flexible.

>> I must say that i am still worried about having to leave all the knowledge that we ave until now with webforms and start a new technology and still think that we would need some kind of a bridge to close the gap between today solution of webforms and tomorrow solution of MVC. Although the way you structure application flow will be different, I think you’ll be pleasantly surprised by the amount of knowledge overlap that exists. Authentication, Authorization, Caching, Configuration, Compilation, Session State, Profile Management, Health Monitoring, Administration, Deployment, and many, many other things are exactly the same. MVC views are also .aspx pages (that use .ascx user controls and .master files). So the concept re-use is quite heavy there as well. »)

  • http://weblogs.asp.net/scottgu/archive/2007/12/06/asp-net-mvc-framework-part-3-passing-viewdata-from-controllers-to-views.aspx (« The last few weeks I have been working on a series of blog posts that cover the new ASP.NET MVC Framework we are working on. The ASP.NET MVC Framework is an optional approach you can use to structure your ASP.NET web applications to have a clear separation of concerns, and make it easier to unit test your code and support a TDD workflow. The first post in this series built a simple e-commerce product listing/browsing site. It covered the high-level concepts behind MVC, and demonstrated how to create a new ASP.NET MVC project from scratch to implement and test this e-commerce product listing functionality. The second post in this series drilled deep into the URL routing architecture of the ASP.NET MVC framework, and discussed both how it worked as well as how you can handle more advanced URL routing scenarios with it. In today’s blog post I’m going to discuss how Controllers interact with Views, and specifically cover ways you can pass data from a Controller to a View in order to render a response back to a client. In Part 1 of this series, we created an e-commerce site that implemented basic product listing/browsing support. We implemented this site using the ASP.NET MVC Framework, which led us to naturally structure the code into distinct controller, model and view components. When a browser sends a HTTP request to our web site, the ASP.NET MVC Framework will use its URL routing engine to map the incoming request to an action method on a controller class to process it. Controllers in a MVC based application are responsible for processing incoming requests, handling user input and interactions, and executing application logic based on them (retrieving and updating model data stored in a database, etc). When it comes time to render an HTML response back to the client, controllers typically work with « view » components – which are implemented as separate classes/templates from the controllers, and are intended to be focused entirely on encapsulating presentation logic. Views should not contain any application logic or database retrieval code, instead all application/data logic should only be handled by the controller class. The motivation behind this partitioning is to help enforce a clear separation of your application/data logic from your UI generation code. This makes it easier to unit test your application/data logic in isolation from your UI rendering logic.Views should only render their output using the view-specific data passed to it by the Controller class. In the ASP.NET MVC Framework we call this view-specific data « ViewData ». The rest of this blog post is going to cover some of the different approaches you can use to pass this « ViewData » from the Controller to the View to render.

>> One question Scott: Let say i’m jumpng on MS MVC bandwagon, do i have to abandon asp.net Page Life cycle godddies, should i set up my mind to different approach. When you use the ASP.NET MVC approach you’ll want to have all post in your site go to your Controller. This helps ensure that the application can be easily tested and preserves the separation of concerns. This is different from using ASP.NET server controls which postback to themselves (which is very powerful too – but means that it can sometimes be slightly harder to test). What doesn’t change is that all of other ASP.NET pieces (forms authentication, role management, session state, caching, profiles, configuration, compilation, httprequest/response, health monitoring, etc, etc) works with both web forms based pages and MVC based pages. MVC UI are also built with .aspx, .master, and .ascx files – so there is a high level of skill re-use there as well.

>> Some asp.net controls require <form runat=server>. If we use a asp:dropdownlist for example, we have to place in the asp:form. And this means viewstate comes back! Is there any way to get rid of hidden form fields? Or you suggest that we do must use classic HTML controls ? I’ll cover this more in my next blog in this series. We have helpers that can automate generating things like dropdownlists, etc. Think of them as controls for MVC. These don’t use viewstate and give you a little more control over the output of your HTML.

>> It would be nice if you can just compare a bit our MVC with ROR. Within ROR, we can create tables, Columns and Rows with Ruby, without using a single line of SQL, and all its done through ActiveRecord. In short all CRUD advantages.

>> SubSonic is almost in this line. Can you explain more in this line or how SubSonic can be used to take ActiveRecord Type advantages.

RoR is made up of several components.

« Action Controller » is the name of the MVC framework that Rails uses. That is the closest analogy to the ASP.NET MVC Framework – and at a high-level the ASP.NET MVC framework uses many of the same core concepts (URLs map to controller actions). The ASP.NET MVC Framework has a few additional features (like the ability to map incoming parameters directly to action method parameters). It is also more explicit about calling RenderView within the request.

« Active View » is the name of the View engine that Rails uses. This is analagous to the .aspx/.master/.ascx infrastructure ASP.NET has. Our view engine is IMO a little richer, and supports several additional features (declarative controls/components, templating, multiple regions for nested master pages, WYSIWYG designer, strongly typed ViewData access, pluggable storage provider, declarative localization, etc).

« Active Record » is the name of the ORM (object relational mapper) that RoR uses. This is analagous to an ORM in the .NET world – whether it is LINQ to SQL, LINQ to Entities, LLBLGen, SubSonic, NHibernate, ActiveRecord (the .NET version), etc. All of these ORMs have ways to map rows and columns in a database to objects that a developer then manipulates and works against (and can save changes back). The LINQ to SQL ORM is built-in to .NET 3.5 today, and LINQ to Entities will be built-in with .NET 3.5 SP1.

I think from your follow-up question above you are referring specifically to the « migrations » feature in RoR – which allows you to define table schemas using code, and version the schemas forward/backward. There isn’t a built-in version of this in the core .NET Framework today – although the SubSonic project has recently released a version that allows you to-do this using .NET. You can find out more about it here: www.subsonicproject.com.

>> Superb, …but I still longing for the IOC integration (Spring.NET, Windsor, StructureMap)…maybe in the next post ? I am planning on posting about IOC and dependency injection in the future (the ASP.NET MVC framework fully supports it and can be used with Spring.NET, Windsor, StructureMap, etc). I have a few other more basic MVC tutorials I need to get out of the way first – but testing and dependency injection are on the list for the future.

>> Nice series, eagerly waiting to see AJAX approach in the new ASP.NET MVC Framework, so when shall we expext that.
We will have ASP.NET AJAX support with the ASP.NET MVC Framework. I’ll talk more about this in a future tutorial series post.

>> This is coming together nicely. I was just hoping you might explain why there are 3 different ways to pass the ViewData? Does each method offer something that the others don’t? If not, surely it would be best to choose one method and force all developers to follow the same practice? Conceptually there are two ways to pass viewdata – either as a dictionary, or as a strongly typed object. In general I recommend using the strongly typed dictionary approach – since this gives you better compilation checking, intellisense, and refactoring support. There are, however, some times when having a more latebound dictionary approach ends up being flexible for more dynamic scenarios« )

  • http://blog.wekeroad.com/2007/10/26/microsoft-subsonic-and-me/ (« Rather than try and come up with some lame metaphors and trite pop-culture references, I’ve decided to use some advice from English 101 Professor:

    “Whatever the hell you’re trying to say, just say it”

    So I will: I’m going to work for Microsoft. I just signed the offer letter. I’ll be working with the ASP.NET guys on the new MVC platform as well as some other groovy things like Silverlight. I get to work “across the hall” from one of my very good friends – Phil Haack. I think it’s worth pointing out that SubSonic hasn’t been “bought”. Some might smell a conspiracy here, but I’ll leave that to the X-Files and Cap’n Crunch crowd to drum up all the evil reasons why the mothership has “beamed me up”. SubSonic will remain under the same MPL 1.1 license it always has, and will remain as completely Open Source as it always has – nothing will change at all. I’m just getting paid, essentially, to work on it :)...This is crucial to me. I decided to be direct with him and make sure we both understood these important points:

    “I want to be sure I have complete creative control over SubSonic, and that you don’t censor my blog… is that cool?”

    Shawn’s response is why I took the job:

    “Well Duh…” (he added some more things that were a bit more eloquent than “duh” – but I don’t think I was listening).

    I can make jokes about the UAC on my blog? And make up fictional Matrix converstations with ScottGu? Sign me up! I start on November 12th, right after DevConnections in Vegas (come on by if you’re out that way at the DNN Open Force« )

  • http://www.subsonicproject.com/ (« A Super High-fidelity Batman Utility Belt. SubSonic works up your DAL for you, throws in some much-needed utility functions, and generally speeds along your dev cycle. Why SubSonic ? Because you need to spend more time with your friends, family, dog, bird, cat… whatever. You work too much. Coding doesn’t need to be complicated and time-consuming. »)
  • http://en.wikipedia.org/wiki/Test-driven_development (« Test-Driven Development (TDD) is a software development technique consisting of short iterations where new test cases covering the desired improvement or new functionality are written first, then the production code necessary to pass the tests is implemented, and finally the software is refactored to accommodate changes. The availability of tests before actual development ensures rapid feedback after any change. Practitioners emphasize that test-driven development is a method of designing software, not merely a method of testing. Test-Driven Development began to receive publicity in the early twenty-first century as an aspect of Extreme Programming, but more recently is creating more general interest in its own right. Along with other techniques, the concept can also be applied to the improvement and removal of software defects from legacy code that was not developed in this way . »)
  • ss
  • http://weblogs.asp.net/scottgu/archive/2007/12/09/asp-net-mvc-framework-part-4-handling-form-edit-and-post-scenarios.aspx
  • (« ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios   The last few weeks I have been working on a series of blog posts that cover the new ASP.NET MVC Framework we are working on.  The ASP.NET MVC Framework is an optional approach you can use to structure your ASP.NET web applications to have a clear separation of concerns, and make it easier to unit test your code and support a TDD workflow. The first post in this series built a simple e-commerce product listing/browsing site.  It covered the high-level concepts behind MVC, and demonstrated how to create a new ASP.NET MVC project from scratch to implement and test this e-commerce product listing functionality.  The second post drilled deep into the URL routing architecture of the ASP.NET MVC framework, and discussed both how it worked as well asthird post discussed how Controllers interact with Views, and specifically covered ways you can pass view data from a Controller to a View in order to render a response back to a client.  In today’s blog post I’m going to discuss approaches you can use to handle form input and post scenarios using the MVC framework, as well as talk about some of the HTML Helper extension methods you can use with it to make data editing scenarios easierClick here to download the source code for the completed application we are going to build below to explain these concepts… Our Data Model. We are going to use the SQL Server Northwind Sample Database to store our data.  We’ll then use the LINQ to SQL object relational mapper (ORM) built-into .NET 3.5 to model the Product, Category, and Supplier objects that represent rows in our database tables. We’ll begin by right-clicking on our /Models sub-folder in our ASP.NET MVC project, and select « Add New Item » -> « LINQ to SQL Classes » to bring up the LINQ to SQL ORM designer and model our data objects…To learn more about LINQ and LINQ to SQL, please check out my LINQ to SQL series here The HtmlHelper object (as well as the AjaxHelper object – which we’ll talk about in a later tutorial) have been specifically designed to be easily extended using « Extension Methods » – which is a new language feature of VB and C# in the VS 2008 release.  What this means is that anyone can create their own custom helper methods for these how you can handle more advanced URL routing scenarios with it.  The objects and share them for you to use. We’ll have dozens of built-in HTML and AJAX helper methods in future previews of the ASP.NET MVC Framework.  In the first preview release only the « ActionLink » method is built-into System.Web.Extensions (the assembly where the core ASP.NET MVC framework is currently implemented).  We do, though, also have a separate « MVCToolkit » download that you can add to your project to obtain dozens more helper methods that you can use with the first preview release.
  • >> This is nice. But do you handle subcomponents? subviews? Is view reuse possible inside other view? This is very important for even for modest sized applications? How would you handle posts correcly inside of subviews ;) ?The first public MVC preview doesn’t have the concept of SubControllers yet (where you can attach them for regions of a larger view).  That is something we have planned for to tackle soon though.

    >> However, liviu raises good questions about Sub-Controllers, Composite Views and AJAX scenarios. How Will the MVC framework address the complex wiring of different parts of a page to different controllers for async updates?? My brain hurts thinking about it, yet I have implement these portal pages all the time cos our customers demand it. The first ASP.NET MVC Preview allows you to call RenderView (for example: RenderView(« Edit »)) and have it apply to either a .aspx viewpage or a .ascx viewusercontrol.  This ends up being really useful for scenarios where you are doing AJAX callbacks and want to refresh a portion of a page.  These callbacks could either be to the same Controller that rendered the origional page, or to another Controller in the project. We don’t have all the AJAX helper methods yet for this – but you could roll them yourself today.  We’ll obviously be releasing an update that does include them in the future.

  • >> Can you provide an example of how we might use a server side control to generate the drop down list or a textbox (a la WebForms) along with the pro’s and con’s of each approach? Personally, I do not like the old ASP <%= … %> syntax; but if there is a good reason to use it then I am willing to change that opinion. The main reason I showed the <% %> syntax in this post was that we don’t have the server-side MVC control equivalents available yet for this dropdown and text scenario.  That is on our roadmap to-do though – at which point you don’t need to necessarily use the <% %> syntax. In general what we’ve found is that some developers hate the <% %> syntax, while others prefer it (and feel that controls get in the way).  We want to make both sets of developers happy, and will have options for both. :-)
  • >> Great work on the MVC model, it is a clean and intuitive model that appears to scale well. My only recommendation is that your actions (verbs) appear after the ids (nouns), e.g. [Controller]/[Id]/[Action]/  That would keep the architecture noun focused, opposed to verb focused. With this approach you can easily build an administrative interface on a public read-only site by adding verbs such as /edit/ or /delete/ at the end of your URL. A simple security rule can be added to the Controller that says ignore all Verbs after a noun, such as category or product, if user is not part of an administrative group. Thanks for the suggestion Josh.  You can do this today by creating your own custom route registration.  In the next preview I believe Route will be extensible so that you could also create a single resource route that supports these semantics.>> I was wondering if we could get an idea of the official « roadmap » for asp.net mvc?  Specifically, I’d like to know what features the team plans to release on what dates … ultimately, when this thing will RTM.  As I’ll be evaluating mvc and monorail for an upcoming app, this kind of information would really be helpful in determining which direction to go. We don’t have a formally published roadmap just yet – we will hopefully publish one early next year though.« )
  • http://en.wikipedia.org/wiki/ASP.NET_AJAX (« ASP.NET AJAX, formerly code-named Atlas, is a set of extensions to ASP.NET developed by Microsoft for implementing Ajax functionality. Including both client-side and server-side components, ASP.NET AJAX allows the developer to create web applications in ASP.NET 2.0 (and to a limited extent in other environments) which can update data on the web page without a complete reload of the page. The key technology which enables this functionality is the XMLHttpRequest object, along with Javascript and DHTML. ASP.NET AJAX was released as a standalone extension to ASP.NET in January 2007 after a lengthy period of beta-testing. It was subsequently included with version 3.5 of the .NET Framework, which was released alongside Visual Studio 2008 in November 2007.« )

Posted in 2007, Acces aux données, active record, AJAX, Architecture logicielle, ASP.NET, Développement logiciel, design pattern, DotNet, IDE-GUI, Ironpython, javascript, open source, ORM, RIA, ruby, tests, Web Frameworks | Tagué: , , , , , , , | Leave a Comment »

Un nouveau framework web python: le framework « Gluon »

Posted by patrick le octobre 5, 2007

Une nouvelle arrivée sur la liste WebSig (http://www.python.org/sigs/web-sig) sous le titre « NOOO! Another web framework »

please do not shoot me! I know you don’t think you need a new web framework but please give me the benefit of the doubt (I teach a class on Web Frameworks at DePaul University):

http://mdp.cti.depaul.edu/examples

Why?
here are some unique features:
1) full web based development, deployment and management of applications, no more shell commands (unless you want them)
2) built-in ticketing system to report bugs to administrator (not to the users, ever)
3) can compile applciations to byte-code for speed and distribution in closed source (some people want this)
4) 100% python (including template language).
5) no installation or configuration required. Just download and click. (includes python, web server, sqlite3, administrative interface and examples)
6) everything has a default: you write the model, you get an administrative interface; you write a controller, you get a generic view; etc.
7) The API are stable and there is no plan for a change.

It shares with Django and Turbogears some features: model-view-controller design, form generators and validation, internationalization, ORM, although all code has been written from scratch.

Here is an example application, a CMS to manage groups (members, wikis, blogs, votes, minutes, documents):

https://mdp.cti.depaul.edu/groups

Plus de détails ici: http://mdp.cti.depaul.edu/examples/default/index (Acknowledgments

  • This project uses paste.httpserver developed by Ian Bicking. Moreover we learned a lot from his writings on wsgi.
  • Many aspects of its design are inspired to Django, developed by Adrian Holovaty
  • The compilation of the applications would not have been possible without advice provided by Atul Varma
  • We use and include SyntaxHighlighter developed by Google
  • EditArea developed by Christophe Dolivet
  • TinyMCE developed by Moxiecode
  • and SortTable by Stuart Langridge.
  • This project also uses css layouts and images donwloaded from the web. Their authors are acknowledged inside the respective files, if known.)

A consulter:

  • la liste des frameworks  web  python :  http://wiki.python.org/moin/WebFrameworks (« A web application may use a combination of a base HTTP application server, a storage mechanism such as a database, a template engine, a request dispatcher, an authentication module and an AJAX toolkit. These can be individual components or be provided together in a high-level framework. »)

Posted in ORM, python | 2 Comments »

Quelques liens en vrac: plone, grok, sharpdevelop, dabo, geniusql

Posted by patrick le août 21, 2007

Quelques liens en vrac

- sortie de plone 3.0 (http://plone.org, « The culmination of over a year of hard work by the Plone Team, Plone 3.0 is available for download for all platforms today. This release is the most user-friendly, powerful and highly anticipated release of Plone ever, and has an amazing amount of new functionality. Some highligts:

  • Full versioning support, history and reverting to older revisions
  • Improved performance
  • Inline (Ajax) editing
  • Link and reference integrity checking
  • Automatic locking and unlocking
  • Improved handling of permissions and sharing
  • Upgraded visual (WYSIWYG) content editor
  • Full-text indexing of Word and PDF documents
  • Wiki support and multiple new mark-up formats
  • Rules engine for content
  • Strengthened security« )

Dans le même genre de produits basés sur Zope voir

- Grok (http://grok.zope.org/, « Grok is a web application framework for Python developers. It is aimed at both beginners and very experienced web developers. Grok has an emphasis on agile development. Grok is easy and powerful. You will likely have heard about many different web frameworks for Python as well as other languages. Why should you consider Grok?

  • Grok offers a lot of building blocks for your web application.
  • Grok is informed by a lot of hard-earned wisdom.

Grok accomplishes this by being based on Zope 3, an advanced object-oriented web framework. While Grok is based on Zope 3, and benefits a lot from it, you do not need to know Zope at all in order to get productive with Grok« )

- SharpDevelop(« Vous voulez coder en .net mais sans utiliser l’IDE de Microsoft ? SharpDevelop est celui qu’il vous faut. SharpDevelop (SD) est un IDE basé sur la plateforme .NET (2) qui offre un environnement de développement de qualité et libre comparable à VisualStudio. D’autres possibilités de développement sont intégrées et sont envisageables (mono intégré ; conversion auto en c#… You need to have at least the .NET 2.0 runtime installed on your machine. The SDK is optional but recommended. .NET Framework 2.0 Runtime download (x86), .NET Framework 2.0 SDK download (x86). Supported operating systems: Windows XP SP2 and later (eg Windows Server 2003 and Windows Vista)« )

- dabo (« http://dabodev.com/, Desktop applications: That’s what Dabo does. It’s not YAWF (yet another web framework). There are plenty of excellent web frameworks out there, so if that’s what you are looking for, Dabo isn’t for you. But there are almost no desktop application frameworks out there, and if you want to create applications that run on Windows, OS X or Linux, Dabo is for you!

Dabo is a 3-tier, cross-platform application development framework, written in Python wxPython GUI toolkit. And while Dabo is designed to create database-centric apps, that is not a requirement. Lots of people are using Dabo for the GUI tools to create apps that have no need to connect to a database at all..Dabo’s authors, Ed Leafe and Paul McNett, have strong backgrounds in database application development using the awesome and underrated Microsoft Visual FoxPro development environment.« )

- http://projects.amor.org/geniusql (« Geniusql is a public domain, low-level Object-Relational Mapper for Python applications. If you’re familiar with Martin Fowler’s work, you can think of Geniusql as providing a Data Source layer. It primarily uses a generic Table Data Gateway architecture (as opposed to the more tightly-coupled Active Record architecture recently popularized by Ruby On Rails and Django).

If you want a more powerful solution, we recommend skipping Active Record and going straight to a Data Mapper like Dejavu. Dejavu uses Geniusql behind the scenes for RDBMS back ends, but allows you to mix and match them with RAM, filesystem, and other stores.« )

- http://www.aminus.org/blogs/index.php/fumanchu/2007/08/18/storm_sqlalchemy_and_geniusql (« As Mike Bayer mentioned, I recently did some cross-ORM comparisons. The charts below all show « number of requests » on the X axis and « number of seconds to complete those requests » on the Y axis…I used trunk versions of Geniusql (1.0) and SQLAlchemy (0.4, without using the orm subpackage), and the latest stable distro of Storm (0.10). All test runs were done on my Win2k laptop, which has a 2GHz CPU and 512MB of RAM. PostgreSQL 8.0.0rc1 was the DB engine, and psycopg2 was the driver.« )

Posted in CMS, Dabo, ORM, python | Leave a Comment »

Mapping objet relationnel avec NHibernate, SqlAlchemy et RubyOnRails

Posted by patrick le août 17, 2007

D’abord quelques définitions:

- http://fr.wikipedia.org/wiki/Object-relational_mapping (« L’object-relational mapping (ORM), que l’on pourrait traduire par « correspondance entre monde objet et monde relationnel » est une technique de programmation informatique qui crée l’illusion d’une base de données orientée objet à partir d’une base de données relationnelle en définissant des correspondances entre cette base de données et les objets du langage utilisé« )

- http://fr.wikipedia.org/wiki/Hibernate (« Hibernate est un framework open source gérant la persistance des objets en base de données relationnelle. Hibernate est adaptable en terme d’architecture, il peut donc être utilisé aussi bien dans un développement client lourd, que dans un environnement web léger de type Apache Tomcat ou dans un environnement J2EE complet : WebSphere, JBoss Application Server et WebLogic de BEA Systems (voir (en) BEA Weblogic).

…NHibernate est un framework open source gérant la persistance des objets en base de données relationnelle. Il est l’implémentation .NET de Hibernate qui a vu le jour en Java« )

Le patron de conception ActiveRecord

- http://fr.wikipedia.org/wiki/Active_record_%28patron_de_conception%29 (« En génie logiciel, le patron de conception (design pattern) active record est une approche pour lire les données d’une base de données. Les attributs d’une table ou d’une vue sont encapsulés dans une classe. Ainsi l’objet, instance de la classe, est lié à un tuple de la base. Après l’instanciation d’un objet, un nouveau tuple est ajouté à la base au moment de l’enregistrement. Chaque objet récupère ses données depuis la base; quand un objet est mis à jour, le tuple auquel il est lié l’est aussi. La classe implémente des accesseurs pour chaque attribut« )

- http://www.theserverside.com/tt/articles/article.tss?l=RailsHibernate (« ActiveRecord is « an object that wraps a row in a database table or view, encapsulates database access and adds domain logic on that data »[Fowler, 2003]. This means the ActiveRecord has « class » methods for finding instances, and each instance is responsible for saving, updating and deleting itself in the database. It’s pretty well suited for simpler domain models, those where the tables closely resemble the domain model. It is also generally simpler then the more powerful, but complex Data Mapper pattern« )

Le patron de conception DataMapper

- http://martinfowler.com/eaaCatalog/dataMapper.html (« Objects and relational databases have different mechanisms for structuring data. Many parts of an object, such as collections and inheritance, aren’t present in relational databases. When you build an object model with a lot of business logic it’s valuable to use these mechanisms to better organize the data and the behavior that goes with it. Doing so leads to variant schemas; that is, the object schema and the relational schema don’t match up….The Data Mapper is a layer of software that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. With Data Mapper the in-memory objects needn’t know even that there’s a database present; they need no SQL interface code, and certainly no knowledge of the database schema« )

- http://www.theserverside.com/tt/articles/article.tss?l=RailsHibernate (« The Data Mapper is « a layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself »[Fowler, 2003]. It moves the responsibility of persistence out of the domain object, and generally uses an identity map to maintain the relationship between the domain objects and the database. In addition, it often (and Hibernate does) use a Unit of Work (Session) to keep track of objects which are changed and make sure they persist correctly.« )

- http://en.wikipedia.org/wiki/SQLAlchemy (« SQLAlchemy is an open source SQL toolkit and object-relational mapper for the Python programming language released under the MIT License. SQLAlchemy provides « a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language ». SQLAlchemy’s philosophy is that SQL databases behave less and less like object collections the more size and performance start to matter, while object collections behave less and less like tables and rows the more abstraction starts to matter. For this reason it has (like Hibernate for Java) adopted the Data Mapper pattern rather than the active record pattern used by a number of other object-relational mappers. »)

Le patron de conception UnitOfWork

- http://martinfowler.com/eaaCatalog/unitOfWork.html (« When you’re pulling data in and out of a database, it’s important to keep track of what you’ve changed; otherwise, that data won’t be written back into the database. Similarly you have to insert new objects you create and remove any objects you delete…A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you’re done, it figures out everything that needs to be done to alter the database as a result of your work« )

- http://www.sqlalchemy.org/features.html (« The Unit Of Work system, a central part of SQLAlchemy’s Object Relational Mapper (ORM), organizes pending create/insert/update/delete operations into queues and flushes them all in one batch. To accomplish this it performs a topological « dependency sort » of all modified items in the queue so as to honor foreign key constraints, and groups redundant statements together where they can sometimes be batched even further. This produces the maxiumum efficiency and transaction safety, and minimizes chances of deadlocks. Modeled after Fowler’s « Unit of Work » pattern as well as Hibernate, Java’s leading object-relational mapper.[More]« )

Comparaison de Hibernate avec le patron de conception ActiveRecord de Ruby On Rails

- Différence d’architecture logicielle:

- http://www.theserverside.com/tt/articles/article.tss?l=RailsHibernate (« The core difference between Rails ActiveRecord and Hibernate is the architectural patterns the two are based off of. Rails, obviously, is using the ActiveRecord pattern, where as Hibernate uses the Data Mapper/Identity Map/Unit of Work patterns. Just knowing these two facts gives us some insight into potential differences…general implication of which should be fairly obvious. The ActiveRecord (Rails) will likely be easier to understand and work with, but past a certain point more advanced/complex usages will likely be difficult or just not possible. The question is of course, when or if many projects will cross this line. Let’s look at some specifics of the two frameworks. To illustrate these differences, we will be using code from my « Project Deadwood » sample app. (Guess what I’ve been watching lately. :)

Exemples de code:

Soit une table créée avec l’ordre SQL suivant:

create table miners (

   id BIGINT NOT NULL AUTO_INCREMENT,

   first_name VARCHAR(255),

   last_name VARCHAR(255),

   primary key (id)

)

Avec RubyOnRails:

Your corresponding ruby class (miner.rb) and sample usage looks like this.

class Miner < ActiveRecord::Base

endminer.first_name = "Brom"

Avec Hibernate:

On the other hand, your Hibernate class (Miner.java) specifies the fields, getters/setters and xdoclet tags looks like so.

/**  * @hibernate.class table="miners"  */
public class Miner
{
private String firstName;
private String lastName;     /**      * @hibernate.id generator-class="native"      */
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }      /**      * @hibernate.property column="first_name"      */
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }      /**      * @hibernate.property column="last_name"      */
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
}
miner.setFirstName("Brom");

Avec sqlalchemy:

# describe a table called 'miner',  query the database for its columns

miners_table = Table('miners', meta, autoload=True, autoload_with=engine)
>>> class Miner(object):

...     def __init__(self, first_name, last_name ):

...         self.first_name = first_name

...         self.last_name = last_name

...

...     def __repr__(self):

...        return "<Miner(%r,%r)>" % (self.first_name, self.last_name)
mapper(Miner, miners_table) 
theMiner = Miner(first_name = "Brom")

Associations

- http://www.theserverside.com/tt/articles/article.tss?l=RailsHibernate (« In the last section, the Miner class we looked at was single table oriented, mapping to a single miners table. ORM solutions support ways to map associated tables to in memory objects, Hibernate and Rails are no different. Both handle the most of the basic mapping strategies. Here’s a non-exhaustive list of association supported by both of them, including the corresponding Hibernate – Rails naming conventions where appropriate.

  • Many to One/One to one – belongs_to/has_one
  • One to Many (set) – has_many
  • Many to Many (set) – has_and_belongs_to_many »)

Exemples d’associations

« As a comparative example, lets look at the many to one relationship. We are going to expand our Deadwood example from part I. We add to the Miner a many to one association with a GoldClaim object. This means there is a foreign key, gold_claim_id in the miners table, which links it to a row in the gold_claims table. »

Avec Hibernate:

(Java)

public class Miner {

   // Other fields/methods omitted    private GoldClaim goldClaim;

    /**

     * @hibernate.many-to-one column="gold_claim_id"

     *         cascade="save"

     */

    public GoldClaim getGoldClaim() { return goldClaim; }

    public void setGoldClaim(GoldClaim goldClaim) {

        this.goldClaim = goldClaim;

    }

}

Avec RubyOnRails:

(Rails)

class Miner < ActiveRecord::Base

    belongs_to :gold_claim

end

Avec Sqlalchemy :

parent_table = Table('parent', metadata,

    Column('id', Integer, primary_key=True),

    Column('child_id', Integer, ForeignKey('child.id')))



child_table = Table('child', metadata,

    Column('id', Integer, primary_key=True),

    )



class Parent(object):

    pass

 class Child(object):

    pass

 mapper(Parent, parent_table, properties={

    'child':relation(Child)

})



mapper(Child, child_table)

Pour aller plus loin

- http://www.castleproject.org/activerecord/gettingstarted/index.html ( » The Castle ActiveRecord project is an implementation of the ActiveRecord pattern for .NET. The ActiveRecord pattern consists on instance properties representing a record in the database, instance methods acting on that specific record and static methods acting on all records… Complex databases structures (legacy databases mostly) usually are not covered by the range of mapping features supported by ActiveRecord. In this case you might consider using NHibernate directly« )

- http://www.sqlalchemy.org/docs/choose.html (« La documentation de sqlalchemy »)

- http://en.wikipedia.org/wiki/Nhibernate (« NHibernate is an Object-relational mapping (ORM) solution for the Microsoft .NET platform. It is licensed under the GNU Lesser General Public License.It is a port of the popular Java O/R mapper Hibernate to .NET. Version 1.0 mirrors the feature set of Hibernate 2.1, adding a number of features from Hibernate 3.

NHibernate 1.2.0, released May of 2007, introduces many more features from Hibernate 3 and support for .NET 2.0, stored procedures, generics and nullable types« )

- http://www.hibernate.org/343.html (« NHibernate 1.2 introduces many additional features from Hibernate 3. Details about the new features can be found in this blog post. »)

- http://blog.hibernate.org/cgi-bin/blosxom.cgi (« The groupblog of the Hibernate Team »)

- http://blog.hibernate.org/cgi-bin/blosxom.cgi/Sergey%20Koshcheyev/nhibernate12-is-here.html (« NHibernate 1.2 is not a drop-in replacement for NHibernate 1.0. Before you jump to upgrading all your applications to NHibernate 1.2, note that there are several things that can break. The migration guide in the Wiki contains information about all the changes you need to make to successfully migrate...The next major release of NHibernate will drop support for .NET 1.1. We will continue porting the remaining Hibernate 3 features over to NHibernate. »)

- http://www.ayende.com/Blog/category/510.aspx (« Les principales nouvelles sur NHibernate« )

- http://www.ayende.com/Blog/ (Blog principal de Ayende @ Rahien)

- http://www.hibernate.org/362.html (« NHibernate Quick Start Guide

Posted in Architecture logicielle, DotNet, Nhibernate, ORM | 2 Comments »

Une application Web Django : le modèle ORM

Posted by patrick le juillet 18, 2007

Avant d’aborder la méthode HTTP ‘POST‘ je vais regarder rapidement le modèle ORM de Django.

Pourquoi ?

  1. Par simple curiosité :)
  2. parce qu’en relisant le tutoriel 01, j’ai vu que l’on pouvait manipuler les objets de la base de données avec une notation objet
  3. parce qu’hier je n’ai pas pu faire ceci dans le fichier bookmarks/template/bookmark/details.html

{% for tag in bookmark.tags %}
<li>{{tag.name}} </li>
{% endfor %}

On a bseoin de la documentation suivante:

- http://www.djangoproject.com/documentation/db-api/

- http://www.djangoproject.com/documentation/tutorial01/

Sous le répertoire cygwin : /cygdrive/e/projets/pybookmarks on lance la commande suivante:

$ python manage.py shell
Python 2.5.1 (r251:54863, Jun 19 2007, 22:55:07)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type « help », « copyright », « credits » or « license » for more information.
(InteractiveConsole)
>>>

On se retrouve donc sous l’interpréteur Python mais on va voir qu’on a également accès aux objets de la base de données sqlite. Je rappelle le modèle de données utilisé qui est dans le fichier /cygdrive/e/projets/pybookmarks/bookmarks/models.py:

class Tag(models.Model):    name = models.SlugField(maxlength=100)

def __unicode__(self):

return self.name

    class Admin:

pass

class Bookmark(models.Model):

user = models.ForeignKey(User)

url = models.URLField(db_index=True)

short_description = models.CharField(maxlength=255)

long_description = models.TextField(blank=True)

timestamp = models.DateTimeField(default=datetime.datetime.now)

public = models.BooleanField()

tags = models.ManyToManyField(Tag)

def __unicode__(self):

return self.url

class Admin:

pass

Voyons les requêtes que l’on peut faire en ligne de commande.

>>> import datetime
>>> from bookmarks.models import Bookmark, Tag
>>> from django.contrib.auth.models import User

>>> from django.shortcuts import get_object_or_404
>>> dir(Bookmark)
[‘AddManipulator’, ‘ChangeManipulator’, ‘DoesNotExist’, ‘__class__’, ‘__delattr_ _’, ‘__dict__’, ‘__doc__’, ‘__eq__’, ‘__getattribute__’, ‘__hash__’, ‘__init__’, ‘__metaclass__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex_ _’, ‘__repr__’, ‘__setattr__’, ‘__str__’, ‘__unicode__’, ‘__weakref__’, ‘_collec t_sub_objects’, ‘_default_manager’, ‘_get_FIELD_display’, ‘_get_FIELD_filename’, ‘_get_FIELD_height’, ‘_get_FIELD_size’, ‘_get_FIELD_url’, ‘_get_FIELD_width’, ‘ _get_image_dimensions’, ‘_get_next_or_previous_by_FIELD’, ‘_get_next_or_previous _in_order’, ‘_get_pk_val’, ‘_meta’, ‘_prepare’, ‘_save_FIELD_file’, ‘add_to_class’, ‘delete’, ‘get_next_by_timestamp’, ‘get_previous_by_timestamp’, ‘objects‘, ‘ save‘, ‘tags‘, ‘user’, ‘validate’]
>>> Bookmark.objects.all()
[<Bookmark: http://www.python.org&gt;, <Bookmark: http://gump.apache.org/index.html&gt;, <Bookmark: http://www.chomsky.info/&gt;, <Bookmark: http://www.chomsky.info/audi onvideo.htm>, <Bookmark: http://people.csail.mit.edu/meyer/iandc-WWW/Authors/chomskynoam.html>%5D

>>> b = get_object_or_404(Bookmark, pk=3)

>>> dir(b)
[‘AddManipulator’, ‘ChangeManipulator’, ‘DoesNotExist’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__doc__’, ‘__eq__’, ‘__getattribute__’, ‘__hash__’, ‘__init__’, ‘__metaclass__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__str__’, ‘__unicode__’, ‘__weakref__’, ‘_collect_sub_objects’, ‘_default_manager’, ‘_get_FIELD_display’, ‘_get_FIELD_filename’, ‘_get_FIELD_height’, ‘_get_FIELD_size’, ‘_get_FIELD_url’, ‘_get_FIELD_width’, ‘
_get_image_dimensions’, ‘_get_next_or_previous_by_FIELD’, ‘_get_next_or_previous_in_order’, ‘_get_pk_val’, ‘_meta’, ‘_prepare’, ‘_save_FIELD_file’, ‘add_to_class’, ‘delete’, ‘get_next_by_timestamp’, ‘get_previous_by_timestamp’, ‘id’, ‘long_description’, ‘objects’, ‘public’, ‘save’, ‘short_description’, ‘tags’, ‘timestamp’, ‘url’, ‘user’, ‘user_id’, ‘validate’]

>>> b.__metaclass__
<class ‘django.db.models.base.ModelBase’>


>>> b.tags
<django.db.models.fields.related.ManyRelatedManager object at 0x7fc0644c>
>>> dir(b.tags)
[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__doc__’, ‘__getattribute__’, ‘__hash_, _’, ‘__init__’, ‘__module__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__str__’, ‘__weakref__’, ‘_add_items’, ‘_clear_items’, ‘_pk_val’, ‘_remove_items’, ‘add’, ‘all’, ‘clear’, ‘complex_filter’, ‘contribute_to_class’, ‘core_filters’, ‘count’, ‘create’, ‘creation_counter’, ‘dates’, ‘distinct’, ‘exclude’, ‘extra’, ‘filter’, ‘get’, ‘get_empty_query_set’, ‘get_or_create’,’get_query_set’, ‘in_bulk’, ‘instance’, ‘iterator’, ‘join_table’, ‘latest’, ‘model’, ‘none’, ‘order_by’, ‘remove’, ‘select_related’, ‘source_col_name’, ‘symmetrical’, ‘target_col_name’, ‘values‘]
>>> b.tags.values()
[{‘id': 2, ‘name': u’django’}, {‘id': 3, ‘name': u’chomsky’}]

OK, c’est ce que je cherchais donc les modifications sont les suivantes:

  • Dans le fichier details.html

{% if mark %}
<ul>
<li> {{mark.url}} </li>
<li> {{mark.user}} </li>
{# <li> {{mark.long_description}} </li> #}
<ul>
{% for tag in tags %}
<li>{{tag.name}} </li>
{% endfor %}
</ul>
</ul>
{% else %}
<p>pas de bookmark.</p>
{% endif %}

  • dans le fichier views.py

c=Context({‘mark': bookmark,’tags': bookmark.tags.values()})

Pour information:

- un nouvel ORM python vient de sortir: c’est storm (https://storm.canonical.com/FrontPage)

Lu sur la liste https://lists.ubuntu.com/mailman/listinfo/storm

I’ve started to experiment a little bit exploring whether storm can be used inside of Django. Django has feature to decouple the column names used in the database from the attribute names used when accessing the ORM in python, such as:

class DjangoModel(meta.Model):    bla = IntegerField(db_column="foo")

The equivalent in Storm is:

class MyClass(object):    bla = Int("foo")

Posted in ORM, python | Leave a Comment »

 
Suivre

Recevez les nouvelles publications par mail.

Rejoignez 79 autres abonnés