Welcome to RHPConsulting.NET Sign in | Join | Help

Behavior Driven Development - BDD

I am very excited about a new design and testing methodology called BDD that I have been researching for a new project. The acronym means Behavior Driven Development, and the basic difference from good old TDD (Test Driven Depelopment) is that it changes the focus of the test from the programmers perspective to the business perspective. 

Behavior Driven Development (BDD) allows you to build automated tests to validate stories based on the business requirements and the scenarios that are extracted from these.  In my honest opinion this adds plenty of value to your testing strategy and its output which can now be used to directly validate the user acceptance criteria. 

A lot of you might be saying, can't I already do that in TDD? Yes, but the difference is now you have a standard way of describing stories and tasks around a common terminology that both you and the end user (business) will understand.
 
The following is a short list of resources on the topic:
- There is a nice video that Rob Connery published last night in the following url: http://blog.wekeroad.com/mvc-storefront/kona-3/
- Dan North's blog (http://dannorth.net/)
- Frameworks for BDD in .NET

Thank you for reading,

Roberto Hernandez

posted by rhernandez | 0 Comments
Filed Under: ,

Richmond Code Camp 2009.01 - Slides and Demo

The Richmond Code Camp was great, the venue was beautiful and inspiring (http://www.reynolds.edu/).  The organizers did a wonderful job, and I am really looking forward to the next Richmond Code Camp in August.

The slides and demo for my presentation as are attached to this post.  I will be writing additional posts in the near future about Validation and the ASP.NET MVC Framework.

Thank you for reading,

Roberto Hernández

Speaking at both the Ricmond Code Camp and Nova Code Camp

As you all know, I have a passion for sharing knowledge. I guess it is still hard wired in my brain from my old days as a full time MCT (Microsoft Certified Trainer) at Productivity Point International.   So in the spirit of sharing knowledge and preaching good practices I will be presenting at the Richmond Code Camp and the Nova Code Camp.  Registration is now open for both so make sure to keep the dates open in your calendar.

Dates
Richmond Code Camp - 25-April-2009
Nova Code Camp - 23-May-2009


Thank you for Reading,

Roberto Hernández



posted by rhernandez | 0 Comments

ASP.NET MVC 1.0 Released!!!

I am very excited to announce that Microsoft has officially released the RTM version of the ASP.NET MVC Framework during the Mix'09 developer's conference.  Make sure to download as soon as possible, and welcome to the ASP.NET MVC Framework generation.

Thank you for Reading,

Roberto Hernandez


Additional Links
(Download) http://www.microsoft.com/downloads/details.aspx?FamilyID=53289097-73ce-43bf-b6a6-35e00103cb4b&displaylang=en
(Official Website) http://www.asp.net/mvc
posted by rhernandez | 0 Comments

Extension Method Solution for adding Security Trimming to a SiteMapCollection

Yes, I know what everybody is thinking right now, Don't SiteMaps already provide functionality for Security Trimming?   Well they do and they don't.  This functionality is available only if you are using an implementation of the ASP.NET MembershipProvider and RoleProvider.  In the applications that I have to work with in a day to day basis that is rarely the case, I always have to develop a custom security provider using forms or windows authentication that support some far fetched business requirements.   I still however love to use SiteMaps and have rarely seen the need to customize the base SiteMap provider for any other reason.    So, in order to have security trimming and still use and bind the information from my SiteMap I wrote the following block of code that just begged to be re-factored.

Exhibit A - Code that needs (begs) for refactoring.

    1                 // do security trimming.

    2                 List<SiteMapNode> nodes = new List<SiteMapNode>();

    3                 foreach (SiteMapNode node in SiteMap.RootNode.ChildNodes)

    4                 {

    5                     if (node.Roles.Count == 0)

    6                     {

    7                         // just add.

    8                         nodes.Add(node);

    9                         // continue loop.

   10                         continue;

   11                     }

   12                     else

   13                     {

   14                         // validate security.

   15                         foreach (var role in node.Roles)

   16                         {

   17                             if (this.Page.User.IsInRole(role.ToString()))

   18                             {

   19                                 nodes.Add(node);

   20                                 break;

   21                             }

   22                         }

   23                     }

   24                 }

   25 

   26                 // return list.

   27                 this.ListViewTopMenu.DataSource = SiteMap.RootNode.ChildNodes;

   28                 this.ListViewTopMenu.DataBind();


I decided that, because I was going to need to reuse this functionality in several places and I wanted to avoid creating a class that would perform this task specifically,  that I should add a new method to the SiteMapCollection class using a C# 3.0 Extension Method. 

Step 1 - Extension Method

    1 public static class SiteMapNodeCollectionExtension

    2     {

    3         public static IList<SiteMapNode> FilterByRoles(this SiteMapNodeCollection nodeCollection, IPrincipal user)

    4         {

    5             // collection used to store array values to return to browser.

    6             List<SiteMapNode> nodes = new List<SiteMapNode>();

    7 

    8             // iterate through the node collection to return the valid nodes.

    9             foreach (SiteMapNode node in nodeCollection)

   10             {

   11                 if (node.Roles.Count == 0)

   12                 {

   13                     // just add.

   14                     nodes.Add(node);

   15                     // continue loop.

   16                     continue;

   17                 }

   18                 else

   19                 {

   20                     // validate security.

   21                     foreach (var role in node.Roles)

   22                     {

   23                         if (user.IsInRole(role.ToString()))

   24                         {

   25                             // add to collection.

   26                             nodes.Add(node);

   27                             // break from for-each loop.

   28                             break;

   29                         }

   30                     }

   31                 }

   32             }

   33 

   34             // return array of information.

   35             return nodes;

   36         }

   37     }

 

This blog is not intended to be a tutorial, but I would like to point out the facts that C# Extension methods have to be defined in a static class as a static method and the first parameter must be the class to be extended (Notice the use of the 'this' keyword on the fist parameter).

Step 2 - Refactoring of the client code.

    1                 // return list.

    2                 this.ListViewTopMenu.DataSource = SiteMap.RootNode.ChildNodes.FilterByRoles(this.Page.User);

    3                 this.ListViewTopMenu.DataBind();

Thank you for reading,

Roberto Hernandez

Interesting Caching Abstraction Solution - .NET 3.5

Today, as I was writing the frontend to an ASP.NET web application I noticed a trend in my code.  I had the following block of code in one form or another in several places. 

    1         protected string MemberFullName()

    2         {

    3 

    4 

    5             // build the cache key.

    6             string cacheKey = string.Format("Member@FullName@{0}"

    7                 , this.Page.User.Identity.Name);

    8 

    9             // build cache entry.

   10             if (this.Cache[cacheKey] == null)

   11             {

   12                 // get membership service.

   13                 var membershipService = DependencyFactory.MembershipService();

   14 

   15                 // get member.

   16                 var member = membershipService.MemberGetByUsername(this.Page.User.Identity.Name);

   17 

   18                 // get full name.

   19                 string fullName = string.Format("{0}, {1}", member.Lastname, member.Firstname);

   20 

   21                 // add to cache.

   22                 this.Cache.Insert(cacheKey, fullName, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero);

   23             }

   24 

   25             // return value.

   26             return (string)this.Cache[cacheKey];

   27 

   28         }

 
Immediately I decided to address the issues that could arise from letting this behavior continue. First of all, I wanted to decouple the direct dependency to the ASP.NET Caching implementation, that way if in the future I decided to cache using another provider I would be able to make the switch without huge problems. I also wanted to use some of the cool features that have been available since the release of the .NET 3.0 Framework like Lambdas, and some oldies but goodies, like Generics and Anonymous Methods.

Step 1 - I coded a basic enum to use as the type of information to be cached.

    1     public enum CacheKey

    2     {

    3         MembershipRolesByUsername,

    4         MembershipFullNameByUsername,

    5     }


Step 2 -  I built the following interface that will provide the abstraction.

    1     interface ICacheProvider<T>

    2     {

    3         T GetItemFromCache(CacheKey type, string key, int minutes, Func<T> builderFunction);

    4     }


Generics is used to add flexibility to the Cache provider while retaining the elegance and compile time advantages of strongly typed code. It has a couple of parameters but the one that should really catch your eye is the builderFunction (Func<T>) which allows us to pass in the function used to create the item to cache by using a Lambda expression or an Anonymous Method.

Step 3 - Implement the cache provider.

    1     public class CacheProvider<T> : ICacheProvider<T>

    2     {

    3         #region ICacheProvider Members

    4 

    5         public T GetItemFromCache(CacheKey type, string key, int minutes, Func<T> builderFunction)

    6         {

    7             // build the cache key.

    8             string cacheKey = string.Format(string.Concat(type.ToString(), "{0}"), key);

    9 

   10             // get current cache.

   11             var context = HttpContext.Current;

   12 

   13             // build cache entry.

   14             if (context.Cache[cacheKey] == null)   

   15                 context.Cache.Insert(cacheKey, builderFunction.Invoke(), null, DateTime.Now.AddMinutes(minutes), TimeSpan.Zero);

   16 

   17             // return value.

   18             return (T)context.Cache[cacheKey];

   19         }

   20 

   21         #endregion

   22     }


Nothing real fancy to explain here, the only thing I would point out is that the function to build the item doesn't get called if the item is already in the cache which is the whole point of caching.

Step 4 - Use the Cache provider
Option A - With an anonymous method.

    1             // anonymous function.

    2             Func<string> memberFullNameFunction = delegate()

    3             {

    4                 var member = DependencyFactory.MembershipService().MemberGetByUsername(this.Page.User.Identity.Name);

    5                 return string.Format("{0},{1}", member.Lastname, member.Firstname);

    6             };

    7 

    8             // return value.

    9             return new CacheProvider<string>().GetItemFromCache(CacheKey.MembershipFullNameByUsername

   10                 , this.Page.User.Identity.Name

   11                 , 5

   12                 , memberFullNameFunction);


Option B - With a Lambda Expression

    1             // return value.

    2             return new CacheProvider<string>()

    3                 .GetItemFromCache(CacheKey.MembershipFullNameByUsername

    4                     , this.Page.User.Identity.Name

    5                     , 5

    6                     , ()  => 

    7                         {

    8                             var member = DependencyFactory.MembershipService().MemberGetByUsername(this.Page.User.Identity.Name);

    9                             return string.Format("{0},{1}", member.Lastname, member.Firstname);

   10                         });


Depending on personal taste I guess one way of calling the provider might seem simpler than the other.

Thanks for reading,

Roberto Hernandez

posted by rhernandez | 0 Comments
Filed Under: ,

Ramblings on ASP.NET MVC - A new start!

The following is a link to a free PDF book chapter on ASP.NET MVC.  It is no secret that I am a big fan of ASP.NET MVC and I believe that it is one of the key new technologies that we should all be looking into sooner rather than later.

http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx

The following is a list of my personal beliefs regarding ASP.NET MVC and how I think it currently affects my day to day decisions as an application architect and developer.

  • I believe it is easier to code with a strict separation of concerns using the ASP.NET MVC Framework.
    • Duh! It is one of the goals of the MVC Pattern, but I still think it should be mentioned since this makes ASP.NET MVC the appropriate technology to use when working with multi-tiered enterprise applications.
  • I believe it is easier to develop a Web 2.0 application using the ASP.NET MVC Framework.
    • No viewstate, and strange ASP.NET WebForms control renderings that get in the way of using current web standards and top of the line AJAX frameworks like jquery, extjs, yui, and prototype.
  • I believe it is easier to implement, and manage security in an ASP.NET MVC application.
    • There is less exposure as security is managed at the controller method instead of the .aspx page.
    • Implementing security trimming as an attribute rocks!! It is not a new idea by any means, but it should be noted that it provides you with the ability to move your security configuration out of the Web.Config file without having to go code crazy.
  • I don’t believe ASP.NET MVC is an environment for building RAD applications.  So for small/medium projects and applications that are less prone to change over time, I would still recommend using ASP.NET WebForms.
    Warning: I reserve the right to change my mind in the near future.
    • No current UI designer support.
    • No existing third party controls available.
    • No need to be an Architecture Astronaut.
    • Exception: If you are building a RIA application it makes perfect sense to use ASP.NET MVC as you JSON web services tier and you can use any third party controls developed for your presentation tier technology (Silverlight, Flex, Flash, Air, Ajax, etc.) while still maintaining a solid architecture.

Have fun reading the book,

Roberto Hernandez

posted by rhernandez | 1 Comments
Filed Under: ,

Extending a Virtual Hard Disk - Extendiendo un Disco Virtual

I was playing around with Windows Server 2008, and Team Foundation Server in a Virtual Machine (VirtualPC 2007 SP1) environment when the darndest thing happened, I ran out of disk space in the virtual hard drive.  My first reaction was, "ok let's start from a scratch", but honestly, I just don't have the time to do so.  The project that I am currently working on has deadlines, and I'm a father of two beautiful daughters who deserve my time.  Therefore, I can't be investing much time in this R&D task. 

I decided to hit the Google Machine for information, and I found this link that solved all my problems. One thing that I didn't like about the original blogger's post was that it did not provide detailed step-by-step instructions on how to use both the tool provided by the vmToolKit website or the DiskPart utility.   Having said that, the following is a step by step on how to deal with this issue:

1. - Download the VHDResizer tool from the vmToolKit website. 
2. - Use VHDResizer to create a sector by sector copy of the original VHD while changing the VHD Size.  Important: this will not resize the partition on that drive, it will only give you additional disk space on the VHD so that can be use the Diskpart utility to extend the partition.
3. - Add the new VHD file to you're existing Virtual Machine.  Important: do not remove the existing VHD, what you want to do is add the new VHD drive so you can boot up with you're existing configuration and use the DiskPart utility to expand that drive.  This step is needed because of limitations built in to the DiskPart utility. The Diskpart utility will not extend a system or boot partition.
4. - Boot up the VM and execute the following commands from an command console.  Important: X is the volume number for the drive you want to extend.
        C:\>DiskPart
        DISKPART> LIST VOLUME
        DISKPART> SELECT VOLUME X
        DISKPART> EXTEND
        DISKPART> EXIT
5. - Shutdown you're VM, and change settings so that from now on it boots from the new VHD that has all the available you neede.

Thanks/Regards,
_____________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE


Estaba jugando con Windows Server 2008, y Team Foundation Server en una máquina virtual (VirtualPC 2007 SP1) cuando me sucedió lo  menos esperado, se me acabó el espacio en el disco virtual. Mi primera reacción fue, "vamos a comenzar desde cero", pero sinceramente no tengo el tiempo que se le necesita dedicar. El proyecto en que estoy trabajando actualmente tiene fechas de entrega y, adicionalmente soy el padre de dos hermosas niñas que merecen de mi tiempo. En otras palabras, no puedo dedicarle tanto tiempo a un proyecto de investigación y desarrollo.

Decidí ahorrarme un poco de tiempo usando el fabuloso Google, que me trajo al siguiente vínculo que honestamente resolvió todos mis problemas.  Pero, una cosa que no me gustó de la publicación original es que no provee instrucciones paso a paso de como utilizar las herramientas que nos facilita el vmToolKit y DiskPart. Habiendo establecido esto, la siguiente es una lista de instrucciones que explica paso a paso como solucionar el problema:

1. - Descargue la herramienta VHDResizer del sitio en internet vmToolKit. 
2. - Utilice el VHDResizer para crear una copia sector por sector del disco original, especificando el nuevo tamaño del disco.  Importante: esta operación no cambia el tamaño de la partición, solo le agrega el espacio al disco virtual nuevo para utilizar Diskpart y asignarle el nuevo espacio disponible.
3. - Añadir el nuevo disco virtual a la máquina virtual.  Importante: no remueva el disco original, lo que debe hacer es añadirlo como un nuevo disco para poder encender la maquina virtual y utilizar la herramienta Diskpart para extender el tamaño del disco.  Este paso es necesario por limitaciones existentes en la herramienta, Diskpart no permite extender particiones 'system' or 'boot'.
4. - Encienda la máquina virtual y ejecute los siguientes comandos en una consola del sistema operativo. Importante: X es el número del volumen nuevo que usted quiere extender.
        C:\>DiskPart
        DISKPART> LIST VOLUME
        DISKPART> SELECT VOLUME X
        DISKPART> EXTEND
        DISKPART> EXIT
5. - Apague la máquina virtual, y cambie la configuración para poder correr desde la nueva partición que ahora tiene todo el espacio que usted necesita.

Gracias/Disfruten,
_____________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE

posted by rhernandez | 0 Comments

Silverlight 1.0 (RC) - Surface Demo

Hi Everybody,

One of my favorite demos of Silverlight 1.1 Alpha (Currently Silverlight 2.0) has always been the Surface demo (click here). Having said that it has always been frustrating for me that this demo was only available for the Managed Code version of Silverlight.   So, I took it as a task to make this demo available and downloadable for the Silverlight 1.0 RC crowd.

So, without any delays,

Click here to view and here to download.

Thank you,
_____________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE


Saludos!!!

De las demostraciones de Silverlight 1.1 Alpha (actualmente Silverlight 2.0) que he visto la favorita siempre ha sido el "Silverlight Surface" (click here). Habiendo dicho eso, siempre me ha molestado que esta demostración solo este disponible para codigo manejado.  Obviamente, me decidi a escribir esta demostración para Javascript y Silverlight 1.0 RC.

Entonces, sin más retrasos,

Dele aqui para  visualizar y aqui para descargar.

Gracias,
_____________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE -

posted by rhernandez | 0 Comments
Filed Under: , ,

Silverlight 1.0 (RC) - Scrolling Barchart - Silverlight does have a place in business applications!!!!

Hi Everybody,

One of the more frequent questions regarding Silverlight is:

Does it add any value to traditional business applications?  

My quick reply to this question has always been:

Of course, Silverlight as well as any other fancy user interface/rich content technology can be used to enhance the value of any business aplication by providing a better presentation for critical business information. 

In fact, if you do some research on the web, there are many companies currently building web controls for Silverlight that fall into the business application niche.  Also, some of the recent demos that have been published are all business related, like the Jelly Demo that shows how easy it is to design an animated bar chart, pie chart, and line chart using plain old XAML. 

As I commonly do with the demos that I like, I went ahead and decided to enhance it. Obviously the first order of business was to add functionality to it so that can render live information being gathered from a webservice.  Additionaly, I added functionality so it could scroll, like a stock market index ticker, and provide real time data to the user.

So, without further delays, you can use the following link to download and view the new demo.

Click here to view and here to download.

Thank you,
_____________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE - Plus Father of Two
"Execution is the key to success!!!!!"


Saludos a Todos!

Una de las preguntas mas frecuentes sobre Silverlight es:

Es Silverlight una tecnologia que le probee valor a las aplicaciones de negocio?  

Mi respuesta rapida siempre ha sido:

Claro!!! Silverlight, al igual que toda tecnologia de desarrollo de interfaces de usuario ricas, puede ser utilizada para agregarle valor a las aplicaciones de negocio, mediante la implementación de una mejor presentación de la información crítica que las mismas exponen.

Expandiendo sobre el mismo tema, si se fijan hoy en día en el internet, ya existen muchas companias que estan desarrollando controles para aplicaciones de negocio utilizando Silverlight.  Adicionalmente, mucho de los demos que estan siendo presentados son relacionados a aplicaciones de negocio, como el Jelly Demo que nos demuestra que tan sencillo es implementar una grafica animada de barras, pastel y linea utilizando solamente XAML. 

Como ya habran notado en mi blog, a mi me encanta re-estructurar y hacer más ricas las demostraciones que encuentro que pueden ser productivas en las aplicaciones que diseño en el día a día.  En esta caso expandí la funcionalidad actual de la demostracion para poder utilizar información extraida dinamicamente de un servicio web, así como le añadi la funcionalidad de ir presentando la data en tiempo real.

Sin retrasarles mas el tema les doy los siguientes vinculos:

Dele aqui para visualizar ó aquí descargar.

Gracias,
_____________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE - Plus Father of Two
"La Ejecución es la clave del exito!!!!!"

 

posted by rhernandez | 0 Comments
Filed Under: ,

Webcast - Consumiendo Servicios Web utilizando AJAX ASP.NET 1.0 Extensions

Anexo el código fuente de las demostraciones presentadas durante el webcast - Consumiendo Servicios Web utilizando AJAX ASP.NET 1.0 Extensions.

Para aquellos que no tuvieron la oportunidad de verlo en vivo, presionen aquí.

___________________________________________________________________


Attached is the source code for the demos that I did during the webcast - Using Web Services with AJAX ASP.NET 1.0 Extensions.
____________________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE - Plus Father of Two
"Execution is the key to success!!!!!"




posted by rhernandez | 0 Comments
Filed Under: ,
Attachment(s): AJAX.WebServices.Demos.zip

Scott Guthrie's August Links

My humble blog just got listed on Scott Guthrie's Ausgust Links as an interesting Silverlight Resource. Thank you Scott!!!!!

Follow this link.
____________________________________________________________________
Mi humilde blog acaba de ser mencionado por Scott Guthrie's como un link interesante para información de Silverlight.  Gracias mil Scott!!!!

Presione aquí.
____________________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE - Plus Father of Two
"Execution is the key to success!!!!!"


posted by rhernandez | 0 Comments

Silverlight Drag and Drop Javascript Class - RC

Este articulo busca presentar los beneficios de la programación Javascript orientada a objectos para diseñar aplicaciones Silverlight.   Este articulo no es una introducción a Silverlight, XAML, ó Javascript.  Para una introducción a Silverlight y sus diferentes modelos de programación les exhorto a que visiten el sitio de comunidad de Silverlight de Microsoft.

Problema
La implementación de la funcionalidad 'Drag and Drop' es una de la manera mas sencilla en la que se puede mejorar una aplicación básica Silverlight 1.0 RC. Microsoft nos describe el proceso de implementación paso a paso en MSDN (presione aquí). Sin embargo, cuando se comienza a desarrollar una interfaz de usuario relativamente compleja en Silverlight, uno nota que va a tener que re-escribir todo este código para cada uno de los elementos que componen la interfaz de usuario que requieran esta funcionalidad. 

Solución
Javascript nos permite diseñar codigo re-utilizable utilizando tecnicas de programación orientada a objetos.  Nuestro objetivo es re-factorizar todo el codigo relacionado al proceso de 'Drag and Drop' en un componente re-utilizable una clase en javascript.

Acción
Comencemos por describir los elementos del XAML que vamos a mejorar mediante la implementación del 'Drag and Drop'.  Como puede ver en la siguiente imagen, el XAML consiste de dos diferentes elementos un rectangulo y un "TextBlock" que colocados uno encima de otro dan la apariencia de un "Label". Adicionalmente, tenemos un rectangulo adicional que servira como punto de inicio del proceso de "Drag and Drop".

 

Visualización del XAML:

Si quisieramos implementar "Drag and Drop" utilizando las técnicas descritas en MSDN, tendriamos que manejar los siguientes eventos:

1.    MouseLeftButtonDown: Utilizando el captureMouse method para obtener acceso exclusivo a todos los eventos relacionados al mouse. Adicionalmente, persistir la posición original del mouse.  Finalmente, habilitar una variable booleana (flag) que marque el inicio del proceso de drageo.

2.   MouseMove: Utilizar la posición original  del mouse y la nueva para relocalizar el elemento dentro de su contenedor.  Adicionalmente, persistir la posición actual del mouse como la original.

3.    MouseLeftButtonUp: Soltar el control exclusivo de los eventos del Mouse utilizando el metodo releaseMouseCapture.  Finalmente, pasar un valor de falso a la variable que marca el inicio del proceso de drageo.

El siguiente es el código,

Nuevamente, este proceso es relativamente sencillo,  pero si quisieramos añadir esta misma funcionalidad a elementos adicionales, encontrariamos que tendriamos que reescribir todo el código una y otra vez para cada elemento nuevo.  Esto obviamente es una señal clara que que se debe re-factorizarse inteligentemente el código actual. 

Después de un poco de trabajo el resultado de re-factorización, y encapsulación produjo el siguiente código. 

Esta clase Javascript resuelve dos problemas que se presentan en el desarrollo de aplicaciones Silverlight:

1.- Permite a desarrolladores habilitar la funcionalidad de "Drag and Drop" con solo una ó dos lineas de código.
2.- Adicionalmente, provee metodos adicionales para calcular las posición absoluta, o en otras palabras, la posición con relación al Canvas que es el elemento raiz del Xaml.

El siguiente código nos permite visualizar la funcionalidad implementada.

Se puede bajar el código incluido en este posteo. O pueden navegar los ejemplos en linea RHPConsulting.NET Silverlight Demos.

Gracias por leer,

____________________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE - Plus Father of Two
"Execution is the key to success

__________________________________________________________________

This article is meant to show the benefits of sound Javascript programming with your Silverlight Applications. It is not an introduction to Silverlight, XAML or Javascript. For an introduction to Silverlight, and its programming object model visit the Silverlight quickstarts.

Problem
Drag and Drop interaction is one of the simplest ways you can improve your basic Silverlight 1.0 RC application. Microsoft has a great sample on MSDN, that shows you how to implement it step by step (click here). However, once you start building a fairly complex Silverlight user interface, you come to the realization that you’re going to have to re-write this code over and over again for every single element on your canvas that you're going to want to enable drag and drop functionality for.

Solution
Javascript allows us to design re-usable code using object oriented techniques. So our goal should be to re-factor all code related to the dragging and dropping interaction into a re-usable javascript class.

Action
Lets start by describing the elements of a simple XAML file that we will be enabling drag and drop functionality for.  As you can see in the following code snippet, the xaml has two visual elements defined within it, a rectangle and a textblock that is layered on top of the rectangle, giving the illusion of a fancy label. Additionally, there is a small rectangle that we will be using as a handle where users will click to start the dragging process.

 

Rendering of XAML:

If we wanted to enable simple drag and drop functionality for this item (as described in MSDN).  We would have to handle the following events, in order to perform the following tasks:

1.    MouseLeftButtonDown: Use captureMouse method to capture all mouse related events to the element that fired the event. Additionally, persist original mouse coordinates.  Finally, set flag to enable dragging.

2.   MouseMove: Using original persisted coordinates relocate element to new location within its container.  Additionally, persist current mouse coordinates as original.

3.    MouseLeftButtonUp: Release exclusive mouse event handling using releaseMouseCapture method.  Finally, set flag to disable dragging.

See the following snippet.

And again this a fairly simple operation but what if we wanted to add a second, or third element, in the Silverlight user interface that required additional  drag and drop functionality. If we follow the current code pattern we would have to add additional handlers in the handleLoad method, and additional methods for every single element. For anybody who’s been involved in programming for more than 24 hours, this should be an obvious sign that some smart re-factoring needs to be done. 

So I started refactoring and adding additional functionality to the original MSDN sample, and I came up with the following Javascript Class. 

This Javascript Class solves two problems when developing Silverligth Aplications:

1.- It allows the programmer to enable drag and drop functionality to any Silverlight user interface element with just a couple of lines of code.
2.- It also provides helper methods to determine the Canvas.Top, Canvas.Left coordinates of any element related to its parents container (usually a Canvas), or to the Silvelight Host control.  

The following is a code snippet for enabling drag and drop functionality for the original xaml user interface in the top of this post.

You can download all the code included in this post by downloading a VisualStudio 2005 Solution and Projects that is attached to this post.  Additionaly, you can browse the samples online at RHPConsulting.NET Silverlight Demos.

Thank you for reading,

____________________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE - Plus Father of Two
"Execution is the key to success

posted by rhernandez | 23 Comments
Filed Under: ,
Attachment(s): Silverlight.DragDropExtender.zip

News for Latin America - Noticias Latino America

I have received word from my friend Ricardo Jimenez of a new web design contest, in light of the product launch of the Expression Products.   There are going to be 10 different prizes for 3 categories:

- Web Design
- Interactive Content Design.
- Graphics Design.

For more information here.


He recibido noticias de mi amigo Ricardo Jimenez sobre un nuevo concurso de diseño en vispera del lazamiento de los nuevos productos Expression.  Se repartiran 10 premios en 3 diferentes categorias como pueden observar en la siguiente publicidad del curso.

Las categorias son:

- Diseño Web
- Diseño Interactivo
- Diseño Gráfico

Para mas información aquí.

____________________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE - Plus Father of Two
"Execution is the key to success!!!!!"

 

posted by rhernandez | 0 Comments
Filed Under:

TAMPA CODE CAMP - 2007

I had the pleasure of being invited, by my good friend Jose Luis Manners, to participate as a speaker on Silverlight at the Tampa Code Camp.  There are many words I could probably use to describe the event, but only amazing comes to mind.  The venue for the event, the St. Petersburgh College EpiCenter its beautiful and extremely high tech, and the people who attended the event were extremely enthusiastic about technology.  Also, did I mention it was free to the public!!!!

I would certainly like to extend my gratitude to Keith Kabza, and Jose Luis Manners they organized an amazing event for the Tampa Community, I am privileged to have been a part of it.

I will be discussing some of the information I presented during the code camp online on this blog.  Oh and by the way the Sessions that I took part of as a speaker were,

Introduction to Silverlight (60 Participants) - A basic introduction to Silverlight and all the technologies that come together to make it happen.  Additionaly, I introduced the topic of programming Silverlight applicactions using Javascript and the 1.0 Beta Release.

Silverlight 1.1 Alpha Custom Control Development (35 Participants) - Introduction to developing custom controls using Silvlight 1.1 Aplha and Managed Code.  

Thanks for reading,




Tuve el placer de ser invitado a participar como presentador de Silverlight, por mi buen amigo Jose Luis Manners, en el 
Tampa Code Camp.  Hay muchas palabras que yo pudiera utilizar para describir el evento, pero solo increíble me viene a la mente.  Las facilidades utilizadas para el evento, el St. Petersburgh College EpiCenter,  son hermosas y poseen lo ultimo en tecnología de audio visuales.  Adicionalmente, la gente que participo en el evento son extremamente entusiasta acerca de la tecnología.  No se me puede olvidar de mencionar que el evento era gratis para los participantes!!!

Debo agradecer a Keith Kabza, y Jose Luis Manners que organizaron un evento maravilloso para la comunidad de Tampa. Para mi definitivamente fue un privilegio haber participado.

Los temas que trate en la conferencia voy a escribir sobre ellos mas adelante en mi blog, y son:

Introducción a Silverlight (60 Participantes) -  Una introduccion basica de Silverlight y todas las tecnologias que la componen.  Asi mismo,  programación con Silverlight utilizando Javascript y el Release 1.0 Beta.

Desarrollo de Controles Personalizados utilizando Silverlight 1.1  (35 Participantes) - Introducción al desarrollo de controles personalizados utilizando Silvlight 1.1 Aplha y código manejado. 



Gracias por leer,

____________________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE - Plus Father of Two
"Execution is the key to success!!!!!"

posted by rhernandez | 0 Comments
Filed Under: ,
More Posts Next page »