Showing posts with label Shared News. Show all posts
Showing posts with label Shared News. Show all posts

Lecture de la semaine #7




~ Franky

Lecture de la semaine #6

 

from BluPointe Blog

“to read more about the filter attribute, see bit.ly/kMPBYB
“The list of built-in MVC filters can be found here: bit.ly/jSaD5N
“Profiling Your .NET Code : bit.ly/dDXWsF
“ - Guide to Improving Code Performance in .NET: Part I” by Satesh Arveti on C# Corner (bit.ly/gyImk9)
- Writing Efficient C and C Code Optimization” by Koushik Ghosh on Code Project (bit.ly/icnYEi)
- Writing High Performance .NET Code” by Juan A Rodriguez and Simonijt Dutta from Intel (intel.ly/fvweaP)”
“Deploy sites to Windows Azure in less than 30 seconds Enables deployments to multiple Web Role instances using Web Deploy Saves Web Deploy packages & IIS configuration in Windows Azure storage to provide durability A web administrator portal for managing web sites deployed to the role The ability to upload and manage SSL certificates Simple logging and diagnostics tools.”
“Installing the WAAWR is as easy as download, extract, buildme.cmd and you’re done.”

~ Franky

Lecture de la semaine #5

“In this post, I’ll show you how to build an Azure AppFabric adapter for StreamInsight.  In the next post, I’ll walk through the steps to deploy the on-premises StreamInsight application to Windows Azure and StreamInsight Austin.”

“You can find the source code here.”

“As the datacenters get upgraded, the version number of the database engine will increase, which will result in errors when connecting”

“we encourage you to immediately download and install the latest updates to the SQL Server Management Studio (SSMS) tools for managing your SQL Server and SQL Azure databases.  The links to get the latest updates available in SQL Server 2008 R2 SP1 are:

“…if you really want to debug and trace an Azure application you had better read this MSDN article which explains how to create custom debugging and trace agents and write logs to Azure storage.”

 

~ Franky

Lecture de la semaine #4


Cette semaine il y a une “petite” tendence…

~Franky

Google Desktop pour développeur

Est-ce que vous utilisez Google Desktop?  Est-ce que vous connaissez?  Vous devriez, c’est merveilleux.  Comme son nom l’indique c’est un Google, mais pour le contenu de votre ordinateur.  Mais vous me direz:”Windows propose déjà un outil de recherche pourquoi je devrais en installer un autre?”.   Voici la réponse…

Portable volé. Que faire?


J'ai un ultra portable que je traine partout.  À plusieurs reprises je me suis demandé quoi faire si je l'oublais quelque part, ou si je me le faisais voler.  Et bien François Lapierre-Messier à trouvé: Prey Project!



 






Prey project est une application gratuite qui permet de garder une trace non seulement de votre portable, mais aussi votre téléphone à tout moment.  Et vous aidera si jamais le pire se produit.  Effectivement à l'aide d'une petite application qu'on installe, il permet de retracer l'adresse IP, le réseau WIFI le plus proche, de barré l'écran, de faire partir une alarme et même de prendre des photos, pour le moins que votre portable est une caméra.


Prey est un projet "Open source", et est donc gratuit jusqu'à trois appareils ordinateur et téléphone.  Il est possible de passer à une version Pro moins limité.



Un must!

~ Franky



Référence:
Émission M.Net. François Lapierre-Messier nous présente Prey Project.
- Prey Project

One day in the Life of a coder

This one was to good...

~Franky

Read all of ASP.NET MVC 2 in Action now while you wait for the printed book

I just read this on the Jeffrey Palermo's blog, awesome reading.  I'm in a hurry to start...
image
Read all of ASP.NET MVC 2 in Action now while you wait for the printed book : Jeffrey Palermo (.com): "First, you should place your advance order for ASP.NET MVC 2 in Action at http://manning.com/palermo2. That way, you will receive the printed book even before you see it at your local bookstore.
The entire book is finished, and we are just moving through production right now. But that doesn’t mean you have to wait to read it and learn about ASP.NET MVC 2. Since the beginning of the book project, you have been able to see the progression of the book on GitHub, our project site and version control system. That’s right, version control is for more than just code!
Head over to http://github.com/jeffreypalermo/mvc2inaction and go to the “manuscript” folder to read the entire book in Word document form. All the content is there. In fact, the Word documents for the 1st edition is there as well. You can see just how much we have expanded the 2nd edition to not only cover version 2 but also to incorporate lessons learned using the framework over the last 2 years."
References: http://jeffreypalermo.com/blog/read-all-of-asp-net-mvc-2-in-action-now-while-you-wait-for-the-printed-book/

The Official jQuery Podcast – Episode 18 – Jeffery Way (Nettuts)

The Official jQuery Podcast – Episode 18 – Jeffery Way (Nettuts)
Posted April 2nd, 2010 by Ralph Whitbeck

The Official jQuery PodcastThis week we talked with Jeffrey Way. He is the editor of Nettuts+, and the Site Manager of ThemeForest and CodeCanyon. Jeffrey gives an overview of the Nettuts+ website and explains why their tutorials focus so much on jQuery and gives some examples of recent jQuery related articles.

We also announce the winner of the Nettuts giveaway for a free jQuery Conference Bay Area ticket. And that wasn’t the only thing we gave away this week either!

You can subscribe to the show in iTunes or via the raw RSS feed or you can download the MP3.
jQuery: » The Official jQuery Podcast – Episode 18 – Jeffery Way (Nettuts)

Print Friendly?

Lors d'un post précédant, je vous ai présenté PDFmyUrl, un outil qui permet d'imprimer en PDF. Le problème avec ce genre d'outil c'est que le format de la page n'est pas toujours conservé. Parfois, le résultat est même inutilisable, une publicité vient se placer par dessus du texte. Et si l'on imprime sur papier alors il y a tellement de vide entre les publicités les marges et menus qu'on imprime 2 fois plus de papier que nécessaire.



Voici donc ce que j'ai trouvé pour régler ce problème : Print Friendly.

En PDF svp

J'ai trouvé un petit service bien simple, mais très utile:  Pdf my url. Comme son nom l'indique, il permet de transformer une page web en un fichier PDF. Donc au lieu de devoir installer les cutePDF de ce monde on peut à partir de n'importe quel ordinateur convertir toutes les pages web en un fichier PDF.

Suivre un colis sans se fatiguer en 3 étapes

De nos jours rien de plus banal que de faire des achats directement sur le web!  Puis après commence la torture, est-ce que mon paquet arrive bientôt? Où est-il rendu?  Une des solutions est de ce connecter au site web tu transporteur (USP, Purolator, etc) et de faire une requête pour avoir le status de notre colis.  Une autre est de tout simplement le suivre avec TrackThis!

TrackThis est un service gratuit qui permet de suivre (comme son nom l'indique) un colis.  Les particularités de ce dernier, est qu'il permet de suivre votre paquet peut importe le transporteur et qu'il vous informe via plusieurs médiums tels que e-mail, SMS, RSS, faceBook.

Étape 1

Pour l'utiliser rien de plus simple, rendez-vous sur le site et créer un profil (account).  Au lieu de créer encore un autre nom d'usage et un mot de passe, TrackThis emploiera votre compte d'AOL, de Facebook, de Google, ou de Yahoo. Il vous permet aussi de créer un OpenID pour libre chez myOpenID.com.

Étape 2

Ajouter à votre compte le ou les médiums que vous désiriez utiliser : SMS, E-Mail ou autre.

Étape 3

Enregistrer votre colis à l'aide du numéro de suivi (tracking number) 

voilà maintenant reste plus qu'à attendre....

~Franky

Pourquoi delicious est mieux que Google Shared Items

Dernièrement j'ai écrit un article Recherche du parfait lecteur de flux RSS qui expliquait pourquoi j'ai "quitté" Google Reader au profit de NewsGator. Cependant, les shared Items me manquaient ardemment, juqu'à tout récemment ou j'ai trouvé beaucoup mieux! Delicious ou plutôt Deli.cio.us.

 

Avant : Les Shared Items

Pour ceux que ne savent pas ce que sont le Shared Items,  voici une courte description. Avec Google Reader il s’agit d’identifier certain article comme étant partageable que vous trouvez intéressant pour les voir automatiquement partagé avec vos "friends".  Vos friends étant les contacts GMail ou autres personnes que vous autorisez.

 

Après: Deli.cio.us

Delcious est un gestionnaire de favoris (bookmarks) social, qui permet de partager les liens utiles ou intéressants avec d’autres utilisateurs.  Vous pouvez identifier les catégories auxquelles se rapporte ce lien et donc organiser votre collection comme bon vous semble.

 

 

Lire

Pour lire les favoris de quelq'un rien de plus facile,  et aucune obligation.  Vous n'avez pas besoin d'un compte, vous n'avez même pas besoin de connaitre la personne. 

Voici vos options:

  • Via le site web: Vous pouvez aller quand bon vous semble aller sur Delicious.com et lire les liens qui selon votre guise sont: les plus populaires, les plus récent ou se rapportant à un sujet particulier.
  • Via le site web personnel: Si vous connaissez un membre, visitez le site de la personne (Delicious.com/NomDeLaPersonne).  Ce site est autogénéré donc est toujours à jour.  Voici mon lien: http://delicious.com/fboucheros
  • Via un fil RSS: Vous préférez être averti lors de changement, rien de plus simple ajouté le fil RSS à votre lecteur favori, NewsGator ;) et le tour est joué.  Voici mon fil pour mes découvertes delicieuses... http://feeds.delicious.com/v2/rss/fboucheros

Publier

Tout d’abord, vous devez vous créer un compte, en allant sur le site de Delicious.com.  Voilà vous êtes prêt!  Chaque fois que vous voulez partager ou seulement conserver ( car il est possible de garder des liens privés) plusieurs options s’offrent à vous:

  • Par le site: Vous pouvez vous connecter à votre compte et ajouter un nouveau lien en suivant le wizard.
  • Par l’icon: Directement sur la page que vous voulez noter chercher l’icon image .  Il est de plus en plus répandu.  Ceci vous amènera à un formulaire pour créer votre nouveau bookmark.
  • Par Addons: Il existe plusieurs addons ajoutant des fonctionnalités à votre navigateur… 

 

Plusieurs API (application programming interface) s’offrent à vous pour partager ou présenter vos favoris à même votre blog ou site web.  Ainsi, sur le site de Delicious à la page des Settings dans la section Blogging, vous trouverez quatre options de publication:

  • Network Badges: Montrez vos lecteurs que vous êtes un membre de délicieux et donnez-leur une manière simple de vous ajouter à leur réseau.
  • Link Rolls: Montrez une liste de vos récents Bookmark Delicious en tant qu'élément de votre site Web.

 

 

  • Tags Roll: Montrez un nuage (tags cloud) ou une liste de vos Bookmark Delicious en tant qu'élément de votre site Web.

 

  • Blog Posting: Dispositif expérimental qui peut automatiquement signaler des entrées à votre blog journalier contenant vos derniers liens.

Voilà j’espère vous retrouver à dans mes abonnés, et si vous avez des questions ou suggestions laisser un commentaire!

~Franky

 

Liens intéressants:

ASP.NET MVC 1.0 Release Candidate Now Available

Read on:

ASP.NET MVC 1.0 Release Candidate Now Available
ScottGu
Tue, 27 Jan 2009 20:13:09 GMT

 

Today we shipped the ASP.NET MVC 1.0 Release Candidate (RC).  Click here to download it (note: the link just went live so if it isn’t working wait a few minutes for the server you are hitting to refresh).  It works with both Visual Studio 2008 and Visual Web Developer 2008 (which is free).

Today’s RC is the last public release of ASP.NET MVC that we’ll ship prior to the final “1.0” release.  We expect to ship the final ASP.NET MVC 1.0 release next month.

In addition to bug fixes, today’s build includes several new features.  It also includes some refinements to existing features based on customer feedback.  Please read the release notes that ship with the ASP.NET MVC download for full details on all changes.  The release notes include detailed instructions on how to upgrade existing applications built with the ASP.NET MVC Beta to the RC.

Visual Studio Tooling Improvements

The RC includes several new Visual Studio tooling features (above and beyond the existing support in the beta – which I won’t cover here).  These features include:

Add Controller Command

You can now type Ctrl-M, Ctrl-C within an ASP.NET MVC project, or right-click on the /Controller folder and choose the “Add->Controller” context menu item to create new controller classes:

This will cause an “Add Controller” dialog to appear that allows you to name the Controller to create, as well as optionally indicate whether you wish to automatically “scaffold” common CRUD methods:

Clicking the “Add” button will cause the controller class to be created and added to the project:

Add View Command

You can now type Ctrl-M, Ctrl-V within a Controller action method, or right-click within an action method and choose the “Add View” context menu item to create new view templates:

This will cause an “Add View” dialog to appear that allows you to name and create a new view (it is pre-populated with convention-based options).  It allows you to create “empty” view templates, or automatically generate/scaffold view templates that are based on the type of object passed to the view by the Controller action method.  The scaffolding infrastructure uses reflection when creating view templates – so it can scaffold new templates based on any POCO (plain old CLR object) passed to it.  It does not have a dependency on any particular ORM or data implementation.

For example, below we are indicating that we want to scaffold a “List” view template based on the sequence of Product objects we are passing from our action method above:

Clicking the “Add” button will cause a view template to be created for us within the \Views\Products\ directory with a default “scaffold” implementation:

We can then run our application and request the /products URL within our browser to see a listing of our retrieved products:

The RC ships with a number of built-in scaffold templates: “Empty”, “List”, “Details”, “Edit” and “Create” (you can also add your own scaffold templates – more details on this in a moment). 

For example, to enable product editing support we can implement the HTTP-GET version of our “Edit” action method on our Products controller like below and then invoke the “Add View” command:

Within the “Add View” dialog we can indicate we are passing a “Product” object to our view and choose the “Edit” template option to scaffold it:

Clicking the “Add” button will cause an edit view template to be created with a default scaffold implementation within the \Views\Products\ directory:

We can then run our application and request the /products/edit/1 URL within our browser to edit the Product details:

To save edit changes we can implement the HTTP-POST version of our “Edit” action method on our Products controller:

Notice in the code above how in the case of an error (for example: someone enters a bogus string for a number value) we redisplay the view.  The “edit” and “create” scaffold templates contain the HTML validation helper methods necessary to preserve user input and flag invalid input elements in red when this happens:

You’ll rarely end up using a scaffold-created template exactly as-is, and often will end up completely replacing it.  But being able to get an initial implementation up and running quickly, and having an initial view template for your scenario that you can then easily tweak is really useful.

Because the scaffold infrastructure supports scaffolding views against any plain-old CLR object, you can use it with both domain model objects (including those mapped with LINQ to SQL, LINQ to Entities, nHibernate, LLBLGen Pro, SubSonic, and other popular ORM implementations) as well as to create scaffolds with custom Presentation Model/ViewModel classes.

Adding and Customizing Scaffold Templates

ASP.NET MVC’s scaffolding infrastructure is implemented using Visual Studio’s built-in T4 templating architecture (Scott Hanselman has a nice blog post on T4 here). 

You can customize/override any of the built-in ASP.NET MVC scaffold template implementations.  You can also create additional scaffold templates (for example: the “ScottGu Crazy Look” scaffold option) and have them be displayed as options within the “Add View” dialog.

To customize/add scaffold templates at the machine-wide level, open the “C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC\CodeTemplates” folder:

The “AddController” sub-folder contains the scaffold template for the “Add Controller” dialog.  The “AddView” sub-folder contains the scaffold templates for the “Add View” dialog:

The scaffold templates populated within the “Add View” dialog are simply text files that have the “.tt” file-name extension.  These “.tt” text files contain inline C# or VB code that executes when the template is selected. 

You can open and edit any of the existing files to customize the default scaffolding behavior.  You can also add new “.tt” template files – like I have above with the “Scott Crazy Look.tt” file.  When you add a new template file the “Add View” dialog will be updated to automatically include it in the list of available scaffold options:

In addition to customizing/adding template files at the machine level, you can also add/override them at the individual project level.  This also enables you to check-in the templates under source control and easily use them across a team.

You can customize the scaffold templates at a project level by adding a “CodeTemplates” folder underneath your project.  You can then have “AddController” and “AddView” sub-folders within it:

You can override any of the default machine-wide templates simply be adding a “.tt” file with the same name to the project.  For example, above we are overriding the default “Controller.tt” scaffold template used in “Add Controller” scenarios. 

You can add new view-template scaffold files to the list by placing them within the “AddView” folder.  For example, above we added a “Yet Another Crazy Look.tt” view template to our project.  When we use the “Add View” dialog we’ll now see a union of the templates defined at the machine and project level:

Note: When you add “.tt” templates under the \CodeTemplates folder make sure to set the “Custom Tool” property of each of the “.tt” template files to an empty string value within the property grid (otherwise you’ll get an error trying to run it).  You might also need to close and reopen the project to clear a spurious error from the error list.  We’ll be publishing more blog posts that cover creating/customizing scaffolding templates shortly.

Go To Controller / Go To View

The RC build now supports the ability to quickly navigate between the Controllers and Views within your projects. 

When your cursor is within a Controller action method you can type Ctrl-M, Ctrl-G to quickly navigate to its corresponding view template.  You can also perform this same navigation jump by right-clicking within the action method and selecting the “Go To View” menu option:

In the example above we used the “Go To View” command within the “Edit” action method of the ProductsController class.  This will cause the \Views\Products\Edit.aspx view template to be opened and have the default focus within VS:

Within view templates you can also now type Ctrl-M, Ctrl-G to quickly navigate to the view’s corresponding Controller class.  You can also perform this navigation jump by right-clicking within the view template and selecting the “Go To Controller” menu option:

MSBuild Task for Compiling Views

By default when you do a build on an ASP.NET MVC project it compiles all code within the project, except for the code within view template files.  With the ASP.NET MVC Beta you had to roll your own MSBuild task if you wanted to compile the code within view templates.  The ASP.NET MVC RC build now includes a built-in MSBuild task that you can use to include views as part of the project compilation process.  This will verify the syntax and code included inline within all views, master pages, and partial views for the application, and give you build errors if it encounters any problems.

For performance reasons we don't recommend running this for quick compiles during development, but it is convenient to add to particular build configuration profiles (for example: staging and deployment) and/or for use with Build or CI (continuous integration) servers.  Please review the release notes for the steps to enable this.

View Refactoring Support

The names of the files and folders under the \Views application sub-folder will now automatically be updated when you perform controller class rename or action method rename using the “Rename” refactoring command in VS 2008.  VS 2008 will apply the standard convention-based naming pattern to existing view files/folders when the Controller class is updated.

View Improvements

The RC build includes a number of view-specific enhancements that were incorporated based on feedback during the preview releases.

Views without Code-Behind Files

Based on feedback we’ve changed view-templates to not have a code-behind file by default.  This change helps reinforce the purpose of views in a MVC application (which are intended to be purely about rendering and to not contain any non-rendering related code), and for most people eliminates unused files in the project.

The RC build now adds C# and VB syntax support for inheriting view templates from base classes that use generics.  For example, below we are using this with the Edit.aspx view template – whose “inherits” attribute derives from the ViewPage<Product> type:

One nice benefit of not using a code-behind file is that you'll now get immediate intellisense within view template files when you add them to the project.  With previous builds you had to do a build/compile immediately after creating a view in order to get code intellisense within it.  The RC makes the workflow of adding and immediately editing a view compile-free and much more seamless.

Important: If you are upgrading a ASP.NET MVC project that was created with an earlier build make sure to follow the steps in the release notes – the web.config file under the \Views directory needs to be updated with some settings in order for the above generics based syntax to work.

Model Property

With previous builds of ASP.NET MVC, you accessed the strongly typed model object passed to the view using the ViewData.Model property:

The above syntax still works, although now there is also a top-level "Model" property on ViewPage that you can also use:

This property does the same thing as the previous code sample - its main benefit is that it allows you to write the code a little more concisely.  It also allows you to avoid using the ViewData dictionary in cases where you want the view template to only interact with the strongly-typed model passed to it.

Setting the Title

The default master-page template added to new ASP.NET MVC projects now has an <asp:contentplaceholder/> element within its <head> section.  This makes it much easier for view templates to control the <title> element of the HTML page rendered back – and not require the Controller to explicitly pass a “title” parameter to configure it (which was the default with previous ASP.NET MVC builds and we thought questionable from a responsibilities perspective). 

For example, to customize the <title> of our Edit view to include the current product name we can now add the below code to our Edit.aspx template to drive the title directly off of the model object being passed the view:

The above code will then cause the browser to render the title using the Product name at runtime:

In addition to setting the <title> element, you can also use the above approach to dynamically add other <head> elements at runtime.  Another common scenario this is useful with is configuring model/view specific <meta/> elements for search engine optimization. 

Strongly Typed HTML/AJAX Helpers

One of the requests a few people have asked for is the ability to use strongly-typed expression syntax (instead of strings) when referring to the Model when using a View's HTML and AJAX helper objects.

With the beta build of ASP.NET MVC this wasn't possible, since the HtmlHelper and AjaxHelper helper classes didn't expose the model type in their signature, and so people had to build helper methods directly off of the ViewPage<TModel> base class in order to achieve this. 

The ASP.NET MVC RC build introduces new HtmlHelper<TModel> and AjaxHelper<TModel> types that are exposed on the ViewPage<TModel> base class.  These types now allow anyone to build strongly-typed HTML and AJAX helper extensions that use expression syntax to refer to the View's model.  For example:

The HTML form helper extension methods in the core ASP.NET MVC V1 assembly still use the non-expression based string syntax.  The “MVC Futures” assembly released today (which works with the RC) has a few initial implementations of expression-syntax based form helper methods.   We are going to iterate on these a bit longer and then consider adding them into the ASP.NET MVC core assembly in the next release. 

You can of course also add your own helper methods (using either strings or strongly-typed expressions).  The built-in HTML/AJAX helper methods can also optionally be removed (because they are extension methods) if you want to replace or override them with your own

Form Post Improvements

The RC build includes a number of form-post specific enhancements:

[Bind(Prefix=””)] No Longer Required for Common Scenarios

The RC build no longer requires you to explicitly use a [Bind] attribute (or set its prefix value to “”) in order to map incoming form post parameters that do not have a prefix to complex action method parameters.

To see what this means, let’s implement the “Create” scenario for our ProductsController.  We’ll begin by implementing the HTTP-GET version of our “Create” action method.  We’ll do this with code below that returns a View based on an empty Product object:

We can then right-click within our action method, choose the “Add View” command and scaffold a “create” view template that is based on a Product:

Notice above how our Html.TextBox() helper methods are referencing the “ProductName” and “SupplierID” properties on our Product object.  This will generate HTML markup like below where the input “name” attributes are “ProductName” and “SupplierID”:

We can then implement the HTTP-POST version of our “Create” action method. We’ll have our action method take a Product object as a method parameter:

With the ASP.NET MVC Beta we would have had to add a [Bind(Prefix=””)] attribute in front of our Product argument above – otherwise the ASP.NET MVC binding infrastructure would have only looked for form post values with a “productToCreate.” prefix (for example: productToCreate.ProductName and productToCreate.SupplierID) and not found the submitted values from our form (which don’t have a prefix). 

With the RC build, the default action method binders still first attempt to map a productToCreate.ProductName form value to the Product object.  If they don’t find such a value, though, they now also attempt to map “ProductName” to the Product object.  This makes scenarios where you pass in complex objects to an action method syntactically cleaner and less verbose.  You can take advantage of this feature both when mapping domain objects (like our Product object above) as well as with Presentation Model/ViewModel classes (like a ProductViewModel class).

A completed implementation of our Create action method (including basic input type error handling) might look like below:

Now our create action will save the Product object if all values are entered correctly.  When a user attempts to create a Product with invalid Product property values (for example: a string “Bogus” instead of a valid Decimal value), the form will redisplay and flag the invalid input elements in red:

ModelBinder API Improvements

The model binding infrastructure within the ASP.NET MVC Release Candidate has been refactored to add additional extensibility points to enable custom binding and validation schemes.  You can read more about these details in the ASP.NET MVC RC release notes.

Model Binders can also now be registered for interfaces in addition to classes. 

IDataErrorInfo Support

The default model binder with ASP.NET MVC now supports classes that implement the IDataErrorInfo interface.  This enables a common approach to raise validation error messages in a way that can be shared across Windows Forms, WPF and now ASP.NET MVC applications.

Unit Testing Improvements

The ASP.NET MVC RC includes some significant improvements to unit testing:

ControllerContext changed to no longer derive from RequestContext

The RC build includes a refactoring of the ControllerContext class that significantly simplifies common unit testing scenarios.  The ControllerContext class no longer derives from RequestContext and now instead encapsulates RequestContext and exposes it as a property.  The properties of ControllerContext and its derived types are also now virtual instead of sealed – making it significantly easier to create mock objects.

To see how this helps, let’s consider an action method like below that uses both the “Request” and “User” intrinsic objects:

Testing the above action method with previous ASP.NET MVC builds would have required mocking RequestContext and ControllerContext (with some non-obvious constructors that also brought in a RouteData object).

With the RC build we can now unit test it like below (using Moq to mock a ControllerContext for our Controller that allows us to simulate the Request.IsAuthenticated and User.Identity.Name properties):

The refactoring improvements made help out not just with testing Controller actions – but also help with testing filters, routes, custom actionresult types, and a variety of other scenarios.

AccountsController Unit Tests

The ASP.NET MVC Project Template included with the RC build now adds 25 pre-built unit tests that verify the behavior of the AccountsController class (which is a controller added to the project by default to handle login and account management scenarios).  This makes refactoring/updating AccountsController easier.  The AccountsController implementation has also been modified to more easily enable non-Membership Provider based credential systems to be integrated.

Cross Site Request Forgery (CSRF) Protection

Cross-site request forgery (CSRF) attacks (also referred to as XSRF attacks) cause users of a trusted browser agent to take unintended actions on a site.  These attacks rely on the fact that a user might still be logged in to another site.  A malicious Web site exploits this by creating a request to the original site (for example: by linking to a URL on the site using a <img src=””/> element on the hacker site). The request is made using the user’s browser and thus with the user’s authentication token and credentials. The attacker hopes that the user’s authentication or session cookie is still valid and if so, the attacker can sometimes take disruptive action.  You can learn more about this hacking technique here.

The ASP.NET MVC RC now includes some built-in CSRF protection helpers that can help mitigate CSRF attacks.  For example, you can now use the Html.AntiForgeryToken() helper to render a hidden input token within forms:

This helper issues a HTTP cookie and renders a hidden input element into our form.  Malicious web-sites will not be able to access both values.

We can then apply a new [ValidateAntiForgeryToken] attribute onto any action method we want to protect:

This will check for the existence of the appropriate tokens, and prevent our HTTP-POST action method from running if they don’t match (reducing the chance of a successful CSRF attack).

File Handling Improvements

The ASP.NET MVC RC includes a number of file handling enhancements:

FileResult and File() helper method

The RC build adds a new FileResult class that is used to indicate that a file is being returned as an ActionResult from a Controller action method.  The Controller base class also now has a set of File() helper methods that make it easy to create and return a FileResult.

For example, let’s assume we are trying to build a photo management site.  We could define a simple “Photo” class like below that encapsulates the details about a stored Photo:

We could then use the new File() helper method like below to implement a “DisplayPhoto” action method on a PhotoManager controller that could be used to render the Photo out of a database store.  In the code below we are passing the File() helper the bytes to render, as well as the mime-type of the file. If we pointed a <img src=””/> element at our action method URL the browser would display the photo inline within a page:

If we wanted an end-user to be able to download the photo and save it locally, we could implement a “DownloadPhoto” action method like below.  In the code below we are passing a third parameter – which will cause ASP.NET MVC to set a header that causes the browser to display a “Save As…” dialog which is pre-populated with the filename we’ve supplied:

When a user clicks a link to the /PhotoManager/DowloadPhoto/1232 URL they’ll be prompted to save the picture:

File Uploading Support

The RC build also includes built-in model-binder support for uploaded files and multi-part mime content. 

For example, we could have a <form> whose enctype attribute is set to “multipart/form-data” perform a post to the /PhotoManager/UploadPhoto URL.  If a <input type=”file” name=”fileToUpload”/> element was within the form it would cause the file selected by the end-user to be passed to our action method as an HttpPostedFileBase object:

We could then use the HttpPostedFileBase object to get access to the raw bytes of the uploaded file, its mime-type, and optionally save it to a database or disk.

AJAX Improvements

The ASP.NET MVC RC includes a number of AJAX enhancements:

jQuery Intellisense Files included within ASP.NET MVC Project Template

Newly created ASP.NET MVC projects now include both the standard jQuery library (both full and compressed versions), as well as the –vsdoc intellisense documentation file used by Visual Studio to provide richer intellisense support for it (you can learn more about this here):

This enables rich jQuery JavaScript intellisense within client-script blocks and JavaScript files:

Today’s RC build ships jQuery 1.2.6.  We are planning to ship the upcoming jQuery 1.3.1 release for the final ASP.NET MVC 1.0 release, and will include an updated JavaScript intellisense file for it. 

Request.IsAjaxRequest Property

The Request.IsAjaxRequest property can be used to detect whether a request is being sent from an AJAX call on the client (and is useful for scenarios where you want to gracefully degrade if AJAX is not enabled).  The logic within this method was updated with the RC to now recognize the “X-Requested-With” HTTP header (in addition to the form field sent by ASP.NET AJAX).  This is a well known header sent by JavaScript libraries such a Prototype, jQuery, and Dojo – and now enables a unified way to check for AJAX within an ASP.NET MVC request. 

JavaScriptResult ActionResult and JavaScript() helper method

The Controller base class now has a JavaScript() helper method that returns a new ActionResult class of type JavaScriptResult.  This supports the ability to return raw JavaScript that will then be executed on the client by the built-in ASP.NET MVC helper methods.  This can be useful for scenarios where you want to cause conditional JavaScript to execute on the client based on server logic.

Summary

We are pretty excited to be in the final “home stretch” of ASP.NET MVC V1.  Please report any issues you find with the RC build as soon as possible so that we can get them resolved for the final release.  The team plans to carefully monitor feedback over the next few weeks, and assuming no big issues come up ship the official V1 build next month.

Hope this helps,

Scott

ASP.NET MVC 1.0 Release Candidate Now Available
ScottGu
Tue, 27 Jan 2009 20:13:09 GMT