вторник, 27 декабря 2011 г.

Текст по кругу средствами Photoshop


C помощью этого простого урока можно красиво оформлять тексты кривыми любой сложности.


Открываем наш документ. Выбираем инструмент Ellipse Tool (с указанными настройками). Рисуем круг, удерживая клавишу Shift:
 

Выбираем инструмент Type (Текст). Помещаем курсор над линией круга, пока он не примет следующий вид. 
 

Печатаем наш текст, он будет распределяться по линии круга. Редакировать текст: крутить его, устанавливать положение внутри или снаружи, можно с помощью инструмента Path Selection Tool и точек управления. 


все просто, нужно только привыкнуть)
надеюсь, что вам этот урок пригодится 

воскресенье, 25 декабря 2011 г.

Using MEF with Common Service Locator

“The Managed Extensibility Framework (MEF) simplifies the creation of extensible applications. MEF offers discovery and composition abilities that you can leverage to load application extensions.” – (mef.codeplex.com)

“The common service locator library contains a shared interface for service location which application and framework developers can reference” - (commonservicelocator.codeplex.com)

Wow!

How to get them both working together, is as below.

NOTE: I am assuming that the reader is aware of Dependency Injection pattern & the Common Service Locator.

The Steps:

Download the CommonServiceLocator_MefAdapter.4.0.zip file & extract the MefServiceLocator class written by Glen Block
Create a new ASP.Net MVC 2.0 Web Application Project
Include the MefServiceLocator class into this project
Open the Global.asax.cs file
Make the following code change in the Application_Start event:
protected void Application_Start(){

RegisterDIContainer();

AreaRegisteration.RegisterAllAreas();

RegisterRoutes(RouteTable.Routes);

}

Write the RegisterDIContainer method as:
protected void RegisterDIContainer(){
var catalog = new AggregateCatalog(

new AssemblyCatalog(Assembly.GetExecutingAssembly()),

new DirectoryCatalog(Server.MapPath(“~/Plugins”))
);

var composition = new CompositionContainer(catalog);

composition.ComposeParts(this);

var mef = new MefServiceLocator(composition);

ServiceLocator.SetLocatorProvider(() => mef);
}


With this in place, you are now good to do:

var controllers = ServiceLocator.Current
.GetAllInstances();

Code on…

пятница, 23 декабря 2011 г.

Lambda Expressions

In order to learn functional programming and a more declarative style of writing code, we need first to cover some basic material. One of the first concepts is that of lambda expressions. Lambda expressions can be summarized in one sentence:

Lambda expressions are simply functions/methods.

They have a different syntax, primarily so that they can be written in expression context (more on this shortly) instead of as a member of a class. However, that is all they are. For instance, the following lambda expression:

c => c + 1

is a function that takes one argument, c, and returns the value c + 1.

Actually, they are slightly more complicated than this, but not much more. For the purposes of this tutorial, you only use lambda expressions when calling a method that takes a delegate as a parameter. Instead of writing a method, creating a delegate from the method, and passing the delegate to the method as a parameter, you can simply write a lambda expression in-line as a parameter to the method.

To show lambda expressions in context, consider the problem where you have an array with 10 digits in it, and you want to filter for all digits greater than 5. In this case, you can use the Where extension method, passing a lambda expression as an argument to the Where method:

int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };

foreach (int i in source.Where(x => x > 5))
Console.WriteLine(i);

To understand the semantics of this code, you needn't find some method elsewhere in the source code that does the selection; the code that you need to read is much tighter and smaller. It reflects your intent in a much cleaner fashion.

Later on in this tutorial, you'll see a number of uses of the standard query operators. Many of the standard query operators, including Where, take delegates as an argument, so this means that we can call them passing a lambda as an argument.

First, a quick review of delegates:

Defining, Creating, and Using a Delegate
In C#, a delegate is a data structure that refers to either a static method, or an object and an instance method of its class. When you initialize a delegate, you initialize it with either a static method, or a class instance and an instance method.

The following code shows the definition of a delegate and a method that can be used to initialize the delegate:

// Defines a delegate that takes an int and returns an int
public delegate int ChangeInt(int x);

// Define a method to which the delegate can point
static public int DoubleIt(int x)
{
return x * 2;
}

Now, you can create and initialize an instance of the delegate, and then call it:

ChangeInt myDelegate = new ChangeInt(DelegateSample.DoubleIt);
Console.WriteLine("{0}", myDelegate(5));

This, as you would expect, writes 10 to the console.

Using an Anonymous Method
With C# 2.0, anonymous methods allow you to write a method and initialize a delegate in place:

ChangeInt myDelegate = new ChangeInt(
delegate(int x)
{
return x * 2;
}
);
Console.WriteLine("{0}", myDelegate(5));

Using a Lambda Expression
With Lambda expressions, the syntax gets even terser:

ChangeInt myDelegate = x => x * 2;
Console.WriteLine("{0}", myDelegate(5));

This lambda expression is an anonymous method that takes one argument x, and returns x * 2. In this case, the type of x and the type that the lambda returns are inferred from the type of the delegate to which the lambda is assigned.

If you wanted to, you could have specified the type of the argument, as follows:

ChangeInt myDelegate = (int x) => x * 2;
Console.WriteLine("{0}", myDelegate(5));

Using a Lambda with Two Arguments
When using the Standard Query Operators, on occasion, you need to write a lambda expression that takes two arguments.

If you have a delegate that takes two arguments:

// Defines a delegate that takes two ints and returns an int
public delegate int MultiplyInts(int arg, int arg2);

You can declare and initialize a delegate:

MultiplyInts myDelegate = (a, b) => a * b;
Console.WriteLine("{0}", myDelegate(5, 2));

Statement Lambda Expressions
You can write a more complicated lambda expression using statements, enclosing the statements in braces. If you use this syntax, you must use the return statement, unless the lambda returns void:

int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };

foreach (int i in source.Where(
x =>
{
if (x <= 3) return true; else if (x >= 7)
return true;
return false;
}
))
Console.WriteLine(i);

Sometimes developers wonder how to pronounce the => token.

If the lambda expression is a predicate, expressing some condition: c => c.State == "WA" then the => can be spoken as "such that". In this example, you could say "c such that c dot state equals Washington". If the lambda expression is a projection, returning a new type: c => new XElement("CustomerID", c.CustomerID); then the => can be spoken as "becomes". In the above example, you could say "c becomes new XElement with a name of CustomerID and its value is c dot CustomerID". Or "maps to", or "evaluate to", as suggested in the comments below. But most often, I just say "arrow". J

A quick note: predicates are simply boolean expressions that are passed to some method that will use the boolean expression to filter something. A lambda expression used for projection takes one type, and returns a different type. More on both of these concepts later.

Lambda Expressions that Return Void
A lambda expression that returns void is not very useful in the context of functional programming because the only possible reason for such a function is that it has side-effects, and is not pure (more on this later in the tutorial), but it is part of C# 3.0 syntax, so I'll cover it here. Sometimes developers will use a void statement lambda expression for writing an event handler. This has the benefit that the syntax is terser, and the program is smaller. In addition, the lambda expression can refer to local variables in the enclosing scope. This is part of C#'s implementation of closures. The only way to write a lambda expression that returns void is to write a statement lambda expression. The following example shows defining a void delegate, declaring an instance of it, and calling it.

// Defines a delegate that takes a string and returns void
public delegate void OutputToConsole(string arg);

static void Main(string[] args)
{
OutputToConsole o = a => {
Console.WriteLine(a);
};
o("Hello, World");
}

If you write a lambda expression for a delegate that returns void and takes no arguments, it results in interesting syntax:

// Defines a delegate that takes no arguments and returns void
public delegate void OutputHelloToConsole();

static void Main(string[] args)
{
OutputHelloToConsole o = () =>
{
Console.WriteLine("Hello, World");
};
o();
}

The Func Delegate Types
The framework defines a number of parameterized delegate types:

public delegate TR Func();
public delegate TR Func(T0 a0);
public delegate TR Func(T0 a0, T1 a1);
public delegate TR Func(T0 a0, T1 a1, T2 a2);
public delegate TR Func(T0 a0, T1 a1, T2 a2, T3 a3);

In the above delegate types, notice that if there is only one type parameter, it is the return type of the delegate. If there are two type parameters, the first type parameter is the type of the one and only argument, and the second type is the return type of the delegate, and so on. Many of the standard query operators (which are just methods that you call) take as an argument a delegate of one of these types. These delegate definitions are useful to you when writing your own methods that take a delegate as an argument.

using System;
using System.Collections.Generic;

class Program
{
static List MyWhereMethod(IEnumerable source,
Func predicate)
{
List l = new List();
foreach (T item in source)
if (predicate(item))
l.Add(item);
return l;
}

static void Main(string[] args)
{
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };

List filteredList = MyWhereMethod(source,
i => i >= 5);
foreach (int z in filteredList)
Console.WriteLine(z);
}
}

The Action Delegate Types
The framework defines a number of parameterized delegate types for delegates that return void:

public delegate void Action();
public delegate void Action(T0 a0);
public delegate void Action(T0 a0, T1 a1);
public delegate void Action(T0 a0, T1 a1, T2 a2);
public delegate void Action(T0 a0, T1 a1, T2 a2, T3 a3);

Sometimes API designers will include an event that takes one of these delegate types as an argument, and you can write a lambda expression for the argument. As with the Func delegate types, these delegate definitions are useful to you when writing your own methods that take a delegate as an argument. This uses the interesting syntax of () => { /* body of void function here */ };

using System;
using System.Collections.Generic;
using System.Threading;

class Program
{
static void SomeAsynchronousMethod(Action complete)
{
// just pretending to be asynchronous in this example
Thread.Sleep(1000);
complete();
}

static void Main(string[] args)
{
SomeAsynchronousMethod(() => { Console.WriteLine("Done"); });
}
}

Expression Trees
Lambda expressions can also be used as expression trees. This is an interesting topic, but is not part of this discussion on writing pure functional transformations.

среда, 21 декабря 2011 г.

Converting objects or arrays of objects to DataTables

Recently there have been some articles about not using DataSets or DataTables in web applications. Scott Mitchell has Why I Don't Use DataSets in My ASP.NET Applications and More On Why I Don't Use DataSets in My ASP.NET Applications. Karl Sequin has On the Way to Mastering ASP.NET: Introducing Custom Entity Classes.

I prefer to use custom objects also, mostly because I like to abstract the database away from the client app. So I have this API with custom classes (fed from DataReaders) and a coworker wants to use my API to drive some reports. The only problem is the tool they are using doesn't work with arrays of objects. They say it needs DataSets, DataTables or DataReaders.

At first I started getting nervous but then I thought about it. DataSets and DataTables are fed from DataReaders. That's when I said to myself, "Self, you can feed DataSets and DataTables from your custom classes by using reflection."

Now I am far from a Reflection guru, but all they need are column names, data types and values. I can build DataColumns from the property info of classes dynamically using Reflection. The following code is my first pass. If anyone sees a way to improve on this then by all means, let's hear it.

using System;
using System.Data;
using System.Reflection;
using System.Reflection.Emit;

namespace ObjToAdo
{
///
/// Summary description for Converter.
///

public class Converter
{
private Converter() {}

///
///
///

/// ///
public static DataTable ConvertToDataTable(Object o)
{
PropertyInfo[] properties = o.GetType().GetProperties();
DataTable dt = CreateDataTable(properties);
FillData(properties, dt, o);
return dt;
}

///
///
///

/// ///
public static DataTable ConvertToDataTable(Object[] array)
{
PropertyInfo[] properties = array.GetType().GetElementType().GetProperties();
DataTable dt = CreateDataTable(properties);

if (array.Length != 0)
{
foreach(object o in array)
FillData(properties, dt, o);

}

return dt;
}

///
///
///

/// ///
private static DataTable CreateDataTable(PropertyInfo[] properties)
{
DataTable dt = new DataTable();
DataColumn dc = null;

foreach(PropertyInfo pi in properties)
{
dc = new DataColumn();
dc.ColumnName = pi.Name;
dc.DataType = pi.PropertyType;

dt.Columns.Add(dc);
}

return dt;
}


///
///
///

/// /// /// private static void FillData(PropertyInfo[] properties, DataTable dt, Object o)
{
DataRow dr = dt.NewRow();

foreach(PropertyInfo pi in properties)
dr[pi.Name] = pi.GetValue(o, null);

dt.Rows.Add(dr);
}


}
}

среда, 14 декабря 2011 г.

How to write fluent interface with C# and Lambda.


Last week I had a nice discussion in the office about “how to write fluent interface” and I have found a couple of articles over the internet about that. As usual I disagree with some of them and, as usual, my friend Mauro Servienti (MVP C#) has a nice article about it, unfortunately in Italian. He just gave me the startup input.
If you think about the Fluent Interface, it is just a trick that you use with C# in order to cheat the intellisense of Visual Studio and in order to create a nice style for your code. Of course there is a specific way to write fluent interface.
Let’s make a short sample. The classic Person class and the factory pattern.
We have a class which represents the Person Entity and has some common properties.
image
Very easy. Now, in a normal world you would have something like this, in order to create a new instance of a class person.
First way, the classis way:
Classic Person Factory
  1. public class PersonFactory
  2. {
  3. public static Person CreatePerson(string firstName, stringmiddleName, string lastName)
  4. {
  5. var person = new Person
  6. {
  7. FirstName = firstName,
  8. MiddleName = middleName,
  9. LastName = lastName
  10. };
  11. return person;
  12. }
  13. }
This code is classic and very verbose. If you want to use it the syntax would be something like this:
Create Person
  1. var person = PersonFactory.CreatePerson("Raffaele", string.Empty,"Garofalo");

Now, if we want to add an address to this person we need an additional like of code like this one, and of course a new factory for the class person or a new method in the person factory … whatever …
Create Address
  1. var address = PersonFactory.CreateAddress("1st Lane", "Main Road","Hamilton", "Bermuda", "HM10");
  2. person.Addresses.Add(address);

First of all, here we have a big problem. All the parameters are strings. So, if we don’t explain in a proper verbose way each parameter, the developer that will use our factory won’t be able to know what to write in each parameter. Second thing, if we don’t use C# 4 we have to specify each parameter value anyway … Finally we are avoiding a nice readability in our code.

The first step for a fluent interface.

I saw a lot of code around the web but a lot of people forget about the name of this technique … The name is Fluent Interface so this means that probably we should add some interfaces in our code in order to have a good result. Well VS 2010 is able to create an interface from a class just with a couple of clicks … And this is the final result:
image
Now we need to translate each method in a Fluent method. Let’s start with the class person. What I am doing is an interface for my Factory and two methods, one for the Factory initialization, where we initialize a new instance of the class person and one to finalize it where we will return the current instance of that class. Of course we need also the methods to add some values to the person properties. Look at the UML:
image
At here is the code:
IPersonFactory
  1. public interface IPersonFactory
  2. {
  3. IPersonFactory Initialize();
  4. IPersonFactory AddFirstName(string firstName);
  5. IPersonFactory AddLastName(string lastName);
  6. IPersonFactory AddMiddleName(string middleName);
  7. IPerson Create();
  8. }

And this is the implementation:
PersonFactory
  1. public class PersonFactory : IPersonFactory
  2. {
  3. private IPerson person = null;
  4. public IPersonFactory Initialize()
  5. {
  6. person = new Person();
  7. return this;
  8. }
  9. public IPersonFactory AddFirstName(string firstName)
  10. {
  11. person.FirstName = firstName;
  12. return this;
  13. }
  14. public IPersonFactory AddLastName(string lastName)
  15. {
  16. person.LastName = lastName;
  17. return this;
  18. }
  19. public IPersonFactory AddMiddleName(string middleName)
  20. {
  21. person.MiddleName = middleName;
  22. return this;
  23. }
  24. public IPerson Create()
  25. {
  26. return person;
  27. }
  28. }

So now we start to have a FluentInterface capability in our code.
Code Snippet
  1. var person = new PersonFactory()
  2. .Initialize()
  3. .AddFirstName("Raffaele")
  4. // we can skip this line now ...
  5. .AddMiddleName(string.Empty)
  6. .AddLastName("Garofalo")
  7. .Create();

Very well done but we still have a problem here. We are not giving a constraint to the developer that will use our fluent syntax. Let’s say that we are working with a retarded colleague, nobody can prohibit him to write something like this:
Wrong Person
  1. var wrongPerson = new PersonFactory().Create();

In this case he will get a nice NullReferenceException because if he doesn’t call the method Initialize the factory won’t create a new instance of the class person … So how can we add a constraint to our interface? Very simple, we need 3 interfaces and not only one anymore. We need IInitFactory, IPersonFactory and ICreateFactory.

Let’s see the code:

IPersonFactory
  1. public interface IPersonFactory
  2. {
  3. IPersonFactory AddFirstName(string firstName);
  4. IPersonFactory AddLastName(string lastName);
  5. IPersonFactory AddMiddleName(string middleName);
  6. IPerson Create();
  7. }

The IPersonFactory now will not be in charge anymore of creating a new instance of the class person, it will just be in charge of working with it. We will use dependency injection to inject a new instance. Let’s the concrete implementation of this factory:
Person Factory refactored
  1. public class PersonFactory : IPersonFactory
  2. {
  3. private IPerson person = null;
  4. public PersonFactory(IPerson person)
  5. {
  6. this.person = person;
  7. }
  8. public IPersonFactory AddFirstName(string firstName)
  9. {
  10. this.person.FirstName = firstName;
  11. return this;
  12. }
  13. public IPersonFactory AddLastName(string lastName)
  14. {
  15. this.person.LastName = lastName;
  16. return this;
  17. }
  18. public IPersonFactory AddMiddleName(string middleName)
  19. {
  20. this.person.MiddleName = middleName;
  21. return this;
  22. }
  23. public IPerson Create()
  24. {
  25. return this.person;
  26. }
  27. }

Now we need an orchestrator. Somebody that will be visible outside and will be in charge of giving to the fluent syntax a static flavor (we want to avoid the new Factory() syntax …) and that will return a PersonFactory ready to work …
Person Fluent Factory
  1. public static class PersonFluentFactory
  2. {
  3. public static IPersonFactory Init()
  4. {
  5. return new PersonFactory(new Person());
  6. }
  7. }

And now Visual Studio will follow our rules …
Parallels Picture
Parallels Picture 1

Final Step, Lamba expression for a cool syntax.

Ok this is cool and it works like we want but … it is really time consuming. We want a fluent interface and that’s fine but if you a domain with 100 entities and more or less 100 factories, can you imagine the pain in the neck in order to adopt this pattern all over?? Well this is the reason you should study more in depth C#!! If you didn’t know, there is a cool syntax future in C# called Lambda Expressions. If you don’t know what I am talking about have a look here.
First of all we need a generic interface for our factory with only two methods, one to add a value to a property and one to return the current instance of the entity created by the factory.
IGenericFactory
  1. public interface IGenericFactory
  2. {
  3. IGenericFactory AddPropertyValue(Expression<Funcobject>> property, object value);
  4. T Create();
  5. }
Then following the same logic of the previous steps we need a concrete implementation but using generics and lambda expressions (I really love this part).
Generic Factory <T>
  1. public class GenericFactory : IGenericFactory
  2. {
  3. T entity;
  4. public GenericFactory(T entity)
  5. {
  6. this.entity = entity;
  7. }
  8. public IGenericFactory AddPropertyValue(Expression<Funcobject>> property, objectvalue)
  9. {
  10. PropertyInfo propertyInfo = null;
  11. if (property.Body is MemberExpression)
  12. {
  13. propertyInfo = (property.Body asMemberExpression).Member as PropertyInfo;
  14. }
  15. else
  16. {
  17. propertyInfo = (((UnaryExpression)property.Body).Operand asMemberExpression).Member as PropertyInfo;
  18. }
  19. propertyInfo.SetValue(entity, value, null);
  20. return this;
  21. }
  22. public T Create()
  23. {
  24. return this.entity;
  25. }
And the Fluent Factory, now generic, in this way:
Code Snippet
  1. public static class GenericFluentFactory
  2. {
  3. public static IGenericFactory Init(T entity)
  4. {
  5. return new GenericFactory(entity);
  6. }
  7. }

The final syntax will be this one:
Code Snippet
  1. var person = GenericFluentFactory<Person>
  2. .Init(new Person())
  3. .AddPropertyValue(x => x.FirstName, "Raffaele")
  4. .AddPropertyValue(x => x.LastName, "Garofalo")
  5. .Create();

Ta da!! One generic factory with syntax constraints to create as many entities as you want! And thesmart developer that is working with you won’t be able to complain at all.

Final notes.

We can make this code better by:
  • Adding a custom type reflected by the property we are using, so you won’t be able to add an integer value to a property of type string and so on …
  • Remove that ugly .Init(new Person()) using an IoC engine or a new constraint to our class, of course in this case you must provide classes with at least 1 parameters less constructor.
That’s it! Have fun!