Wednesday, March 27, 2013
Wednesday, December 12, 2012
ChordFactory on Windows 8
Not exactly the height of Metro design excellence either.
Monday, November 26, 2012
LINQ Outer Joins
I found out today how to do outer joins in LINQ and thought I’d save it as an Aide Memoire post.
Given a typical Foreign-Key relationship:
class Preference
{
public int Id { get; set; }
public string Description { get; set; }
}
class Person
{
public int Id { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public int? PreferenceId { get; set; }
}
And this sample data:
var peopleList = new List<Person>();
peopleList.Add(new Person {Id = 77, Forename = "Fred", Surname = "Flintstone", PreferenceId = 2 });
peopleList.Add(new Person {Id = 154, Forename = "Barney", Surname = "Rubble", PreferenceId = 1 });
peopleList.Add(new Person {Id = 308, Forename = "Wilma", Surname = "Flintstone" });
peopleList.Add(new Person {Id = 462, Forename = "Betty", Surname = "Rubble", PreferenceId = 1 });
peopleList.Add(new Person {Id = 616, Forename = "Bam Bam", Surname = "Rubble", PreferenceId = 4 });
peopleList.Add(new Person {Id = 770, Forename = "Pebbles", Surname = "Flintstone" });
var preferenceList = new List<Preference>();
preferenceList.Add(new Preference {Id = 1, Description = "Coffee"});
preferenceList.Add(new Preference {Id = 2, Description = "Tea"});
preferenceList.Add(new Preference {Id = 3, Description = "Hot Chocolate"});
preferenceList.Add(new Preference {Id = 4, Description = "Fruit Juice"});
The obvious LINQ query:
var peopleWithPreferences = from p in peopleList
join pr in preferenceList
on p.PreferenceId equals pr.Id
select new {p.Forename, p.Surname, pr.Description};
Produces results that contain only the inner joined pairs of people and their beverage preference:
Forename Surname Description
Fred Flintstone Tea
Barney Rubble Coffee
Betty Rubble Coffee
Bam Bam Rubble Fruit Juice
In order to retrieve the full list of people with their beverage preference if they have one, the LINQ query becomes:
var peopleAnyPreferences = from p in peopleList
join pr in preferenceList
on p.PreferenceId equals pr.Id into joinedPreferences
from j in joinedPreferences.DefaultIfEmpty()
select new {p.Forename, p.Surname, pref = j != null ? j.Description : string.Empty};
Forename Surname Description
Fred Flintstone Tea
Barney Rubble Coffee
Wilma Flintstone
Betty Rubble Coffee
Bam Bam Rubble Fruit Juice
Pebbles Flintstone
The differences being the intermediate results joinedPreferences and its use with the DefaultIfEmpty extension, with a null check for the nullable column.
UPDATE: From a technique shown in this post by Jim Wooley:
A way of avoiding the need for intermediate results, using old-fashioned T-SQL style joins via a LINQ Where extension:
var betterPeopleAnyPreferences = from p in peopleList
from pr in preferenceList
.Where(x => p.PreferenceId == x.Id)
.DefaultIfEmpty()
select new {p.Forename, p.Surname, pref = pr != null ? pr.Description : string.Empty};
Friday, March 23, 2012
System.Collections.Generic.List<T> ForEach method is missing in Windows 8 Runtime
It seems that the handy ForEach method has been removed from the List of T class in the WinRT. According to Wes Haggard of the .NET Framework Bas Class Library (BCL) Team:
“List<T>.ForEach has been removed in Metro style apps. While the method seems simple it has a number of potential problems when the list gets mutated by the method passed to ForEach. Instead it is recommended that you simply use a foreach loop.”
Which is a shame, as I use this method quite a bit to invoke method group calls to do one-time iterations over Lists, like this:
keywordResults.ForEach(this.searchActivity.Keywords.Add);For situations like this, the mutation issue doesn’t arise and it would be safe to use the ForEach method if it existed. So I did an extension method implementation of the functionality by taking a look at the decompiled code of the method in earlier versions of the .NET Framework:
public void ForEach(Action<T> action)
{
if (action == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
for (int index = 0; index < this._size; ++index)
action(this._items[index]);
}
Using this as a starting point it was fairly easy to come up with an extension method version:
public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
foreach (var t in list)
{
action(t);
}
}
Now I can use the extension to give me the same ForEach functionality on IEnumerable objects such as List<T> as I had before.
Thursday, April 21, 2011
Five Minute Silverlight 5 Aides-Memoire #4 – Mouse Click Count
- <Rectangle Width="154"
- Height="77"
- MouseLeftButtonDown="RectangleMouseLeftButtonDown">
- <Rectangle.Fill>
- <LinearGradientBrush x:Name="GradientFill" StartPoint="0,0" EndPoint="1,1">
- <GradientStop Offset="0" Color="Red" />
- <GradientStop Offset="0.1667" Color="Orange" />
- <GradientStop Offset="0.334" Color="Yellow" />
- <GradientStop Offset="0.5001" Color="Green" />
- <GradientStop Offset="0.6668" Color="Blue" />
- <GradientStop Offset="0.8335" Color="Indigo" />
- <GradientStop Offset="1" Color="Violet" />
- </LinearGradientBrush>
- </Rectangle.Fill>
- </Rectangle>
- <TextBlock x:Name="ClickCountTextBlock"
- Foreground="White"
- HorizontalAlignment="Center"
- VerticalAlignment="Center"
- FontSize="40"
- Opacity="0.4"
- Text="" />
- private void RectangleMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
- {
- this.ClickCountTextBlock.Text = e.ClickCount.ToString();
- var topLeft = new Point(0, 0);
- var topRight = new Point(1, 0);
- var bottomLeft = new Point(0, 1);
- var bottomRight = new Point(1, 1);
- switch (e.ClickCount)
- {
- case 2:
- this.GradientFill.StartPoint = topRight;
- this.GradientFill.EndPoint = bottomLeft;
- break;
- case 3:
- this.GradientFill.StartPoint = bottomRight;
- this.GradientFill.EndPoint = topLeft;
- break;
- case 4:
- this.GradientFill.StartPoint = bottomLeft;
- this.GradientFill.EndPoint = topRight;
- break;
- default:
- this.GradientFill.StartPoint = topLeft;
- this.GradientFill.EndPoint = bottomRight;
- break;
- }
- }
Five Minute Silverlight 5 Aides-Memoire #3 – Out-of-Browser Native Windows
- private void ButtonClick(object sender, RoutedEventArgs e)
- {
- if (!Application.Current.IsRunningOutOfBrowser)
- {
- return;
- }
- var newGrid = new Grid
- {
- Background = new SolidColorBrush(Colors.White),
- HorizontalAlignment = HorizontalAlignment.Stretch,
- VerticalAlignment = VerticalAlignment.Stretch
- };
- var newTextBlock = new TextBlock
- {
- HorizontalAlignment = HorizontalAlignment.Center,
- VerticalAlignment = VerticalAlignment.Center,
- Text = "New TextBlock in a new Window..."
- };
- newGrid.Children.Add(newTextBlock);
- new Window { Content = newGrid, Visibility = Visibility.Visible, Width = 300, Height = 300 };
- }
Wednesday, April 20, 2011
Five Minute Silverlight 5 Aides-Memoire #2 – Implicit DataTemplates
- /// <summary>
- /// The cartoon character.
- /// </summary>
- public class CartoonCharacter
- {
- /// <summary>
- /// Gets or sets the forename.
- /// </summary>
- /// <value>The forename.</value>
- public string Forename { get; set; }
- }
- /// <summary>
- /// The flintstone.
- /// </summary>
- public class Flintstone : CartoonCharacter { }
- /// <summary>
- /// The griffin.
- /// </summary>
- public class Griffin : CartoonCharacter { }
- /// <summary>
- /// The simpson.
- /// </summary>
- public class Simpson : CartoonCharacter { }
- <Grid x:Name="LayoutRoot"
- Background="White">
- <Grid.Resources>
- <Style x:Key="SimpsonStyle"
- TargetType="TextBlock">
- <Setter Property="FontFamily" Value="Comic Sans MS" />
- <Setter Property="FontSize" Value="16" />
- <Setter Property="Foreground" Value="Blue" />
- <Setter Property="FontStyle" Value="Italic" />
- </Style>
- <DataTemplate DataType="this:Simpson">
- <Border Background="Yellow">
- <StackPanel Orientation="Horizontal">
- <TextBlock Style="{StaticResource SimpsonStyle}"
- Text="{Binding Forename}" />
- <TextBlock Margin="5,0,0,0"
- Style="{StaticResource SimpsonStyle}"
- Text="Simpson" />
- </StackPanel>
- </Border>
- </DataTemplate>
- <DataTemplate DataType="this:Flintstone">
- <Border Background="Orange">
- <Border.RenderTransform>
- <TransformGroup>
- <SkewTransform AngleX="-20" />
- <ScaleTransform ScaleX="2"
- ScaleY="0.75" />
- <TranslateTransform X="30" />
- </TransformGroup>
- </Border.RenderTransform>
- <StackPanel Orientation="Horizontal">
- <TextBlock Text="{Binding Forename}" />
- <TextBlock Margin="5,0,0,0"
- Text="Flintstone" />
- </StackPanel>
- </Border>
- </DataTemplate>
- <DataTemplate DataType="this:Griffin">
- <Border BorderBrush="DarkSlateBlue" BorderThickness="2">
- <StackPanel Orientation="Horizontal">
- <TextBlock Text="{Binding Forename}" FontSize="18">
- <TextBlock.Effect>
- <BlurEffect />
- </TextBlock.Effect>
- </TextBlock>
- <TextBlock Margin="5,0,0,0"
- FontSize="22" CharacterSpacing="5"
- Text="Griffin">
- <TextBlock.Effect>
- <DropShadowEffect />
- </TextBlock.Effect>
- </TextBlock>
- </StackPanel>
- </Border>
- </DataTemplate>
- </Grid.Resources>
- <ListBox x:Name="CartoonCharactersListBox"
- Margin="50,20"
- BorderBrush="Blue"
- BorderThickness="2"
- ItemsSource="{Binding}" />
- </Grid>
Yeugh!!
Five Minute Silverlight 5 Aides-Memoire #1 – Style Setter Binding
- <Grid x:Name="LayoutRoot"
- Background="White">
- <Grid.RowDefinitions>
- <RowDefinition />
- <RowDefinition Height="Auto" />
- </Grid.RowDefinitions>
- <Grid.Resources>
- <Style x:Key="VariableFontTextBlockStyle"
- TargetType="TextBlock">
- <Setter Property="Foreground" Value="DarkOrange" />
- <Setter Property="FontWeight" Value="Bold" />
- <Setter Property="FontSize" Value="{Binding ElementName=FontSizeSlider, Path=Value}" />
- </Style>
- </Grid.Resources>
- <TextBlock x:Name="SampleTextBlock"
- Grid.Row="0"
- HorizontalAlignment="Center"
- VerticalAlignment="Center"
- Style="{StaticResource VariableFontTextBlockStyle}"
- Text="No Mr Bond - I expect you to die" />
- <Slider x:Name="FontSizeSlider"
- Grid.Row="1"
- MaxWidth="500"
- Margin="100,30"
- Maximum="64"
- Minimum="8"
- Value="12" />
- </Grid>
Friday, April 15, 2011
Building Silverlight Chord Factory: Part 3 – The View and Windows Phone 7
Despite my good intentions, it’s been a year since I posted the second part of my set of posts on Building Silverlight Chord Factory (see Part 1 and Part 2). The third part – on the View in the Model-View-ViewModel (MVVM) triptych has been a bit delayed, mainly by work and other pressures, but also by my attention being diverted by the arrival of Windows Phone 7 (WP7).
My practice of exploring new development platforms and languages by converting my hobby project – the Openfeature Chord Factory – kicked in and the application got yet another transformation. Which worked out quite well as it illustrated some of the power and benefits of the MVVM pattern. Converting the Silverlight Chord Factory code to WP7 Silverlight code was pretty simple and the main area of change – the View – was nicely isolated from the remaining code allowing the XAML markup to be adapted to the WP7 Control Toolkit easily and the custom controls in the app to work with virtually no modifications for the new platform.
So now this belated post can be both a look at the original View and at the adaptions involved in moving the app to the WP7 platform.
Here are a few screenshots of the Silverlight application in a couple of incarnations, running in a browser:
Note the unfinished musical stave controls…
Screenshots of Silverlight ChordFactory application
And here are screenshots of the Wp7 application:
Screenshots of WP7 app
Leaving aside my relative lack of UI/UX design capability, you can see that basically the User Experience is the same for both versions of the ChordFactory app. And in some of the UI itself the styling is exactly the same – the keyboard keys for example.
In fact I was able to reuse large chunks of the Openfeature Silverlight music controls (Keyboard, Octave and PianoKey controls) that I developed for the browser app because they consist of generic, compatible XAML markup and C# code. The Views in either case are of course nothing more than the markup/styling with bindings to the appropriate data sources in the ViewModel. With the Model and ViewModel classes being completely platform independent, they needed no redevelopment at all.
So I was able to get the WP7 ChordFactory app up and running in not much more than an easy afternoon of working on it. The majority of the work required lay in adding XNA code to play piano note samples added to the app so that the user can hear the selected chord or scale. Something I couldn’t do as easily with the browser version and hadn’t got around to implementing with MediaElements. Registering with the App Hub and submitting the app took a few trips back and forth to cross all the ‘Ts’ and dot all the ‘Is’, but the app is now live here:
Tuesday, April 13, 2010
Building Silverlight Chord Factory: Part 2 – The ViewModel
This is part 2 in my series of posts on building the latest MVVM incarnation of my ChordFactory hobby project; in Part 1 I discussed modelling musical chord and scale data in XML – the Model in the MVVM (Model-View-ViewModel) pattern. In this post I will look at the next part of the pattern – the ViewModel.
Loading the data
In the MVVM pattern, data is held in properties of the ViewModel to allow the Views to data-bind UI elements directly onto those properties. In the ChordFactory application, the mechanics of loading the data from the XML and building the Chords and Scales collections to supply the View-Model are implemented using the Repository pattern with individual repository classes, deriving from a repository base class, for the Chords and the Scales collections. These classes implement private static methods to load their respective data and then surface the collections retrieved via public methods that return ObservableCollections of Chords and Scales respectively.
- public class RepositoryBase
- {
- protected static Stream GetResourceStream(string resourceFile)
- {
- Uri uri = new Uri(resourceFile, UriKind.RelativeOrAbsolute);
- StreamResourceInfo info = Application.GetResourceStream(uri);
- if (info == null || info.Stream == null)
- throw new ArgumentException("Missing resource file: " + resourceFile);
- return info.Stream;
- }
- }
- public class ChordRepository : RepositoryBase
- {
- private readonly ObservableCollection<Chord> observableChords = new ObservableCollection<Chord>();
- public ChordRepository(string chordDataFile)
- {
- LoadChords(chordDataFile).ForEach(observableChords.Add);
- }
- private static List<Chord> LoadChords(string chordDataFile)
- {
- using (Stream stream = GetResourceStream(chordDataFile))
- using (XmlReader xmlRdr = XmlReader.Create(stream))
- return (from chordElem in XDocument.Load(xmlRdr).Element("Chords").Elements("Chord")
- select
- Chord.CreateChord((string) chordElem.Element("Description"),
- chordElem.Element("NoteList").Elements("NoteIndex").Select(
- x => int.Parse(x.Value)).ToList())).ToList();
- }
- public ObservableCollection<Chord> GetChords()
- {
- return observableChords;
- }
- }
- public class ScaleRepository : RepositoryBase
- {
- private readonly ObservableCollection<Scale> observableScales = new ObservableCollection<Scale>();
- public ScaleRepository(string scaleDataFile)
- {
- LoadScales(scaleDataFile).ForEach(observableScales.Add);
- }
- private static List<Scale> LoadScales(string scaleDataFile)
- {
- using (Stream stream = GetResourceStream(scaleDataFile))
- using (XmlReader xmlRdr = XmlReader.Create(stream))
- return (from ScaleElem in XDocument.Load(xmlRdr).Element("Scales").Elements("Scale")
- select
- Scale.CreateScale((string)ScaleElem.Element("Description"),
- ScaleElem.Element("NoteList").Elements("NoteIndex").Select(
- x => int.Parse(x.Value)).ToList())).ToList();
- }
- public ObservableCollection<Scale> GetScales()
- {
- return observableScales;
- }
- }
Data in the ViewModel
The ViewModel uses the Repositories to load the data and provides it as bindable collections together with other bindable properties such as the currently selected items in the collections and implementation of change notification so that bound UI can respond to updates in the ViewModel.
- public class ChordsViewModel : INotifyPropertyChanged
- {
- private readonly ObservableCollection<Chord> chords;
- private readonly ObservableCollection<Scale> scales;
- private List<int> selectedChord;
- private List<int> selectedScale;
- private RootNotes rootNote;
- private Inversion inversion;
- public event PropertyChangedEventHandler PropertyChanged;
- private readonly List<Inversion> inversions = new List<Inversion>
- {
- Inversion.Basic,
- Inversion.First,
- Inversion.Second,
- Inversion.Third,
- Inversion.Fouth
- };
- public ChordsViewModel()
- {
- chords = new ChordRepository("/Openfeature.ChordFactory;component/Data/chords.xml").GetChords();
- scales = new ScaleRepository("/Openfeature.ChordFactory;component/Data/scales.xml").GetScales();
- }
- public ObservableCollection<Chord> Chords
- {
- get { return chords; }
- }
- public ObservableCollection<Scale> Scales
- {
- get { return scales; }
- }
- public List<Inversion> Inversions { get { return inversions; } }
- public List<int> SelectedChord
- {
- get { return selectedChord; }
- private set
- {
- selectedChord = value;
- OnPropertyChanged("SelectedChord");
- }
- }
- public List<int> SelectedScale
- {
- get { return selectedScale; }
- private set
- {
- selectedScale = value;
- OnPropertyChanged("SelectedScale");
- }
- }
- public Inversion Inversion
- {
- get { return inversion; }
- set
- {
- inversion = value;
- OnPropertyChanged("Inversion");
- }
- }
- public RootNotes RootNote
- {
- get { return rootNote; }
- set
- {
- rootNote = value;
- OnPropertyChanged("RootNote");
- }
- }
- public void ChordSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- SelectedChord = ((Chord)e.AddedItems[0]).Notes;
- }
- public void InversionSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- Inversion = (Inversion)e.AddedItems[0];
- }
- public void RootNoteChanged(object sender, SelectionChangedEventArgs e)
- {
- RootNote = (RootNotes)e.AddedItems[0];
- }
- public void ScaleSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- SelectedScale = ((Scale)e.AddedItems[0]).Notes;
- }
- private void OnPropertyChanged(string propertyName)
- {
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
- }
- }
- }
The Chords and Scales collection properties of the ViewModel are bound to UI elements, (initially ComboBoxes – UI/UX enhancement will have to come later), and their SelectionChanged events wired back to the ViewModel using the CallDataMethod behaviour from the excellent Expression Blend Samples on Codeplex:
- <StackPanel x:Name="BoundData" Orientation="Horizontal" Margin="10,10,10,20" >
- <ComboBox x:Name="ChordsList" ItemsSource="{Binding Chords}" DisplayMemberPath="Description" Margin="10,0">
- <i:Interaction.Triggers>
- <i:EventTrigger EventName="SelectionChanged">
- <si:CallDataMethod Method="ChordSelectionChanged" />
- </i:EventTrigger>
- </i:Interaction.Triggers>
- </ComboBox>
- <ComboBox x:Name="ScalesList" ItemsSource="{Binding Scales}" DisplayMemberPath="Description" Margin="10,0">
- <i:Interaction.Triggers>
- <i:EventTrigger EventName="SelectionChanged">
- <si:CallDataMethod Method="ScaleSelectionChanged" />
- </i:EventTrigger>
- </i:Interaction.Triggers>
- </ComboBox>
- <ComboBox x:Name="InversionsList" Margin="10,0" ItemsSource="{Binding Inversions}">
- <i:Interaction.Triggers>
- <i:EventTrigger EventName="SelectionChanged">
- <si:CallDataMethod Method="InversionSelectionChanged" />
- </i:EventTrigger>
- </i:Interaction.Triggers>
- </ComboBox>
- </StackPanel>
The ViewModel handles selection changes and sets its SelectedChord and SelectedScale properties appropriately. The piano keyboard which displays the notes from the selected chord and scale is written as a Silverlight Control and it too has SelectedChord and SelectedScale properties; these bind to the properties on the ViewModel with the same name. The keyboard control also responds to left-mouse clicks in order to allow the selection of the root note of the chord or scale.
So now I have my data loaded and in a bindable ViewModel, creating a user interface in XAML to represent it to the user of the Silverlight ChordFactory is next, together with some stuff about testing. That’s for part 3.
