Month: July 2009

T-SQL copy and clone an existing table.

Something really useful that I like in Microsoft Access, is the capacity to select and clone an object just with a menu command.

The options we have in access are:


Structure only – will copy/paste into a new table the table structure, so the index, the primary key and so on.

Structure and Data – will copy/paste everything inside a new table.

Append – will copy the data into the existing cloned object.

What can we do with SQL Server?

Of course with SQL Server we cannot simply do that, especially if we are considering to automate this process inside a script or better, inside a job.

The first idea is to use the simple script SELECT INTO in this way:

  1: IF  EXISTS 
  2:    (SELECT * 
  3:    FROM sys.objects 
  4:    WHERE object_id = OBJECT_ID(N'[schema].[tbl_pippo]') 
  5:    AND type in (N'U'))
  6: DROP TABLE [schema].[tbl_pippo]
  7: GO
  9: SELECT * 
 10: INTO [schema].[tbl_pippo]
 11: FROM [schema].[tbl_pluto]

In this way we will copy: the records, the table structure but not the index or the primary keys.

We can try to use the right click command Drop and Create and then change the destination name of our table:

New Picture (9)

Finally, we can use the SSIS service and create a powerful package able to do that. In this way we can be sure we are going to clone everything and decide if we want to copy/paste also the data.

Transfer SQL Server object task. This task will do everything we need to copy and paste an object inside SQL:


We can also use some variables in order to make our task dynamic.

Pretty cool, isn’t it?


UI Validation with the MVP pattern. Part #03

As we discussed in the previous posts, MVP UI Validation 01 and MVP UI Validation 02, thanks to the Microsoft enterprise library, we can easily handle a perfect and professional UI Validation without leaving the MVP pattern in our Client applications.

Today I want to show you a final solution, that will handle in a professional way the UI validation.

The basic validation, refractor process.

In order to view what I am going to do today, you MUST read the previous articles related to the UI validation with the enterprise library. Actually we have our domain object that is in this way:


We need to do some refactoring, in order to use our validation process in a better way. First of all let’s create a new entity called ErrorResult that will contain some useful information and, of course, its custom collection.


Now let’s go back to the Domain Object entity and let’s do some refactoring. First of all we need to change the ListResults in this way:

  1: /// <summary>
  2: /// Custom collection used to interact with the UI
  3: /// </summary>
  4: public ErrorResultCollection ListResults 
  5: { 
  6:     get; set; 
  7: }

Then we need to change the validation function. We still declare the validation results collection:

  1: Validator validator = 
  2:    ValidationFactory.CreateValidator(
  3:       Type.GetType(this.ToString())
  4:    );
  5: ValidationResults errors = validator.Validate(this);

Then we verify that our custom collection is initialized:

  1: if (ListResults == null) {
  2:     ListResults = new ErrorResultCollection();
  3: }

And finally we loop the errors and we populate the custom collection in this way:

  1: foreach (var error in errors) {
  2:     ListResults.Add(
  3:         new ErrorResult() 
  4:         { 
  5:             Field = error.Key,
  6:             Target = error.Target,
  7:             ErrorMessage = error.Message
  8:         });
  9: }

The Customer Entity and its validation attributes.

Now we can have fun and build a custom entity that will inherit from the domain object abstract class and that will implement some custom validations.

  1: [NotNullValidator(
  2:     MessageTemplate="Id cannot be null.")]
  3: public int Id { get; set; }
  4: [NotNullValidator(
  5:     MessageTemplate="First name cannot be null.")]
  6: [StringLengthValidator(
  7:     1,
  8:     30,
  9:     MessageTemplate="First name leght has to be grater then 0 and lower then 31.")]
 10: public string FirstName { get; set; }
 11: [NotNullValidator(
 12:     MessageTemplate = "Last name cannot be null.")]
 13: [StringLengthValidator(
 14:     1,
 15:     30,
 16:     MessageTemplate = "Last name leght has to be grater then 0 and lower then 31.")]
 17: public string LastName { get; set; }

And we can do some simple test. The first test will verify that we respect the NotNull validation rule:

  1: [TestMethod]
  2: public void TestNotNull() {
  3:     Customer target = new Customer();
  4:     Assert.IsTrue(
  5:        target.IsValid(),
  6:        target.ListResults.ToString()
  7:     );
  8: }

Note: I added a simple ToString() function in the custom error collection in order to have the entire output in one line, only for my tests …

  1: public override string ToString() {
  2:     StringBuilder message = new StringBuilder();
  3:     for (int i = 0; i < this.Count; i++) {
  4:         message.Append(this[0].ErrorMessage);
  5:     }
  6:     return message.ToString();
  7: }

Reflect the validation trough the Presentation layer.

Now we need to create a simple form and a custom presentation layer in order to apply the UI logic. First of all, the form. Remember to include and error component in your form:


Then this is the view:

  1: int Id { get; set; }
  2: string Firstname { get; set; }
  3: string Lastname { get; set; }
  4: void ShowError(string message, string controlName);
  5: void Validate(object sender, EventArgs e);
  6: void ClearErrors();

Finally, this is the implementation of the view in our Windows Form:

  1:         public int Id {
  2:             get {
  3:                 try {
  4:                     int id = Convert.ToInt32(txtId.Text);
  5:                     return id;
  6:                 } catch (Exception ex) {
  7:                     return 0;
  8:                 }
  9:             }
 10:             set {
 11:                 txtId.Text = value.ToString();
 12:             }
 13:         }
 15:         public string Firstname {
 16:             get {
 17:                 return txtFirstname.Text;
 18:             }
 19:             set {
 20:                 txtFirstname.Text = value;
 21:             }
 22:         }
 24:         public string Lastname {
 25:             get {
 26:                 return txtLastname.Text;
 27:             }
 28:             set {
 29:                 txtLastname.Text = value;
 30:             }
 31:         }
 33:         public void ShowError(string message, string controlName) {
 34:             MyError.SetError(GetControl(controlName), message);
 35:         }
 37:         private Control GetControl(string fieldName) {
 38:             switch (fieldName) {
 39:                 case "Id":
 40:                     return txtId;
 41:                 case "FirstName":
 42:                     return txtFirstname;
 43:                 case "LastName":
 44:                     return txtLastname;
 45:                 default:
 46:                     return txtId;
 47:             }
 48:         }
 50:         public void ClearErrors(){
 51:             foreach (Control item in grpCustomer.Controls) {
 52:                 if (item.GetType() == typeof(TextBox)) {
 53:                     MyError.SetError(item, "");
 54:                 }
 55:             }
 56:         }
 58:         public void Validate(object sender, EventArgs e) {
 59:             presenter.SubmitChange();
 60:         }

I just added a couple of routines to better manage the control in my form: ClearErrors and GetControl.

Now it’s time for the presenter. This presenter will be very easy. It will have a private IView as a field and only one constructor:

  1:         //Instance of the current view
  2:         ICustomerView view;
  3:         //Constructor
  4:         public CustomerPresenter(ICustomerView _view) {
  5:             this.view = _view;
  6:         }

I have created also a custom init routine in order to fill my form from the presenter:

  1:         //Initialization
  2:         public void Initialize() {
  3:             Customer newCustomer = 
  4:                 new Customer() { 
  5:                     Id = 0, 
  6:                     FirstName = "Raffaele", 
  7:                     LastName = "Garofalo" };
  8:             PassViewInfo(newCustomer);
  9:         }

And this is the routing that fill the view from the presenter:

  1:         private void PassViewInfo(Customer customer) {
  2:             view.Id = customer.Id;
  3:             view.Firstname = customer.FirstName;
  4:             view.Lastname = customer.LastName;
  5:         }

Last is the SubmitChanges called by the view. Here is where we are running the domain validation logic:

  1:         //Submit the change, but before, validate them
  2:         public void SubmitChange() {
  3:             Customer currentCustomer = new Customer();
  4:             GetViewInfo(currentCustomer);
  5:             if (currentCustomer.IsValid()) {
  6:                 view.ClearErrors();
  7:             } else {
  8:                 foreach (ErrorResult error in currentCustomer.ListResults) {
  9:                     view.ShowError(error.ErrorMessage, error.Field);
 10:                 }
 11:             }
 12:         }

So for each error raised by our Entity, I am going to add the error to the corresponding control in the view. If there are no errors at all, the view will be cleaned. In this way we can also enable/disable a save button for example. But it is not the purpose of this article.

The final result will be:


I hope you enjoy my series of articles, and if you have any feedback, feel free to post them on my blog.

The next series will focus on the MVVM, I have already posted something.

If you want the solution of this tutorial, it is saved in my sky drive here


Inversion of Control with NET Framework.

Today I want to break-out my series of posts about WPF to talk about an interesting design pattern. The Inversion of Control or Dependency Injection. You can find a clear definition at this address: Martin Fowler.

What is it the Dependency Injection?

The dependency injection is a way to inject some information and configuration inside an object, from another one. In this way we keep our object abstract and recyclable.


As you can see in this example, we have two concrete tasks, and each one has an execute command that is exposed by the interface IBaseTask. This will be our bridge from the interface and the concrete implementation.

Manually Dependency Injection.

Now, if we would like to run our example, manually, we should write something like this code:

  1: IBaseTask firstTask = new RunTask();
  2: firstTask.Execute();
  3: IBaseTask secondTask = new WalkTask();
  4: secondTask.Execute();

And the code in each task should be something like that:

  1: public class WalkTask : IBaseTask {
  2:     #region IBaseTask Members
  4:     public string TaskName {
  5:         get;
  6:         set;
  7:     }
  9:     public void Execute() {
 10:         Console.WriteLine("I am a Walk task");
 11:     }
 13:     #endregion
 14: }

Microsoft Unity for Dependency Injection.

Microsoft Unity is an open source project done by the Microsoft patterns and practice. It can be downloaded here: and the actual version is the 1.2 present also in the enterprise library 4.1

After you install it, you will have a folder with some .dlls that you have to reference into your solution.


Now let’s go back to our project and let’s change the code in order to have Unity and not a concrete implementation of our interface.

  1: //Unity container
  2: IUnityContainer container = new UnityContainer();
  3: //Type association
  4: container.RegisterType<IBaseTask, WalkTask>();
  5: IBaseTask firstTask = container.Resolve<IBaseTask>();
  6: firstTask.Execute();

This is the first step, but as you can notice, it’s not so far from a concrete implementation. I mean, in this way we still have to procedural declare the type we want to convert to our interface.

The next step will be to remove the type association and use a configuration file. First of all we need to declare in our app.config file the unity section:

  1: <?xml version="1.0" encoding="utf-8" ?>
  2: <configuration>
  3:   <configSections>
  4:     <section name="Unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, 
  5:              Microsoft.Practices.Unity.Configuration, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  6:   </configSections>

Then we need to associate some type to our container. This is easy.

  1:   <Unity>
  2:     <typeAliases>
  3:       <!-- Lifetime manager types -->
  4:       <typeAlias alias="singleton"
  5:            type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
  6:                Microsoft.Practices.Unity" />
  7:       <typeAlias alias="external"
  8:            type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,
  9:                Microsoft.Practices.Unity" />
 10:       <!-- Custom types -->
 11:       <typeAlias alias="myInterface" type="InversionOfControl.Model.IBaseTask, InversionOfControl" />
 12:     </typeAliases>

As you can see at the end, we are going to declare our IBaseTask interface. Remember always to declare the complete path otherwise Unity will search the class into the Unity namespace!!

Now let’s build a couple of custom map inside the XML file:

  1:     <containers>
  2:       <container name="firstContainer">
  3:         <types>
  4:           <type type="myInterface" mapTo="InversionOfControl.Model.RunTask, InversionOfControl" name="RunMapping" />
  5:           <type type="myInterface" mapTo="InversionOfControl.Model.WalkTask, InversionOfControl" name="WalkMapping" />
  6:         </types>
  7:       </container>
  8:     </containers>
  9:   </Unity>
 10: </configuration>

As you can see, we are using our Alias to declare the interface and then we are giving a custom name the our mapping. Now we can go back to our code and do some fancy operations.

Declare the configuration section and initialize the container:

  1: IUnityContainer container = new UnityContainer();
  2: UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("Unity");
  3: section.Containers["firstContainer"].Configure(container);

Then let’s Inject a couple of objects inside our interface:

  1: IBaseTask firstTask = 
  2:    container.Resolve<IBaseTask>("RunMapping");
  3: firstTask.Execute();
  4: IBaseTask secondTask = 
  5:    container.Resolve<IBaseTask>("WalkMapping");
  6: secondTask.Execute();

Very easy right? In our example we are going to write in a procedural way which mapping we want to use, but of course this information should be retrieved at run-time from a Database or a serialized object.

Inject property and change values at run-time.

Until now our objects were exposing an execute method that was simply printing some fixed text in the console. But we have a name property so we should change the execute method with something like that:

  1: public void Execute() {
  2:     Console.WriteLine
  3:       ("I am a Run task. My name is: {0}",
  4:       TaskName);
  5: }

Now we have two ways to initialize the TaskName property value without using a procedural code inside the program. First of all we have to say that the TaskName property of each concrete implementation has a dependency:

  1: [Dependency()]
  2: public string TaskName {
  3:    get;set;
  4: }

And now we can change the configuration in this way:

  1: <type type="myInterface" mapTo="InversionOfControl.Model.WalkTask, InversionOfControl" name="WalkMapping" >
  2:   <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,
  3:                      Microsoft.Practices.Unity.Configuration">
  4:     <property name="TaskName"  propertyType="System.String">
  5:       <value value="SecondTask"/>
  6:     </property>
  7:   </typeConfig>
  8: </type>

We are assigning for the mapping called WalkMapping a value of “SecondTask” for the property TaskName. This solution is fine but it’s still fixed. I mean, and if I would like to change the value at run-time and I cannot access the serialization of my object?

Here is coming the second solution:

  1: container.Configure<InjectedMembers>()
  2:    .ConfigureInjectionFor<RunTask>(
  3:    //.ConfigureInjectionFor<IBaseTask>(
  4:    //.ConfigureInjectionFor<WalkTask>(
  5:       new InjectionProperty("TaskName", "12345"));

I put a couple of comments to show you what you can configure.

I hope this short article will be useful to evaluate this amazing IoC framework.

You can find the complete solution here, in my sky drive


WPF and MVVM tutorial 07, the List search.

Ok, starting from this post we are going to do something really interesting. In this episode we need to create a simple List windows, but as you will see the logic will not be so different then a one-to-many form.

This will be the final result:


The ViewModel for the List Window.

First of all we need to create the view model. The view model should have the following commands:

  1. New – Add a new Customer
  2. Save – Save all the changes we did …
  3. Edit – Edit the current selected customer
  4. Delete – Delete the current selected customer
  5. Text box and search button – to operate search activity
  6. Exit the form

Then we need to add the following objects:

  1. An observable collection for the list of customers
  2. A current customer object, but this is not mandatory …
  3. The search information we retrieve from the view, or better, the view sends to us.

The final result will be this view model class:


Let’s have a look at the View Model commands. As you know when we assign a RelayCommand, we can do it in 2 ways:

By passing with a lambda expression the corresponding action.

By passing with a lambda expression the corresponding action and a predicate (something like true/false).

So for some commands like Save or Delete we can also build a predicate action like CanSave? CanDelete? and encapsulating some validation logic inside.

So the code should look like:


The RelayCommands.

Simple command like Create a new customer:

  1: //Private field
  2: public ViewCommand newCommand;
  3: //Public property to be assigned in the XAML code
  4: public ViewCommand NewCommand {
  5:    get {
  6:       if (newCommand == null)
  7:          newCommand = 
  8:          //Lambda expression for assigning the action
  9:          new ViewCommand(param => this.NewCustomer());
 10:       return newCommand;
 11:    }
 12: }
 13: //Real routine executed in the ViewModel
 14: private void NewCustomer() {
 15:    NavigationActions.OpenCustomerView();
 16: }

Or something more complex like Delete a customer:

  1: //Private command field
  2: private ViewCommand deleteCommand;
  3: //Public databinded ICommand
  4: public ViewCommand DeleteCommand {
  5:    get {
  6:       if (deleteCommand == null) {
  7:       deleteCommand = new ViewCommand(
  8:           param=>this.DeleteCustomer(),
  9:           //Lambda expression for evaluating the execution
 10:           param=>this.CanDeleteCustomer
 11:           );
 12:       }   
 13:       return deleteCommand;
 14:    }
 15: }
 16: //Real delete command
 17: public void DeleteCustomer() {
 18:    if (SelectedCustomer != null) {
 19:       if(NavigationActions.QueryConfirmation(
 20:          "Delete Customer.",
 21:          string.Format("Do you want to delete {0}?",SelectedCustomer.FirstName))){
 22:          ListOfCustomers.Remove(SelectedCustomer);
 23:          repository.DeleteCustomer(SelectedCustomer);
 24:       }
 25:    } else {
 26:       NavigationActions.ShowError(
 27:         "Delete Customer.", 
 28:         "You must select a Customer!");
 29:    }
 30: }
 31: //Additional logic can go here ...
 32: private bool CanDeleteCustomer {
 33:    get { return true; }
 34: }

Then of course we will have two different command for Edit a Customer or create a new one, and at the end the difference will be just here:

  1: //Open the Customer window empty
  2: NavigationActions.OpenCustomerView();

  4: NavigationActions.OpenCustomerView(SelectedCustomer);
  3: //Open the Customer window passing a Customer

The others commands are the same, but if you want in my solution you can find the complete implementation.

Loading and working with a Collection.

After we build all the commands and we bind them to the XAML code, we need to load our entities. For this we will use a ObservableCollection List that we will implement in the initialization of our View Model, so when the Window will open we will also load the Collection inside the ListView.

  1: //We need an instance of our repository
  2: CustomerRepository repository;
  3: //This will contain our Customers
  4: ObservableCollection<Customer> listOfCustomers;
  5: //This will be the current selected customer
  6: Customer selectedCustomer;
  7: public CustomersViewModel() {
  8:    if (repository == null) {
  9:       //Initialization of the Repository
 10:       repository = new CustomerRepository();
 11:    }
 12:    Initialization of the List
 13:    listOfCustomers = 
 14:       new ObservableCollection<Customer>(
 15:          repository.GetAllCustomers());
 16:    this.SearchText = "Some text to search ...";
 17: }
 18: //Binded property containing the Customer list
 19: public ObservableCollection<Customer> ListOfCustomers {
 20:    get { return listOfCustomers; }
 21: }


If we want to advise the UI that we loaded a new customers list, we have to build a ViewModel that implements the INotifyPropertyChanged in this way:

  1: #region INotifyPropertyChanged Members
  3: public event PropertyChangedEventHandler PropertyChanged;
  5: public void NotifyPropertyChanged(String info) {
  6:    if (PropertyChanged != null) {
  7:       PropertyChanged(
  8:          this, 
  9:          new PropertyChangedEventArgs(info)
 10:       );
 11:    }
 12: }
 14: #endregion

And then change the property code in this way:

  1: public ObservableCollection<Customer> ListOfCustomers {
  3:     get { return listOfCustomers; }
  4:     private set {
  5:         if (listOfCustomers != value) {
  6:             listOfCustomers = value;
  7:             NotifyPropertyChanged("ListOfCustomers");
  8:         }
  9:     }
 10: }

Now, everytime we are going to load something new into the collection, or we are going to use a view of the collection the ViewModel will send a message in the view saying “Hey, look I changed something in the list, update the UI!!”.

Some XAML code.

Now we have the Commands, the Model and we need to bind them to the view.

Loading the viewmodel into the view:

  1: ...
  2: <xmlns:vm=
  3:    "clr-namespace:MVVM.ViewModel;
  4:    assembly=MVVM.ViewModel />
  6: ...
  7: <Window.DataContext>
  8:    <vm:CustomersViewModel/>
  9: </Window.DataContext>

Binding one command to a Button:

  1: <Button Name="btnNew" Command="{Binding Path = NewCommand}">

Binding the List to the ListView and assigning the selected customer:

  1: <ListView 
  2:   Name="lstCustomers" 
  3:   ItemsSource="{Binding Path=ListOfCustomers}"
  4:   SelectedItem="{Binding Path=SelectedCustomer}" 
  5:   SelectionMode="Single"
  6:   IsSynchronizedWithCurrentItem="True"
  7:   HorizontalAlignment="Stretch" 
  8:   VerticalAlignment="Stretch"
  9:   MinHeight="100">

The IsSynchronizedWithCurrentItem bind the listview and the selecteditem together.

Now, what we should be able to do here is to Load the customers, press delete and wipe one or more then one. Then:

  1. If we close the window and we reopen it the Customer will re-appear again.
  2. If we commit all the changes with the SaveCommand and the we close and re-open the window, the Customer will not be there anymore.

In this lesson we will see only how to implement the search function. In the next one we will see each single command in details.

The user types some text and after that he searches for a result.

  1: private void FindCustomers() {
  2:    //If there is no text, prompt an error
  3:    //In the future this will be a XAML trigger
  4:     if (this.SearchText == string.Empty || this.SearchText == null) {
  5:         NavigationActions.ShowError("Search Customers.", "Please enter some text ...");
  6:         return;
  7:     }
  8:    //Keep the search text and build a dynamic query for the DAL
  9:     ListOfCustomers = new ObservableCollection<Customer>(
 10:         repository.GetCustomersByQuery(
 11:         p => p.CompanyName.StartsWith(SearchText)
 12:         || p.FirstName.StartsWith(SearchText)
 13:         || p.LastName.StartsWith(SearchText)));
 14: }

At this point we will have a first final search solution like these screenshots:

image image