Aug
13
Filed Under (.NET, SP1) by jcisneros on 13-08-2008

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:

Aug
05
Filed Under (.NET, SP1) by jcisneros on 05-08-2008

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.

Jul
25
Filed Under (.NET) by jcisneros on 25-07-2008

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

Jul
24
Filed Under (.NET) by jcisneros on 24-07-2008

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

Jun
22
Filed Under (.NET, Uncategorized) by jcisneros on 22-06-2008

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!

Jun
16
Filed Under (.NET) by jcisneros on 16-06-2008

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