How to bind to a Grouped Items ViewModel with sample data


In MVVM development, you need to define some items collections bindable to your User Interface (View).
First, you must create your collection and items, next, you can create some samples and finally you need to bind these objects to your View (UI).
Since Visual Studio 2013, it’s possible to create your Views and bind data directly in the Visual Editor (without know XAML).

All of that is available for Windows WPF, Windows Phone 8.1, Windows Store Apps, or Windows Universal Apps.

In the following example, I create all classes and XAML code from scratch. This example is a list of contacts grouped by letter’s category.

1. Create the ViewModel

First, we need write all items and collections classes like that.

The following code defines these 3 classes.

using System;
using System.Collections.ObjectModel;
namespace MyApplication.ViewModel
{
    public class ContactsViewModel
    {
        public ContactsViewModel() { this.Groups = new ObservableCollection<ContactsGroupViewModel>(); }
        public ObservableCollection<ContactsGroupViewModel> Groups { get; set; }
    }
    public class ContactsGroupViewModel
    {
        public ContactsGroupViewModel() { this.Items = new ObservableCollection<ContactsItemViewModel>();  }
        public ObservableCollection<ContactsItemViewModel> Items { get; set; }
        public string Letter { get; set; }
    }
    public class ContactsItemViewModel
    {
        public string LastName { get; set; }
        public string FirstName { get; set; }
    }
}

2. Fill the ViewModel with sample data

In the section 3 (below), we’ll use a sample data items to bind with our User Interface… in design mode and/or in runtime mode.

First, create a XAML file with a reference to your ViewModel to easier fill sample items.

<SampleData:ContactsViewModel
          xmlns:SampleData="using:MyApplication.ViewModel" 
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <SampleData:ContactsViewModel.Groups>
        <SampleData:ContactsGroupViewModel Letter="A">
            <SampleData:ContactsGroupViewModel.Items>
                <SampleData:ContactsItemViewModel LastName="Voituron" FirstName="Denis" />
                <SampleData:ContactsItemViewModel LastName="Dubois" FirstName="Anne" />
            </SampleData:ContactsGroupViewModel.Items>
        </SampleData:ContactsGroupViewModel>
    </SampleData:ContactsViewModel.Groups>
</SampleData:ContactsViewModel>

And create an associated class to load this XAML file in memory.

using System;
namespace MyApplication.SampleData
{
    public class ContactSample : ViewModel.ContactsViewModel
    {
        public ContactSample()
        {
            Uri resourceUri = new Uri("ms-appx:/SampleData/ContactsSample.xaml", UriKind.RelativeOrAbsolute);
            Windows.UI.Xaml.Application.LoadComponent(this, resourceUri);
        }
    }
}

3. Draw your User Interface (View).

a. Create a new Page with a ListView.

Add a new Blank Page (right-click / Add / New Item) and drop a ListView or a GridView in your main screen (from the toolbox).

b. Create a CollectionViewSource in your page.

In your new Page, go in the top of XAML file to add this code (a CollectionViewSource and a DataContext):

<Page … 
    xmlns:sample="using:MyApplication.SampleData" />
<Page.Resources>
    <CollectionViewSource x:Key="ItemsGrouped" IsSourceGrouped="True" ItemsPath="Items" Source="{Binding Groups}"/>
</Page.Resources>
<d:Page.DataContext>
    <sample:ContactSample />
</d:Page.DataContext>

Note that d:Page.DataContext defines a DataContext to our ContactSample data, only in Design Mode. So, in runtime you can fill your ViewModel with real data.

That’s all for coding: all of following steps will be only in visual mode in Visual Studio.

c. Set the ListView.ItemsSource

Switch your interface from XAML to Design mode (menu View / Designer), and select the ListView control.
Press F4 to display the ListView control properties and click on the square next to ItemsSource property, and choose the Create DataBinding command.
Define the Binding type to a StaticResource, select your resource ItemsGrouped and click on OK.

d. Define a look for the HeaderTemplate.

Right-click on the ListView and choose the command Add GroupStyle. So, the command GroupStyle / HeaderTemplate is available.
Before to draw visually your Group Header box, hide this listview ;-) For me, it’s a bug in Visual Studio.

And now, go to edit the current Header Template.

And draw as you want: add a Grid and a TextBlock… and bind the
TextBlock.Text property to the Letter property of your SampleData.Groups collection item.

e. Define a look for the ItemTemplate.

Right-click on the ListView and choose the command Edit ItemTemplate / Create Empty. And choose a name for this ItemTemplate (ex. ContactItemTemplate).

And draw as you want (a Grid, 2 TextBlock)… and bind the TextBox.Text to LastName and FirstName of a contact item.

That’s all… you can unhide the ListView or run this application to display a contact list grouped by letter. Of course, in runtime, you need select correct data (not sample from xaml) and sort all contacts by first letter.

Tagged with: , ,
Posted in Formation, MVVM

Asynchronous Simplified


Introduction

For recent developments, users want reactive graphical interfaces, even if you need to recover data from external sources (ex. with web services).
The best solution is to create asynchronous operations to let a responsive UI.
Since the Framework 4.5, Microsoft offers a new and easy way to use asynchronous methods.

Basically, you can create a software with two methods:

  • void LongMethod() to run something that takes a lot of time (ex. 2 seconds).
  • string QuickMethod() to run something that takes little time (ex. 1 second).

public void LongMethod()
{
    System.Threading.Thread.Sleep(2000);
}
public string QuickMethod()
{
    System.Threading.Thread.Sleep(1000);
    return "ABC";
} 

1. Synchronous methods

when you start successively these two methods, of course the User Interface freezes until the procedure is completed.

MyLongMethod();
MyQuickMethod();

And the execution traces will be… and my UI not responding.

 

2. Classic Asynchronous methods

To avoid the UI freezes, you can run these methods into two Threads, via Task.Factory.StartNew or simply Task.Run (see difference on PFXTeaml’s Blog).

Task.Run( () => MyLongMethod() );
Task.Run( () => MyQuickMethod() );

And the execution traces will be… My UI is responding, but of course, you can see a problem: the Main Finished come before each method Finished steps.

3. async / await methods

The best solution, is to use the new async / await keywords. In this case, my methods will be run in different threads (versus my UI) and they wait each finish to continue my main program. And note that, by convention, a method called asynchronously will be suffixed by the Async keyword.

async void Go()
{
   await MyLongMethodAsync();
   await MyQuickMethodAsync();
}

And the execution traces will be… My UI is responding, and the program workflow is correct.

Quick Tips

Unfortunately, if you try to update a UI component or a Collection binded to your UI, from a thread, you’ll receive a NotSupportedException.

You can solve that with two different methods (for a WPF application):

  • The full parameterized method, where you can define a priority level and a timeout beyond which the process will be canceled.

Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, 
                                      TimeSpan.FromSeconds(1), 
                                      new Action( () =>
   {
      // Method to execute in the UI Thread.
      this.ConsoleItems.Add(new ConsoleItem(text, level));
   }
));

  • The light method: before run your asynchronous methods, keep a reference of UI (SynchronizationContext.Current), and next call the Send method.

public SynchronizationContext UIContext { get; set; }

UIContext.Send((state) => 
{
   // Method to execute in the UI Thread.
   this.ConsoleItems.Add(new ConsoleItem(text, level));
}, 
null);
 

 

Finally, if sometime you need to run some methods in a Thread different of UI Thread, but you must ensure that all of these methods will be run in the same Thread (only one). So, download the StaTaskScheduler class wrote by Microsoft and available in a ParallelExtensionsExtras package and write your async method like that:

StaTaskScheduler _sta = new StaTaskScheduler(1); // 1 is the NumberOfThreads

Task<TResult> RunTask<TResult>(Func<TResult> function)
{
   return Task.Factory.StartNew<TResult>(function, CancellationToken.None, TaskCreationOptions.None, _sta);
}

Posted in Formation, Thread, Tips and others

Team Foundation Server TEAM tab is removed every time Excel is opened


if like me, you use TFS and Excel to manage your WorkItems, and maybe your TEAM tab is removed every time Excel is opened. To solve this :

1. Check if this Registry key is on 3 (autostart).
HKEY_CURRENT_USER\Software\Microsoft\Office\Excel\Addins\TFCOfficeShim.Connect.5\LoadBehavior (DWORD)

2. Enable TFS plugin in Excel :
– Go to File / Options / Add-ins
– in the bottom of screen, select Manage COM Add-ins, and click on the GO button.
– Check Team Foundation Ass-in and click on OK button confirm.

That’s all ;-)

Tagged with: , ,
Posted in Uncategorized

How to restore a SQL Server Database to a new location and name


This post explains how to restore a full database backup to a new location and with a new name. This procedure enables you to move a database or create a copy of a database on either the same server instance or a different server instance. This example is usefully for a LocalDB instance of SQL Server 2012.

1. First, you need to know the logical database names (ex. “MyDatabase_data” and “MyDatabase_log”).

RESTORE FILELISTONLY FROM DISK = 'C:\MyBackup.bak'

2. Next, you can restore the backup to a new Database.

RESTORE DATABASE MyNewDataBase
 FROM DISK = 'C:\MyBackup.bak'
 WITH RECOVERY,
 MOVE 'MyDatabase_Data' TO 'C:\Data\NewData.mdf',
 MOVE 'MyDatabase_Log' TO 'C:\Data\NewData_Log.ldf'

To execute these commandes, you can use SQLCMD utility (available in C:\Program Files\Microsoft SQL Server\110\Tools\Binn).

Tagged with: , ,
Posted in General, SQL Server, Tips and others

Add “Extract MSI” command to Windows Explorer Context Menu


Many software or tools are provided as MSI files. There are some tools like LessMSI, but there is a simpler way to add a “Extract MSI” command to your Windows Explorer Context Menu. However, if you make a small registry modification (without Windows reboot), you can add the ability to Extract these file…

Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\Msi.Package\shell\Extract MSI\command]
@="msiexec.exe /a \"%1\" /qb TARGETDIR=\"%1 Extracted\""

Download this file and merge with your registry. Right-click on a MSI file and click on the new command “Extract MSI”.

Tagged with:
Posted in General, Tips and others

Changing the scope of the AssignedTo field in TFS 2012 Work Items


By default, Team Foundation Server presents all “available or existing” users when you assign a work item to somebody. Of course, it’s possible to customize TFS to display only members of one or multi groups in Assign To field.

To do that…

  1. Open Visual Studio (with Team Foundation Server Power Tools).
  2. Go to Tools / Process Editor / Work Item Types / Open WIT From Server.
  3. Select your Team Collection and your Work Item Type.
  4. Select and edit « Assigned To » Field.
  5. Add a new Rule « AllowedValues » and a new value « [project]\Contributors » (see picture below).
  6. Close all dialog boxes.
  7. Save the WIT file to the server (CTRL+S).

Note the [project] should be as is and not substituted for your own project name.

TFS-AllowedContributorsOnly

Tagged with:
Posted in Team Foundation Server, Tips and others

How to sign an assembly in Visual Studio, from a validated certificate (Verisign, Globasign)


If, like me, you want sign your assembly from Visual Studio, you received probablely an error message like “Cannot import the following key file … The key file may be password protected”.

First, read an excellent article about Differences between certificate signing and strong naming (from Eric Lippert).

Next, use this procedure to transform your Code Certificate purchased from Verisign or Globasign to a valid certificate for Visual Studio Strong Name.

1. Download OpenSSL from this site.
2. Execute the following commands to export to a key file usable by Visual Studio.

openssl pkcs12 -in GlobalSignCodeCertificate.pfx -out BackupCertFile.key
openssl pkcs12 -export -out CertFileToSignWith.pfx -keysig -in BackupCertFile.key

3. Then in the project properties of Visual Studio, you can use the PFX file.

Capture

Tagged with: ,
Posted in General
Follow me
   RSS Feed    Twitter    Linked In

Write you email address to subscribe at this blog and to receive new posts by mail.

Join 8 other followers

Who I am?


Follow

Get every new post delivered to your Inbox.