Quantcast
Channel: Muhammad Rehan Saeed
Viewing all 138 articles
Browse latest View live

WPF Metro Part 1 - Modern UI for WPF

$
0
0

https://www.youtube.com/watch?v=Bk7mlEQI2rk

In these series of posts I'm going to do a quick review of a few different open source WPF Metro (Or Modern if you prefer) style SDK's. Each of them provides styles and new controls to build your WPF application from scratch. Here are the home pages for the open source projects in question where you can download the source code and the binaries to play with them yourself:

Modern UI for WPF

In this first post I will be discussing Modern UI for WPF. This is a very lightweight framework which has a complete set of styles for the built in WPF controls.

Look and Feel

The look of the application seems to borrow quite heavily from Microsoft's Zune application, which is Microsoft's equivalent of Apple's iTunes. Zune was used by Microsoft as an early test bed for their Metro style. Microsoft then went on from there to build Windows 8. This is Zune below:

Microsoft Zune Software

The Window style is quite stunning, mostly achieved by providing some very nice soft backgrounds to go with the option of white or black themes. The theme is fairly flexible, allowing a selection of 'Accent' colours and even selection of small and large font sizes. One cool feature I discovered is that changing the them does not simple change the colours but the Developer has used a colour animation to transition from one colour to another.

Modern UI for WPF Heart Background

Modern UI for WPF Themes

The controls themselves are more toned down. Employing simple grey lines and a very minimalist design. Most of the controls are slightly on the small side compared to Windows 8 but having played with Zune I can tell you that the developer has recreated everything pretty accurately.

Modern UI for WPF Input Controls

All the built in WPF controls seem to have been styled and a type ramp is even included, giving a simple way to show text in different guises. Validation of input is supported via the TextBox control. It would have been nice for other controls to have been supported too but it is very nicely done.

Custom Controls

ModernMenu

The main control of interest is the tab control called ModernMenu, this provides a very interesting multi-level tabbed experience. It allows you to split the tab contents into seperate user controls using the URI to the XAML page a bit like the Silverlight experience. Navigation is always a problem that needs to be solved in a WPF application and this is one very clean method of doing it.

Modern UI for WPF ModernMenu

ModernButton

A Windows 8 style circular app-bar button. Comes in two sizes.

Modern UI for WPF ModernButton

ModernWindow, ModernDialog and MessageBox

The developer has inherited from the Window class to create three very useful window types.

Modern UI for WPF ModernDialog

Modern UI for WPF MessageBox

ModernProgressRing

This is very easily the best progress indicator I have seen. It has several modes, allowing you to select the method of showing progress. Simply mesmerizing.

Modern UI for WPF ModernProgressRing

BBCodeBlock

This is a nice little control allowing you to use BB code to write some text.

Modern UI for WPF BBCodeBlock

Source Code

The source code seems pretty lightweight and nicely structured, with each controls style having it's own XAML file. There are only two DLL's which need to be deployed, they even provide a NuGet package which is great. Looking at the checking history, the single developer (The creator of XAML Spy no less) seems fairly active with the last check-in performed on 21st January 2014, so the project is still very much active. Looking at the discussion forums he seems to also be very helpful.

Conclusions

Overall I'm very impressed with this SDK, it's a labour of love from a single developer. It has a very high attention to detail and covers most bases for most developers, providing a full set of WPF styles.

If the developer is reading, I would suggest adding a tab in his sample showing the colours and brushes available to the developers and expanding his validation to other input controls.

This is a great project and it would be a pleasure to use any application developed using this SDK.


WPF Metro Part 2 - MahApps Metro

$
0
0

https://www.youtube.com/watch?v=FLmCkKfIp84

In these series of posts I'm going to do a quick review of a few different open source WPF Metro (Or Modern if you prefer) style SDK's. Each of them provides styles and new controls to build your WPF application from scratch. Here are the home pages for the open source projects in question where you can download the source code and the binaries to play with them yourself:

MahApps Metro

This is the second post in the series, I take a look at MahApps Metro. Again, this SDK provides a complete set of WPF styles and several custom controls, mostly inspired by the new Windows 8 WinRT applications.

Look and Feel

This SDK borrows heavily from the Windows 8 Metro design language. It provides fairly large controls (For desktop applications, Windows 8 seems to have larger buttons to be touch friendly) with fairly thick borders, which gives each control a more imposing look. There are lots of brushes used by this SDK and the developer has provided a nice colour swatch.

MahApps Metro screenshot of the available brushes

The Window itself positively glows as the developer has spent a lot of time customizing the window drop shadow. The title bar of the window also stands out as it is highlighted in the applications accent colour. Theme support is built in, with light or dark combined with an accent colour as shown below.

MahApps Metro screenshot of the button controls

MahApps Metro screenshot of the changed theme

Custom Controls

ToggleSwitch

(See Above) Similar to the ToggleSwitch in Windows 8, this control provides an optional replacement for the standard CheckBox control. Every metro SDK seems to include this control.

CircleButton

(See Above) Again this control borrows from the Windows 8 application bar buttons. A staple of all metro SDK's it seems.

NumericUpDown

This is a great control that is sorely needed in most WPF applications. Internally it handles numbers of type Double but I suppose you could use a converter to work with Integer and other numeric types.

Various TextBox Controls

There is a great selection of text box controls. They all seem to have the watermark capability (Again, a simple addition sorely missed in WPF). There is also the option of text boxes with buttons.

MahApps Metro screenshot of the input controls

ProgressRing

A simple circular progress indicator control. I can stare at these things for hours. Very mesmerizing.

Range Slider

The range slider is another great addition. It looks very much like the Slider control with an additional thumb button.

MahApps Metro screenshot of the progress and slider controls

Various MessageDialog's and MessageBox's

This is a truly great message box. Instead of copying and restyling the standard Windows MessageBox, it has been totally reshaped and re-imagined ala Windows 8 to cover the entire parent Window. Not only that but you can place your own custom content in there. There are a few different options to choose from, the version below shows a text box.

MahApps Metro screenshot of the message box

Flyout

This Windows 8 style fly-out control does what it says on the tin, it flies in and out of the side of the Window. A nice feature is that it covers the title bar of the window but the caption buttons are still overlayed above the fly-out control.

MahApps Metro screenshot of the fly-out control

FlipView

This control also exists in Windows 8, although it works slightly differently. It allows you to view several items one at a time and provides next and previous buttons to cycle between them.

MahApps Metro screenshot of the custom controls

Source Code

I downloaded the source code hosted on GitHub and took it for a whirl. All the XAML is pretty well layed out and there is a fair amount of code in the project but that's expected as there are lots of custom controls to play with. There is only a single dependency on System.Windows.Interactivity, so you only need to add references to two DLL's to your projects.

Looking at the discussion boards, there seems to be a fair amount of activity with the developers answering questions and even responding to feedback which is great to see. The last check-in was just four days ago at the time of writing so this project is still very much active. I can see this project getting better and better in the future.

Conclusions

Once again I'm very impressed with this SDK, it provides styles for all the standard WPF controls and takes a pretty good stab at bringing a lot of Windows 8 Metro controls to the desktop. It does all this while looking and feeling great. They even provide a NuGet package which is great.

MahApps Metro screenshot of the calendar controls

MahApps Metro screenshot of the DataGrid control

MahApps Metro screenshot of the DataGrid control

Windows 8.1 TouchScreen Gaming Laptops

$
0
0

Would you buy a sandwich without the filling? Would you buy a car without the radio? No? Then why are most Windows 8.1 laptops sold without touch screens?

I do a bit of Windows 8 and Windows Phone development on the side, so a touch screen is handy for testing but you're probably asking, whats so good about a touch screen? Well this is a little difficult to quantify. Having tried a laptop with one, there are some operations which are just more natural with your fingers. Resizing an image with a two finger gesture sticks out as one good example. You find yourself using it every now and then wherever appropriate.

Windows 8 seems to have gotten a bad rap in recent times, mostly due to the full screen start screen. I personally can't see the problem, it just downright statistically more efficient and quicker to open an application than the old cramped Windows7/Vista start menu and has lots of cool features like pausing file transfers and mounting ISO files which I use all the time.

Windows 7 Start Menu

Heat map of time to reach items in the Start menu from the Start button
(green items are the fastest to get to, red items are the slowest)

Windows 8 Start Menu

Heat map of time to reach tiles in the Start screen from the Start button
(green tiles are the fastest to get to, red tiles are the slowest)

That's not to say it doesn't have its problems, I like to use the Windows 8.1 mail application. I like it because I can pin it to my start screen and get notifications on the tile for any new emails. As a heavy desktop user though, I want to open the application on the desktop in a window and not in the full screen touch friendly window. Happily though :), this is going to be fixed in the next update where WinRT apps can now be run on the good old desktop.

Windows 8 app running on Desktop

Windows 8 Bing Finance app running on Desktop

Ihave been looking to replace my trusty old non-touch screen Samsung laptop running Windows 8.1 with a new touch screen model. However, I like to shoot a few HE shells at some tanks while playing World of Tanks on the weekend in my down time. Its not the most demanding of games but I'd like to look forward to future updates and other games like Battlefield 4.

So I've been doing my research on what my options are for a touch screen gaming laptop and was very surprised to discover that they are pretty non-existent. The closest thing you'll find is the Asus N550JV-CN201H, which is not really a gaming laptop with an nVidia GT750M low to mid-range graphics card. It'll play today's games at mid-range settings and will probably choke on tomorrows games altogether.

Why is this? Well after some reading I get the impression that laptop manufacturers believe that enthusiasts don't like glossy screens and adding a touch screen means adding a glossy layer on top of the screen. This I think is personal preference, I have seen one matt screened touch screen laptop in the wild but I can't remember where, so it is at least possible to have a matt screen. So why the delay?

What I really want is the MSI GS70 Stealth but with a touch screen. This is the worlds thinnest 17" laptop with an Intel i7 CPU, a GT765M mid to high end graphics card and even a SSD RAID 0 array. Overall its a very impressive beast packed into a small a space as possible.

MSI GS70 Stealth Laptop

So if MSI is listening, the demand is here for touchscreen gaming laptops, surprise us.

Reactive Extensions (Rx) - Part 4 - Replacing Timers

$
0
0

Reactive Extensions (Rx) is a huge library. In this series of blog posts I've tried to illustrate real world applications where using Rx can significantly improve and/or simplify your code. So far I've talked about using Rx to replace standard C# events and also wrapping C# events with observables.

In this post I'm going to talk about another area where Rx provides a nicer API surface, as compared to an existing .NET API. In particular, I'm talking about the .NET Timers. There are a few different timers available in the .NET framework. The main ones being System.Threading.Timer and System.Timers.Timer. Each one has their pros and cons but I'm not going to go into which ones are better as that's a whole other conversation.

Existing .NET Timers

Below is a very simple example of how to use the System.Timers.Timer (System.Threading.Timer is very similar). We new-up a Timer with the number of milliseconds we want to timer to raise it's Elapsed event, register for the Elasped event and finally start the timer.

public void StartTimer()
{
    Timer timer = new Timer(5000);
    timer.Elapsed += this.OnTimerElapsed;
    timer.Start();
}

private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
    // Do Stuff Here
    Console.WriteLine(e.SignalTime);
    // Console WriteLine Prints
    // 11/03/2014 10:58:35
    // 11/03/2014 10:58:40
    // 11/03/2014 10:58:45
    // ...
}

Reactive Extensions (Rx) Timers

Now here is how to do almost the exact same thing with Reactive Extensions. In this scenario we use the Interval method to specify the timer interval and simply subscribe to the observable. The only difference is that we don't get a DateTime with the time of the timer elapsed event but an integer representing the number of times the timer elapsed delegate has been fired (Much more useful in my opinion, as you can always derive the time from this number).

public void StartTimer()
{
    Observable
        .Interval(TimeSpan.FromSeconds(5))
        .Subscribe(
            x =>
            {
                // Do Stuff Here
                Console.WriteLine(x);
                    // Console WriteLine Prints
                    // 0
                    // 1
                    // 2
                    // ...
            });
}

But that's not all, Reactive Extensions provides another method which can be quite useful. In the example below which looks almost exactly the same, we use the Timer method instead of Interval. This method only calls the timer elapsed delegate once.

public void StartTimerAndFireOnce()
{
    Observable
        .Timer(TimeSpan.FromSeconds(5))
        .Subscribe(
            x =>
            {
                // Do Stuff Here
                Console.WriteLine(x);
                // Console WriteLine Prints
                // 0
            });
}

The Timer method has lots of overloads which you can take a look at. The example below calls the timer elapsed delegate every five seconds but only starts to do so, after a minute has passed.

public void StartTimerInOneMinute()
{
    Observable
        .Timer(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5))
        .Subscribe(
            x =>
            {
                // Do Stuff Here
                Console.WriteLine(x);
                // Console WriteLine Prints
                // 0
                // 1
                // 2
                // ...
            });
}

The final thing you need to know about the Interval and Timer methods is that they can optionally take an IScheduler as a final parameter. This allows the timer elapsed delegate to be run on any thread of your choosing. In the example below we are subscribing the event on the WPF UI thread. There are several other Scheduler's you can use, so just take a look.

public void StartTimerOnUIThread()
{
    Observable
        .Interval(TimeSpan.FromSeconds(5), DispatcherScheduler.Current)
        .Subscribe(
            x =>
            {
                // Do UI Stuff Here
            });
}

Conclusions

If you haven't started using Reactive Extensions yet, then here is yet another reason to get going. What I have not shown in this post is the shear superhuman power you get when you use the Linq methods to modify your observable just before you make the call to Subscribe.

WPF Metro Part 3 - Elysium

$
0
0

https://www.youtube.com/watch?v=YChJguA6ai8

In these series of posts I'm going to do a quick review of a few different open source WPF Metro (Or Modern if you prefer) style SDK's. Each of them provides styles and new controls to build your WPF application from scratch. Here are the home pages for the open source projects in question where you can download the source code and the binaries to play with them yourself:

Elysium

This is the third post in the series. I've been using Elysium at work for the last year and have been pretty impressed with it. There are a few gaps in terms of the styles it provides but that's where Elysium Extra comes in.

Look and Feel

This SDK takes its own view of what Metro ought to look like. It makes much more use of the accent colour in its controls which have a bold and striking look to them. Where colour is used, it is used in abundance, on the otherwise plain white canvas.

Once again, this SDK supports themes out of the box. It gives you the option of a dark or light background, an accent colour and contrast colour.

Elysium Screenshot Light Buttons Showcase

Elysium Screenshot Dark Buttons Showcase

Custom Controls

AppBar, CommandButton, DropDownCommandButton and ToggleCommandButton

The standard Windows 8 buttons are all here but composed of three variants. The SDK also provides a Windows 8 style application bar which pops up from the bottom of the screen on right click. Buttons placed in the application but have separate styles and look pretty pleasing. The developer has done a pretty good job of recreating the Windows 8 application bar experience.

ToggleSwitch

The standard alternative to the CheckBox control is here too.

Elysium Screenshot Light Selectors And Ranges Showcase

Elysium Screenshot Dark Selectors And Ranges Showcase

ProgressBar and ProgressRing

These are the alternatives to the standard WPF ProgressBar control and are quite pleasing to the eye.

Source Code

The code is available on GitHub and you could download the latest change set but it seems to be broken at the time of writing because the developer is doing some pretty major re-factoring (Use Team Foundation Server shelve-sets to avoid checking in broken code). That's a bit of a shame as the basics of this SDK are pretty solid.

Looking at the discussion boards, there seems to be a fair amount of activity but the developer seems to have gone on holiday as I've been unable to contact him to talk about Elysium Extra which I'll be discussing in my next post (Update: The developer is back and says he is continuing development after a brief pause).

Conclusions

This is a solid SDK but it does lack basic styles for some WPF controls such as the DatePicker and DataGrid, for some this is a deal breaker but Elysium Extra covers these bases and more. Elysium does provide a NuGet package which is great and even an MSI which has full integration with Visual Studio!

Elysium Screenshot Light Text And Menus Showcase

Elysium Screenshot Dark Text And Menus Schowcase

WPF Metro Part 4 - Elysium Extra

$
0
0

https://www.youtube.com/watch?v=PGM_uBy99GA

In these series of posts I'm going to do a quick review of a few different open source WPF Metro (Or Modern if you prefer) style SDK's. Each of them provides styles and new controls to build your WPF application from scratch. Here are the home pages for the open source projects in question where you can download the source code and the binaries to play with them yourself:

Elysium Extra

::: warning I am the developer of Elysium Extra. It was developed at the company where I work, where I had an excellent manager who saw the advantage of open sourcing the code and making it widely available to the .NET community.

My intention was to submit this code to the Elysium project, however, the developer had been away for a couple of months, so I released Elysium Extra as a separate project. Happily though, the developer of Elysium has returned and resumed development of the SDK. I've yet to discuss how we can move forward with the two code bases.

This post will be a bit longer as I need to outline the contents of Elysium Extra as it's a new SDK and needs a little explaining (It contains a lot of cool stuff!). :::

Elysium Extra is an add-on project to Elysium. It fills in some gaps which existed in the Elysium SDK, improves some styles and adds lots of new styles, new controls and style guidelines.

As the code has been used in a real life, large scale application (Albeit heavily modified and cleaned up to make it ready for open sourcing), it should in theory (Fingers crossed) be production quality. It also seems to contain a lot of attached properties and other small bits of code which were found to be required when building a WPF application, that other SDK's do not contain. All of these have demo's in the sample application.

Look and Feel

The look and feel picks up from where Elysium leaves off. Some control styles have been modified and improved, others have been modified for consistency.

The window has be heavily modified to allow full customization. Pretty much every feature you can think of has been added. Changes include Window border glow effects, saving window placement, full screen mode...the list goes on.

Other major differences between this SDK over Elysium are that the TextBox and ComboBox controls have been brought more into line with each other, so if you add them in a form they don't look out of place.

The ability to change theme's is unfortunately currently broken as a side effect of Elysium Extra having to wrap the Elysium XAML styles. This is pretty high up the list of things planned to be fixed though.

Elysium Extra - Sample application screenshot of the Colours

Custom colours over and above what Elysium provides and guidelines on how to use them.

As this SDK has been open sourced from a live application. There are lots of styles for icons, menu items and app-bar buttons. These are things you'd use in every application. Things like cut, copy and paste buttons etc.

Elysium Extra - Sample application screenshot of the App Bar

Elysium Extra - Sample application screenshot of the built in MenuItem's

Custom Controls

ElasticPicker

The ElasticPicker is a very unique control that I'm most proud of. It can be used to filter a collection of things with a few clicks, all while looking fantastic and doing lots of flashy animations that will make your eyes light up. The screen-shots do not do it justice, so do watch the video for a better understanding.

In the example below the ElasticPicker is bound to a collection of people and we have given the user the ability to filter based on four attributes of the people. Each attribute shows the number of people in that category, when the use selects a category all the numbers, sizes and colours of all of the other boxes change. It is a sight to behold.

Elysium Extra - Sample application screenshot of the ElasticPicker 1

Elysium Extra - Sample application screenshot of the ElasticPicker 2

Icon

Icons are ridiculously underestimated in their ability to improve the look and feel of an application and also in the difficulty of getting them right. I've had to use PNG icons in the past and I can tell you finding an off the shelf icon that matches the look and feel of your application and indeed your other icons is hard work. Creating your own icons from scratch is even harder.

With XAML combined with the Metro look and feel though, all this becomes easy. Nearly 3000 icons have been provided out of the box. Icons are a single colour, making them all look consistent and in keeping with each other. Its simple to create your own with the options of Geometry, Text or icons using PNG images using opacity masks.

Elysium Extra - Sample application screenshot of the Geometry Icons

Wizard

The wizard control is the basis of all my screens. It can be used like the Frame and Page controls in Silverlight or Windows Phone, where you navigate between pages. The difference being that you can optionally structure your pages or WizardItem's into a linear or tree hierarchy and use the breadcrumb navigation bar to navigate between pages.

It gets even better. Each WizardItem supports entrance and exit animations. So when you are moving pages, some really nice transition animations can be applied to any of your controls on the page. If you set backgrounds to your pages, they even fade into each other.

Elysium Extra - Sample application screenshot of the Wizard 1

Elysium Extra - Sample application screenshot of the Wizard 2

Elysium Extra - Sample application screenshot of the Wizard 3

DataGrid

Although not an entirely new control, the DataGrid has been augmented with quite a bit of extra functionality. There are a few new column types like the DataTime and ProgressBar columns. Attached properties have been used to add the ability to add column specific group summaries, save column settings, add single click editing and single click row/cell de-selection among other things.

Elysium Extra - Sample application screenshot of the DataGrid

ExpanderMenu

The ExpanderMenu is a great control that a colleague came up with. We've generally used it in the DataGrid. When a user clicks on a row, the ExpanderMenu appears in a nice sliding animation and can be used instead of or in conjunction with a ContextMenu.

Elysium Extra - Sample application screenshot of the ExpanderMenu

Drag & Drop

The ability to drag and drop in a completely MVVM friendly method has been added. It is super simple to use and you can get it working with just four lines of XAML! The DragManager is used to make something draggable and the DragCommand is used to fire a standard ICommand. It's super customizable and very easy to use.

Furthermore, styles have been created for the ListBoxItem and DataGridRow which allow re-ordering using drag and drop.

Elysium Extra - Sample application screenshot of Drag & Drop 1

Elysium Extra - Sample application screenshot of Drag & Drop 2

FishEyeListBox and NotesListBox

The Fish Eye list box is just a standard list box, except mousing over or selected in item makes it grow and it gives you a nice top level menu bar. The NotesListBox can be used to display several rich text notes, which expand gradually when you mouse over them.

Elysium Extra - Sample application screenshot of the ListBox's 1

Elysium Extra - Sample application screenshot of the ListBox's 2

Accordian

The Accordian is a bit like the Expander control, except that you have more than one and can control how may can open at any one time.

The Accordian control has been taken from the left overs of the WPF Toolkit (Buggy controls which did not make it into the proper .NET framework). It has been fixed and totally restyled to resemble the Expander style.

Elysium Extra - Sample application screenshot of the Expander and Accordion

Flyout

For those that have used the Flyout control in Windows 8, this is very much the same. In the SDK, it's just an Expander control with a custom style (I like to re-use existing controls as much as possible where it makes sense).

Elysium Extra - Sample application screenshot of the

Elysium Extra - Sample application screenshot of the Flyout

Various Input Controls

Various input controls have been added or improved. Notable additions include the NumericUpDown controls which allow you to select a number and the ButtonTextBox, which can be used to add a button action to a text box.

Elysium Extra - Sample application screenshot of the TextBox

Elysium Extra - Sample application screenshot of of the RichTextBox

Elysium Extra - Sample application screenshot of the ButtonTextBox

Elysium Extra - Sample application screenshot of the numeric input

Elysium Extra - Sample application screenshot of the DatePicker

Validation

Validation is something that's built into WPF but is so often neglected by people styling controls. So far, this SDK supports validation on the TextBox, ComboBox, DatePicker and numeric up down controls such as IntegerUpDown. I recomend using the INotifyDataErrorInfo interface on your view models or the NotifyDataErrorInfo base class provided in conjunction with these controls.

Elysium Extra - Sample application screenshot of the validation of built in controls

HyperlinkButton

The HyperlinkButton is just a button with a custom style which underlines the text in the button on mouse over and changes the mouse cursor to a hand.

Elysium Extra - Sample application screenshot of the Buttons

Window

Several new abilities have been added to the window. These include better customization of look and feel, full screen mode, saving window placement, setting the task-bar overlay icon using XAML and/or binding and a custom window drop shadow.

Elysium Extra - Sample application screenshot of the Window styles 1

OverlayWindow

This is a special Window which allows you to overlay another window with some content. Crucially this window is not modal but allows modal style interaction with the underlying window.

Elysium Extra - Sample application screenshot of the OverlayWindow

MessageDialog

The standard WPF MessageBox is ugly and uses a really bad design where you can only ask Yes or No style questions. The MessageDialog comes to the rescue with a Windows 8 style dialogue. You can ask any questions and even customize the allowed response buttons.

Elysium Extra - Sample application screenshot of the MessageDialog

NotifyBox

The NotifyBox is like the Microsoft Outlook style email notifications. A small window fades in on the bottom right and slowly disappears, unless you mouse over it.

Elysium Extra - Sample application screenshot of the NotifyBox

LoadingContent

The loading content control can be used to cover any content with a loading animation and loading message. You can toggle it on or off using a simple boolean value.

Elysium Extra - Sample application screenshot of the Progress showing controls

Paging

You can add any fixed size content to the Paging control and it will separate it into pages which the user can switch between with a nice transition animation.

Elysium Extra - Sample application screenshot of the Paging control

Elysium Extra - Sample application screenshot of the Paging control

GraphTreeView

The GraphTreeView is just a style for a TreeView, which shows the TreeViewItem's horizontally instead of vertically. In the past I've allowed users to switch between horizontal and vertical views on my TreeView's and users have been pretty appreciative.

Elysium Extra - Sample application screenshot of the TreeView

Animation Made Easy

Animating controls has been made simple. All you need to do is add a couple of lines of XAML and your ItemsControl's will fade and slide in sequentially or randomly.

Elysium Extra - Sample application screenshot of the Animations

FlipControl

The flip control is basically an ItemsControl which only shows the selected item. When the selected item changes, it flips between the items until it gets to the new selected item.

Elysium Extra - Sample application screenshot of the FlipControl

Various Border Controls

There are several custom border controls available, although usage is discouraged because they are not very metro!

Elysium Extra - Sample application screenshot of the Borders

Source Code

The code is available on GitHub and I've tried to keep it up to date with new additions and fixes being made over the weekends.

I have tried to keep the code in keeping with the existing Elysium project, so when controls are moved to the parent Elysium project (I don't know how or when this will happen) this should be a fairly simple process.

The code is fully StyleCop compliant. If you don't use StyleCop or even don't know what it is, I suggest you read this.

If nothing happens in the next couple of months I will start to consider creating a NuGet package, along with all the niceties that make a developers life a little easier.

Conclusions

This is a very young project with currently only one developer but I do intend to keep it working. Your mileage with this SDK may vary but any contributions or bug fixes are welcome.

Reactive Extensions (Rx) - Part 5 - Awaiting Observables

$
0
0

So I've just finished extolling the wonderful virtues of TaskCompletionSource with a colleague and thought I'd share the joy more widely. Eventually this will turn into a post about how great Reactive Extensions (Rx) is, I promise.

TaskCompletionSource

TaskCompletionSource is a great tool to turn any asynchronous operation which does not follow the Task Parallel Library (TPL) pattern into a Task. The example below is something I've started to do in a few places.

public Task<bool?> ShowDialog()
{
    TaskCompletionSource<bool?> taskCompletionSource = new TaskCompletionSource<bool?>();

    Window window = new MyDialogWindow();
    EventHandler eventHandler = null;
    eventHandler = 
        (sender, e) =>
        {
            window.Closed -= eventHandler;
            taskCompletionSource.SetResult(window.DialogResult);
        };
    window.Closed += eventHandler;
    window.Show();

    return taskCompletionSource.Task;
}

In the example above we are creating a new window, registering for its Closed event and then showing the window. When the window is closed, we de-register from the closed event handler (To avoid a remaining reference to the window, causing a memory leak) and the DialogResult of the window is passed to the TaskCompletionSource using the SetResult method.

The TaskCompletionSource gives us a nice Task object which we can return at the end of the method. When we return the task its status is WaitingForActivation. Only when the SetResult method is called when the window closes, does the tasks status change to RanToCompletion.

This whole operation has been wrapped up and packaged nicely in a Task<bool?> with a nice bow on top with the help of TaskCompletionSource. Now we can call the method and await the results from the method call, thus allowing us to savour the power and simplicity the TPL affords us.

bool? result = await ShowDialog();

There are other great ways to use TaskCompletionSource of course. Generally speaking though I have found myself using it to turn an operation where I am waiting for an event into a task. For more information on TaskCompletionSource or the TPL in general I highly recommend reading Stephen Toub's blog.

Awaiting Observables

Having showed my colleague the above example and feeling very content, I suddenly realised that Reactive Extensions (Rx) can make the code even simpler. With the advent of the latest version of Reactive Extensions (Rx) you can now await observables and we can turn the method above into this:

public async Task<bool?> ShowDialog()
{
    var window = new MyDialogWindow();
    var closed = Observable
        .FromEventPattern<EventHandler, EventArgs>(
            h => window.Closed += h,
            h => window.Closed -= h);

    window.Show();
    await closed.FirstAsync()

    return window.DialogResult;
}

The await keyword is just some syntactic sugar in the C# language that makes writing thorny asynchronous code effortless. The real meat of what drives it is the GetAwaiter method. The Reactive Extensions (Rx) team seeing the genius that is the Task Parallel Library (TPL) took advantage. They added this method (actually an extension method) to IObservable<T>, allowing us to await an observable as seen in the example above.

However, there is a caveat which I shall explain. In the example above the Closed event could conceivably be fired any number of times (If the window was opened and closed a few times) and the observable wrapper around the Closed event never completes. So our observable returns multiple results but a task can only return a single result.

The secret in our example is the FirstAsync method. We are actually awaiting the first result returned by our observable and don't care about any further results. By default awaiting an observable without the FirstAsync method above will actually await the last result before completion. If your observable does not complete, then you will be waiting forever!

Handily the Reactive Extensions (Rx) team has added several methods which you can use before you use await to modify the result of what you are awaiting. All of these methods end with the word Async. I've added a short list of these methods below (There are lots of overloads so I've just highlighted the main ones):

// Returns the first element of an observable sequence.
string result = await observable.FirstAsync();

// Returns the first element of an observable sequence, or a default value if no such element exists.
string result = await observable.FirstOrDefaultAsync();

// Returns the last element of an observable sequence. 
// This is the default action of awaiting an observable.
string result = await observable.LastAsync();

// Returns the last element of an observable sequence, 
// or a default value if no such element exists.
string result = await observable.LastOrDefaultAsync();

// Returns the only element of an observable sequence, and throws an exception if there is not exactly 
// one element in the observable sequence.
string result = await observable.SingleAsync();

// Returns the only element of an observable sequence, or a default value if the observable sequence 
// is empty; this method reports an exception if there is more than one element in the observable sequence.
string result = await observable.SingleOrDefaultAsync();

// Invokes an action for each element in the observable sequence and returns a Task that will get 
// signalled when the sequence terminates.
await observable.ForEachAsync(x => Console.WriteLine(x));

All of the above methods allow you to pick a single result from your observable. ForEachAsync is different though as it performs an action on each item and when your observable completes (If it does) then the task completes.

Conclusions

So we've learned how to await observables in different ways and how it can be another way of doing the same thing that TaskCompletionSource does but in a cleaner more elegant way.

We've also learned that there are some caveats that you need to be aware of when awaiting an observable i.e. that observables return multiple results and you have to pick one to return in your task.

GetHashCode Made Easy

$
0
0

::: tip Update (2019-06-12) I updated my HashCode implementation to cover a few more scenarios which I discuss below. :::

::: tip Update (2018-08-14) I updated this article to talk about a new HashCode class included in .NET Core 2.1 and licensing information for my code since I've been asked repeatedly. :::

Implementing GetHashCode is hard work and little understood. If you take a look on MSDN or Stack Overflow for a few pointers, you'll see a plethora of examples with all kinds of little used C# operators and magic numbers with little explanation for developers (Especially the newbies) what they are for and why we need them. This, for a method which exists on the Object class and is the root of all that is good and wholesome in C# is surprising.

Before I continue, I recommend reading Eric Lippert's blog post about the subject. He does not show any code, just goes into when and where we need to implement the GetHashCode method. Eric does a much better job than I could do but in short, GetHashCode is implemented wherever you implement the Equals method and ideally your class should be immutable.

Now down to the nitty gritty. How do we make implementing GetHashCode easy. Well, suppose we have the following class:

public sealed class SuperHero
{
    private readonly string name;
    private readonly int age;
    private readonly ReadOnlyCollection<string> powers;

    public SuperHero(string name, int age, IEnumerable<string> powers)
    {
        this.name = name;
        this.age = age;
        this.powers = new ReadOnlyCollection<string>(powers.ToList());
    }

    public int Age => this.age;

    public string Name => this.name;

    public ReadOnlyCollection<string> Powers => this.powers;

    public override bool Equals(object obj)
    {
        // ...
    } 

    public override int GetHashCode()
    {
        // TODO
    }
}

In our example we have an immutable object with a variety of fields of different types, including a collection. One possible implementation of GetHashCode according to the highest rated Stack Overflow post (If modified to fit our example and deal with null's) may be:

public override int GetHashCode()
{
    unchecked
    {
        int hashCode = 17;

        hashCode = (hashCode * 23) + (name == null ? 0 : this.name.GetHashCode());

        hashCode = (hashCode * 23) + this.age;

        foreach (string power in this.powers)
        {
            hashCode = (hashCode * 23) + (power == null ? 0 : power.GetHashCode());
        }

        return hashCode;
    }
}

I don't know about you but that code looks awfully unwieldy to me. For a start we've got two different magic numbers 17 and 23. Why? As it happens these are prime numbers and reduces the chance of getting collisions between hashes (Two un-equal objects are supposed to have different hash codes but sometimes this is not the case due to hash collisions that can occur).

We've also got the unchecked C# keyword which stops overflow checking to improve performance (That's not something you see every day). Bear in mind that the whole point of the GetHashCode method is to allow things like the Dictionary type to quickly retrieve objects.

I personally would not be able to remember how to do this each time I need to implement GetHashCode and it seems like you could very easily introduce bugs by making a typo. How about a helper class (Well actually a struct for better performance)?

/// <summary>
/// A hash code used to help with implementing <see cref="object.GetHashCode()"/>.
/// </summary>
public struct HashCode : IEquatable<HashCode>
{
    private const int EmptyCollectionPrimeNumber = 19;
    private readonly int value;

    /// <summary>
    /// Initializes a new instance of the <see cref="HashCode"/> struct.
    /// </summary>
    /// <param name="value">The value.</param>
    private HashCode(int value) => this.value = value;

    /// <summary>
    /// Performs an implicit conversion from <see cref="HashCode"/> to <see cref="int"/>.
    /// </summary>
    /// <param name="hashCode">The hash code.</param>
    /// <returns>The result of the conversion.</returns>
    public static implicit operator int(HashCode hashCode) => hashCode.value;

    /// <summary>
    /// Implements the operator ==.
    /// </summary>
    /// <param name="left">The left.</param>
    /// <param name="right">The right.</param>
    /// <returns>The result of the operator.</returns>
    public static bool operator ==(HashCode left, HashCode right) => left.Equals(right);

    /// <summary>
    /// Implements the operator !=.
    /// </summary>
    /// <param name="left">The left.</param>
    /// <param name="right">The right.</param>
    /// <returns>The result of the operator.</returns>
    public static bool operator !=(HashCode left, HashCode right) => !(left == right);

    /// <summary>
    /// Takes the hash code of the specified item.
    /// </summary>
    /// <typeparam name="T">The type of the item.</typeparam>
    /// <param name="item">The item.</param>
    /// <returns>The new hash code.</returns>
    public static HashCode Of<T>(T item) => new HashCode(GetHashCode(item));

    /// <summary>
    /// Takes the hash code of the specified items.
    /// </summary>
    /// <typeparam name="T">The type of the items.</typeparam>
    /// <param name="items">The collection.</param>
    /// <returns>The new hash code.</returns>
    public static HashCode OfEach<T>(IEnumerable<T> items) =>
        items == null ? new HashCode(0) : new HashCode(GetHashCode(items, 0));

    /// <summary>
    /// Adds the hash code of the specified item.
    /// </summary>
    /// <typeparam name="T">The type of the item.</typeparam>
    /// <param name="item">The item.</param>
    /// <returns>The new hash code.</returns>
    public HashCode And<T>(T item) => 
        new HashCode(CombineHashCodes(this.value, GetHashCode(item)));

    /// <summary>
    /// Adds the hash code of the specified items in the collection.
    /// </summary>
    /// <typeparam name="T">The type of the items.</typeparam>
    /// <param name="items">The collection.</param>
    /// <returns>The new hash code.</returns>
    public HashCode AndEach<T>(IEnumerable<T> items)
    {
        if (items == null)
        {
            return new HashCode(this.value);
        }

        return new HashCode(GetHashCode(items, this.value));
    }

    /// <inheritdoc />
    public bool Equals(HashCode other) => this.value.Equals(other.value);

    /// <inheritdoc />
    public override bool Equals(object obj)
    {
        if (obj is HashCode)
        {
            return this.Equals((HashCode)obj);
        }

        return false;
    }

    /// <summary>
    /// Throws <see cref="NotSupportedException" />.
    /// </summary>
    /// <returns>Does not return.</returns>
    /// <exception cref="NotSupportedException">Implicitly convert this struct to an <see cref="int" /> to get the hash code.</exception>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public override int GetHashCode() =>
        throw new NotSupportedException(
            "Implicitly convert this struct to an int to get the hash code.");

    private static int CombineHashCodes(int h1, int h2)
    {
        unchecked
        {
            // Code copied from System.Tuple so it must be the best way to combine hash codes or at least a good one.
            return ((h1 << 5) + h1) ^ h2;
        }
    }

    private static int GetHashCode<T>(T item) => item?.GetHashCode() ?? 0;

    private static int GetHashCode<T>(IEnumerable<T> items, int startHashCode)
    {
        var temp = startHashCode;

        var enumerator = items.GetEnumerator();
        if (enumerator.MoveNext())
        {
            temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));

            while (enumerator.MoveNext())
            {
                temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));
            }
        }
        else
        {
            temp = CombineHashCodes(temp, EmptyCollectionPrimeNumber);
        }

        return temp;
    }
}

The helper struct can be used in our SuperHero class like so:

public override int GetHashCode()
{
    return HashCode
        .Of(this.name)
        .And(this.age)
        .AndEach(this.powers);
}

Now isn't that pretty? All the nasty magic numbers and unchecked code has been hidden away. It is a very lightweight and simple struct, so although we create new instances of it, it's stored in the stack rather than the memory heap. What's more, is that is code is just as fast (I've timed it)! We're using generics so there is no boxing or unboxing going on. We're still using the unchecked keyword, so overflow checking is still disabled.

One interesting edge case is what to do when hashing a collection and you get either a null or empty collection. Should you use a zero to represent both scenarios (zero is usually used to represent a null value) or differentiate them somehow. I managed to get a response from Jon Skeet himself on Stack Overflow:

if both states are valid, it seems perfectly reasonable to differentiate between them. (Someone carrying an empty box isn't the same as someone not carrying a box at all...)

This is why we use the prime number 19 (it could have been any prime number) to represent an empty collection. Whether this matters or not depends on your use case. If an empty collection means something different in your scenario, then we've got you covered. Generally speaking though, if you are exposing a collection property in your class you should consider making it a getter only and initializing it in the constructor, so that it is never null in the first place but here we're trying to cover all scenarios.

.NET Core HashCode

If you are using .NET Core 2.1, consider using the System.HashCode struct instead of my code. There are two ways to use it:

HashCode.Combine

The Combine method can be used to create a hash code, given up to eight objects.

public override int GetHashCode() =>
  HashCode.Combine(object1, object2);

HashCode.Add

The Add method is similar to my code but it does not handle collections and is not fluent:

public override int GetHashCode()
{
    var hash = new HashCode();
    hash.Add(this.object1);
    hash.Add(this.object2);
    return hash.ToHashCode();
}

Advantages and Disadvantages

There are several advantages to using the .NET Core HashCode:

  • It's part of the .NET Core base class library (BCL), so it's maintained and officially supported.
  • It has good performance. I haven't written a benchmark against comparing my code to the .NET Core code. If you do, I'd be interested to hear the results.
  • Like my code, it handles null's automatically.

The disadvantages are:

  • You have to be using .NET Core 2.1 or above.
  • It does not handle collections, you have to write a for loop to handle that yourself. You could be clever and write a quick extension method to handle this scenario.
  • It's not fluent, so you end up with slightly uglier code in my opinion. If you are a fan of C# 7 expression bodied members, then my fluent code lets you use them, while the .NET Core HashCode.Add method does not.

License

I have been asked repeatedly for licensing of my code above. Developers have been asking permission to use it in a Kerbal Space program plugin and even in the excellent Chocolatey project which has been totally unexpected for me because this is code I wrote years ago. It just goes to show how fundamental GetHashCode is. Please consider the code as MIT licensed, do good with it and be excellent to each other!


Reactive Extensions (Rx) - Part 6 - Task ToObservable

$
0
0

A Quick Recap

In my previous posts on Reactive Extensions (Rx) I've outlined a few clear areas where Reactive Extensions can be used in the real world. I've uncovered areas where it provides a cleaner and improved API surface as compared to older .NET code. Namely, replacing C# events, wrapping existing C# events and replacing System.Threading.Timers (Or other Timer classes, of which there are a few in .NET).

Once you have your observables, you need to do something with them. In my last post on the subject I showed how and when you can await an observable.

In this post I'm going to show how you can also go the other way around. You can turn tasks into an observable. I'll also show one clear reason to use this facility.

Converting Tasks to Observables

The ToObservable extension method allows you to convert a Task or Task<T> into an IObservable<T>. Calling ToObservable on a Task returns an IObservable<Unit>. A Unit is a kind of empty object that does nothing, the only reason it is there is because there is no IObservable (Without the T) interface.

IObservable<Unit> observable = Task.Run(() => Console.WriteLine("Working")).ToObservable();

IObservable<string> observableT = Task<string>.Run(() => "Working").ToObservable();

If you subscribe to the above observables, they will only ever return one value and then complete. You might be thinking, hang on just a second Rehan, whats the point of doing this?

Putting It All Together

So when should we use this feature? Well, lets walk through some examples and see what happens. Lets assume we have the following contrived code:

public Task<string> GetHelloString()
{
    return Task.Run(
        async () =>
        {
            await Task.Delay(500);
            return "Hello";
        });
}

public Task<string> GetWorldString()
{
    return Task.Run(
        async () =>
        {
            await Task.Delay(1000);
            return "World";
        });
}

What happens in the case where we call both of these methods and want to get the first result back. How does this code look using the Task Parallel Library (TPL) as compared to Reactive Extensions (Rx).

public async Task<string> WaitForFirstResultAndReturn()
{
    Task<string> task1 = this.GetHelloString();
    Task<string> task2 = this.GetWorldString();

    return await Task.WhenAny(task1, task2);
}

public async Task<string> WaitForFirstResultAndReturn()
{
    IObservable<string> observable1 = this.GetHelloString().ToObservable();
    IObservable<string> observable2 = this.GetWorldString().ToObservable();

    return await observable1.Merge(observable2).FirstAsync();
}

In the Task Parallel Library (TPL) example, I simply use the WhenAny method to await the first task that completes and then return the result.

In the Reactive Extensions example above, I'm converting my tasks to observables, using the Merge method to convert them to a single observable and then using the FirstAsync method to await the first result (We covered await'ing observables in the last post).

Overall the two techniques look pretty similar, with the TPL having a slight edge in terms of simplicity.

How about another example. Here we will try to await both of the results and put them together to get some meaningful result.

public async Task<string> WaitForAllResultsAndReturnCombinedResult()
{
    Task<string> task1 = this.GetHelloString();
    Task<string> task2 = this.GetWorldString();

    return string.Join(" ", await Task.WhenAll(task1, task2));
}

public async Task<string> WaitForAllResultsAndReturnCombinedResult()
{
    IObservable<string> observable1 = this.GetHelloString().ToObservable();
    IObservable<string> observable2 = this.GetWorldString().ToObservable();

    return await observable1.Zip(observable2, (x1, x2) => string.Join(" ", x1, x2));
}

In the Task Parallel Library (TPL) example, I'm using the WhenAll method to await the results of both tasks which are returned as an array of strings. I then join these strings and return the results.

In the Reactive Extensions example above, I'm converting my tasks to observables, then using the Zip method to combine the results returned from both observables by providing it with a delegate which joins the two strings.

Again, both look pretty similar but with the pure TPL example being slightly simpler to understand.

One more example, this time we'll return the first result but add a timeout to the equation.

public async Task<string> WaitForFirstResultAndReturnResultWithTimeOut()
{
    Task<string> task1 = this.GetHelloString();
    Task<string> task2 = this.GetWorldString();
    Task timeoutTask = Task.Delay(100);

    Task completedTask = await Task.WhenAny(task1, task2, timeoutTask);
    if (completedTask == timeoutTask)
    {
        throw new TimeoutException("The operation has timed out");
    }

    return ((Task<string>)completedTask).Result;
}

public async Task<string> WaitForFirstResultAndReturnResultWithTimeOut()
{
    IObservable<string> observable1 = this.GetHelloString().ToObservable();
    IObservable<string> observable2 = this.GetWorldString().ToObservable();

    return await observable1.Merge(observable2).Timeout(TimeSpan.FromMilliseconds(100)).FirstAsync();
}

In the Task Parallel Library (TPL) example, I'm awaiting a third task which represents the timeout. If the timeout task finishes first, I raise a TimeoutException.

In the Reactive Extensions example, we merge the two observables again but this time use the Timeout method to achieve the same results.

Here we have a clear winner, the Reactive Extensions code is more concise and easier to follow.

What happens when we combine the two approaches.

public async Task<string> WaitForFirstResultAndReturnResultWithTimeOut2()
{
    Task<string> task1 = this.GetHelloString();
    Task<string> task2 = this.GetWorldString();

    return await Task
        .WhenAny(task1, task2)
        .ToObservable()
        .Timeout(TimeSpan.FromMilliseconds(1000))
        .FirstAsync();
}

Here we use the ToObservable and Timeout methods right at the end. As you can see this combined approach gives us the best of both worlds and makes the code much easier to read.

Conclusions

One definite reason to convert Task's to Observables is to use the Timeout method. There may be other reasons but I'm having a hard time thinking of any right now. In fact, I'm having a hard time thinking of any other posts to make about Reactive Extensions (Rx). It's an interesting chunk of code and I've learned a lot writing this series of posts as I hope you have too.

Portable Class Library (PCL) version of NotificationsExtensions NuGet package

$
0
0

I have recently got into creating NuGet packages, when I had to create one for Elysium Extra. I discovered it was really easy to do too. I've just finished creating another one called, you guessed it NotificationsExtensions.Portable and I did in in 5 minutes!

About

NotificationsExtensions.Portable is a Portable Class Library (PCL) version of other NotificationsExtensions NuGet Packages. It's used to Create Windows 8.1 or Windows Phone 8.1 Tile, Toast and Badge Notification XML. This package is intended for use, instead of or as well as the following NuGet packages:

Tile, Toast and Badge Templates

This project helps to create XML representing Tile, Toast and Badge notifications on the Windows 8.1 and Windows Phone 8.1 platforms. You can take a look at the template catalogue to see the types of templates available on these platforms.

Wide Tile Template

Why is this Useful?

It's useful when trying to send notifications from the server side using Azure Mobile Services .NET Backend or some other .NET based push notification. When you want to create notification XML in a standard .NET project and not a WinRT project. I personally use it for my London Travel Live and Currency Converter Pro apps.

NuGet

NotificationsExtensions.Portable is available on NuGet. Simply follow the instructions below:

  1. Click Tools Menu Item in Visual Studio
  2. Click NuGet Package Manager
  3. Click Package Manager Console
  4. Select Your Project in the Package Manager Console
  5. Execute the following command to install NotificationsExtensions.Portable:
    Install-Package NotificationsExtensions.Portable -Version 1.0.0

Attribution and Changes Made

All praise goes to the above two projects and the Microsoft developers who built them. The only changes I made to the code was to switch from XmlDocument to XDocument, remove a few WinRT specific references and stick it into a Portable Class Library (PCL).

Model-View-ViewModel (MVVM) - Part 1 - Overview

$
0
0

I have been meaning for some time to do a series of posts about Model-View-ViewModel (MVVM) and its potential base classes. Then I read Mike Taulty's post about why MVVM 'bits' not built in to .NET.

My aim in these posts will be to either, pick off the shelf components which are best of breed where there is no point reinventing the wheel or build my own components where necessary.

Assuming you already know about the basic Model-View-ViewModel (MVVM) pattern described in the title image of this post, when we talk about MVVM, what do we really mean?

Platforms

Well there are several .NET platforms that all provide some basic low level support for Model-View-ViewModel (MVVM), Windows Store, Windows Phone, Silverlight and Windows Presentation Foundation (WPF). It is all of these platforms that I'll be discussing and targeting my code towards.

MVVM 'Bits'

In Mike Taulty's post, he goes through a list of 'bits' which all come together to help with building an application that fits into the MVVM design pattern. I've added to that list below:

  1. IDisposable - When you have a scarce resource like a GPS, gyroscope or compass, you inevitably need to dispose of it somewhere. Implementing IDisposable properly is hard work. A base class would be handy.
  2. INotifyPropertyChanged - This is the building block of all .NET based MVVM. There needs to be a base class for this that is high performance and yet simple and easy to use.
  3. INotifyDataErrorInfo - Validation is an often overlooked part of an application. This handy interface makes doing validation of your view models a cinch.
  4. IEditableObject (WPF only) - This interface helps with implementing undo and redo but is used specifically in the WPF data grid.
  5. ObservableCollection<T> - This collection is a good start out of the box but why does it still not have an AddRange method? Why do we not have an ObservableDictionary<TKey, TValue> or a KeyedObservableCollection<TKey, TValue>? What if you have a collection of items implementing INotifyPropertyChanged and you want to know if one of those items changes, why can't the collection type help you there also?
  6. ICommand - Most implementations out there provide a base class for ICommand and usually call it RelayCommand or DelegateCommand. They usually have another implementation with a generic argument RelayCommand<T> or DelegateCommand<T>. These are a quick way to add a command to your view model, where the implementation of the command is usually a method in your view model passed in as a delegate. Sometimes though, this is not enough. What if you have a largish command and want to split it off into a separate class, a base class for ICommand would be useful. What if you have a command that does async and await? ICommand doesn't support that but can we provide some help here?
  7. Inversion of control (IoC) - There are a lot of IoC frameworks out there already, why reinvent the wheel. Just pick one but which one?

I'll pause just here as I think the above listed items are all base classes that could be used across the board on all the major platforms. They are at the very heart of MVVM in .NET. The rest of the list below are more dependant on the type of application you are building.

  1. Navigation - This has always been a stone in my shoe. Navigation is inherently something that happens in the view but it is something that view models often need to understand. The problem is, that the view model is not supposed to know about the view at all. This problem occurs again and again in different forms on each platform.
    • Navigating pages in Windows Store, Windows Phone, Silverlight.
    • Navigating Windows in Windows Presentation Foundation (WPF) and Windows Store.
  2. User Interaction - I'm talking about MessageBox's, MessageDialog's, Toast's etc. Giving the user information or asking them questions happens on all platforms. This problem is very similar to the Navigation problem.
  3. Connecting your Views to ViewModels - This is usually some by-product of which IoC container you choose to use, whether it's MEF, Unity, Autofac or some other. There is no recommended way of doing this and I don't think I've ever found a 'correct' way of doing this.
  4. Saving View Model state - This usually needs to be done when the application closes or suspends due to some user interaction. A lot of frameworks simply serialize the whole View Model and save it away but is that the best way and what about doing that in a WPF application?
  5. Events - Passing events between view models is a fairly useful ability, allowing communication and passing of state.
  6. Composing Views - Some MVVM frameworks like PRISM provide support for composing different views together. Alternatively, this process usually has a connection with the type of IoC container you are using.
  7. Firing Commands - A lot of controls can't fire off ICommand's in XAML because they don't provide a Command property or sometimes you want to fire a command based on some event or even a key press.
  8. Other Stuff - Reactive Extensions can help in some pretty interesting ways with MVVM. What about Portable Class Library's? Why does the MVVM on one platform need to be different from another?

The last two things in the list are more abstract requirements for any MVVM framework.

  1. Testability - Writing a view model which is easy to test is hard work. Especially if you want to use MessageBox's, GPS API's or other API's which make testing difficult. You don't want a MessageBox popping up in the middle of your test do you?
  2. Performance - Your application needs to run fast, especially if it's running on a phone. For example, a lot of MVVM frameworks use expression trees and reflection to raise property changed notifications . What impact does this have in the performance versus maintainability trade off?

Existing Frameworks

Wow, that's a lot of stuff! All of this 'stuff' is related but covers a huge range of subjects. A lot of existing MVVM frameworks try to do all of this at once!

In my humble opinion, because they do so much, they usually only cover some, say 70-80% of the full functionality. What business does an MVVM framework have including an IoC framework? There are lots of IoC frameworks out there that are far more powerful than anything we could write but a lot of MVVM frameworks include one too.

Conclusions

So ideally what we need is something modular, that you can plug bits into but also something that covers all the bases.

Whats your opinion? I've looked at a lot of frameworks MVVM Light, PRISM, etc. In my opinion, the seven top items are the most important but also the most neglected bits of MVVM. Is there some framework out there that does all this and more?

I'll discuss this and a lot more in the coming posts.

Model-View-ViewModel (MVVM) - Part 2 - IDisposable

$
0
0

View models these days interact with all kinds of precious resources like Compasses and the GPS. Implementing IDisposable is an important pattern you can follow to dispose of these resources cleanly. Freeing them up to be used elsewhere and saving the users battery (Particularly important on mobile devices). Using the IDisposable interface in the Model-View-ViewModel (MVVM) pattern is a wise decision.

Implementing IDisposable correctly is ridiculously hard. If you don't know how hard it really is, I recommend reading the top comment on this Stack Overflow article.

Implementing IDisposable is one of the rare times in C# where a developer has to use C# Destructors and also one of the few times when we have to tickle the garbage collector to stop it from trying to release the unmanaged resources twice by calling SuppressFinalize on GC.

Having to write this code repeatedly is difficult and error prone, so how about a base class?

namespace Framework.ComponentModel
{
    using System;
    using System.Reactive;
    using System.Reactive.Linq;
    using System.Reactive.Subjects;

    /// <summary>
    /// Base class for members implementing <see cref="IDisposable"/>.
    /// </summary>
    public abstract class Disposable : IDisposable
    {
        private bool isDisposed;
        private Subject<Unit> whenDisposedSubject;

        /// <summary>
        /// Finalizes an instance of the <see cref="Disposable"/> class. Releases unmanaged
        /// resources and performs other cleanup operations before the <see cref="Disposable"/>
        /// is reclaimed by garbage collection. Will run only if the
        /// Dispose method does not get called.
        /// </summary>
        ~Disposable() => this.Dispose(false);

        /// <summary>
        /// Gets the when errors changed observable event. Occurs when the validation errors have changed for a property or for the entire object.
        /// </summary>
        /// <value>
        /// The when errors changed observable event.
        /// </value>
        public IObservable<Unit> WhenDisposed
        {
            get
            {
                if (this.IsDisposed)
                {
                    return Observable.Return(Unit.Default);
                }
                else
                {
                    if (this.whenDisposedSubject == null)
                    {
                        this.whenDisposedSubject = new Subject<Unit>();
                    }

                    return this.whenDisposedSubject.AsObservable();
                }
            }
        }

        /// <summary>
        /// Gets a value indicating whether this <see cref="Disposable"/> is disposed.
        /// </summary>
        /// <value><c>true</c> if disposed; otherwise, <c>false</c>.</value>
        public bool IsDisposed => this.isDisposed;

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            // Dispose all managed and unmanaged resources.
            this.Dispose(true);

            // Take this object off the finalization queue and prevent finalization code for this
            // object from executing a second time.
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Disposes the managed resources implementing <see cref="IDisposable"/>.
        /// </summary>
        protected virtual void DisposeManaged()
        {
        }

        /// <summary>
        /// Disposes the unmanaged resources implementing <see cref="IDisposable"/>.
        /// </summary>
        protected virtual void DisposeUnmanaged()
        {
        }

        /// <summary>
        /// Throws a <see cref="ObjectDisposedException"/> if this instance is disposed.
        /// </summary>
        protected void ThrowIfDisposed()
        {
            if (this.isDisposed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources;
        /// <c>false</c> to release only unmanaged resources, called from the finalizer only.</param>
        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this.isDisposed)
            {
                // If disposing managed and unmanaged resources.
                if (disposing)
                {
                    this.DisposeManaged();
                }

                this.DisposeUnmanaged();

                this.isDisposed = true;

                if (this.whenDisposedSubject != null)
                {
                    // Raise the WhenDisposed event.
                    this.whenDisposedSubject.OnNext(Unit.Default);
                    this.whenDisposedSubject.OnCompleted();
                    this.whenDisposedSubject.Dispose();
                }
            }
        }
    }
}

There are several interesting facets to this implementation.

  1. There is a difference between disposing of managed and unmanaged resources in the disposable pattern. To facilitate this, there are two separate protected methods which can be overridden in a derived class to dispose of each of them.
  2. The disposable pattern requires you to throw an ObjectDisposedException when you try to access a property or method after the object has been disposed. To achieve this, there is a ThrowIfDisposed helper method which can be added to the top of each property or method.
  3. There is an IsDisposed property which can be useful if we don't know if the object is disposed or not.
  4. Finally, there is a Reactive Extensions (Rx) observable WhenDisposed property. This allows us to register for the dispose event.

Here is an example of how the base class is used to dispose of both a managed and unmanaged (COM object) resources.

public class DisposableExample : Disposable
{
    private ManagedResource managedResource;
    private UnmanagedResource unmanagedResource;

    public void Foo()
    {
        this.ThrowIfDisposed();

        // Do Stuff
    }

    protected override void DisposeManaged() =>
        this.managedResource.Dispose();

    protected override void DisposeUnmanaged()
    {
        Marshal.ReleaseComObject(this.unmanagedResource);
        this.unmanagedResource = null;
    }
}

An example of how to dispose of an instance of the above object.

DisposableExample disposable = new DisposableExample();
disposable.WhenDisposed.Subscribe(x => Console.WriteLine("Disposed Event Fired"));
disposable.Dispose();
Console.WriteLine(disposable.IsDisposed);

As you can see, it looks a whole lot simpler and has some pretty cool helper functions and features. No more need to remember how to implement this complicated pattern.

Model-View-ViewModel (MVVM) - Part 3 - INotifyPropertyChanged

$
0
0

I know there have been lots of Model-View-ViewModel (MVVM) articles talking about INotifyPropertyChanged. I've read lots of them and this is the aggregation of all the knowledge I've learned plus some cool new stuff (I've not seen it done anywhere else but I could be wrong) which I've also covered in my Reactive Extensions (Rx) posts.

So what are the main aims of a base class implementing INotifyPropertyChanged? Well, I think there are a few:

  • Performance - Performance is king. It needs to be fast and I mean really fast. You can't afford for your UI to freeze up while your view works out all its bindings to the properties in your view model.
  • Simplicity - I want to raise property changed events with one line of code and I don't want to mess around with strings if I can help it.
  • Reactive Extensions (Rx) - Events are old school, I want an observable property changed event notification system instead of the PropertyChanged C# event.
  • Human Error - I don't want to raise property change events for properties that don't exist by accident.
  • Dependent Properties - Often, the value of one property depends on the value of another. I need to handle this somehow.
  • Re-factoring - I don't want my code to break when I rename a property and forget to rename a string too.
  • Has it Really Changed - I don't want to raise a property changed event if the value of a property has not really changed.

So, without further ado, here is my implementation.

namespace Framework.ComponentModel
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Reactive.Linq;
    using System.Reflection;
    using System.Runtime.CompilerServices;

    /// <summary>
    /// Notifies subscribers that a property in this instance is changing or has changed.
    /// </summary>
    public abstract class NotifyPropertyChanges : Disposable, INotifyPropertyChanged //, INotifyPropertyChanging
    {
        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
        {
            add { this.propertyChanged += value; }
            remove { this.propertyChanged -= value; }
        }

        /// <summary>
        /// Occurs when a property value is changing.
        /// </summary>
        // event PropertyChangingEventHandler INotifyPropertyChanging.PropertyChanging
        // {
        //     add { this.PropertyChanging += value; }
        //     remove { this.PropertyChanging -= value; }
        // }

        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        private event PropertyChangedEventHandler propertyChanged;

        /// <summary>
        /// Occurs when a property value is changing.
        /// </summary>
        // private event PropertyChangingEventHandler PropertyChanging;

        /// <summary>
        /// Gets the when property changed observable event. Occurs when a property value changes.
        /// </summary>
        /// <value>
        /// The when property changed observable event.
        /// </value>
        public IObservable<string> WhenPropertyChanged
        {
            get
            {
                this.ThrowIfDisposed();

                return Observable
                    .FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
                        h => this.propertyChanged += h,
                        h => this.propertyChanged -= h)
                    .Select(x => x.EventArgs.PropertyName);
            }
        }

        /// <summary>
        /// Gets the when property changing observable event. Occurs when a property value is changing.
        /// </summary>
        /// <value>
        /// The when property changing observable event.
        /// </value>
        // public IObservable<EventPattern<PropertyChangingEventArgs>> WhenPropertyChanging
        // {
        //     get
        //     {
        //         return Observable
        //             .FromEventPattern<PropertyChangingEventHandler, PropertyChangingEventArgs>(
        //                 h => this.PropertyChanging += h,
        //                 h => this.PropertyChanging -= h)
        //             .AsObservable();
        //     }
        // }

        /// <summary>
        /// Raises the PropertyChanged event.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            Debug.Assert(
                string.IsNullOrEmpty(propertyName) ||
                (this.GetType().GetRuntimeProperty(propertyName) != null),
                "Check that the property name exists for this instance.");

            PropertyChangedEventHandler eventHandler = this.propertyChanged;

            if (eventHandler != null)
            {
                eventHandler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Raises the PropertyChanged event.
        /// </summary>
        /// <param name="propertyNames">The property names.</param>
        protected void OnPropertyChanged(params string[] propertyNames)
        {
            if (propertyNames == null)
            {
                throw new ArgumentNullException(nameof(propertyNames));
            }

            foreach (string propertyName in propertyNames)
            {
                this.OnPropertyChanged(propertyName);
            }
        }

        /// <summary>
        /// Raises the PropertyChanging event.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        protected virtual void OnPropertyChanging([CallerMemberName] string propertyName = null)
        {
            Debug.Assert(
                string.IsNullOrEmpty(propertyName) ||
                (this.GetType().GetRuntimeProperty(propertyName) != null),
                "Check that the property name exists for this instance.");

            // PropertyChangingEventHandler eventHandler = this.PropertyChanging;

            // if (eventHandler != null)
            // {
            //     eventHandler(this, new PropertyChangingEventArgs(propertyName));
            // }
        }

        /// <summary>
        /// Raises the PropertyChanging event.
        /// </summary>
        /// <param name="propertyNames">The property names.</param>
        protected void OnPropertyChanging(params string[] propertyNames)
        {
            if (propertyNames == null)
            {
                throw new ArgumentNullException(nameof(propertyNames));
            }

            foreach (string propertyName in propertyNames)
            {
                this.OnPropertyChanging(propertyName);
            }
        }

        /// <summary>
        /// Sets the value of the property to the specified value if it has changed.
        /// </summary>
        /// <typeparam name="TProp">The type of the property.</typeparam>
        /// <param name="currentValue">The current value of the property.</param>
        /// <param name="newValue">The new value of the property.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns><c>true</c> if the property was changed, otherwise <c>false</c>.</returns>
        protected bool SetProperty<TProp>(
            ref TProp currentValue,
            TProp newValue,
            [CallerMemberName] string propertyName = null)
        {
            this.ThrowIfDisposed();

            if (!object.Equals(currentValue, newValue))
            {
                this.OnPropertyChanging(propertyName);
                currentValue = newValue;
                this.OnPropertyChanged(propertyName);

                return true;
            }

            return false;
        }

        /// <summary>
        /// Sets the value of the property to the specified value if it has changed.
        /// </summary>
        /// <typeparam name="TProp">The type of the property.</typeparam>
        /// <param name="currentValue">The current value of the property.</param>
        /// <param name="newValue">The new value of the property.</param>
        /// <param name="propertyNames">The names of all properties changed.</param>
        /// <returns><c>true</c> if the property was changed, otherwise <c>false</c>.</returns>
        protected bool SetProperty<TProp>(
            ref TProp currentValue,
            TProp newValue,
            params string[] propertyNames)
        {
            this.ThrowIfDisposed();

            if (!object.Equals(currentValue, newValue))
            {
                this.OnPropertyChanging(propertyNames);
                currentValue = newValue;
                this.OnPropertyChanged(propertyNames);

                return true;
            }

            return false;
        }

        /// <summary>
        /// Sets the value of the property to the specified value if it has changed.
        /// </summary>
        /// <param name="equal">A function which returns <c>true</c> if the property value has changed, otherwise <c>false</c>.</param>
        /// <param name="action">The action where the property is set.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns><c>true</c> if the property was changed, otherwise <c>false</c>.</returns>
        protected bool SetProperty(
            Func<bool> equal, 
            Action action,
            [CallerMemberName] string propertyName = null)
        {
            this.ThrowIfDisposed();

            if (equal())
            {
                return false;
            }

            this.OnPropertyChanging(propertyName);
            action();
            this.OnPropertyChanged(propertyName);

            return true;
        }

        /// <summary>
        /// Sets the value of the property to the specified value if it has changed.
        /// </summary>
        /// <param name="equal">A function which returns <c>true</c> if the property value has changed, otherwise <c>false</c>.</param>
        /// <param name="action">The action where the property is set.</param>
        /// <param name="propertyNames">The property names.</param>
        /// <returns><c>true</c> if the property was changed, otherwise <c>false</c>.</returns>
        protected bool SetProperty(
            Func<bool> equal, 
            Action action,
            params string[] propertyNames)
        {
            this.ThrowIfDisposed();

            if (equal())
            {
                return false;
            }

            this.OnPropertyChanging(propertyNames);
            action();
            this.OnPropertyChanged(propertyNames);

            return true;
        }
    }
}

Simple Example

An example of how you can use this base class is as follows.

public class CatCountViewModel : NotifyPropertyChanges
{
    private int numberOfCats;

    public int NumberOfCats
    {
        get => this.numberOfCats;
        set => this.SetProperty(ref this.numberOfCats, value);
    }
}

Performance

As I said before, performance is king. A slow application is a frustrating application. However, there has always been a problem. When you want to raise a property changed event, you have to pass in a string. We can't check the validity of the string at compile time, only at runtime. So we can get errors due to typos etc. which can get overlooked.

There are a lot of implementations of INotifyPropertyChanged that use reflection or expression trees and as this and this blog show, using reflection is a terribly slow method of raising an event and to be avoided.

Luckily, Microsoft introduced the CallerMemberNameAttribute attribute, which means that as in the above example, we don't need to add a string for the property name, it gets added for us to the last optional parameter in the SetProperty method.

The SetProperty method uses the ref keyword to pass the parameter by reference (Passing parameters by reference is faster). It then checks to see if the numberOfCats parameter is different from the value parameter (There is no point raising a property changed event if they are the same). Only then, do we raise a property changed event.

Handling Dependent Properties

But what about dependent properties. Where one property affects the value of another. Well, lets take a look at another example.

public class CatCounter : NotifyPropertyChanges
{
    private int numberOfCats;

    public int NumberOfCats
    {
        get => this.numberOfCats;
        set => this.SetProperty(ref this.numberOfCats, value, "NumberOfCats", "NumberOfCatsDescription");
    }

    public string NumberOfCatsDescription => $"{this.NumberOfCats} Cats Counted";
}

You can see, that I've not done anything spectacular and just passed in the strings. As I'm using the params keyword, you can pass in as many strings as you want and the SetProperty method will raise a property changed event for each one.

If you give me a moment, I will explain why I think this is the right compromise to make. Lets make no mistake, you do need to compromise between performance and simplicity/maintainability. There are approaches which make this eventuality simpler and easier to understand but they can and will degrade performance.

So does using strings cause problems? First of all, if you use a Visual Studio Add-in like Resharper, this problem is solved as it checks that the strings match the property name for you. Secondly, as a backup the OnPropertyChanged method in the implementation above contains some Debug.Assert statements (These are removed in Release mode and have no effect on performance) to check that the property names exist and are correct, if they are not you get a error message. Thirdly, this is fairly rare in my experience and I can deal with the overhead of having a couple of extra strings.

Again, this is a choice I've made to go with performance over maintainability.

Dealing with Wrapped Objects

What if you want to wrap an object that looks like the one below with a class that supports INotifyPropertyChanged? This is a scenario I have not seen many people cover but occurs fairly often in my experience.

public class CatCount
{
    public int Count { get; set; }
}

An example view model for the CatCount class can be found below.

public class CatCountModel : NotifyPropertyChanges
{
    private CatCount catCount;

    public int NumberOfCats
    {
        get { return this.catCount.Count; }
        set { this.SetProperty(() => this.catCount.Count == value, () => this.catCount.Count = value); }
    }
}

So here we are providing the SetProperty method with two delegates. We can't use the ref keyword we used earlier because this gives us the compiler error "A property, indexer or dynamic member access may not be passed as an out or ref parameter". So we use delegates as an alternative which is not as fast as the ref keyword but almost as fast.

The first delegate determines if the cat count has actually changed. Only if it has (Remember, executing a delegate is far cheaper than updating the UI), do we call the next delegate which actually sets the value. Finally the SetProperty method raises a property changed event.

Using Reactive Extensions (Rx) to Replace the PropertyChanged Event

C# events are old school. Reactive Extensions (Rx) provides a cleaner and far more powerful drop-in replacement for C# events. I'm not going to go over the advantages of Reactive Extensions here but you can take a look at a series of blog posts I've done in the past.

We can hide the PropertyChanged C# event by explicitly implementing the interface (Click here for details on implicit versus explicit implementations of interfaces).

The PropertyChanged C# event can still be accessed by first casting the object to INotifyPropertyChanged. Binding in XAML languages, which uses this interface continues to work. Our new Reactive Extensions (Rx) observable event called WhenPropertyChanged of type IObservable<string> (The string is the property name) is now the default method of subscribing for property changed events and we've hidden away the old C# event.

Implementing INotifyPropertyChanging

Take another look at the title of this paragraph, it says INotifyPropertyChanging and not INotifyPropertyChanged.

This interface has a single event called PropertyChang**ing** and is raised before a property is about to be changed. This interface is not actually used by any XAML framework but does complement the INotifyPropertyChanged interface and can be useful in your view models when you want to know that a property is about to change and do something about it.

Given that we've written a base class, it is super easy to include it too. You should note that this interface only exists in the full .NET Framework and Silverlight. It does not exist on Windows Store or Windows Phone platforms.

As we are writing a base class for a Portable Class Library (PCL), I've commented it out. However, if I were to create a full .NET or Silverlight class library, I would definitely put that code back in.

If you find the interface useful and you too are using a Portable Class Library (PCL), you could take a copy of the INotifyPropertyChanging interface and include it with your base class. If Microsoft ever decide to include it into the PCL, you simply need to remove your class and use the one in the framework.

Conclusions

I have gone through many iterations to get to this base class. As I've shown, I've had very particular goals in mind. Your mileage may vary but I believe with the tools Microsoft have given us, this is a good compromise and covers all the scenarios I can think of. I'd be very interested if anyone has any comments or thoughts on improvements. Feel free to sound-off in the comments.

Naming Conventions

$
0
0

Code is written to be read by humans, not for machines so it makes sense that following some basic ground rules for the look and feel of your code could make your code easier to read and boost your productivity. This is particularly important if you work in teams where each developer can go off and write their code in entirely different ways. Reading these different styles hinders your productivity. In my opinion if you add up all the few extra seconds here and there, it all adds up to extra hours or even days wasted over the course of a year per developer.

::: warning Disclaimer At the end of the day, there are no rules for coding style. This is all a matter of personal preference. :::

I have recently been doing a fair amount of T-SQL and C++ and thought I'd look into some form of naming conventions for the two languages. If you've read my previous blog post 'Stop the Brace Wars, Use StyleCop', then you'll know how I feel about coding style in the C# language.

SQL Coding Style

The SQL language is an interesting case, its a really old language from 1974 and in those days they didn't even have keyboards that could deal with upper and lower case letters!

A lot of examples you'll see in books have used all-caps for the SQL keywords like SELECT and WHERE. As is widely researched, all-caps is really bad for readability. However, as this Stack Overflow article shows, all-caps is still a really popular style of writing SQL.

SELECT s.Name, s.Size
FROM Spaceship s
WHERE s.Name = 'Death Star'
select s.Name, s.Size
from Spaceship s
where s.Name = 'Death Star'

In the above example, the all capitals doesn't look too bad. It's a very short SQL statement and helps break up the three parts of the query. You could argue, that the SQL keywords are coloured blue, so we don't need the capitalization and that's a pretty good argument. As an aside please remember that colour blindness affects approximately 1 in 12 men and 1 in 200 women in the world (source).

But this is a really simple SQL statement, if you start writing a stored procedure of any complexity, things get ugly pretty fast (Imagine writing C# with upper case keywords, yuck!). Happily though, SQL developers seemed to have cottoned onto this. A lot more real world SQL examples on blogs and forums seem to be all lower-case. Even to me though, all lower case SQL does not look entirely correct, perhaps I've just been conditioned into all-caps, it is however easier to read for more complex T-SQL.

C++ Coding Style

C++ is fairly similar to C#, so for me as a mainly C# developer it's easier to write in a similar style. However, I was not happy with this approach and wanted to see what was being done elsewhere and what was the more 'correct' approach, if there was one.

I found the Google C++ Style Guide which is a really detailed, yet simple set of guidelines for how to write your C++. Definitely worth a quick read.

Conclusions

Coding style is a deeply personal subject and a pretty important one too that is often overlooked. In my opinion, it's always worth spending a little time looking up the preferred methods (There will usually be more than one) of writing in any particular language and picking one of the most popular approaches.

If you're working in a team, you'll reap the benefits pretty quickly. Code written by others will look just like yours, saving you precious seconds. Even if your a solo developer, you'll benefit. Developers are inherently plagiarists, copying snippets of code found on-line written by others. Using a common coding style will mean that your style is more likely to be the same as the next snippet of code you or I shamelessly copy from the internet.

Model-View-ViewModel (MVVM) - Part 4 - INotifyDataErrorInfo

$
0
0

In this next part, I'm going to discuss validation of your view models using the INotifyDataErrorInfo interface. Validation is an often ignored part of the Model-View-ViewModel (MVVM) story. If you need to create a form for your users to fill in (which is probably most applications, I would have thought), then you probably need to validate user input in some way and the INotifyDataErrorInfo interface can get you there.

INotifyDataErrorInfo Valid TextBox

That was a valid TextBox using INotifyDataErrorInfo.

INotifyDataErrorInfo Invalid TextBox

That was an invalid TextBox using INotifyDataErrorInfo.

In the example above you can see a name text box which requires text, to be in a valid state. In the valid state there is a big green tick next to the text box and conversely in an invalid state, there is a big yellow warning sign, the text box background becomes pink and you get a nice tool-tip telling you what the error is. By the way, this example is taken from my Elysium Extra WPF project which is freely available on GitHub.

How Does It Work?

You can see the interface and its corresponding event arguments below. If the name property in our view model changes and is empty then the state of our view model is invalid, we can raise the ErrorsChanged event, set the HasErrors property to return true and make any calls to GetErrors return a list of the errors (In our case we only have one but there could be multiple errors).

namespace System.ComponentModel
{
    public interface INotifyDataErrorInfo
    {
        bool HasErrors { get; }

        event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

        IEnumerable GetErrors(string propertyName);
    }

    public class DataErrorsChangedEventArgs : EventArgs
    {
        public DataErrorsChangedEventArgs(string propertyName);

        public virtual string PropertyName { get; }
    }
}

That's a fair amount of work and a base class to do all that makes life much easier. So what are the main aims of a base class implementing INotifyDataErrorInfo?

  • Integration - I usually want to raise an error in response to a property changing. So, we probably want to also implement INotifyPropertyChanged. Handily, I showed how best to create a base class for that in my last article in this series. So our new base class can inherit from the NotifyPropertyChanges base class.
  • Performance - Performance is king. It needs to be fast and I mean really fast. You can't afford for your UI to freeze up while your view model works out if it has an error to raise or not. Some validation frameworks use an attribute based approach but this requires reflection so we will not be using that here.
  • Reactive Extensions (Rx) - Events are old school, I want an observable error changed event notification system instead of the ErrorsChanged C# event.
  • Human Error - I don't want to raise error change events for properties that don't exist by accident.
  • Has it Really Error'ed - I don't want to raise a error changed event twice by accident or if it has not really error'ed.

So, without further ado, here is my implementation. Note that there are three classes:

namespace Framework.ComponentModel
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Linq;
    using System.Reactive.Linq;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using Framework.ComponentModel.Rules;

    /// <summary>
    /// Provides functionality to provide errors for the object if it is in an invalid state.
    /// </summary>
    /// <typeparam name="T">The type of this instance.</typeparam>
    public abstract class NotifyDataErrorInfo<T> : NotifyPropertyChanges, INotifyDataErrorInfo
        where T : NotifyDataErrorInfo<T>
    {
        private const string HasErrorsPropertyName = "HasErrors";

        private static RuleCollection<T> rules = new RuleCollection<T>();

        private Dictionary<string, List<object>> errors;

        /// <summary>
        /// Occurs when the validation errors have changed for a property or for the entire object. 
        /// </summary>
        event EventHandler<DataErrorsChangedEventArgs> INotifyDataErrorInfo.ErrorsChanged
        {
            add { this.errorsChanged += value; }
            remove { this.errorsChanged -= value; }
        }

        /// <summary>
        /// Occurs when the validation errors have changed for a property or for the entire object. 
        /// </summary>
        private event EventHandler<DataErrorsChangedEventArgs> errorsChanged;

        /// <summary>
        /// Gets the when errors changed observable event. Occurs when the validation errors have changed for a property or for the entire object. 
        /// </summary>
        /// <value>
        /// The when errors changed observable event.
        /// </value>
        public IObservable<string> WhenErrorsChanged
        {
            get
            {
                return Observable
                    .FromEventPattern<DataErrorsChangedEventArgs>(
                        h => this.errorsChanged += h,
                        h => this.errorsChanged -= h)
                    .Select(x => x.EventArgs.PropertyName);
            }
        }

        /// <summary>
        /// Gets a value indicating whether the object has validation errors. 
        /// </summary>
        /// <value><c>true</c> if this instance has errors, otherwise <c>false</c>.</value>
        public virtual bool HasErrors
        {
            get
            {
                this.InitializeErrors();
                return this.errors.Count > 0;
            }
        }

        /// <summary>
        /// Gets the rules which provide the errors.
        /// </summary>
        /// <value>The rules this instance must satisfy.</value>
        protected static RuleCollection<T> Rules => rules;

        /// <summary>
        /// Gets the validation errors for the entire object.
        /// </summary>
        /// <returns>A collection of errors.</returns>
        public IEnumerable GetErrors() => this.GetErrors(null);

        /// <summary>
        /// Gets the validation errors for a specified property or for the entire object.
        /// </summary>
        /// <param name="propertyName">Name of the property to retrieve errors for. <c>null</c> to 
        /// retrieve all errors for this instance.</param>
        /// <returns>A collection of errors.</returns>
        public IEnumerable GetErrors(string propertyName)
        {
            Debug.Assert(
                string.IsNullOrEmpty(propertyName) ||
                (this.GetType().GetRuntimeProperty(propertyName) != null),
                "Check that the property name exists for this instance.");

            this.InitializeErrors();

            IEnumerable result;
            if (string.IsNullOrEmpty(propertyName))
            {
                List<object> allErrors = new List<object>();

                foreach (KeyValuePair<string, List<object>> keyValuePair in this.errors)
                {
                    allErrors.AddRange(keyValuePair.Value);
                }

                result = allErrors;
            }
            else
            {
                if (this.errors.ContainsKey(propertyName))
                {
                    result = this.errors[propertyName];
                }
                else
                {
                    result = new List<object>();
                }
            }

            return result;
        }

        /// <summary>
        /// Raises the PropertyChanged event.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            base.OnPropertyChanged(propertyName);

            if (string.IsNullOrEmpty(propertyName))
            {
                this.ApplyRules();
            }
            else
            {
                this.ApplyRules(propertyName);
            }

            base.OnPropertyChanged(HasErrorsPropertyName);
        }

        /// <summary>
        /// Called when the errors have changed.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        protected virtual void OnErrorsChanged([CallerMemberName] string propertyName = null)
        {
            Debug.Assert(
                string.IsNullOrEmpty(propertyName) ||
                (this.GetType().GetRuntimeProperty(propertyName) != null),
                "Check that the property name exists for this instance.");

            EventHandler<DataErrorsChangedEventArgs> eventHandler = this.errorsChanged;

            if (eventHandler != null)
            {
                eventHandler(this, new DataErrorsChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Applies all rules to this instance.
        /// </summary>
        private void ApplyRules()
        {
            this.InitializeErrors();

            foreach (string propertyName in rules.Select(x => x.PropertyName))
            {
                this.ApplyRules(propertyName);
            }
        }

        /// <summary>
        /// Applies the rules to this instance for the specified property.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        private void ApplyRules(string propertyName)
        {
            this.InitializeErrors();

            List<object> propertyErrors = rules.Apply((T)this, propertyName).ToList();

            if (propertyErrors.Count > 0)
            {
                if (this.errors.ContainsKey(propertyName))
                {
                    this.errors[propertyName].Clear();
                }
                else
                {
                    this.errors[propertyName] = new List<object>();
                }

                this.errors[propertyName].AddRange(propertyErrors);
                this.OnErrorsChanged(propertyName);
            }
            else if (this.errors.ContainsKey(propertyName))
            {
                this.errors.Remove(propertyName);
                this.OnErrorsChanged(propertyName);
            }
        }

        /// <summary>
        /// Initializes the errors and applies the rules if not initialized.
        /// </summary>
        private void InitializeErrors()
        {
            if (this.errors == null)
            {
                this.errors = new Dictionary<string, List<object>>();

                this.ApplyRules();
            }
        }
    }
}

namespace Framework.ComponentModel.Rules
{
    using System;

    /// <summary>
    /// A named rule containing an error to be used if the rule fails.
    /// </summary>
    /// <typeparam name="T">The type of the object the rule applies to.</typeparam>
    public abstract class Rule<T>
    {
        private string propertyName;
        private object error;

        /// <summary>
        /// Initializes a new instance of the <see cref="Rule<T>"/> class.
        /// </summary>
        /// <param name="propertyName">The name of the property this instance applies to.</param>
        /// <param name="error">The error message if the rules fails.</param>
        protected Rule(string propertyName, object error)
        {
            if (propertyName == null)
            {
                throw new ArgumentNullException(nameof(propertyName));
            }

            if (error == null)
            {
                throw new ArgumentNullException(nameof(error));
            }

            this.propertyName = propertyName;
            this.error = error;
        }

        /// <summary>
        /// Gets the name of the property this instance applies to.
        /// </summary>
        /// <value>The name of the property this instance applies to.</value>
        public string PropertyName => this.propertyName;

        /// <summary>
        /// Gets the error message if the rules fails.
        /// </summary>
        /// <value>The error message if the rules fails.</value>
        public object Error => this.error;

        /// <summary>
        /// Applies the rule to the specified object.
        /// </summary>
        /// <param name="obj">The object to apply the rule to.</param>
        /// <returns>
        /// <c>true</c> if the object satisfies the rule, otherwise <c>false</c>.
        /// </returns>
        public abstract bool Apply(T obj);
    }
}

namespace Framework.ComponentModel.Rules
{
    using System;

    /// <summary>
    /// Determines whether or not an object of type <typeparamref name="T"/> satisfies a rule and
    /// provides an error if it does not.
    /// </summary>
    /// <typeparam name="T">The type of the object the rule can be applied to.</typeparam>
    public sealed class DelegateRule<T> : Rule<T>
    {
        private Func<T, bool> rule;

        /// <summary>
        /// Initializes a new instance of the <see cref="DelegateRule<T>"/> class.
        /// </summary>
        /// <param name="propertyName">>The name of the property the rules applies to.</param>
        /// <param name="error">The error if the rules fails.</param>
        /// <param name="rule">The rule to execute.</param>
        public DelegateRule(string propertyName, object error, Func<T, bool> rule)
            : base(propertyName, error)
        {
            if (rule == null)
            {
                throw new ArgumentNullException(nameof(rule));
            }

            this.rule = rule;
        }

        /// <summary>
        /// Applies the rule to the specified object.
        /// </summary>
        /// <param name="obj">The object to apply the rule to.</param>
        /// <returns>
        /// <c>true</c> if the object satisfies the rule, otherwise <c>false</c>.
        /// </returns>
        public override bool Apply(T obj) => this.rule(obj);
    }
}

namespace Framework.ComponentModel.Rules
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;

    /// <summary>
    /// A collection of rules.
    /// </summary>
    /// <typeparam name="T">The type of the object the rules can be applied to.</typeparam>
    public sealed class RuleCollection<T> : Collection<Rule<T>>
    {
        /// <summary>
        /// Adds a new <see cref="Rule{T}"/> to this instance.
        /// </summary>
        /// <param name="propertyName">The name of the property the rules applies to.</param>
        /// <param name="error">The error if the object does not satisfy the rule.</param>
        /// <param name="rule">The rule to execute.</param>
        public void Add(string propertyName, object error, Func<T, bool> rule) =>
            this.Add(new DelegateRule<T>(propertyName, error, rule));

        /// <summary>
        /// Applies the <see cref="Rule{T}"/>'s contained in this instance to <paramref name="obj"/>.
        /// </summary>
        /// <param name="obj">The object to apply the rules to.</param>
        /// <param name="propertyName">Name of the property we want to apply rules for. <c>null</c>
        /// to apply all rules.</param>
        /// <returns>A collection of errors.</returns>
        public IEnumerable<object> Apply(T obj, string propertyName)
        {
            List<object> errors = new List<object>();

            foreach (Rule<T> rule in this)
            {
                if (string.IsNullOrEmpty(propertyName) || rule.PropertyName.Equals(propertyName))
                {
                    if (!rule.Apply(obj))
                    {
                        errors.Add(rule.Error);
                    }
                }
            }

            return errors;
        }
    }
}

Simple Example

An example of how you can use this base class is as follows.

public class ZombieViewModel : NotifyDataErrorInfo<ZombieViewModel>
{
    private string name;
    private int limbsRemaining;

    static ZombieViewModel()
    {
        Rules.Add(new DelegateRule<ZombieViewModel>(
            "Name",
            "Name cannot be empty.",
            x => !string.IsNullOrEmpty(x.Name)));
        Rules.Add(new DelegateRule<ZombieViewModel>(
            "LimbsRemaining",
            "A zombie can't have less than zero limbs.",
            x => x.LimbsRemaining >= 0));
        Rules.Add(new DelegateRule<ZombieViewModel>(
            "LimbsRemaining",
            "A zombie can only have up to four limbs.",
            x => x.LimbsRemaining <= 4));
    }

    public string Name
    {
        get => this.name;
        set => this.SetProperty(ref this.name, value);
    }

    public int LimbsRemaining
    {
        get => this.limbsRemaining;
        set => this.SetProperty(ref this.limbsRemaining, value);
    }
}

As you can see, our view model has two properties and as shown in the last post in the series we are using the SetProperty method to raise PropertyChanged events. The only bit I've added for validation is in the static constructor containing the three validation rules.

The Name property has a single rule applied to it. When the name is empty a validation error is raised. The LimbsRemaining property has two rules and when it is less than zero or more than four, validation errors are raised auto-magically.

Under the covers, each time the PropertyChanged event is raised, we apply the corresponding rule relating to the property and if the rule fails, we raise the ErrorsChanged event, raise a PropertyChanged event for the HasErrors property (Which is now true) and finally ensure that any calls to GetErrors now returns the error shown in the rule.

Extensibility

The DelegateRule<T> class shown above is a really easy way to provide nice, simple rules. If you need something more complex you can create your own rule by inheriting from the Rule<T> base class. An example of this could be a custom rule to validate an email address or telephone number.

Using Reactive Extensions (Rx) to Replace the ErrorsChanged Event

C# events are old school. Reactive Extensions (Rx) provides a cleaner and far more powerful drop-in replacement for C# events. I'm not going to go over the advantages of Reactive Extensions here but you can take a look at a series of blog posts I've done in the past.

We can hide the ErrorsChanged C# event by explicitly implementing the interface (Click here for details on implicit versus explicit implementations of interfaces).

The ErrorsChanged C# event can still be accessed by first casting the object to INotifyDataErrorInfo. Validation in XAML languages, which uses this interface continues to work. Our new Reactive Extensions (Rx) observable event called WhenErrorsChanged of type? IObservable<string> (The string is the property name) is now the default method of subscribing for error changed events and we've hidden away the old C# event.

INotifyDataErrorInfo Support

The INotifyDataErrorInfo interface is supported by most XAML frameworks including WPF, Silverlight and Windows Phone. Currently WinRT does not support the interface at the time of writing but you can bet that they will in future and in the mean time you can use the WinRT XAML Validation library in conjunction with the code below to plug this gap.

Quick nod to IDataErrorInfo

This interface used to be used for validation but was replaced by INotifyDataErrorInfo. The new interface provides a much nicer API which is easier to code against and better performance. If you are still using the old interface, its time to make the change.

Conclusions

I have been tweaking this base class for the last few years and feel I've got a fairly good balance. I've not seen too many implementations of this interface, most blogs seem to cover INotifyPropertyChanged pretty well though. I'd be very interested if anyone has any comments or thoughts on improvements. Feel free to sound-off in the comments.


Elysium Extra 1.1 Released

$
0
0

https://www.youtube.com/watch?v=PGM_uBy99GA

Version 1.1.4 of Elysium Extra has just been released! If you've never heard of it, Elysium Extra is a Windows Presentation Foundation (WPF) SDK which provides a wide variety of controls and styles. Here are the relevant links to get started with the project:

  • Review - A comprehensive review of the controls and styles available.
  • GitHub - The home of the Elysium Extra project. Hosted on GitHub. Submit issues, ask questions and view source code.
  • Getting Started - A quick start guide to using Elysium Extra in your WPF project.
  • NuGet - The Elysium Extra NuGet package link.

Elysium Extra NuGet

At the time of writing the NuGet package has been downloaded 900 times which is pretty exciting given that its been live for only a few months and the project had no theme support in its early life.

The Future of WPF

WPF has not been getting a lot of love recently. You only have to trek the internet to see all the old WPF projects which have died or gone into hibernation with little or no new updates. I've also seen a lot of 'troll like' comments in Microsoft comment boards asking why no more updates for WPF have been forthcoming.

My personal opinion is that WPF is a very mature product and does not need as many new 'features'. Even still, there have been minor updates by Microsoft fairly recently as part of .NET 4.5. Let us not forget that Visual Studio is written in WPF and the technology is being maintained. There is a lot of noise being made about upstart XAML technologies like Windows Phone and Windows Store apps (I've written a few myself and they're great too) so sometimes it's easy to overlook WPF.

What's New

Theming Support

The latest version of Elysium Extra adds full theming support. There is now a Dark and Light theme (A bit like Windows Store Apps). You can even change the Accent and Contrast colours dynamically on the fly. I've taken a screenshot of the sample application in the Dark them with a nice red accent colour:

Elysium Extra Dark Theme

So how do you change the theme? Well you can do it in XAML by changing your App.xaml file like so:

<extra:ElysiumApplication x:Class="[YOUR NAMESPACE GOES HERE].App"
                          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                          xmlns:extra="http://schemas.extra.com/ui"
                          AccentColor="Red"
                          ContrastColor="LightBlue"
                          SemitransparentContrastColor="LightCoral"
                          Theme="Dark"
                          StartupUri="MainWindow.xaml"/>

In the above sample code, I'm setting the theme to dark and changing the three theme related colours. This is all totally optional of course. You can even change the theme in code behind instead like so:

public partial class App
{
    public App()
    {
        this.Theme = Theme.Dark;
        this.AccentColor = Colors.Red;
        this.ContrastColor = Colors.LightBlue;
        this.SemitransparentContrastColor = Colors.LightCoral;
    }
}

One final feature that I think is very cool is that individual controls can now have a different theme from the rest of the application. You can take a look at the example below where there are two text boxes but one of them has the theme explicitly set to Dark.

Dark Theme For Individual Controls

<extra:Window x:Class="WpfApplication1.MainWindow"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:extra="http://schemas.extra.com/ui"
              Height="100" 
              Title="Main Window" 
              Width="200">
    <StackPanel>
        <TextBox Margin="5"
                 Text="Hello World"/>
        <TextBox extra:ThemeManager.Theme="Dark"
                 Margin="5"
                 Text="Hello World"/>
    </StackPanel>
</extra:Window>

Performance

In the previous version of Elysium Extra, we were making judicious use of ResourceDictionary merging to allow us to split up our XAML files, so that each control has it's own separate XAML file. This led to a large amount of duplication of objects in memory because the contents of various ResourceDictionary's were being instantiated multiple times.

There are a few different approaches to this WPF problem. One that most library writers take (including Microsoft) is to only have a single massive XAML file containing all styles and templates. I hope you like scrolling and never being able to find anything because this is very difficult to maintain. Another approach that the original Elysium project took was to split your xaml  files but then use .tt template files to generate a single ResourceDictionary which I thought was an elegant approach.

Elysium Extra has taken a different route. There is a new SharedResourceDictionary type which only instantiates its contents once. You can use this type yourself too in the same way you use ResourceDictionary. It's very useful if you are merging a dictionaries from more than one location. Here is an example take from Elysium Extra itself where we are merging two resource dictionaries:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <controls:SharedResourceDictionary Source="/Framework.UI;component/Themes/WPF/Base/Converter.xaml"/>
        <controls:SharedResourceDictionary Source="/Framework.UI;component/Themes/WPF/Base/Brush.xaml"/>
    </ResourceDictionary.MergedDictionaries>

    <!-- Your Code Here -->

</ResourceDictionary>

Whats Next

We Need You

So far, there are two contributing developers working on Elysium Extra (Myself and zsKengren who has contributed new controls which are still to be added to the library) and 22 people following the project according to GitHub. That is not nearly enough and I would like to see more community activity.

Elysium Extra is a totally open source project. You can look at the source code and even use bits of it in your own projects freely. I occasionally get people contacting me telling me that they want to use the project or even how it has really helped them. That's great feedback and long may it continue!

ASP.NET Core Boilerplate

$
0
0

ASP.NET Core Boilerplate is a professional ASP.NET MVC template for building secure, fast, robust and adaptable web applications or sites. It provides the minimum amount of code required on top of the default MVC template provided by Microsoft.

New Project

The main benefits of using this template are:

  • Security
  • Performance
  • Search Engine Optimization (SEO)
  • Accessibility
  • Browser Compatibility
  • Resilience and Error Handling
  • Easier Debugging and Performance Testing Tools
  • Patterns and Practices
  • Atom Feed
  • Search
  • Social Media Support

ASP.NET 4.6 MVC 5 and ASP.NET Core Support

Two templates are provided. One for ASP.NET 4.6 MVC 5 and another ASP.NET Core template which is currently under development and is missing some features due to ASP.NET Core still being in Beta. For more information about what's new in the ASP.NET Core template, see here.

MVC 5 Technology Map

ASP.NET Core Boilerplate Technology Map]

ASP.NET Core Technology Map

ASP.NET Core Technology Map

Why Do I Need It?

The default MVC template that Visual Studio gives you does not make best use of the tools available. It's insecure, slow, and really has a very basic feature list (That's the point of it). ASP.NET Core Boilerplate provides you with a few more pieces of the puzzle to get you started quicker. It makes liberal use of comments and even gives you a check-list of tasks which you need to perform to make it even better.

The rest of this article is going to briefly go through the improvements made over using the default MVC template. I'll then finish up with instructions on how you can use it. Also, look out for more posts in the future, where I will go through each feature in detail.

Secure By Default

The default MVC template is not as secure as it could be. There are various settings (Mostly in the web.config file) which are insecure by default. For example, it leaks information about which version of IIS you are using and allows external scripts to access cookies by default!

ASP.NET Core Boilerplate makes everything secure by default but goes further and uses various HTTP headers which are sent to the browser to restrict things further.

It also makes use of the new Content Security Policy (CSP) HTTP Header using the NWebSec NuGet packages. CSP revolutionizes web security and I highly recommend reading the above link.

Setting up SSL/TLS, so that your site runs over HTTPS is made easy with easy step by step instructions and links.

Fast By Default

The default MVC template does a pretty poor job in the performance department. Probably because they don't make any assumptions about which web server you are using. Most of the world and dog that are writing ASP.NET MVC sites use IIS and there are settings in the web.config file under the system.webServer section which can make a big difference when it comes to performance.

ASP.NET Core Boilerplate makes no such assumptions. It turns on GZip compression for static and dynamic files being sent to the browsers making them smaller and quicker to download. It also uses Content Delivery Networks (CDN) by default to make common scripts like jQuery quicker to download (You can turn this off of course but the point is ASP.NET Core Boilerplate is fast by default).

That's not all! There are a bunch of other tweaks and examples of practices which can help improve the performance of the site. ASP.NET Core Boilerplate achieves a score of 96/100 on YSlow (Its not possible to get the full 100 as some of it's criteria contradict each other and site scripts need to be moved to a CDN).

Search Engine Optimization (SEO)

The default ASP.NET MVC template takes no consideration of Search Engine Optimization at all. ASP.NET Core Boilerplate adds a dynamically generated robots.txt file to tell search engines which pages they can index. It also adds a dynamically generated sitemap.xml file where you can help search engines even further by giving them links to all your pages.

ASP.NET MVC has some very useful settings for appending trailing slashes to URL's and making all URL's lower case. Unfortunately, both of these are turned off by default, which is terrible for SEO. This project turns them on by default.

It also includes an MVC filter which helps to redirect non-canonical URL's (URL's without a trailing slash or mixed case characters which are considered different URL's by search engines) to their canonical equivalent.

Accessibility

4% of the world population is estimated to be visually impaired, while 0.55% are blind. Get more statistics here. ASP.NET Core Boilerplate ensures that your site is accessible by adding aria attributes to your HTML mark-up and special short-cuts for people using screen readers.

Browser Compatibility

Websites need to reach as many people as possible and look good on a range of different devices. ASP.NET Core Boilerplate supports browsers as old as IE8 (IE8 still has around 4% market share and is mostly used by corporations too lazy to port their old websites to newer browsers).

ASP.NET Core Boilerplate also supports devices other than desktop browsers as much as possible. It has default icons and splash screens for Windows 8, Android, Apple Devices and a few other device specific settings included by default.

Resilience and Error Handling

At some point your site is probably going to throw an exception and you will need to handle and log that exception to be able to understand and fix it. ASP.NET Core Boilerplate includes Elmah, the popular error logging addin. It's all preconfigured and ready to use.

ASP.NET Core Boilerplate uses popular Content Delivery Networks (CDN) from Google and Microsoft but what happens in the unlikely event that these go down? Well, ASP.NET Core Boilerplate provides backups for these.

Not only that but standard error pages such as 500 Internal Server Error, 404 Not Found and many others are built in to the template. ASP.NET Core Boilerplate even includes IIS configuration to protect you from Denial-of-Service (DoS) attacks.

Easier Debugging and Performance Testing Tools

ASP.NET Core Boilerplate makes use of Glimpse (As advertised by Scott Hanselman). It's a great tool to use as you are developing, to find performance problems and bugs. Of course, Glimpse is all preconfigured, so you don't need to lift a finger to install it.

Patterns and Practices

Doing things right does sometimes take a little extra time. Using the Inversion of Control (IOC) pattern for example should be a default. ASP.NET Core Boilerplate uses the Autofac IOC container by default. Some people get a bit tribal when talking about IOC containers but to be honest, they all work great. I picked Autofac because it has lots of helpers for ASP.NET MVC and Microsoft even uses it for Azure Mobile Services.

ASP.NET Core Boilerplate also makes use of the popular LESS files for making life easier with CSS. For an example, it can make overriding colours and fonts in the default Bootstrap CSS a cinch.

ASP.NET MVC is a complicated beast. You can end up with lots of magic strings which can be a nightmare when renaming something. There are many ways of eliminating these magic strings but most trade maintainability for slower performance. ASP.NET Core Boilerplate makes extensive use of constants which are a trade-off between maintainability and performance, giving you the best of both worlds.

Atom Feed

An Atom 1.0 has been included by default. Atom was chosen over RSS because it is the better and newer specification. PubSubHubbub 0.4 support has also been built in, allowing you to push feed updates to subscribers.

There is a lot more to implementing search in your application than it sounds. ASP.NET Core Boilerplate includes a search feature by default but leaves it open for you to choose how you want to implement it. It also implements Open Search XML right out of the box. Read Scott Hanselman talk about this feature here.

Social Media Support

Open Graph meta tags and Twitter Card meta tags are included by default. Not only that but ASP.NET Core Boilerplate includes fully documented HTML helpers that allow you to easily generate Open Graph object or Twitter Card meta tags easily and correctly.

How can I get it?

That's easy, just choose one of the following options:

  1. Get the Visual Studio 2013 extension here and in Visual Studio go to File -> New Project -> Web.
  2. Clone the git repository:
    git clone https://github.com/Dotnet-Boxed/Templates

Release Notes and To-Do List

You can find release notes for each version here and a To-Do list of new features and enhancements coming soon here.

Bugs and Issues

Please report any bugs or issues on the GitHub issues page here.

Future of the project

At some point, I will try to create a Visual Studio Deployment package (VSIX) and list this project template on the Visual Studio extensions site. To use the template, it will be as easy as choosing ASP.NET Core Boilerplate from the online templates in the File -> New Project -> Online Template menu. Unbelievably, it's actually pretty complicated to create one of these. I found the Export Template Wizard Visual Studio extension which can do this easily but it's not been updated since Visual Studio 2010.

I am also taking a look at creating separate Visual Studio templates which include ASP.NET Web API and OAuth authentication. This is of course an open source project, I fully expect contributions and suggestions from the community.

Internet Favicon Madness (Updated)

$
0
0

These days there is a ridiculous range of devices that can access your website from phone and desktop browsers to phone apps, operating systems and search engine bots. Most of them will require some kind of icon or image to display for your website. Some of them go even further and even allow you to specify splash screens for when your page is loading or an RSS feed URL for the latest updates from your site.

A brain dump of all my knowledge regarding favicon's and many other ASP.NET MVC features can be found in the ASP.NET Core Boilerplate project on GitHub. Its a professional ASP.NET MVC template for building secure, fast, robust and adaptable web applications or sites. It provides the minimum amount of code required on top of the default MVC template provided by Microsoft.

This blog post tries to be as comprehensive as possible in explaining the absolute madness that is the internet favicon and its related 'bits' for want of a better word. So without further ado, here is a list of files that you need to add to support all the different devices that can access your site:

Favicon Files

The list of all files required to support favicon's and splash screen images on all devices.

Now you can add all these files to the root directory of your site and have a really messy project or you can add the files to a /content/icons folder in your project and add the following link and meta tags to the head section of your HTML pages:

<!-- Icons & Platform Specific Settings - Favicon generator used to generate the icons below http://realfavicongenerator.net -->
<!-- shortcut icon - This file contains the following sizes 16x16, 32x32 and 48x48. -->
<link rel="shortcut icon" href="/content/icons/favicon.ico">
<!-- favicon-96x96.png - For Google TV https://developer.android.com/training/tv/index.html#favicons. -->
<link rel="icon" type="image/png" href="/content/icons/favicon-96x96.png" sizes="96x96">
<!-- favicon-32x32.png - For Safari on Mac OS. -->
<link rel="icon" type="image/png" href="/content/icons/favicon-32x32.png" sizes="32x32">
<!-- favicon-16x16.png - The classic favicon, displayed in the tabs. -->
<link rel="icon" type="image/png" href="/content/icons/favicon-16x16.png" sizes="16x16">

<!-- Android/Chrome -->
<!-- manifest-json - The location of the browser configuration file. It contains locations of icon files, name of the application and default device screen orientation. Note that the name field is mandatory.
    https://developer.chrome.com/multidevice/android/installtohomescreen. -->
<link rel="manifest" href="/content/icons/manifest.json">
<!-- theme-color - The colour of the toolbar in Chrome M39+
    http://updates.html5rocks.com/2014/11/Support-for-theme-color-in-Chrome-39-for-Android -->
<meta name="theme-color" content="#1E1E1E">
<!-- favicon-192x192.png - For Android Chrome M36 to M38 this HTML is used. M39+ uses the manifest.json file. -->
<link rel="icon" type="image/png" href="/content/icons/favicon-192x192.png" sizes="192x192">
<!-- mobile-web-app-capable - Run Android/Chrome version M31 to M38 in standalone mode, hiding the browser chrome. -->
<!-- <meta name="mobile-web-app-capable" content="yes"> -->

<!-- Apple Icons - You can move all these icons to the root of the site and remove these link elements, if you don't mind the clutter.
    https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariHTMLRef/Introduction.html#//apple_ref/doc/uid/30001261-SW1 -->
<!-- apple-touch-icon-57x57.png - Android Stock Browser and non-Retina iPhone and iPod Touch -->
<link rel="apple-touch-icon" sizes="57x57" href="/content/icons/apple-touch-icon-57x57.png">
<!-- apple-touch-icon-114x114.png - iPhone (with 2× display) iOS = 6 -->
<link rel="apple-touch-icon" sizes="114x114" href="/content/icons/apple-touch-icon-114x114.png">
<!-- apple-touch-icon-72x72.png - iPad mini and the first- and second-generation iPad (1× display) on iOS = 6 -->
<link rel="apple-touch-icon" sizes="72x72" href="/content/icons/apple-touch-icon-72x72.png">
<!-- apple-touch-icon-144x144.png - iPad (with 2× display) iOS = 6 -->
<link rel="apple-touch-icon" sizes="144x144" href="/content/icons/apple-touch-icon-144x144.png">
<!-- apple-touch-icon-60x60.png - Same as apple-touch-icon-57x57.png, for non-retina iPhone with iOS7. -->
<link rel="apple-touch-icon" sizes="60x60" href="/content/icons/apple-touch-icon-60x60.png">
<!-- apple-touch-icon-120x120.png - iPhone (with 2× and 3 display) iOS = 7 -->
<link rel="apple-touch-icon" sizes="120x120" href="/content/icons/apple-touch-icon-120x120.png">
<!-- apple-touch-icon-76x76.png - iPad mini and the first- and second-generation iPad (1× display) on iOS = 7 -->
<link rel="apple-touch-icon" sizes="76x76" href="/content/icons/apple-touch-icon-76x76.png">
<!-- apple-touch-icon-152x152.png - iPad 3+ (with 2× display) iOS = 7 -->
<link rel="apple-touch-icon" sizes="152x152" href="/content/icons/apple-touch-icon-152x152.png">
<!-- apple-touch-icon-180x180.png - iPad and iPad mini (with 2× display) iOS = 8 -->
<link rel="apple-touch-icon" sizes="180x180" href="/content/icons/apple-touch-icon-180x180.png">

<!-- apple-mobile-web-app-title - The name of the application if pinned to the IOS start screen. -->
<!-- <meta name="apple-mobile-web-app-title" content=""> -->
<!-- apple-mobile-web-app-capable - Hide the browsers user interface on IOS, when the app is run in 'standalone' mode. Any links to other pages that are clicked whilst your app is in standalone mode will launch the full Safari browser. -->
<!-- <meta name="apple-mobile-web-app-capable" content="yes"> -->
<!-- apple-mobile-web-app-status-bar-style - default/black/black-translucent Styles the IOS status bar. Using black-translucent makes it transparent and overlays it on top of your site, so make sure you have enough margin. -->
<!-- <meta name="apple-mobile-web-app-status-bar-style" content="black"> -->

<!-- Apple Startup Images - These splash screen images are only shown if apple-mobile-web-app-capable is set to true. https://gist.github.com/tfausak/2222823 -->
<!-- apple-touch-startup-image-1536x2008.png - iOS 6 & 7 iPad (retina, portrait) -->
<!-- <link rel="apple-touch-startup-image" href="/content/icons/apple-touch-startup-image-1536x2008.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2)"> -->
<!-- apple-touch-startup-image-1496x2048.png - iOS 6 & 7 iPad (retina, landscape) -->
<!-- <link rel="apple-touch-startup-image" href="/content/icons/apple-touch-startup-image-1496x2048.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2)"> -->
<!-- apple-touch-startup-image-768x1004.png - iOS 6 iPad (portrait) -->
<!-- <link rel="apple-touch-startup-image" href="/content/icons/apple-touch-startup-image-768x1004.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 1)"> -->
<!-- apple-touch-startup-image-748x1024.png - iOS 6 iPad (landscape) -->
<!-- <link rel="apple-touch-startup-image" href="/content/icons/apple-touch-startup-image-748x1024.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 1)"> -->
<!-- apple-touch-startup-image-640x1096.png - iOS 6 & 7 iPhone 5 -->
<!-- <link rel="apple-touch-startup-image" href="/content/icons/apple-touch-startup-image-640x1096.png" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)"> -->
<!-- apple-touch-startup-image-640x920.png - iOS 6 & 7 iPhone (retina) -->
<!-- <link rel="apple-touch-startup-image" href="/content/icons/apple-touch-startup-image-640x920.png" media="(device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 2)"> -->
<!-- apple-touch-startup-image-320x460.png - iOS 6 iPhone -->
<!-- <link rel="apple-touch-startup-image" href="/content/icons/apple-touch-startup-image-320x460.png" media="(device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 1)"> -->

<!-- Windows 7 Taskbar - This depends on your site, so no code here. See http://www.buildmypinnedsite.com/windows7 -->

<!-- Windows 8 IE10 -->
<!-- application-name - The name of the application if pinned to the start screen. -->
<!-- <meta name="application-name" content=""> -->
<!-- msapplication-TileColor - The tile colour which shows around your tile image (msapplication-TileImage). -->
<!-- <meta name="msapplication-TileColor" content="#5cb95c"> -->
<!-- msapplication-TileImage - The tile image. -->
<!-- <meta name="msapplication-TileImage" content="/content/icons/mstile-144x144.png"> -->

<!-- Windows 8.1 IE11 -->
<!-- msapplication-config - The location of the browser configuration file. If you have an RSS feed, go to
    http://www.buildmypinnedsite.com and regenerate the browserconfig.xml file. You will then have a cool live tile! -->
<meta name="msapplication-config" content="/content/icons/browserconfig.xml">

Now don't be too scared, there are only 24 lines that you need, the rest is all comments describing what each line is for, which I'll go through it in the rest of this post.

Now, go ahead take another look above. That is 30 files and almost as many lines of code if you decide to have your files in a nice separate folder. Take a moment to let the insanity of this situation settle in. All we are really trying to do is set an icon for our site!

Performance and Size Trade-Off

This approach does use more bandwidth. Those 24 lines take up around 2.8KB, if you decide to support everything or around 1.4KB if you skip support for Apple splash screens which takes about half the space due to its extremely verbose meta tags.

However, you should be using GZip compression for transferring your HTML pages over the internet (I'll be covering GZip compression in a subsequent post) so when compressed we are talking around 650 Bytes if you include everything or around 465 Bytes if you remove support for Apple splash screens.

At the end of the day it's a trade off and I'll leave making that decision up to you. You can support all of it, none of it or anything in between. 650 Bytes for every page can add up to a fair amount of bandwidth, especially if you have a large number of requests coming into your site. If you had say a million requests, which is not unheard of if you consider that this overhead is added to every page, then you are looking at around 0.6GB of bandwidth and that's before you add up extra bandwidth usage from the images and Android/Chrome/Windows XML/JSON configuration files.

The manifest.json and browserconfig.xml file are small files around 1KB but they can also be GZIP compressed and more importantly they can be cached by the browser. A bigger problem is the image files. These files are up to 37KB in size, they cannot be compressed as PNG's are already compressed but they can be downloaded once and then cached. It's difficult to calculate how often these files will be downloaded and how much bandwidth this will use.

Then again, how do we measure the value of users who feel more engaged with your site because they get a more customized and integrated experience when using your site. It's a difficult question and the answer will be different for every site.

The Favicon.ico File

Favicon's were introduced in 1995 by Microsoft with Internet Explorer 5.0. You could add a favicon.ico file to the root of your site and it would get displayed next to the address bar.

Favicons use the ancient .ico image format which began life as a part of Windows 1.0! A lot of people don't realize that the .ico file can actually contain several images of varying sizes and colour depths. Typically the image sizes can include 16x16, 32x32, 48x48, 64x64, 128x128 and 256x256. Windows or your web browser can then choose the appropriate size they need for display. Most favicon's are uncompressed images and although the images are small the file size is not as small as it could be.

Where Are Favicon's Used

Desktop Browsers

These days favicon's are no longer displayed in the address bar of your browser (IE being an exception). Miscreants were abusing this feature and using padlock favicon's to trick unsavvy users into thinking the page was secure and had SSL enabled. Most browsers now only show icons on tabs or when a site is favourited. You can see a table of how desktop browsers use Favicon's here.

Desktop Browser Favicon's

iOS

iOS devices can pin your site to the home screen and you can provide icons in a variety of sizes to support phone and tablets with differing screen resolutions. All the files shown above start with apple-touch-icon. Increasingly websites are being built to look and feel like everyday phone apps. Apple lets you specify three additional meta tags which allows you to customize what happens after your site is pinned to the home screen:

<!-- apple-mobile-web-app-title - The name of the application if pinned to the IOS start screen. -->
<meta name="apple-mobile-web-app-title" content="Your Site Title">
<!-- apple-mobile-web-app-capable - Hide the browsers user interface on IOS, when the app is run in 'standalone' mode. 
     Any links to other pages that are clicked whilst your app is in standalone mode will launch the full Safari browser. -->
<meta name="apple-mobile-web-app-capable" content="yes">
<!-- apple-mobile-web-app-status-bar-style - default/black/black-translucent Styles the IOS status bar. Using 
     black-translucent makes it transparent and overlays it on top of your site, so make sure you have enough margin. -->
<meta name="apple-mobile-web-app-status-bar-style" content="black">

iOS Web App Capable

The left screen shows a normal web browsing experience on iOS and the right shows a web app capable experience.

If you decide to make your site web app capable by using the meta tag above, you can also set a splash screen which gets shown when your site is first launched. Once again, there are several sizes depending on the screen resolution and all the images start with apple-touch-startup-image. Find more information about iOS favicon's, startup images and meta tags here.

Microsoft Windows 7 Taskbar

If your site is pinned to the Windows 7 taskbar then you can customize the jump list items with additional links to pages on your site. There are lots of other additional features (See image below) but these require JavaScript and some additional work. Also, I'm not really sure how often people pin websites to the taskbar (I personally have never done it), so I'm not sure if its worth it. Check out the Windows 7 Build My Pinned Site page for examples and more information.

Windows 7 Taskbar Settings

Microsoft Windows Phone 8 and Windows 8

Windows Phone 8 and Windows 8 takes a very interesting approach. Pinning a site to the start screen of one of these devices gives you a very large tile. You can specify an icon for your tile and also an RSS feed URL. The RSS feed is polled and new updates are shown on your tile regularly (I've implemented this feature on this site, so pin this site to your Windows 8 home screen and give it a try). You can also specify a background colour which is used when showing the RSS feed items. Pretty cool eh!

Windows 8 Tiles

Now if Microsoft had taken Apple's approach it would be cluttering up the head section of your site with a lot of meta data. Microsoft splits off its tile configuration into a separate browserconfig.xml file (See example below). This is a much cleaner approach and very much welcomed. You can add this file to the root of your site or if you want to move it elsewhere, add a meta tag pointing to it (Note that this file was introduced in Windows 8.1 and Windows 8 still uses meta tags in the head of the page. Windows 8 is on its way out, so I probably would not support it).

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="tiny.png"/>
      <square150x150logo src="square.png"/>
      <wide310x150logo src="wide.png"/>
      <square310x310logo src="large.png"/>
      <TileColor>#fff200</TileColor>
    </tile>
    <notification>
      <polling-uri src="http://notifications.buildmypinnedsite.com/?feed=https://rehansaeed.com/feed/&amp;id=1"/>
      <polling-uri2 src="http://notifications.buildmypinnedsite.com/?feed=https://rehansaeed.com/feed/&amp;id=2"/>
      <polling-uri3 src="http://notifications.buildmypinnedsite.com/?feed=https://rehansaeed.com/feed/&amp;id=3"/>
      <polling-uri4 src="http://notifications.buildmypinnedsite.com/?feed=https://rehansaeed.com/feed/&amp;id=4"/>
      <polling-uri5 src="http://notifications.buildmypinnedsite.com/?feed=https://rehansaeed.com/feed/&amp;id=5"/>
      <frequency>30</frequency>
      <cycle>1</cycle>
    </notification>
  </msapplication>
</browserconfig>

Android/Chrome

Android/Chrome recently introduced new favicon's and browser settings. interestingly, their solution looks very similar to Microsoft's approach. Microsoft includes all their settings in a browserconfig.xml file which can be included in the root of your site or using a meta tag to refer to it. Android/Chrome has taken a very similar step and introduced a manifest.json file which you can also optionally point to in your HTML as shown below.

<!-- manifest-json - The location of the browser configuration file. It contains locations of icon files, name of the application and default device screen orientation. Note that the name field is mandatory.
    https://developer.chrome.com/multidevice/android/installtohomescreen. -->
<link rel="manifest" href="/content/icons/manifest.json">

The manifest.json file contains the name of the site, optional page orientation settings and the location of favicon images. Unfortunately, the name of the site is not an optional field but required according to the specification. The rest of the file is dedicated to specifying the location of the various favicon images of varying pixel densities. You can also optionally control the orientation of the site and how it appears on an Android device. One new feature is the ability to set the browser chrome theme colour. This can be done with the theme-color meta tag and examples of the results can be seen below:

<!-- theme-color - The colour of the toolbar in Chrome M39+
    http://updates.html5rocks.com/2014/11/Support-for-theme-color-in-Chrome-39-for-Android -->
<meta name="theme-color" content="#1E1E1E">

Android Theme Colour

Older versions of Android (M31 to M38) don't use the manifest.json file but are very similar to iOS and even uses some of the iOS icons if they are provided, as iOS icons tend to be a little higher resolution and more widely supported. Android also has the ability to hide the browser chrome to make your site behave like an app. It's meta tag has a different name:

<!-- favicon-192x192.png - For Android Chrome M36 to M38 this HTML is used. M39+ uses the manifest.json file. -->
<link rel="icon" type="image/png" href="/content/icons/favicon-192x192.png" sizes="192x192">
<!-- mobile-web-app-capable - Run Android/Chrome version M31 to M38 in standalone mode, hiding the browser chrome. -->
<!-- <meta name="mobile-web-app-capable" content="yes"> -->

Other

Favicons are used in a few other places, such as pinning your site to the taskbar in Windows for instance or even on your television.

How Can I Make This Easier

Even if you decide not to make your site web app capable and support just the basic iOS, Android and Windows icons and settings, your still in for a fair amount of work to create all the right images and get all the meta tags just right.

The ASP.NET Core Boilerplate project template can help you get started quickly as all of the above files and meta tags are built in from the start, all you need to do is delete the ones you don't want (A lot quicker than starting from scratch).

I also highly recommend using Real Favicon Generator in conjunction with Microsoft's Windows 8 Build My Pinned Site and Windows 7 Build My Pinned Site pages. These three sites combined can help you get most of the way there and fairly quickly.

The Real Favicon Generator site above will generate a .ico file for you but to get a real pixel perfect icon I personally use Paint.NET in conjunction with the Icon plugin to edit .ico image files.

What a Mess

So what is the future? Higher screen resolutions and a wider variety of devices of different sizes is now the norm and each one seems to need it's own images. Each manufacturer has added their own meta tags too.

One approach would be to standardize a set of three or four images sizes and then also provide a colour meta tag. The image can then be shown in the center and the colour shown around the image to fill in any gaps. This means that the image does not have to be resized and this approach would also support splash screens and non-rectangular or odd shaped icons. Indeed, this is the approach Microsoft has already taken with their Windows 8.1 Store App splash screens and it works well in my experience.

An even better and web standards based approach is to use SVG favicon's. These are vector images which do not lose image fidelity even when scaled. Unfortunately, this feature is only currently supported by the Firefox desktop browser. If all browsers implemented this feature we could go back to the days of Internet Explorer 5.0 when we only needed to create a single favicon.ico file. An SVG favicon can be set by adding the following tag:

<link rel="icon" type="image/svg+xml" href="favicon.svg"/>

Lets all hope more browsers support this simple approach but don't hold your breath.

Custom Visual Studio Project Templates

$
0
0

Creating a custom Visual Studio project template that you can use from the 'New Project' dialogue is a great way to reduce the amount of repetitive code you have to write. It gets you running through the jungle with the leaves brushing against your face, instead of sitting at the starting block wondering where your shoes are.

The Visual Studio Gallery is a great place to share your custom Visual Studio project template with the community. There are actually two ways to create a template. I recently had to create one for ASP.NET Core Boilerplate and found it less than simple. This post talks you through creating one and submitting it to the Visual Studio Gallery, allowing anyone to use it from the 'New Project' dialogue.

The project template shown in the 'Web' section of Visual Studio's 'New Project' dialogue.

The project template shown in the 'Web' section of Visual Studio's 'New Project' dialogue.

Export Template as .zip

The first method of creating a custom project template is to use the 'Export Template' wizard in Visual Studio, as shown in the steps below, you can create a .zip file which contains a template of your selected project.

Export .zip Project Template

The Visual Studio Export Template menu item for exporting a .zip project template.

The wizard allows you to select the project from your solution you want to export as a template.

The export template 'Choose template type' screen.

The export template 'Choose template type' screen.

You can even specify an icon and preview image of the project template. This is perfect as this information also gets displayed in the Visual Studio 'New Project' dialogue.

The export template 'Select template options' screen, where you can describe your template.

The export template 'Select template options' screen, where you can describe your template.

The .zip file that is output must be copied into the following folder, for Visual Studio to pick it up:

C:/Users/[Your User Name]/Documents/Visual Studio [2010|2012|2013|2015]/Templates/ProjectTemplates

The .zip file output as part of the Visual Studio Export Template wizard.

The .zip file output as part of the Visual Studio Export Template wizard.

This is a super easy process and you should really consider creating your own templates if you find yourself making the same old changes to every project you are creating. The downside is that its not very customizable and these types of project templates cannot be submitted to the Visual Studio Gallery.

The gallery website only supports project templates created using the VSIX package. Creating a VSIX package is a pretty involved process and will take a couple of hours.

Export Template Wizard Extension

This Visual Studio extension claims to support exporting your projects into VSIX packages using a simple wizard interface. Unfortunately, this tool is only available for Visual Studio 2010 and the Microsoft developers of the extension seem to have stopped further development.

This is a real shame. Here we have an excellent tool which the community really needs. A tool that makes creating a VSIX project template package, a matter of a few clicks. This should be built into Visual Studio out of the box!

SideWaffle Project Templates

There is even an alternative method of creating project templates and sharing them with the community that I should mention. It's called SideWaffle (I like the name for some reason). It makes it slightly easier to create a template but its still not as simple as a few clicks. It's certainly something worth taking a look at though.

Creating a VSIX Package

The first step is to create a .zip project template package using the steps above. Once you've done that, download and install the Microsoft Visual Studio 2013 SDK. This will give you new project templates to create VSIX packages. The first thing to do is create a new C# Project Template (Or a Visual Basic one if you prefer).

The new project dialogue, showing how to create a new VSIX C# project.

The new project dialogue, showing how to create a new VSIX C# project.

The next step is to open the .zip version of your project template and copy the contents into your new project. Copy everything (Including the project file), except the 'Properties' folder as this will conflict with the existing one in the project.

An example of a VSIX C# project from the ASP.NET Core Boilerplate project template.

An example of a VSIX C# project from the ASP.NET Core Boilerplate project template.

Select all the files in the project and in the properties window, ensure that their 'Build Action' is set to 'Content'.

The properties window for a file in a VSIX C# project. Note, that the file build action has been set to 'Content'.

The properties window for a file in a VSIX C# project. Note, that the file build action has been set to 'Content'.

The .vstemplate file in the project contains all the information about the contents of the project template. If you select it and go to the 'Properties' window, you can set the 'Category' property which determines where your project template will appear in the 'New Project' dialogue.

The category a VSIX C# project is displayed under, in the Visual Studio New Project dialogue.

The category a VSIX C# project is displayed under, in the Visual Studio New Project dialogue.

An example of the .vstemplate file is shown below. Note, that I've set the project template name, description and the default name of the project which is shown in the 'New Project' dialogue and the user can rename. The XML then goes on to declare the name of the .csproj file in the Project node, followed by each and every file and folder to be included in the template.

Note, that the AssemblyInfo.cs file is a little special. There are two of them in the project. The one we are interested in was already located in the root of the project when we created it. We also need to add it to the XML below slightly differently than the other files (See below).

You can use the OpenInWebBrowser or OpenInEditor attributes on a ProjectItem to get the file to be opened in a web browser or text editor when the project is first created. I've used OpenInWebBrowser to open the ReadMe.html file containing basic information about the project, when the project is first created.

<?xml version="1.0" encoding="utf-8"?>
<VSTemplate Version="3.0.0" Type="Project" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" xmlns:sdk="http://schemas.microsoft.com/developer/vstemplate-sdkextension/2010">
  <TemplateData>
    <Name>ASP.NET Core Boilerplate</Name>
    <Description>A professional ASP.NET MVC template for building secure, fast, robust and adaptable web applications or sites. It provides the minimum amount of code required on top of the default MVC template provided by Microsoft. Find out more at RehanSaeed.com</Description>
    <Icon>MvcBoilerplateTemplate.ico</Icon>
    <ProjectType>CSharp</ProjectType>
    <RequiredFrameworkVersion>4.5</RequiredFrameworkVersion>
    <SortOrder>1000</SortOrder>
    <TemplateID>f2d50b53-cff3-41b4-8481-dac14c18ea48</TemplateID>
    <CreateNewFolder>true</CreateNewFolder>
    <DefaultName>WebProject</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
  </TemplateData>
  <TemplateContent>
    <Project File="MvcBoilerplate.csproj" ReplaceParameters="true">
      <ProjectItem ReplaceParameters="true" TargetFileName="Properties%5CAssemblyInfo.cs">AssemblyInfo.cs</ProjectItem>
      <Folder Name="App_Start">
        <ProjectItem ReplaceParameters="true" OpenInEditor="false">BundleConfig.cs</ProjectItem>
        <ProjectItem ReplaceParameters="true" OpenInEditor="false">FilterConfig.cs</ProjectItem>
        <ProjectItem ReplaceParameters="true" OpenInEditor="false">RouteConfig.cs</ProjectItem>
        <ProjectItem ReplaceParameters="true" OpenInEditor="false">Startup.Container.cs</ProjectItem>
      </Folder>
      <!-- Omitted lots of Folder and ProjectItem nodes... -->
      <ProjectItem ReplaceParameters="true" OpenInWebBrowser="true">ReadMe.html</ProjectItem>
    </Project>
  </TemplateContent>
</VSTemplate>

The next step is to add a VSIX Project to our solution. This is the project that will actually build a .vsix file.

The new project dialogue, showing how to create a new VSIX project.

The new project dialogue, showing how to create a new VSIX project.

If you open the .vsixmanifest file, you can fill in basic information about the template. This information will be displayed in the 'New Project' dialogue. I have specified an Icon, Preview Image and Licence file. All three of these files are added to the project.

The metadata for the VSIX project, describing the .vsix installer file and also the project shown in the solution explorer, showing the files included.

The metadata for the VSIX project, describing the .vsix installer file and also the project shown in the solution explorer, showing the files included.

The 'Install Targets' tab lets you target a specific version of Visual Studio. I changed this to support Visual Studio 2012 and above by specifying the version range to be [11.0,]. More information here.

The 'Dependencies' tab is very similar. Here you can specify which version of the .NET Framework your project depends on. I stuck with the defaults of .NET 4.5 only.

The installation targets or versions of Visual Studio your VSIX extension will install to.

The installation targets or versions of Visual Studio your VSIX extension will install to.

If you click on the 'Assets' tab on the left, you can add a reference to your other 'C# Project Template' project.

The VSIX C# projects you want to add to the VSIX extension as an asset to be installed.

The VSIX C# projects you want to add to the VSIX extension as an asset to be installed.

Submitting your VSIX Project Template to the Visual Studio Gallery

Submitting your new VSIX extension to the Visual Studio Gallery is a great way to share your new Project Template with the world. The ASP.NET Core Boilerplate extension now has over a hundred downloads within two days of submitting it!

If you've followed the steps above to create a VSIX package and tested that it works correctly then submitting one to the site is really easy. Follow this link to the submission page and fill in the form. An example of what it looks like can be seen below:

An example of the Visual Studio Gallery Submission Page.

An example of the Visual Studio Gallery Submission Page.

Once you have made your submission and you go to the 'New Project' dialogue, you can go to the 'Online' section and see your project template listed.

The project template shown in the 'Web' section of Visual Studio's 'New Project' dialogue.

The project template shown in the 'Web' section of Visual Studio's 'New Project' dialogue.

If you use the template above, explicitly install it from the Visual Studio Gallery or install it from 'Extensions and Updates', you will then see the project appear in the 'New Project' dialogue under the category you specified in the settings above.

The project template shown in the 'Online' section of Visual Studio's 'New Project' dialogue.

The project template shown in the 'Online' section of Visual Studio's 'New Project' dialogue.

Conclusions

Creating a simple .zip project template is super simple and something everyone should know and use for larger projects. Creating VSIX project templates is a lot more involved but to be honest, there is no reason why it should be. I hope Microsoft makes this process a lot easier.

Configuration File Transforms In Visual Studio Should Be Built In

$
0
0

Update 1

I should point out that configuration file transforms have been available for some time for web projects only. I believe the feature was developed by the web team within Microsoft. This fact just makes it more strange, that this feature was not rolled out to the masses.

Update 2

Microsoft has just announced on their UserVoice site that SlowCheetah will be updated for Visual Studio 2015 and future versions will indeed have configuration file transforms built in! That's great news and shows another example of Microsoft listening to its developers.

Introduction

I have used a number of IDE's in my time as a developer, from bare bones text editors like Sublime (Which you should seriously consider purchasing. It beats the pants off of notepad and most notepad competitors) to fully fledged development environments like Netbeans and Visual Studio. It has to be said though that Microsoft does a much better job than most and packs a lot of power into their punch.

It is with puzzlement and confusion then that something as useful and common as transforms for configuration files (.config) are still not supported by Microsoft. You may be wondering what I'm babbling about. Well, every developer at some point has had to release their application on more than one environment, even if it's just your own development machine and wherever your application is released. In the past I've worked with as many as four distinct environments. Each with it's own application settings, database connection strings and other settings stored in .config files. In the past, this has been a nightmare.

Slow Cheetah

Happily though, someone named Sayed Hashimi working for Microsoft has unofficially created a Visual Studio extension called Slow Cheetah. Go ahead, read through, that page if you haven't already, I'm not going to describe the genius that is Slow Cheetah here (I'm not just talking about the ironic name, which I quite like. Sayed Hashimi seems to have a gift for odd names, as he is also a developer for the Side Waffle project).

Unfortunately, according to this post, Slow Cheetah is no longer going to be supported in future versions of Visual Studio. His reasons for dropping support are interesting. In the first paragraph, he suggests that the existence of Slow Cheetah has stopped Microsoft from building configuration file transforms into Visual Studio in the first place.

What Now

It's been a few months since Sayed's post on GitHub. While I'm sure the community will step in and keep the tool updated for future versions of Visual Studio, this is really something that should have been built in to Visual Studio years ago!

Don't despair, there is hope. On the Visual Studio User Voice site, there is a suggestion to support configuration file transforms out of the box. What's more, is that the suggestion is currently number seven in the list of 'hot' ideas and number three if you remove the ideas that Microsoft have already commented on. Please do go and vote for this suggestion, Microsoft does read and more importantly act on them.

I spent some time a year ago teaching a junior developer the new C# async and await feature, as well as the Task Parallel Library (TPL). Not only did it blow his mind but I realized that so much that I had learned had now become obsolete and that this new developer would never have to struggle with asynchronous code as I had. In my opinion, this feature is another one of those moments when we can consign another series of old method to the dustbin of history. We just need to help Microsoft know about it.

Viewing all 138 articles
Browse latest View live