Sunday, October 12, 2008

Discharge Look Like When Pregnant



One thing that always surprised me very pleasantly of. NET framework since its first version, was the flexibility and extensibility that has. These qualities I believe, gradually increased version after version, and could say without committing an error that has become a philosophy. In this way, there is a small example that I now address the problem to be solved is to add a section customized to an application configuration file, either an App.config or Web.config, for this example I will assume that working with a GUI application that supports multi -language, for that I will define a new section called AppIdiomas in App.config and then in the same configuration file I define the languages \u200b\u200bsupported by the application. Let's look a bit like
define my configuration file:

  
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<configSections>

<section name ="AppIdiomas" type ="CR.Util.Lenguaje.IdiomaSection, CR.Util" />

</configSections>

<!-- Seccion de Idiomas-->
<AppIdiomas name ="AppIdiomas" >
<idiomas>
<add name ="en-US" Idioma ="English (United States)" />
<add name ="es-AR" Idioma ="English (Argentina)" />
</idiomas>
</AppIdiomas>
</configuration>

Now let's see how flexible is the mechanism that gives me. NET to extend the configuration file using the ConfigurationElement class, and ConfigurationElementCollection ConfigurationSection. First I will define a new configuration element in this particular case call idiomaConfigElement and that class inherits from ConfigurationElement

  
using System ;
using System . Collections . Generic ;
using System . Text ;
using System. Configuration ;

namespace CR. Useful . Language

{public class IdiomaConfigElement:
ConfigurationElement {public
IdiomaConfigElement ( String newName, String newIdioma )
{Name
= newName;
Language = newIdioma ;

} public
IdiomaConfigElement ()


{} public

IdiomaConfigElement ( string elementName) {

Name elementName = ;}


[ ConfigurationProperty ( "name" , DefaultValue = "English (Argentina)" , IsRequired = true , IsKey = true )]
public string Name
{
get
{
return ( string ) this [ "name" ];
}
set {

this [ "name" ] = value ;
}}


[ ConfigurationProperty ( "Language" , DefaultValue = "es-AR" , IsRequired = true)] public
Language string
{get

{
return (string ) this [ "Language" ];}

September
{
this [ "Language" ] = value;}


}}}


As I can have a list of languages \u200b\u200bsupported by the application and will be listed in the configuration file implement another class that inherits this time ConfigurationElementCollection:

 
System using ;
using System. Collections . Generic ;
using System. Text ;
using System. Configuration ;

namespace CR. Useful . Language
{
public class IdiomaCollection: ConfigurationElementCollection
{
public IdiomaCollection () {

IdiomaConfigElement idiom = ( IdiomaConfigElement ) CreateNewElement ();}


public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType . AddRemoveClearMap ;
}
}

protected override ConfigurationElement CreateNewElement ()
{
return new IdiomaConfigElement ();
}

protected override Object GetElementKey ( ConfigurationElement element )
{
return (( IdiomaConfigElement ) element ). Name ;
}

public IdiomaConfigElement this [ int index ]
{
get
{
return ( IdiomaConfigElement ) BaseGet ( index );
}
set
{
if ( BaseGet ( index ) != null )
{
BaseRemoveAt ( index );
}
BaseAdd ( index , value );
}
}

new public IdiomaConfigElement this [ string Name ] {


get {return
( IdiomaConfigElement ) BaseGet ( Name )
}}


public int IndexOf ( IdiomaConfigElement language )

{return BaseIndexOf ( language);

}}}


Finally I have left "join all" with a class that represents my section that inherits from ConfigurationSecction customized

  
using System ;
using System . Collections . Generic ;
using System . Text ;
using System. Configuration ;

namespace CR. Useful . Language

{public class IdiomaSection: ConfigurationSection
{
IdiomaConfigElement language; public

IdiomaSection () {

language = new IdiomaConfigElement ();}


[ ConfigurationProperty ( "name" , DefaultValue = "Languages" , IsRequired = true , IsKey = false)] public
string Name {



get {return
(string ) this [ "name" ];}

September
{
this [ "name" ] = value ;
}}


[ ConfigurationProperty ( "languages" , IsDefaultCollection = false)] public
IdiomaCollection languages


{get {

IdiomaCollection IdiomaCollection =
( IdiomaCollection ) base [ "languages" ]
return IdiomaCollection ;}


}}}


If we examine this mechanism that gives me the framework. NET to extend its functioning is the same it gives me when I define an exception in particular and I inherit my "new" exception from the Exception class. As we see in the code, the three classes that implement the definitions section, element, and the collection of these then take shape in the configuration file. Using the method attribute [ConfigurationProperty], I can define the attributes of the configuration item such as if required (IsRequired) among others.
gives me the flexibility to define attributes such languages \u200b\u200bsupported by the user interface from the application, from a xml configuration file, make my code much more extensible, and provide greater readability to be in an xml file.
This extensibility mechanism, although in this example was used for "multi-language" can be considered for any other "variable" of an application that can be configured from an xml configuration file, since the mechanism is what is important here.

Friday, October 3, 2008

Woodworm Premier Flame

Custom Config Properties

One of the new features of Visual Studio 2008 for C # 3.0 automatic properties are, what's this about? very simple, remember when I define a class and implement its properties extremely common thing is to result in code like this
 
public class Customer

{string _name ; string
_direccion ;

public string nombre
{
get { return _nombre ; }
set { _nombre = value ; }
}
public string direccion
{
get { return _direccion ; }
set { _direccion = value ;}}

}

Ok, let's see how it would be our code using automatic properties syntax
 
public class Customer

{public string name {get ; September ;} public
string address { get ; September ;} public
int ID { get ; September ;}}


As we can see the new automatic property syntax, increases productivity of code. C # 3.0 compiler in a class when it detects a get and a set vacuum automatically creates a private variable and method to retrieve and assign the value of the property. In many instances the properties that define it are in my classes are of this type, that is why this syntax is very practical

Greetings!

Wednesday, October 1, 2008

How To Renew Temporary Driving License

Automatic Dependency Injection with Unity Application Block

On this occasion I will comment on the Dependency Injection container using Microsoft Unity Application Block.

To begin this story, and especially for those who know nothing about this we can start by reading Martin Fowler's article on his website is a good introduction to pattern Inyection Dependency.

People Patterns and Practices for Microsoft, responsible for Enterprise Library, offers a DI container named Unity Application Block (name, true to form) this tool makes it easier for us when working with Object Builder by encapsulating its functions, if any of you have had to work with OB know what I mean. We can also configure our container through an XML configuration file to do it more clear and declarative (webconfig) in a few months ago InfoQ published an interview Chris Tavares who is the lead developer of Enterprise Library and Unity ( can view the note is very interesting too ).

Now either because Dependency Injection? Consider the classic example, if we have a Logger class, a container of DI would allow us to create a dependency ILogger interface, so that later in runtime can decide that specific logger to use (aLogger, MyLogger, customLogger, etc). While not a total descople and to keep the dependence on ILogger I am taking the maximum free themselves from dependence on the specific types, and that's what Unity pursued.

Let us look at Unity in action

The first thing to do is download the Microsoft Unity Application Block can get to it from the Downloads section of Microsoft Patterns & Practices here or from the version 1.1 . Once the installer (msi package), we are ready for first test with our DI container.

Then in your project (for this example I'll use a console application to display the results) add a reference to

Microsoft.Practices.Unity Microsoft.Practices.Unity.Configuration and


Now well, let's see how to configure your container from the App.config file to add to our project.



  
<? xml version ="1.0" encoding ="utf-8" ? >
< configuration >
< configSections >
< section name ="unity"
type ="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
Microsoft.Practices.Unity.Configuration, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35"
/>
</ configSections >
< unity >

< typeAliases >
...
</ typeAliases >

< containers >
< container name = "containerOne" >
\u0026lt; types >

\u0026lt;/ types >
\u0026lt;/ container> ;
\u0026lt;/ containers >

\u0026lt;/ unity >
\u0026lt;/ configuration >
Here we define a section customized configuration unity for the container and then defininos a container that is called in this case "containerOne." Note also that we have a node in definimeros typeAliasses alias to avoid having to use the full name of the classes and assemblies whenever we refer to them. In the types section there will our objects to be injected. Section typeAliasses Now we can place the following lifeTimeManagers




  
<!-- Lifetime manager types -->
< typeAlias alias ="singleton"
type ="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
Microsoft.Practices.Unity"
/>
< typeAlias alias ="external"
type ="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,
Microsoft.Practices.Unity"
/>


And also we will put our nickname there are going to provide the reference then the node types.
Forget for a moment the configuration file and see some of the code example (this example code is based on an existing one in the blog of Matthew Podwysocki's ). Let
:




 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Configuration;
using Microsoft. Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace UnityAppBlockEjemplo

{public interface ILogger
{
void log ( string message);}


public interface iProductivity

{string name {Get, set;}
double price {get, set;}}


public interface IServicioProducto
void {
GuardarProducto (iProductivity product)


} public class ConsoleLogger: ILogger

{public void log ( string message) {

Console.WriteLine (message);}



} public class Product: {

iProductivity public string Name {get; set;} public
double price {get, set;}

public override string ToString () {

return this . name + "($" + this . precio.ToString () + ")" ;

}} public

ServicioProducto class: {
ILogger
IServicioProducto mylog;
public
ServicioProducto (ILogger logger) {

mylog = logger;}


public void GuardarProducto (iProductivity product)

{string message = producto.ToString() + " - GUARDADO" ;
Mylog.log(mensaje);
}
}

class Program
{
static void Main( string [] args)
{
IUnityContainer myContainer = new UnityContainer();

// load container configuration from App.config
UnityConfigurationSection section =(UnityConfigurationSection) ConfigurationManager.GetSection( "unity" );
section.Containers[ "containerOne" ].Configure(myContainer);

// inyect a IProduct instance
IProductivity myContainer.Resolve \u0026lt;IProducto> myProduct = ();
myProduct.nombre = "tomatoes" ;
myProduct.precio = 4.59;

/ / injected IServicioProducto instance
IServicioProducto srvProducto = myContainer.Resolve \u0026lt;IServicioProducto> ();
srvProducto.GuardarProducto (myProduct)

/ / wait for user
Console.WriteLine ( "Press enter to exit" )
Console.ReadLine ();

}}}



And here we see how the file is complete typeAliasses node configuration with the alias defined for me.




  
<!-- User-defined type aliases -->
< typeAlias alias ="IProducto" type ="UnityAppBlockEjemplo.IProducto, UnityAppBlockEjemplo" />
\u0026lt; typeAlias \u200b\u200b alias = "Product" type = "UnityAppBlockEjemplo.Producto, UnityAppBlockEjemplo" />
\u0026lt; typeAlias \u200b\u200b alias = "ILogger" type = "UnityAppBlockEjemplo.ILogger, UnityAppBlockEjemplo" />
\u0026lt; typeAlias \u200b\u200b alias = "IServicioProducto" type = "UnityAppBlockEjemplo . IServicioProducto, UnityAppBlockEjemplo " />
\u0026lt; typeAlias \u200b\u200b alias = "ConsoleLogger" type = "UnityAppBlockEjemplo.ConsoleLogger, UnityAppBlockEjemplo" />
\u0026lt; typeAlias \u200b\u200b alias = "ServicioProducto" type = "UnityAppBlockEjemplo.ServicioProducto, UnityAppBlockEjemplo" />


Let

soon as I complete my configuration file specifying the node types of "mapping "Type in the following way:





 
\u0026lt; types >
\u0026lt; type type = "iProductivity" MAPT = "Product" />
\u0026lt; type type = "ILogger" MAPT = "ConsoleLogger" />
\u0026lt; type type = "IServicioProducto" MAPT = "ServicioProducto" /> ;
\u0026lt;/ types >


Well explain a little this happening here. As you will see the code is very simple and easy to follow, we have 3 interfaces ILogger, IServicioProducto iProductivity and then have 3 concrete classes that implement 3 interfaces are ConsoleLogger earlier, Product and ServicioProducto. Implementations are trivial. Let's see what happens in the main, first created a new Unity container instance doing, then by the container "containerOne" from the App.config file.
After doing this I am able to "ask" my container for me to desire iProductivity implementation, here is where the "magic" at no time did I

product = new Product iProductivity ();


Avoid new to indicate who will provide the product instance, and I do through my ID container. This gives me an interesting decoupling between classes as I could have if you want more implementations iProductivity that differ from each other and point at runtime type is that I receive at all times. The same with the logger, I can have XMLLogger ConsoleLogger or at runtime and change the type of logger since I'm "programming against interfaces and not against specific types" .

If we look closely at the code ServicioProducto class we see that the constructor is overloaded and get an object of type as a parameter ILogger, now when we ask the container object type in
IServicioProducto
IServicioProducto srvProducto = MyContainer. Resolve ();

can see how the Unity container is responsible for resolving for us the assignment of object in the constructor, in this case we say that dependency injection is of type Constructor Inyection with Unity Inyection Setter also can do (that's for another post.)

Final words

As you will realize this is just the "tip of the iceberg" of what we can do with the dependency injection, I have a worked example where I use the same principle to change at runtime the mechanism to persist the objects Product, selecting from a list of objects in memory and db4objects database.
What we see here gives us a powerful and practical tool for descoplada make it our architecture and achieve a much more flexible, while this tool allows me to ignore how tedious it is to work with the Object Builder.
One of the highlights of the dependency injection is that it is intimately linked to the AOP (Aspect Oriented Programming), if they know nothing about this can start here wiki. Unity does not yet provide a mechanism to intercept methods nor an AOP framework, maybe in the future, time will tell. Other DI containers that can be tested and used are Spring.NET Spring.NET and WindsorCastle.Con about this is a very complete and very flexible framework (Spring is a framework widely used in the Java environment) that I personally love it.

Wednesday, September 24, 2008

Birthday Cakes For Cyclists

Footsteps to Lamba Expressions

lambda expressions are one of the new features that includes the C # compiler (Visual Basic 9 also has), but to understand that they are treated and that we can help, first let's make a little history and understand that the delegates and anonymous methods.

Delegates, the first step

The delegates play an important role within himself. NET Framework and the applications developed with it, in this sense we can see, for example, as an application of Events delegates. But rather than the delegates, without the slightest hint of being rigorous and very personal way to define a delegate gives us a mechanism that serves as a reference (type-safe) to a method. When you declare a delegate, just declare the method signature without any implementation. The delegate has a name and can be referenced like any other. Now when you declare a method whose signature matches the signature of the delegate declared this method can be passed as a parameter to any method that references to the delegate. This essentially gives us an alternative form of polymorphism. Sounds complex is not so in reality we see something more tangible.
Suppose the following problem: a football team calculated points obtained after 5 dates of a tournament in Scheme 2 points for victory, 1 point for a draw and 0 for tracks, but also want to calculate the points earned by the scheme that gives 3 points to victories instead of 2.
models to the team leaving and then follows the method responsible for calculating points



public class Team {
string _name;
_resultados IList;
_puntos int;

public Team (String name) {

_name = name;}


public string Name {get {return _name
;} set {_name =
value;}}

results
public IList {get {return
_resultados;} set {
_resultados = value;}}


points {public int
_puntos get {return;}}

/ / TODO: public CalcularPuntos void ()}


Before Implementing the method CalcularPuntos () declare our delegate: public delegate int
ActualizarEquipo (char character);
But we have our delegate, or declare a signature of a method and ActualizarEquipo name
Now let us look at this statement I make using the keyword delegate, this statement sets the delegate returns an int and receives as a parameter an object of type Task. Any of the following methods consistent with the definition of my delegation:

ContarVictorias int (char character);
ContarEmpates int (char character);

However, any of the following do not match: Team

Pointer (IList listaEquipos) ;
double Average (Equipment);

Now we have declared our delegate and know when a method is consistent with it we can see how to use it in our small example. Our representative will assist us to implement the desired behavior to calculate the points with two different strategies. First full
CalcularPuntos method class public void

Team CalcularPuntos (ActualizarEquipo Updater) {

_puntos = 0;
if (_resultados! = null & & _resultados.Count> 0)
foreach (char character in _resultados)
_puntos + = Updater (character);}

full
This team model.
Then I will implement two methods trivial to implement the two strategies have

points CalcularPuntos_2_1_0 static int (char character)

{switch (character)

{case 'w': return
2;
case ' d ':
return 1;}

return 0;}

CalcularPuntos_3_1_0 static int (char character)

{switch (character)

{case 'w': return
3;
case 'd':
return 1;

} return 0;}


Then I perform a test of it all together with a small console application and two teams that will upload the code

static void Main (string [] args) {

/ / load Team
ComputerA two teams = new Team ("Team"); \u200b\u200b
equipoA.resultados = new List {'w', 'w', 'l', 'l', 'd'};

EquipoB team = new Team ("Team B");
equipoB.resultados = new List {'w', 'l', 'd', 'd', 'd'};

listaEquipos List = new List { ComputerA, equipoB};

/ / Calculating using
2_1_0 Console.WriteLine ("Points per team with the scheme \\ nVictoria = 2 points \\ nEmpate = 1 point \\ n");
CalcularPuntosYMostrar (listaEquipos, CalcularPuntos_2_1_0)

/ / Calculating using
3_1_0 Console.WriteLine ("\\ n \\ nPuntos per team with the scheme \\ nVictorio = 3 points \\ nEmpate = 1 point \\ n");
CalcularPuntosYMostrar (listaEquipos, CalcularPuntos_3_1_0)

/ / wait for user entry
Console.WriteLine ("Press enter key
..."); Console.ReadLine ();}
static void
CalcularPuntosYMostrar (IList equipment ActualizarEquipo updater)

{foreach (eq Team in teams) {

eq . CalcularPuntos (updater);
Console.WriteLine ("{0}: {1} point (s)", eq.Nombre, eq.puntos.ToString ());

}}

Here's the result



The code we use to test our first delegate is fairly simple and created two new teams complete the list of results with the results of matches after five dates. The "magic" occurs when calculating the points for each team, use the delegate as a type parameter that I can pass allows me to create a setting that looks like a pointer or reference to a method, however it is neither as in C # a delegate is an object that inherits from System.Delegate. C # 3.0 compiler performs the "magic" (in C # 2.0 syntax was different, because it was necessary to create an instance of the delegate). Methods

Anonymous (second step)

far our delegation has been helpful but we still have one step to the final approach to lambda expressions, let us return to our example and say now we want to add a new feature for a computer to calculate the number of wins and draws, as I quoted above methods may be as follows int

ContarVictorias (char character);
ContarEmpates int (char character);
Consider how to implement
fucionalidad following, adding the two previous methods that match my delegate

ContarVictorias static int (char character)

{if (character == 'w')
return 1;
return 0;}

ContarEmpates static int (char character)

{if (character == 'd')
return 1;
return 0;}


Then we can proceed as follows: Static int

ContarResultados (IList result ActualizarEquipo updater)

{int count = 0;
foreach (char character in result) {

updater count + = (character);

} return count;}


And in the Main ...

/ / Calculating Victorie
Console.WriteLine ("\\ nVictorias");
foreach (eq Team in listaEquipos)
Console.WriteLine ("{0} {1} win game (s)", eq.Nombre, ContarResultados ( eq.resultados, ContarVictorias). ToString ());

So far nothing new but as we see the same thing with an anonymous method, anonymous methods is a mechanism implemented in C # 2.0, which allows me to make a statement in line for a method using the delegate keyword and a code block to see how we do count the ties:

/ / Calculating drwa
Console.WriteLine (" \\ nEmpates ");
foreach (eq Team in listaEquipos)
Console.WriteLine (" {0} {1} tied game (s) "
, eq.Nombre
, ContarResultados (eq.resultados,
delegate (char character)

{if (character == 'd')
return 1;
return 0;}
). ToString ());

Well that does not make our code more readable, right? This type of statement anonymous methods I reserve it for cases where it really is convenient. (VB. NET 8.0 does not support the use of anonymous methods.)

Here is where you come into play Lambda Expressions, which make the creation of delegates is much more readable and concise.

In C # Programming Guide on MSDN:

" A lambda expression is an anonymous function that can contain expressions and instructions and can be used to create delegates or expression tree types. "

Here's how our code is to have ties using lambda expressions:

/ / Calculating drwa
Console.WriteLine (" \\ nEmpates ");
foreach (eq Team in listaEquipos)
Console.WriteLine ("{0} {1} tied game (s)"
, eq.Nombre
, ContarResultados (eq.resultados,
c => {if (c == ' d ') return 1; return 0;}). ToString ());

see the expected result



This really is much more readable than before. The highlighted part in both is exactly snippets I've only changed the syntax. Highlight the following aspects of these expressions:

• If the lambda expression is one line I can do without the return keyword.
• The C # compiler infers the return type involved in the expression and lambda expressions are always assigned to a delegate the compiler looks for the expected type of the delegate and use this when you validate your code.

LINQ and Lambda Expressions, the next step

Lambda expressions are a concise and readable to define delegates. These expressions can be widely used in LINQ. The vast majority of the delegates used methods of LINQ I can sort, filter and take concrete actions on collections of objects.
We refer back to C # Programming Guide on MSDN, we find
"When you use the method syntax to call the Where method on the Enumerable class (such as is done in LINQ to Objects and LINQ to XML), the parameter is a delegate type. A lambda expression is the most practical way to create such a delegate. When you call the same method, for example, Queryable ..::. System.Linq class (as in LINQ to SQL), the parameter type is System.Linq.Expressions ..::. Expression, where Func Func is a delegate that has five input parameters. Again, a lambda expression is a very concise way to build the expression tree. Lambda expressions allow calls to Where may look similar, but in fact, the type of object created from the lambda expression is different. "
Well here we can as you can see the Lambda Expressions are one of the new features of the compiler C # 3.0 that are going to be very useful when working with delegates for example if we have to pass parameters of such functions LINQ.
Well this is the first post in my blog and I hope it will be useful to someone, the idea will be today and always convey a bit of how much I learn every day, in my college work or did not, in life same.
Greetings.