These days we are seeing the dawn of a new computing generation, that is the 5th generation of computing. The first one were monolithic applications, then came the Client-Server and tiered applications, and currently we are building Web-based and SOA applications, today, the new buzzwords are Services and Cloud computing.
The past week, on PDC (Professional Developers Conference) event, Microsoft announced Windows Azure, a big initiative on the new computing generation. Windows Azure is a “cloud services operating system”, this is, a platform for developing, hosting and managing applications and services in the cloud. Being in the cloud, means that it is hosted on and available from internet, in this case, the hosting service is provided by Microsoft’s datacenters.
But that is not all, Windows Azure is just the lowest level of the Azure Services Platform, this platform includes several services running over Windows Azure, like:

Being part of this extraordinary family that we call Southworks, gave me the opportunity to learnt about these new technologies and participate in the development of a new set of Hands-On Labs about Azure Services Platform for the PDC event. For downloading this HOL go to: Azure Services Training Kit - PDC Preview.
For further reading:
It’s awesome how fast time goes, a year ago, I was playing with .bat files (like putting messages in the autoexec.bat file), a month ago, I was building applications to do my accounting homework at highschool using C++ Builder, a week ago, I was making simple games with Visual Basic 6 and then working with the same tool, yesterday, I was trying to learn the big .NET Framework 1.1 and fighting against ADO.NET (20 lines to do the same thing that I used to do with three lines in ADO 6!), an hour ago, I was building ASP.NET 2.0 web sites and envying the toys from the RoR and J2EE guys, now, a minute ago, I helped to create the Training Kit for the .NET Framework 3.5 SP1 that seconds ago was released the final version.
A bunch of exiting things are included in the .NET Framework SP1 like:
You can get the bits at:
When you build data centric web applications, a big part of the code is related to the implementation of CRUD (Create, Read, Updated, Delete) operations. Scaffolding is a mechanism to generate fully functional data driven applications based on metadata inferred from a model, basically, all the CRUD operations are implemented by using the metadata obtained for each entity/table in the model, making it a very useful tool for prototyping.
That is what ASP.Net Dynamic Data does, it is a scaffolding technology that uses templates (ASP.Net Web Pages) to dynamically generate functional CRUD pages. Like Ruby on Rails, Dynamic Data makes a high use of conventions to infer how the results will be rendered, but it can be highly customized in an really easy way by adding metadata to the model or modifying/adding templates. This allows to start with a raw prototype and continue customizing and tuning it ’till a mature application.
Once you got the bits installed, you are able to create a new project using one of these two templates:
The main difference between both, is the data model that Dynamic Data will use as data source and to infer the metadata needed to do the scaffolding.
As said before, the data model can be LINQ to SQL or Entity Data Model depending on the project type selected.
While LINQ to SQL is tightly bound to the database schema (each property is bound to a specific field in a table), Entity Framework is more flexible and loosely coupled and you can query for entities using either LINQ or Entity-SQL.
When creating the data model is recommendable to create a Model folder to place the data model file (.dbml or .edmx) and the additional classes that we will create through the development to enhance the metadata.
This is the easiest thing, to enable the scaffolding you just need to modify a simple line of code.
In the global.asax.cs file is a method named RegisterRoutes where you will find a big section of commented description on how to register a data context to be used as the model to generate the scaffolds.
To enable scaffolding for all the classes/tables in the data model, you need to register the model in this way: (un-comment the following line and modify the bold parts)
model.RegisterContext(typeof(Model.MyDataModelContext), new ContextConfiguration() { ScaffoldAllTables = true });
Just modifying the previous line your application is ready to run, just press F5 and enjoy the magic!
If you want to generate scaffolds for specific classes/tables you have to set the ScaffoldAllTables property to false and then decorate the classes you want to scaffold with the [Scaffold(true)] attribute.

The generated scaffolds have all the common functions of a data-driven application, the list are filtered, sorted and paged, the fields in the edit and insert forms are validated according to its data types, etc., but it only does the best it can with all the metadata that can retrieve from the data model, therefore you will find that many things that can be improved or refined.
To add metadata to the model, Dynamic Data provides a full set of attributes under the System.ComponentModel.DataAnnotations namespace to be applied to the classes in the data model. But instead of applying the attributes directly over the generated code of the model you have to create partial classes aimed just to add metadata to the model.
Here, we’ll face a problem since a partial class can not redefine a property, thus we won’t be able to add metadata to the properties. This problem is solved by using an inner class and associating it to the data model class with the MetadataType attribute.
The following is a sample of a data model class using an inner class to refine the model:
[MetadataType(typeof(ProductMetadata))]
public partial class Product
{
private class ProductMetadata
{
[StringLength(30)]
[Required(ErrorMessage = "Product name is required.")]
[DisplayName("Product Name")]
public object Name { get; set; }[Range(0, 10000, ErrorMessage = "Standard Cost should be between {1} and {2}.")]
public object Price { get; set; }
}
}
Since the inner class porpoise is to add meta data, the properties only need to match in name and not in type (in the sample, all the properties are of object type).
In this post by María Wenzel you will find a list with some of the attributes available: Dynamic Data Attributes.
Under the folder DynamicData you will find all the templates that Dynamic Data uses to generate the scaffolds. You can modify them to change the look and feel, or to add new functions for all the tables, but if you want to customize the templates for an specific table, you can, just follow these simple steps:![]()
Notice the use of conventions in this case that allows a friendly development experience. Dynamic Data will look for the templates, first under DynamicData\CustomPages\[TableToRender] and then under DynamicData\PageTemplates.
With ASP.NET Dynamic Data you can experience a nice development experience, it is easy to learn and to use. Some people may say that scaffolding is just for prototyping, I agree on that, but I found Dynamic Data very flexible and customizable, you may use it for a part of the application (where only CRUD operations are needed) and, for the rest of the application, continue developing as you are used to. Something that I noticed is a little of lack of performance, I think that it is caused by the use of reflection to get the metadata from the model. Anyway, it is a very interesting and nice framework that worth the try.
The .NET Framework 3.5 Client Profile is a lightweight subset of the full .NET Framework 3.5 aimed to be deployed in Client machines. Therefore, it only have the assemblies that are commonly used on client boxes and does not contains any server or development related assemblies.
This framework subset weight just 27Mb against the 200Mb of the full framework.
You can get the bits from here: Microsoft .NET Framework 3.5 Client Profile (BETA)
It’s pretty easy, if you have installed the Visual Studio 2008 SP1 in the project properties you will find a checkbox that allows to target your application to the Client Profile subset.
Visual Studio will verify all the references and will add an exclamation icon on the references that are not available for the client subset, also when building the project, warnings will be displayed for the unavailable assemblies.
If you got the beta version of the Visual Studio SP1 you have to take in mind that the subset list (Client.xml) that Visual Studio uses to validate the references is out of synch from the actually included assemblies (VS generate warnings for some assemblies that really are in the Client Profile). To solve this issue, you may find useful the Justin Van Patten’s blog post: .NET Framework Client Profile.
This post is aimed to be a quick abstract for all the new C# language constructs introduced with the version 3.0.
By using var keyword to define a local (does not work at class level) variable is not needed to define its type, the compiler will infer it.
Examples:
var i = 0;
var intArr = new[] { 0, 1, 2, 3 };
Object’s properties can be initialized when creating the object and also the collection items.
Examples:
TextBox txt = new TextBox() { Text = "John", Width = 200 };
List<string> colorspaces = new List<string> {"RGB", "CMYK", "GreyScale", "B/W"};
By combining the previous two features (Implicitly typed variables and Object initializers) you can create anonymous types (statically typed, with no name used in the code).
Example:
var guy = new { FirstName = "John", LastName = "Doe" };
Console.WriteLine(guy.FirstName);
You can create properties with no need for a private member to store its value.
Examples:
public string Name { get; set; }
//read-only property
public byte Age { get; private set; }
By using the this keyword in a static method argument you can extend another class. You "injects" methods to an existing class from another one.
Example:
public static class ExtensionClass
{
//Extension method
public static byte ToGray(this Color c)
{
return (byte)(0.3 * c.R + 0.59 * c.G + 0.11 * c.B);
}
}
byte pixelGray = Color.Green.ToGray();
Lambda expressions are like pretty simple functions that takes input parameters and evaluates an expression.
Syntax:
(input parameters) => expression
Examples:
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
Console.WriteLine(oddNumbers.ToString());
Func<int, int> duplicate = number => number * 2;
Console.WriteLine(duplicate.Invoke(2).ToString());
PostSharp is a great open-source tool that allows you to encapsulate the non-business logic in custom attributes. That’s the Aspect Oriented Programming paradigm main goal: the separation of concerns.
This tool heps you to free the business logic from the infrastructure code such as:
Your code will be cleaner than never.
…and why do I call it a “great tool”? Because, unlike other tools that uses reflection and other techniques that reduces performance, PostSharp works at MSIL level!. It generates MSIL code to be injected in your code at compilation time, in that way it supports any .NET language and get the best performance possible.
Furthermore, this tool is really easy to learn. You can quickly get started by using the basic features, follow this simple quick start:
The following example shows a simple PostSharp aspect to trace the execution of the methods marked with that attribute:
public class SimplestTraceAttribute : OnMethodBoundaryAspect
{
public override void OnEntry( MethodExecutionEventArgs eventArgs)
{
Trace.TraceInformation(“Entering {0}.”, eventArgs.Method);
Trace.Indent();
}
public override void OnExit( MethodExecutionEventArgs eventArgs)
{
Trace.Unindent();
Trace.TraceInformation(“Leaving {0}.”, eventArgs.Method);
}
}
…and it works like a charm!
The evidence:
Building the project:
Inspecting the binaries:
Results:
Enjoy it!
In this post I will describe the basics of MAF to quickly introduce this framework.
The Managed Add-In Framework is an Add-In architecture built on top of the .Net Framework aimed to address the following problems:
A MAF solution usually have seven types of projects:
For more details about contracts and adapters go to this post: PDC05 - Managed AddIn Framework (MAF)
As you can deduce from the next picture the Host only references to the Host View and the Add-In only references to the Add-In view, so, each part hast its own view of the contract. In this way, if there is a new contract, it’s just necessary create new adapters to allow forward and backward compatibility.

If you are thinking that it is too much effort to create so many projects I have good news for you, there is an Add-In for Visual Studio that generates the Add-In View, Add-In Adapter, Host View and the Host Adapter from the Contract project. You can find the add-in here: Pipeline Builder.
The first step to create a extensible host is to define a Contract. To do this you have to create a project with an Interface to define the functionalities that the host will expect from the add-ins. This interface have to derive from IContract and have to be marked with the AddInContract attribute. This is an example of an Contract:
using System;
using System.AddIn.Pipeline;
using System.AddIn.Contract;
namespace Contracts
{
[AddInContract]
public interface IHelloMAFContract : IContract
{
string SayHelloMAF();
}
}
Then you can generate the basic Adapters and Views for the Host and Add-Ins using the Pipeline Builder.
The projects in a MAF solution should follow a defined file structure, for the Contract project, a possible output directory can be: “..\output\Contracts\”. You can find more details about the directory requirements in this topic: Pipeline Development Requirements.
To create an Add-In, you just have to create a project with a class implementing the contract from the AddInView project and marked with the AddIn attribute. The following is an example AddIn implementation:
using System;
using System.AddIn;
using Contracts.AddInViews;
namespace AddInV1
{
[AddIn("AddInV1", Version="1.0.0.0")]
public class AddInV1 : IHelloMAF
{
public string SayHelloMAF()
{
return “Hello MAF!!”;
}
}
}
This project may be generated in the directory “..\Output\AddIns\AddInName\”.
To discover the available Add-Ins the host can obtain a list of tokens that represents all the available Add-Ins of a specific type in a specific location. These tokens contains the Add-Ins information such as name and version, with that information then the host can decide which Add-Ins activate.
This is a sample code snippet for discovering and activating add ins:
static void Main()
{
// In this sample we expect the AddIns and components to
// be installed in the current directory
String addInRoot = Environment.CurrentDirectory;
// Check to see if new AddIns have been installed
AddInStore.Rebuild(addInRoot);
// Look for Calculator AddIns in our root directory and
// store the results
Collection tokens =
AddInStore.FindAddIns(typeof(Calculator), addInRoot);
// Ask the user which AddIn they would like to use
AddInToken calcToken = ChooseCalculator(tokens);
// Activate the selected AddInToken in a new AppDomain set sandboxed
// in the internet zone
Calculator calculator = calcToken.Activate(AddInSecurityLevel.Internet);
// Run the read-eval-print loop
RunCalculator(calculator);
}
17 May
Posted by: jcisneros in: Enterprise Library, Patterns & Practices, SCSF, WCSF
The Enterprise Library 4.0 (May 2008) final release is now available to download. These are some of the new features in this version:
You can find more details about this release in Grigori's blog.
In addition, we have just published two How-To documents in the Web Clist Software Factory and Smart Client Software Factory websites that describes the steps required to update existing WCSF/SCSF solutions and create custom Guidance Packages to use the Enterprise Library 4.
You can find them here:
Continuando con el artículo de introducción a CAB, en este post voy a explicar los conceptos básicos de Smart Client Software Factory (SCSF), el proyecto que nos permite automatizar el desarrollo de aplicaciones compuestas usando CAB.
Si ya estuvieron haciendo pruebas con CAB se habrán dado cuenta de que se requiere mucho trabajo extra para crear los nuevos elementos como ser, Workitems, Presenters, Controllers, publicaciones y subscripciones a eventos y comandos, etc.. SCSF nos ofrece un conjunto de asistentes (recipes) y guías que nos ayudan a crear estos elementos en forma automatizada y empleando un diseño adecuado.
Básicamente, SCSF es un agregado para el Visual Studio que añade nuevos tipos de proyectos y asistentes para la creación automatizada de los elementos nombrados. SCSF también posee proyectos de ejemplos (Hands on Labs y Quickstarts) y documentación que nos guían en el aprendizaje e implementación de aplicaciones SCSF.
Si en este artículo encuentra alguna palabra que desconoce es probable que encuentre su definición en el Glosario de CAB en mi post anterior de Introducción a Composite UI Application Block.
Con SCSF se obtienen todos los beneficios del desarrollo de aplicaciones con CAB, y además:
Los proyectos que sean creados usando SCSF poseen en la misma solución un conjunto de clases que añaden nuevas funciones o que encapsulan los elementos originales de CAB. Los nuevos elementos y conceptos que se deben de tener en cuenta en SCSF son:
Nota: Es importante tener en cuenta que la siguiente lista es sólo de algunos de los conceptos más importantes introducidos por SCSF y por lo tanto deja de lado muchos conceptos de CAB que son de vital importancia y que requieren ser abordados previamente para un correcto entendimiento.
Cuando creamos un proyecto de SCSF, este nos crea una solución con varios proyectos listos para funcionar que se encuentran organizados en un conjunto de carpetas. Los proyectos iniciales que se
encuentran en la carpeta Infrastructure son proyectos básicos para el funcionamiento de la aplicación y que brindan los servicios sobre los que se construyen los demás módulos que componen la
aplicación. Dependiendo de la configuración que hayamos elegido en la recipe al momento de crear el proyecto, nuestra solución contendrá básicamente los siguientes proyectos:
Los siguientes pasos, una vez que ya tenemos la solución para comenzar a trabajar, son:
Si empleamos TDD, luego de crear cada módulo y antes de seguir con la implementación del módulo, debemos crear las pruebas y seguir con el proceso del desarrollo dirigido por pruebas.
Todas estas tareas pueden hacerse en forma automatizada usando las recipes que nos ofrece SCSF.
Una situación común en la gente que empieza con SCSF es preguntarse cuál es la forma en que se hace determinada cosa en SCSF, o dónde tengo que poner tal cosa o cuál es la forma correcta de hacer tal otra cosa. Ésta desorientación en los principiantes se puede deber a la gran cantidad de guías y lineamientos que ofrece SCSF para hacer las cosas, dando la sensación que en SCSF existe una forma específica de hacer cada tarea para que funcione.
En realidad, SCSF y CAB son una extensión de funcionalidades que nos ayuda a crear mejores aplicaciones siguiendo una limitada selección de prácticas recomendadas, pero no pretende ser la solución perfecta para todas las situaciones posibles.
En una aplicación SCSF se pueden implementar una cosa de mil formas distintas o como lo hacemos siempre en cualquier aplicación y va a funcionar sin demasiados problemas. SCSF sólo nos facilita realizar una limitada cantidad de tareas en una forma organizada.
Sin embargo, cuando somos ajenos a los patrones y prácticas que se utilizan en CAB/SCSF podemos seguir sin saberlo caminos que nos pueden llevar a encontrarnos con dificultados. A continuación sugiero algunos tips que considero pueden ayudar en esta toma de decisiones:
Pueden existir más recomendaciones, pero lo importante es conocer todos los elementos y herramientas que podamos tener a nuestro alcance y comprender bien cuál es el cometido de cada uno, de esta forma sabremos qué usar en cada escenario y cómo, logrando la combinación más conveniente.
En este post se pasaron por alto los detalles técnicos del uso de SCSF y que escapan al alcance de este post, para eso recomiendo seguir los Hands on Lab que son muy didácticos para el aprendizaje de este excelente framework.
28 Feb
Posted by: jcisneros in: AjGenesis Studio, SCSF
Con el fin de poner en práctica y adquirir experiencia sobre las cosas que fui aprendiendo en mi entrenamiento, me sugirieron que reescriba mi aplicación AjGenesisStudio usando Smart Client Software Factory, lo cual me pareció una buena idea y una oportunidad para lanzar una nueva versión con algo más de futuro, con esto me refiero a que la aplicación será más fácil de mantener y de añadir nuevas funcionalidades, cualquier persona que tenga algún conocimiento de SCSF podrá escribir nuevos módulos fácilmente.
AjGenesisStudio es un IDE que escribí hace unos meses que sirve para trabajar con el generador de código de Angel Lopez: “AjGenesis“, se podría pensar como algo similar al generador “MyGeneration” pero con las ventajas que ofrece el generador AjGenesis (y sin IntelliSense por ahora).
AjGenesisStudio es un IDE inspirado en Visual Studio por lo cual su apariencia y funciones serán muy similares.
Para el resaltado de sintaxis y la interfaz tipo “docking” se emplea el excelente componente open source “DotNetFireball“.
En esta etapa ya tengo diseñado y codificado la shell y los demás elementos y servicios de infraestructura.
El layout principal tiene un menú principal (MainMenu) el cuál debe ser extendido usando el UIExtensionSite “MenuExtension” (los nuevos menús se insertarán entre el menú View y Tools), la barra del menú principal ya posee ítems que son genéricos y que todos los módulos pueden extender (ver imagen). Luego posee una barra de herramientas (MainToolbar) y una barra de estado (MainStatus).
El shell tiene únicamente un Workspace: MainWorkspace, el cual es una implementación de IComposableWorkspace basado en el componente DockContainer de DotNetFireball. Este workspace usa un SmartPartInfo (DockableWindowSmartPartInfo) cuyo propósito es configurar el estado de la ventana (anclado, flotante, auto-ocultable, abajo, arriba, izquierda, derecha, etc). Este workspace se encuentra en el assembly Infrastructure.UI y deberá ser referenciado por los módulos de negocio que deseen mostrar vistas.
El menú archivo (FileMenu) puede ser extendido en 4 lugares:![]()
¿Por qué para extender el menú principal y el menú File hay que extender los elementos MenuExtension y FileMenuExtension respectivamente en lugar de extender directamente MainMenu o FileMenu? Esto ocurre porque se desea que los nuevos elementos se agreguen no al final si no en una posición determinada (entre el menú View y Tools para MainMenu y antes del Exit para FileMenu) y para lograr esto hay que usar un pequeño truco que consiste en insertar al final (luego de agregar los ítems básicos) un elemento no visible al menú en la posición deseada para que luego, los siguientes elementos sean agregados en la misma posición, pero hay que prestar atención al orden en que se agregan los nuevos elementos ya que serán añadidos por encima de los anteriores (al revés de lo normal). Pueden encontrar más información en el blog donde encontré la solución original: Workaround for Injecting menu items into CAB Shell MenuStrip.
Las opciones para edición se deben tratar de una forma particular para cumplir los siguientes dos requerimientos: cada botón (del MainToolbar) o ítem del menú (EditMenu) debe ser habilitado o deshabilitado según se pueda o no realizar la operación (ej. Paste sólo cuando hay algo en el clipboard), y cada función debe poder ser implementada por varios módulos (ej. el módulo Document para la edición del texto y el módulo Proyecto para la edición de los archivos y carpetas). Esto se puede resolver empleando comandos para cada función de edición asociados a los ítems y que estos comandos invoquen un evento individual para cada uno, de esta manera los módulos subscriben a los eventos y son responsables de ejecutar la operación de edición siempre que el usuario haya puesto el foco sobre la vista del módulo en cuestión. Los módulos también son responsables de actualizar el estado de activación de cada comando cada vez que alguna vista recibe el enfoque.
Los eventos a los que deben suscribirse los módulos que necesitan realizar operaciones de edición son los siguientes: EditCopy, EditCut, EditPaste, EditSelectAll, EditDelete, EditUndo, EditRedo, ShowFind, ShowReplace, ShowGoTo. Los comandos, que deben ser utilizados sólo para la activación de los items, tienen el mismo nombre (las constantes, el valor no es el mismo).
Por ahora tengo pensados 2 servicios de infraestructura, el primero, “ExtensionService“, tiene funciones para facilitar la extensión de los menú y las barras de herramienta. El otro, “LoggingService“, permite mostrar al usuario información de la ejecución de las operaciones, este servicio publica un evento al que deberá suscribirse el módulo que se encargue de mostrar resultados.
En los siguientes posts seguiré con el desarrollo de los módulos que compondrán la aplicación.