Welcome to RHPConsulting.NET Sign in | Join | Help

Presentation at Nova Code Camp - “Articulate your Data with FluentNHibernate”

As promised the code for my presentation at the Norhern Virgnia (Nova) Code Camp is attached.  For those of you who missed the presentation I will be presenting again later on this month at the CapArea.NET user's group.  I want to congratulate Jeff Schoolcraft and the rest of the organizers for a very successful code camp and hopefully we will get to do it again during the spring.

Download Code & PPT

If you attended my presentation please rate my presentation at SpeakerRate

Thanks for reading,

Roberto Hernández

posted by rhernandez | 1 Comments
Filed Under: ,

A lap around "Fluent Interfaces" in the .NET World!

As promised, I have attached the code and slides from my presentation at the Richmond Code Camp. I had a helluva of a time talking about Fluent Interfaces to a very interested crowd.  I want to thank again the organizers and event committee for inviting me to participate in this exciting event.

Download Code & PPT (10MB)

Thanks for reading,

Roberto Hernandez-Pou
posted by rhernandez | 0 Comments
Filed Under:

Busy October! Fluent October?

I am excited to announce that I will be speaking at the following venues during the month of October.

Richmond Code Camp - 10/3/2009 - "A Lap around Fluent Intefaces in the .NET world!"
Nova Code Camp - 10/10/2009 - "Articulate your Data with FluentNHibernate"
Caparea.NET - 10/27/2009 - "Articulate your Data with FluentNHibernate"

As always I want to thank the Code Camp, and Community organizers that grant me the privilege of participating in these events.

Thanks again!

Roberto Hernández-Pou
posted by rhernandez | 0 Comments

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
More Posts Next page »