Windows Azure: Everything in the cloud

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:

  • Live Services: allows to create rich applications to run on a variety of platforms and devices.
  • .NET Services: includes:
    • Service Bus: provides a secure, standards-based messaging infrastructure to communicate application components even across organizational boundaries.
    • Workflow Service: hosts and runs workflows on the clouds and provides specialized activities for communication using HTTP and Service Bus.
    • Access Control: integrates standards-based identity providers, including enterprise directories and web identity systems such as Windows Live ID.
  • SQL Services: Stores data in the cloud using ACE structure (Authority, Container, Entity), the entities are flexibles and you can access the data using several standards-based interfaces (SOAP, REST, …).

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:

ASP.Net Dynamic Data (Scaffolding with .net)

image 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.

Getting Started

Once you got the bits installed, you are able to create a new project using one of these two templates:

  • Dynamic Data Web Application: Creates a Dynamic Data web application using a LINQ to SQL data model to generate the scaffolds.
  • Dynamic Data Entities Web Application: Creates a Dynamic Data web application using a Entity Data Model (ADO.NET Entity Framework) to generate the scaffolds.

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.

The Data Model

image 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.

Enabling Scaffolding

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.

image

Adding Metadata

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.

Customizing the Templates

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:image

  1. Create a new folder with the name of the table you want to customize under the DynamicData\CustomPages.
  2. Copy from DynamicData\PageTemplates the aspx templates you want to customize (i.e. List.aspx) and paste in the new folder.
  3. Delete the code behind file of the new template (i.e. List.aspx.cs and List.aspx.designer.cs).
  4. Customize the new template at your desire and using all of your creativity.

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.

Conclusions

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.

.NET Framework 3.5 SP1 - Client Profile

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)

How do you ensure your project will work for the .Net Framework Client Profile?

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.

image

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.

image

image

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.

Technorati Profile

C# 3.0 new features

This post is aimed to be a quick abstract for all the new C# language constructs introduced with the version 3.0.

Implicitly typed local variables

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 and Collection Initializers

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"};

Anonymous types

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);

Automatically Implemented Properties

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; }

Extension methods

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

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());

AOP with PostSharp

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:

  • Transactions
  • Logging
  • Permissions / Security
  • Exceptions handling
  • Caching
  • Settings

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:

Resources:

Enjoy it!

Managed Add-In Framework

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:

  • Loading/Unloading
  • Sandboxing (Add-ins can be sandboxed to a particular security permission set)
  • Isolation (isolation boundary between the Host and the Add-ins)
  • Lifetime Management
  • Discovery
  • Activation
  • Backwards compatibility
  • Forwards compatibility
  • Isolation changes (moving from AppDomain to Process isolation boundaries)
  • Sharing (taking an add-in built for one application and running it in another)

A MAF solution usually have seven types of projects:

  • Host: The main application that supports extensibility and manages the add-ins.
  • Host View: Defines the functionalities that the host expects from the add-ins. The host will work against this view directly.
  • Host Side Adapter: This is the glue between the Host View and the Contract. It has adapter classes that are used to convert to and from the host views and the contracts.
  • Contract: The interfaces used to communicate between Host and Add-Ins.
  • Add-In Side Adapter: This is the glue between the Add-In View and the Contract. It has adapter classes that are used to convert to and from the Add-In views and the contracts.
  • Add-In View: Represents the Add-In view of the methods and object types used to communicate with the host.
  • Add-In: An assembly loaded by the host to extend functionalities.

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.

Creating a contract

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.

Creating an Add-In

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\”.

Discovering and activating the Add-Ins

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);
}

Further readings

The Enterprise Library 4.0 (May 2008) final release is now available to download. These are some of the new features in this version:

  • Visual Studio 2008 support
  • Integration with Unity
  • Windows Management Instrumentation (WMI) 2.0 support and improved instrumentation
  • Pluggable Cache Managers
  • Performance improvements
  • Bug fixes
  • …and more

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:

Smart Client Software Factory

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.

¿Qué nos ofrece SCSF?

Con SCSF se obtienen todos los beneficios del desarrollo de aplicaciones con CAB, y además:

  • Automatización de varias tareas del desarrollo de una aplicación CAB/SCSF.
  • Guías para las tareas que no pueden ser automatizadas.
  • Nuevos elementos que añaden y extienden las funcionalidades originales de CAB (ej. Entity Translator, Disconnected Service Agent, Action Catalog).
  • Ejemplos, documentación y muchos recursos para el aprendizaje.
  • Excelente soporte en el foro del proyecto en CodePlex.

Nuevos elementos

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.

  • Recipe: un asistente en el Visual Studio que nos automatiza la creación de algún elemento de CAB/SCSF.
  • WorkItemController: con SCSF en lugar de heredar nuestros WorkItems de la clase WorkItem podemos heredar de la clase abstracta WorkItemController, esta clase contiene un workitem asociado al cual podemos acceder por medio de la propiedad WorkItem. De esta forma, logramos una mejor separación de responsabilidades del WorkItem, que anteriormente actuaba como contenedor
    (Items, Services, WorkItems) y como lugar donde se colocaba la lógica de negocio de los casos de uso. Ahora el WorkItem sólo actúa como conteneder y nuestra clase que hereda de WorkItemController es el lugar donde colocamos la lógica de negocio.
  • ControlledWorkItem: es una clase genérica (debemos indicarle un WorkItemController) que nos ayuda a instanciar nuestro WorkItem que hereda de WorkItemController.
  • Business Module: es un proyecto (DLL) que contiene una unidad del negocio junto con sus vistas (ej. Módulos Clientes, Stock, Administración, etc.). Cada Business Module tienen un WorkItemController principal llamado ModuleController.
  • ModuleController: es una clase que hereda de WorkItemController que toma el papel de WorkItem raíz para el módulo de negocio. En esta clase es donde realizaremos gran parte de las
    tareas de inicialización del módulo (agregar vistas, añadir ítems a los extension sites, registrar servicios, etc.).
  • Fundational Module: al igual que un Business Module, es una DLL pero generalmente no poseen vistas y no tienen WorkItems. Se emplean, principalmente, para contener servicios globales que utilizan otros módulos (ej. Módulo Logging, Seguridad, Acceso a Datos, etc.). Todos los módulos (tanto fundational como business) tienen una clase Module que hereda ModuleInit con un método Load para que puedan ser cargados por CAB.
  • Action Catalog: servicio de SCSF que implementa un patrón que permite ejecutar acciones basado en condiciones que cambian en tiempo de ejecución.
  • Disconected Service Agent: SCSF provee un recipe para crear disconnected service agents (DSA). DSA es un servicio que permite abstraer un servicio web para poder usarlo en forma desconectada cuando el servicio no está disponible.
  • Entity Translator: servicio de SCSF que permite transformar una entidad de negocio a otro tipo de entidad requerida por servicios externos.

Solución inicial

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:

  • Infrastructure.Interface: contiene elementos globales que necesitan ser expuestos a los módulos de la aplicación como ser: interfaces de los servicios de infraestructura, definiciones de constantes, entidades de negocio que necesitan ser pasadas entre varios módulos, etc.
  • Infrastructure.Library: contiene las implementaciones de los elementos comunes para todas las aplicaciones SCSF como ser los servicios de trasformación de entidades, del DSA, carga
    del ProfileCatalog desde un Web service, etc.
  • Infrastructure.Module: es un business module vacío que podemos usar para la implementación de cualquier elemento que necesita ser compartido por varios módulos de la aplicación.
  • Shell: al igual que una aplicación CAB, es el proyecto inicial que tiene el ProfileCatalog.xml para cargar los módulos y crea el WorkItem raíz y contiene el formulario Shell que posee la interfaz básica con los Workspaces para desplegar las vistas.
  • Infrastructure.Layout: es un módulo que contiene una vista en la que se diseña la interfaz común
    dejando a la shell prácticamente vacía, logrando una mejor separación de responsabilidades y facilitando el reemplazo y reutilización de la interfaz común de la aplicación. Este proyecto se crea sólo si se tildó la opción para crear un módulo separado para el layout del shell.

Los siguientes pasos, una vez que ya tenemos la solución para comenzar a trabajar, son:

  1. Modificar la Shell si la interfaz por default no es lo que necesitamos.
  2. Crear los módulos fundacionales que expondrán servicios para el resto de la aplicación.
  3. Crear los módulos de negocio, las vistas y demás elementos necesarios.

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.

¿Cómo se hace en 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:

  • Utilizar un módulo separado para el layout cuando tengamos mucha lógica de presentación para la interfaz común que no queremos mezclar con las demás responsabilidades del proyecto Shell (el
    proyecto Interface.Layout tiene un ModuleController y el Shell no), o cuando queremos reutilizar la interfaz común o poder “switchearla” dinámicamente (ej. según preferencias del usuario).
  • Las vistas deberían contener el mínimo posible de lógica. La gran parte son llamadas a funciones en el presenter para informar de eventos y propiedades y eventos que el presenter usa para. El presenter contiene la lógica para manejar los eventos y actualizar la vista y el modelo.
  • Es recomendable siempre usar interfaces (principalmente en vistas y servicios) para poder intercambiar las implementaciones y facilitar el testing.
  • Usar siempre constantes para los identificadores de comandos, eventos, extensión sites, etc..
  • No usar la misma cadena para identificar un Evento y un Comando. CAB no distingue entre eventos y comandos del mismo nombre y puede traer problemas.
  • Crear un WorkItem para contener los datos o información de contexto que necesita ser comunicado a los presenters de las vistas de un módulo. Un error común es pasar información a una
    vista o presenter por medio de los parámetros de un evento (Event Broker), es mejor usar States.
  • Utilizar Event Broker cuando se necesita informar de eventos a toda la aplicación sin importar quién lo reciba.
  • TDD es una muy buena práctica que SCSF tiene en cuenta.
  • Gran parte de la lógica de negocio, incluyendo inicializaciones, comandos, y eventos suelen quedar en los ModuleController, es muy normal.

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.

Lecturas recomendadas:

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.

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).

Requerimientos

AjGenesisStudio es un IDE inspirado en Visual Studio por lo cual su apariencia y funciones serán muy similares.

  • Poder abrir y editar cualquier tipo de archivo de texto,
  • Debe permitir realizar todas las funciones de edición de texto conocidas (copiar, pegar, buscar, reemplazar, etc.),
  • Resaltado de sintaxis para la mayor cantidad posible de archivos (XML, VB, CS, HTML. etc.),
  • Ofrecer resaltado de sintaxis en las plantillas de AjGenesis tanto para el código AjBasic como para el texto de salida (similar a ASP.net).
  • Poder abrir carpetas de proyectos de generación y mostrar los archivos en un Explorador de Proyecto en forma de árbol (similar al Explorador de Soluciones de Visual Studio).
  • Ejecutar archivos .build de NAnt con un botón (Run).
  • Administración de herramientas externas (similar al de Visual Studio).
  • Poder crear nuevos archivos y proyectos a partir de plantillas (igual que VS).

Para el resaltado de sintaxis y la interfaz tipo “docking” se emplea el excelente componente open source “DotNetFireball“.

Diseño de la Shell

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).

ajgsshell

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:filemenu

  • FileNewMenu: ítems para crear un nuevo elemento (ej. módulo Documento: “Nuevo Archivo”, módulo Proyecto: “Nuevo Proyecto”).
  • FileOpenMenu: ítems para abrir elementos (ej. Abrir Archivo, Abrir Proyecto).
  • FileAddMenu: ítems que se pueden añadir a un proyecto (ej. Nuevo Xml, Nuevo Template).
  • FileMenuExtension: los módulos deben añadir ítems al menu archivo a travez de este UIExtensionSite (en la imagen se ven ítems añadidos por el módulo Documento).
¿Por qué MenuExtension y FileMenuExtension?

¿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.

Funciones de edición

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).

Servicios de infraestructura

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.

Categories

Calendar

December 2008
M T W T F S S
« Nov    
1234567
891011121314
15161718192021
22232425262728
293031