Not long ago, Microsoft released its new device, the Surface Studio, a powerhorse with a 28” touch screen, with characteristics that make it a go in the wish list for every geek (https://www.microsoft.com/en-us/surface/devices/surface-studio/overview).

With it, Microsoft released the Surface Dial, a rotary wheel that redefines the way you work when you are doing some creative design (https://www.microsoft.com/en-us/surface/accessories/surface-dial). Although it was created to interact directly with the Surface Studio (you can put it on the screen and it will open new ways to work, you can also use it even if you don’t have the Surface Studio.

In fact, you can use it with any device that has bluetooth connection and Windows 10 Anniversary edition. This article will show you how to use the Surface Dial in a UWP application and enhance the ways your user can interact with your app.

Working with the Surface Dial

Work with the Surface Dial is very easy. Just open the “Manage Bluetooth Devices” window and, in the Surface Dial, open the bottom cover to show the batteries and press the button there until the led starts blinking. The Surface Dial will appear in the window:

image

Just click on it and select “Connect”. Voilà, you are ready to go. And what can you do, now? Just out of the box, many things:

  • Go to a browser window and turn the wheel, and you’ll start scrolling the page content
  • Click on the dial and a menu opens:

image

If you turn the wheel, you can change the function the wheel does:

  • Volume, to increase or decrease the sound volume of you machine
  • Scroll, to scroll up and down the content (the default setting)
  • Zoom, to zoom in and out
  • Undo, to undo or redo the last thing

The best thing here is that it works in the program you are in, no matter if it’s a Windows 10 program or no (for example, you can use it for Undo/Redo in Word or to scroll in the Chrome browser). All of this comes for free, you don’t have to do anything.

If you want to give an extra usability for your Surface Dial, you can go to Windows Settings/Devices/Wheel and set new tools for your apps. For example, if you have a data entry form and you want to move between the text boxes, you can create a Custom Tool like this:

image

That way, the user will be able to move between the boxes using the Surface Dial. Nice, no?

But what if you want to create a special experience for your user? We’ll do that now, creating a UWP program that will be able to change properties of a rectangle: change its size, position, angle or color, with just one tool: the Surface Dial.

Creating a UWP program for the Surface Dial

Initially, let’s create a UWP program in Visual Studio. You must target the Anniversary Edition. If you don’t have it, you must install Visual Studio Update 3 on your system.

Then, add the rectangle to MainPage.xaml:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Rectangle Width="100" Height="100" Fill =" Red" x:Name="Rectangle" RenderTransformOrigin="0.5,0.5">
        <Rectangle.RenderTransform>
            <TransformGroup>
                <ScaleTransform x:Name="Scale" ScaleX="1"/>
                <RotateTransform x:Name="Rotate" Angle="0"/>
                <TranslateTransform x:Name="Translate" X="0" Y="0"/>
            </TransformGroup>
        </Rectangle.RenderTransform>
    </Rectangle>
</Grid>

We have added a RenderTransform to the rectangle, so we can scale, rotate or translate it later with the Surface Dial.

The next step is add some png files for the Surface Dial icons. Get some Pngs that represent Rotate, Resize, Move in X Axis, Move in Y Axis and Change Colors (I’ve got mine from https://www.materialui.co) and add them to the Assets folder in the project.

In MainPage.xaml.cs, get the Dial controller, initialize the Surface Dial menu and set its RotationChanged event handler:

public enum CurrentTool
{
    Resize,
    Rotate,
    MoveX,
    MoveY,
    Color
}

private CurrentTool _currentTool;
private readonly List<SolidColorBrush> _namedBrushes;
private int _selBrush;

public MainPage()
{
    this.InitializeComponent();
    // Create a reference to the RadialController.
    var controller = RadialController.CreateForCurrentView();

    // Create the icons for the dial menu
    var iconResize = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Resize.png"));
    var iconRotate = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Rotate.png"));
    var iconMoveX= RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/MoveX.png"));
    var iconMoveY = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/MoveY.png"));
    var iconColor = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Color.png"));

    // Create the items for the menu
    var itemResize = RadialControllerMenuItem.CreateFromIcon("Resize", iconResize);
    var itemRotate = RadialControllerMenuItem.CreateFromIcon("Rotate", iconRotate);
    var itemMoveX = RadialControllerMenuItem.CreateFromIcon("MoveX", iconMoveX);
    var itemMoveY = RadialControllerMenuItem.CreateFromIcon("MoveY", iconMoveY);
    var itemColor = RadialControllerMenuItem.CreateFromIcon("Color", iconColor);

    // Add the items to the menu
    controller.Menu.Items.Add(itemResize);
    controller.Menu.Items.Add(itemRotate);
    controller.Menu.Items.Add(itemMoveX);
    controller.Menu.Items.Add(itemMoveY);
    controller.Menu.Items.Add(itemColor);

    // Select the correct tool when the item is selected
    itemResize.Invoked += (s,e) =>_currentTool = CurrentTool.Resize;
    itemRotate.Invoked += (s,e) =>_currentTool = CurrentTool.Rotate;
    itemMoveX.Invoked += (s,e) =>_currentTool = CurrentTool.MoveX;
    itemMoveY.Invoked += (s,e) =>_currentTool = CurrentTool.MoveY;
    itemColor.Invoked += (s,e) =>_currentTool = CurrentTool.Color;

    // Get all named colors and create brushes from them
    _namedBrushes = typeof(Colors).GetRuntimeProperties().Select(c => new SolidColorBrush((Color)c.GetValue(null))).ToList();
    
    controller.RotationChanged += ControllerRotationChanged;
    
    // Leave only the Volume default item - Zoom and Undo won't be used
    RadialControllerConfiguration config = RadialControllerConfiguration.GetForCurrentView();
    config.SetDefaultMenuItems(new[] { RadialControllerSystemMenuItemKind.Volume });

}

The first step is to get the current controller with RadialController.CreateForCurrentView(). Then, create the icons, initialize the items and add them to the menu. For each item, there will be an Invoked event that will be called when the menu item is invoked. At that time, we select the tool we want. The last steps are to set up the RotationChanged event handler and to remove the default menu items we don’t want.

The RotationChanged event handler is

private void ControllerRotationChanged(RadialController sender, RadialControllerRotationChangedEventArgs args)
{
    switch (_currentTool)
    {
        case CurrentTool.Resize:
            Scale.ScaleX += args.RotationDeltaInDegrees / 10;
            Scale.ScaleY += args.RotationDeltaInDegrees / 10;
            break;
        case CurrentTool.Rotate:
            Rotate.Angle += args.RotationDeltaInDegrees;
            break;
        case CurrentTool.MoveX:
            Translate.X += args.RotationDeltaInDegrees;
            break;
        case CurrentTool.MoveY:
            Translate.Y += args.RotationDeltaInDegrees;
            break;
        case CurrentTool.Color:
            _selBrush += (int)(args.RotationDeltaInDegrees / 10);
            if (_selBrush >= _namedBrushes.Count)
                _selBrush = 0;
            if (_selBrush < 0)
                _selBrush = _namedBrushes.Count-1;
            Rectangle.Fill = _namedBrushes[(int)_selBrush];
            break;
        default:
            break;
    }
    
}

Depending on the tool we have, we work with the desired transform. For changing colors, I’ve used an array of brushes, created from the named colors in the system. When the user rotates the dial, I select a new color in the array.

Now, when you run the program, you have something like this:

image

Conclusions

As you can see, we’ve created a completely new interaction for the user. Now, he can change size, angle, position or even color with the dial, without having to select things with the mouse. That’s really a completely new experience and that can be achieved just with a few lines of code. With the Surface Dial you can give to your users a different experience, even if they are not using the Surface Studio.

The full source code for the project is at https://github.com/bsonnino/SurfaceDial.

2016 is coming to an end (What an year here in Brazil!), and we can see retrospectives everywhere. I don’t want to do a “What happened”  or “What did I do”  retrospective. Instead, I want to write about the open source projects I used along the year.

I use open source projects a lot (I don’t like to reinvent the wheel) and they help me a lot. Although many open source projects have a lot of collaborators, most of the time, they are an effort of a single developer (or a very small group of developers) that spend their own spare time to release these gems to the public, without asking anything in return (yes – they are a case of free as “free beer” and free as “freedom”). Nothing more fair than write some lines about them as a way to say “thank you”. So let’s go!

Microsoft open source projects

In the latest years, Microsoft released a lot of open source projects: Roslyn, .NET Core, Asp.NET core, Reactive Extensions, VSCode, TypeScrypt, SignalR and PowerShell are just some of the projects that can be cloned and modified as you will (do you know that Microsoft has the largest number of open source contributors to GitHub: http://www.networkworld.com/article/3120774/open-source-tools/microsoft-s-the-top-open-source-contributor-on-github.html ?).

Although releasing the core projects is something new, I’ve been using Microsoft open source code for a long time – when I started developing, their sample projects were the best way to learn how to use the technology, and this is already the case. If you haven’t checked, go to the Microsoft samples (https://github.com/Microsoft/Windows-universal-samples) to check how to use the newest technology for Windows 10.

So, the first in this retrospective is Microsoft – you can check its open source projects in https://opensource.microsoft.com/ (there were 193 projects there at the time) and in their GitHub: https://github.com/Microsoft (there were 42 pages of repositories there!).

MVVM Light

If you develop for any of the XAML technologies and don’t use the MVVM pattern, shame on you! You should be using this pattern, as it eases the separation between business rules and UI,  facilitates testing and enhances maintainability of your code.

The pattern is very easy to implement and you don’t need any special framework to use it, but using a framework will make things easier and enforce some good rules for your code. There are several MVVM frameworks out there (MVVM Light, Caliburn Micro, Calcium, MVVM Cross, Prism are some that come to my mind, now – maybe I can add to write an article about them – this can be on my resolutions for 2017 Smile), but the one I use the most is MVVM Light Toolkit (http://www.mvvmlight.net/ , source code at http://mvvmlight.codeplex.com/), a nice work from Laurent Bugnion, an old time MVP from Switzerland.

This framework is very easy to use, you must create your ViewModels derived from ViewModelBase and, when you need a command binding, you can use the RelayCommand class. For communication between ViewModels and Views, you can use the Messenger class for sending messages between them. There is a simple IoC container, so you can use dependency injection in your code (another nice feature to remove coupling).

The simplicity and ease of use is definitely a big plus in this framework and the only thing I can say now is “Thanks, Laurent” !

Json.NET

If you are adding Nuget packages to your project, this is the first project that appears in the list. If you need to process Json data (and most developers need it), you must use this project. It’s a high performance Json package and it’s even included in the template for a new Asp.Net project!

It is mainly developed by James Newton-King and you can find it in http://www.newtonsoft.com/json (source code at https://github.com/JamesNK/Newtonsoft.Json). It has a very good Json serializer/deserializer and you can even use Linq to process the Json data. If you want to see it in use, take a look at my article http://blogs.msmvps.com/bsonnino/2016/05/26/minifying-and-formatting-json-data-with-c/ or check my Json Minifier project at https://github.com/bsonnino/ProcessJson.

LightInject

There are many open source IoC containers frameworks out there, and I like very much SimpleInjector, Unity and Ninject, but the one I use most is LightInject (http://www.lightinject.net , source code at https://github.com/seesharper/LightInject), a framework developed by Bernhard Richter. It’s very fast and lightweight and it works on most platforms I use to develop. It works fine with the IoC container available in MVVM Light, and you have several ways to resolve your dependencies.

I really recommend using an IoC container to break your dependencies and make your code more robust. Although it takes some time to get used to this kind of programming, it certainly pays it off when it comes to reusing code and debugging it.

FakeItEasy

Testing, oh, Testing! Testing is like flossing – everybody knows that they should do it, but very few (I would say nobody, but that would not be fair to some poor souls) really do it. When it comes to testing, I really think that one of the worst parts is to mock objects for the tests: create fake classes that do some fake behavior seems to me like some sin I am doing – I should not be doing that or I will go to hell.

FakeItEasy (https://fakeiteasy.github.io/ , source code at https://github.com/FakeItEasy/FakeItEasy) relieves me from that sin. With it, I am able to mock objects and create behaviors that simulate what I want in my tests. The quantity of source code this library saves me is really huge! Oh, and besides all the documentation you have for it, you can also have a free book, published by Syncfusion (one other thing I really recommend – their Succinctly series, now with 103 free ebooks, have fast documentation about a number of subjects: https://www.syncfusion.com/resources/techportal/ebooks): https://www.syncfusion.com/resources/techportal/details/ebooks/fakeiteasy. The only thing I regret in this library is the lack of support for faking under Windows 8 or Windows 10 (In this case, I have to try the LightMock library and see if it fits – another resolution for 2017).

HtmlAgilityPack

By the name, you can think that this pack is for use in an ASP.NET program, but this is not the case. This framework parses HTML files, and you can use it in any .NET application. It’s wonderful when you want to do some web scraping: just load your HTML file into an HtmlDocument and you can easily get the data in it – you can parse the HTML and even change the data in it.

You can get this package at https://htmlagilitypack.codeplex.com/

DotNetZip

If you need to manipulate Zip files in a .NET program, you can use DotNetZip (https://dotnetzip.codeplex.com/). With it, you can open zip files and add new files to them, extract or list the contents of a zip. You can even use Linq to query for entries you want. The files can have password encryption, and it also supports Zip64.

MetroLog

Logging is something that I always need for my programs. When it comes to UWP, there are not many options out there. One of them is Metrolog (https://github.com/onovotny/MetroLog), a very lightweight logging framework developed by Oren Novotny, that works fine with Windows 8/8.1 or UWP.

Although lightweight, it has many features, you can configure the destination of the logs, the logging format and it’s very easy to use: just configure the logging and get a logger with LogManagerFactory.GetDefaultLogger and you can start logging. 

UWPCommunityToolkit

Although this project is under the Microsoft Github (https://github.com/Microsoft/UWPCommunityToolkit, website at https://developer.microsoft.com/en-us/windows/uwp-community-toolkit), it’s not entirely developed by Microsoft. This is a set of components developed by community developers and Microsoft employees, and  features a set of components that are not in the UWP SDK.

You get there a set of controls, like  the Hamburger menu, a Radial gauge or a listview with the “pull to refresh”, many new animations, some code helpers, like new converters or storage helpers, or even access to services like Bing, Facebook or Twitter.

This set of components can improve your UWP apps with minimal code, it’s highly recommended.

SQLite.Net

If you need some kind of structured storage in a UWP application, the best way to do it is using a Sqlite database. In this case, you should use Sqlite.NET (https://github.com/praeclarum/sqlite-net), a small ORM for SQLite databases.

It’s very easy to use and you can have a very good database to store your data in a UWP app, without having to resort to database commands. I really like ORMs, as they abstract the use of a database and use normal C# classes to store data. When you are using a local SQLite database, this ORM is really nice!

Trinet.Core.IO.Ntfs

You won’t be using this library very often, but if you want to handle Alternate Data Streams, like I did in my article here, the Trinet.Core.IO.Ntfs (https://www.codeproject.com/Articles/2670/Accessing-alternative-data-streams-of-files-on-an , source code at https://github.com/hubkey/Trinet.Core.IO.Ntfs) will help you, without the need of adding P/Invokes and working with the Win32 API.

You can check its use in my article and take a look at the ADSs in your system (it surely worth to see what’s hidden in your files).

WPFFolderBrowser

One missing component in WPF is the Folder Browser. Usual answers to this item is to add System.Windows.Forms as a reference to your project and use the Windows Forms component in the program. That’s something I really don’t like: why should I add Windows Forms to my WPF project if I don’t want to use it?

With the Vista Bridge project (now the Windows API Code Pack – https://blogs.msdn.microsoft.com/windowssdk/2009/06/12/windows-api-code-pack-for-microsoft-net-framework/), there were a lot of components that made the bridge between the Windows 32 API released by Vista and WPF.

WPFFolderBrowser (http://wpffolderbrowser.codeplex.com/) takes the work in The Code Pack and creates a Folder Browser for WPF without having to use Windows Forms.

WriteableBitmapEx

Did you ever had the need to create a bitmap from scratch? Or to take a bitmap and change it? WriteableBitmapEx (https://github.com/teichgraf/WriteableBitmapEx/) is a library to manipulate bitmaps. It extends WriteableBitmaps and adds more processing to the bitmap manipulation.

It’s really fast and easy to use, and if you need to do something with a bitmap, you should really use it.

PCLCrypto

Cryptography is something that is needed in your apps from time to time. Windows 8/8.1 and UWP have cryptographic functions that work very well, but, if you need to have portable functions between UWP and full .NET (WPF, Windows Forms or ASP.NET), you should try PCLCrypto (https://github.com/AArnott/PCLCrypto), that uses façade assemblies to the real implementations in every platform.

This way, you use the native cryptographic assemblies for every platform without having to resort to conditional compilation.

Callisto

Callisto (https://timheuer.github.io/callisto/ , source at https://github.com/timheuer/callisto) is a framework developed by Tim Heuer, a Microsoft Program Manager, and was very useful for Windows 8 apps, especially when there was no Flyout control – at that time, the best way to implement it was to use Callisto.

Now, that a Flyout control is in the SDK, there are still a lot to use in Callisto: the rating control, the numeric up/down and the custom dialog are just some I use normally. If you haven’t checked it, it’s worth giving a look at it.

Conclusions

There was a lot covered here. As you can see, I use open source a lot, and I know it’s a big effort to maintain these libraries up-to date, so I’d like to thank all the developers that maintain these libraries and release them as open source, in a way that anybody can analyze them and use them as source code examples, use them to improve their apps without asking anything in return.

And you, do you have any other library that you think it should be listed? Do you want to know more about any of these (maybe I can write an extra article about it)? If you have anything to comment, please place it in the comments section.

Introduction

On my developer work, there are some tools that make my job much easier and I use them on a daily basis and miss them when I go to a computer where I don’t have them. To create code, I think that there’s no better tool than Resharper (see my article about it here). For debugging code, the equivalent is OzCode (http://oz-code.com/). I’ve been an OzCode user since its early betas (it was called BugAid, at those days), and it’s been improving from version to version, and its features are really valuable when debugging an app.

Using OzCode

When you are creating a program, you won’t see anything about OzCode, but as soon as you start debugging your program, OzCode appears and start to shine. One of my favorite features there is what they call Reveal (but I call this “Show me what I want”). Here’s the problem: if I have a list of items and I open it, all I see is something like this:

image

This is not what I want. As you can see, I have a list of 91 customers, and what is shown is the ToString evaluation of each one (“OzCodeTest.Customer”). I’d like to see what’s in each one of these customers and search for the ones I want. You may argue that I can create a ToString override and show what I want, but that is not intuitive, and I may change my mind while debugging (at the beginning I want to see the Id and Name, but in the middle of debugging I want to see the Name and City). And what about to find which one is located in London?

With OzCode, this is solved by simply opening one member and clicking on the star near it: the member is “favorited” and is shown in the list:

image

And what about searching? You just have to type in the search box and all items that match the search are shown:

image

If you want to create some special data, without having to create a new member, you can do so: just click on the magic wand besides the object and select “Add custom Expression”. Then, you can type the expression you want, and put the name of the new “member” after a double slash, like a comment:

[sourcecode language='csharp'  gutter='false']
[obj].City == “London” // IsFromLondon
[/sourcecode]

And it will appear on the list of members, where you can even make it as a favorite:

image

And if I only want to see the customers from London? Just click on the magic wand and select “Edit Filter”. Then, type the filter “[obj].City == “London””. The list of customers is filtered to show only the ones whose city is London:

image

One other thing that you can do here is to compare versions of the two lists: how many times do you need to know what changed between two points in the debugging? It’s very easy to find out. Just stop on the first point and click on the magic wand and select “Compare/Save value”. This will open a window to confirm. Confirm and continue running until the second point. Then click on the magic wand again and select “Compare/Compare with saved value”. A window appears and you can compare the two values. If you want to show only the differences, just click “Show differences only”:

image

Instant logging

The inspector window on steroids is very nice, but there is more help for our debugging. For me, it’s very common to need some logging in the code, to see what’s happening. I have to add a logging library, add code to log data and then analyze all logs in a separate tool. Too much work and sometimes I miss what I was expecting. So I must add a little more logging, repeat and rinse. Very cumbersome. With OzCode, all I have to do is to select the variable I’m interested, click on the yellow note icon that appears on the left and select Trace value of {variable}. That will add a new trace point that will log the value I’m interested to see.

 

image

When you run the program, you can see the number of messages traced in the bottom of the window, near the yellow note.

image

When you stop the program, you can see all messages sent in the Tracepoint viewer window:

image

There you can search for something, export the data to Excel, csv or text, so you can have a file to analyze later. Two nice features there are the Thread Id and the Stack trace. Often it’s difficult to debug multi-threading programs, when you go step by step, it’s difficult to follow the code, as the same code can be reached by different threads. If you click in the arrow next the thread Id, you will see from which threads this code was logged, and filter only some of them:

image

When you filter one thread, you can get only the messages that come from that thread:

image

The other thing that is nice is the stack trace. I always have the question: “How did the code reached here?”. The stack trace answers this:

image

Nice, no?

Swami sees all, the past and the future

If you take a look at the figure below, you will see a glimpse of the past and the future:

image

Just above line 16, you will see that we are working with the “ALFKI” customer. In line 18, you can see that the customer’s city is Berlin. OzCode will show you the following line dimmed – that line won’t be executed and the execution will go to line 20, where there is the arrow. You can also see that the second part of the If won’t be executed (it’s crossed out). You also can see the red X near the line, indicating it is false.

If you click on the glasses near the line, you will see more info:

image

You can have a lot of info about your data and how you reached there.

Exception handling

One thing that bothers me regarding exceptions is when I get an exception buried inside a bunch of Inner Exceptions. I must drill down the exception until I find something that is valuable. OzCode makes this a lot easier: when an exception is thrown, something like this one is shown:

image

You can see the exception that occurred above the line (in the code, above line 17), with four icons:

  • The first one will open the exception box – it is showing that there are two nested exceptions
  • The second one will toggle break in this kind of exception
  • The third one will go to the line where the exception occurred
  • The fourth one will search for help on Google, StackOverflow, Yahoo or Bing

If you click on the first icon or in the icon on the left of the line, it will open the exception box:

image

On the top, you will see a breadcrumb of the exception. You can click on any exceptions there and it will show you all the data for that exception and you can go to where the exception was thrown or where the exception was handled. You can also search for help in this window.

Another exception helper is the exception prediction. If you are stepping through code that will generate an exception, you get something like this:

image

You can click on the icon and skip the line, thus not throwing the exception or, if you are using Visual studio 2015, you can even edit the code and continue:

image

That’s really a great way to make your code more solid proof!

Conclusion

As you can see, OzCode gives you a lot of help for your debugging, I received a free copy due to the fact I’m a Microsoft MVP, but I really enjoy using it. If you want to try it by yourself, you can download a free version at http://oz-code.com. Happy debugging!