Category Archives: Windows 10

TaskCompletionSource

I’ve had a couple of problems recently, where I’ve had tasks or asynchronous methods and they don’t quote fit into the architecture that I find myself in. I’d come across the TaskCompletionSource before, but hadn’t realised how useful it was. Basically, a TaskCompletionSource allows you to control when a task finishes; and allows you to do so in a synchronous, or asynchronous fashion. What this gives you is precise control over when an awaited task finishes.

UWP

Consider the following code in UWP. Basically, what this does is execute an anonymous function on the UI thread:


await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, async () => 
{
    await MyAyncFunc();
}
System.Diagnostics.Debug.WriteLine("After MyAsyncFunc");

The problem here is that executing an anonymous async function in the above scenario doesn’t work. However, using the TaskCompletionSource, we can bypass that whole conversation:

TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, async () => 
{
    await MyAyncFunc();
    System.Diagnostics.Debug.WriteLine("After MyAsyncFunc");

    tcs.SetResult(true);
});
await tcs.Task;

Now the function will return when the the TaskCompletionSource.SetResult has been called.

Event based

The second scenario where this is useful is where you are trying to use an event based architecture within an async / await scenario. The following example is a little contrived, but it does illustrate the point:

    class Program
    {
        private static Timer _tmr = new Timer();
        private static TaskCompletionSource<bool> _tcs;

        static void Main(string[] args)
        {
            var tmr = StartTimer();

            Console.WriteLine("Before wait...");
            tmr.Wait();

            Console.WriteLine("After wait...");
        }        

        private static async Task StartTimer()
        {            

            _tmr.Interval = 3000;
            _tmr.Elapsed += _tmr_Elapsed;
            _tmr.Start();

            _tcs = new TaskCompletionSource<bool>();
            await _tcs.Task;
        }

        private static void _tmr_Elapsed(object sender, ElapsedEventArgs e)
        {
            _tcs.SetResult(true);
        }
    }

Potentially, a more real world example of this is when you might want to wrap an API in an async/await.

Control over exactly when a task finishes, and the ability to await async void methods

The final scenario where this can be useful is where you either want to await an `async void` method, or where you have a specific part of a method or process that you want to await.

The following code illustrates how to effectively await an async void method:

    class Program
    {        
        private static TaskCompletionSource<bool> _tcs;

        static void Main(string[] args)
        {
            _tcs = new TaskCompletionSource<bool>();
            BackgroundFunction();

            _tcs.Task.Wait();

            Console.WriteLine("Done");
        }        

        private static async void BackgroundFunction()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine($"Processing: {i}");
                await DoStuff();
            }
            _tcs.SetResult(true);
        }

        private static async Task DoStuff()
        {
            await Task.Delay(500);
            
        }

    }

Finally, here is a parallel for loop:

        static void Main(string[] args)
        {
            Parallel.For(1, 3, (i) =>
            {
                BackgroundFunction();
            });

            Console.WriteLine("Done");
        }        

Imagine that BackgroundFunction is performing a long running task where a specific condition needs to return control. There are obviously combinations of functions in the TPL (WaitAll, WhenAll, WhenAny and WhenAll), however, these rely on the whole task, or a set of tasks, completing. Again, the below example is contrived, but it illustrates the granular control over the task that you have.

        static void Main(string[] args)
        {
            _tcs = new TaskCompletionSource<bool>();

            for (int i = 1; i <= 2; i++)
            {
                BackgroundFunction();
            }

            _tcs.Task.Wait();            

            Console.WriteLine("Done");
        }        

        private static async void BackgroundFunction()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine($"Processing: {i}");
                await DoStuff();

                if (i == 7)
                {
                    _tcs.TrySetResult(true);
                    return;                    
                }
            }            
        }

I will re-iterate again, I realise that in the above example, there are better ways to achieve this, and the example is purely for illustration.

Conclusion

Generally speaking, the simplest and most robust code comes from using the task architecture in the way it was designed: that is, use async / await inside a method that returns a Task. I’m not suggesting in this post that the methods I’ve described should replace that; but there are situations where that might not fit.

Aknowledgements

I used the following posts heavily while writing this:

Awaiting the CoreDispatcher
The Nature of TaskCompletionSource
Real life scenarios for using TaskCompletionSource?
Task Parallelism

Deleting Files in a Storage Folder Using UWP

Just a little helper method that I used in a recent project to delete files, given a particular name, and excluding a provided list of files:

        internal static async Task DeleteTempFiles(ObservableCollection<StorageFile> exceptionFiles, StorageFolder folder, string fileNameStartsWith)
        {
            var files = (await folder.GetFilesAsync())
                .Where(p => p.DisplayName.StartsWith(fileNameStartsWith)
                && !exceptionFiles.Any(e => e.DisplayName == p.DisplayName));            

            foreach(var file in files)
            {
                await file.DeleteAsync(StorageDeleteOption.Default);                
            }
        }

You can call it like this:

	await FileHelper.DeleteTempFiles(Files, KnownFolders.PicturesLibrary, "_tmpFile");

It will delete all files in the Pictures folder starting with _tmpFile, and exclude anything in the Files collection.

InkCanvas

Pointlessly Long Introduction (feel free to skip)

Some time ago, in a previous job, I was asked to add spell checking to a WPF textbox. I did some research as to how to do that, and came to the conclusion that the only way was using MS Word automation. I must have spent a good three or four hours writing code that interrogated Word and performed spell checking. It wasn’t until I got to auto correct that one of my searches threw up a property on the text box: “SpellCheck.IsEnabled”.

(At the time of writing) I recently attended a developer conference, and at it, I was shown a control called InkCanvas! Having recently spent a considerable amount of time trying to use a Canvas for drawing, I felt like I’d just found the SpellCheck.IsEnabled property again.

Using the InkCanvas Control

In comparison to the Canvas, the InkCanvas basically works out of the box. If you use the InkToolbar with it, you’ll get some errors, but they aren’t actually errors; for example:

1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2048,5): warning MSB3781: The SDK “InkToolbarControl, Version=0.3.2” depends on the following SDK(s) “Microsoft.VCLibs, version=14.0”, which have not been added to the project or were not found. Please ensure that you add these dependencies to your project or you may experience runtime issues. You can add dependencies to your project through the Reference Manager.

Here’s the XAML that I used to get it working. Don’t be phased by the fact that x:Bind doesn’t seem to resolve.

            <InkCanvas x:Name="drawInkCanvas">                    
            </InkCanvas>
            <inkTools:InkToolbar TargetInkCanvas="{x:Bind drawInkCanvas}" 
                                PenColor="#FFE61021" 
                                VerticalAlignment="Top" HorizontalAlignment="Right"/>

Enabling Input

I found only one thing that caused confusion, and it took a while to solve. Basically, the above XAML doesn’t allow you to actually draw anything; you need this:

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            drawInkCanvas.InkPresenter.InputDeviceTypes =
                Windows.UI.Core.CoreInputDeviceTypes.Mouse |
                Windows.UI.Core.CoreInputDeviceTypes.Pen |
                Windows.UI.Core.CoreInputDeviceTypes.Touch;

        }

Saving the Image

To save what you’ve drawn, you can use something similar to this code:

            if (canvas != null && canvas.InkPresenter.StrokeContainer.GetStrokes().Count > 0)
            {
                if (file != null)
                {
                    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        await canvas.InkPresenter.StrokeContainer.SaveAsync(stream);
                    }
                }
                Clear(canvas);
            }

Generating a Temporary Filename in Windows 10 Universal App

It appears that the functionality to create a temporary file was omitted from Windows 8 / 10

If anyone knows this to not be the case then please add a comment to that effect.

Consequently, I decided to create a little helper method:

        public static async Task<StorageFile> CreateTempFile(
                 StorageFolder folder, string extension)
        {
            string fileName = string.Empty;

            while (true)
            {
                // Get a random filename
                fileName = string.Format("{0}.{1}", 
                     Guid.NewGuid().ToString(), extension);

                // Check if it already exists
                IReadOnlyList<StorageFile> fileList =
                    await folder.GetFilesAsync();

                // If it does then loop until we have a unique one
                if (!fileList.Any(f => f.DisplayName == fileName)) break;
            }

            var newFile = await folder.CreateFileAsync(fileName);
            return newFile;
        }

WPF Drawing Application

The following is a XAML page that allows the user to draw on it. This was written and tested under a Windows 10 desktop application, but should work for WPF. Here’s the XAML:

        <Grid>
            <Border>
                <Canvas PointerPressed="Canvas_PointerPressed" PointerMoved="Canvas_PointerMoved"
                        PointerReleased="Canvas_PointerReleased"
                        Background="Orange" Name="Canvas" />
            </Border>
        </Grid>

The background is a different colour to identify the canvas.

There’s the code to allow drawing:

        
        Path _currentPath;

        private void Canvas_PointerPressed(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
        {            
            _currentPath = new Path
            {
                Data = new PathGeometry
                {
                    Figures = { new PathFigure
                    {
                        StartPoint = e.GetCurrentPoint((UIElement)sender).Position,
                        Segments = { new PolyLineSegment() }
                    }}
                },
                Stroke = new SolidColorBrush(Colors.Black),
                StrokeThickness = 5
            };

            Canvas.Children.Add(_currentPath);
        }

        private void Canvas_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            if (_currentPath == null) return;

            var pls = (PolyLineSegment)((PathGeometry)_currentPath.Data).Figures.Last().Segments.Last();
            pls.Points.Add(e.GetCurrentPoint((UIElement)sender).Position);
            
        }

        private void Canvas_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            _currentPath = null;
        }

As you can see, it doesn’t do anything for my drawing ability:

drawing

It’s all the code behind and, while I typically shy away from this, it seems to fit well for an application such as this (as the drawing relates more to the view than to anything else).

Using a timer to update the UI Thread

In trying to write a Windows 10 Desktop application that refreshes an image on the screen within a timer; I had the following code:

                _timer = new Timer((data) =>
                {
                    if (_imgIdx > Images.Count)
                        _imgIdx = 0;
                    AnimatedImage = Images.ElementAt(_imgIdx);
                    _imgIdx++;
                }, null, 0, 300);

However, when I run this, I get an exception:

The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

My assumption was that the update was occurring on a different thread from the UI (a valid assumption I believe); so I, initially tried to call:

var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;

However, this gave me a null exception.

DispatcherTimer

The answer is the DispatcherTimer class. Here’s how it’s used:

                _dispatcherTimer = new DispatcherTimer();
                _dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 500);
                _dispatcherTimer.Tick += Dt_Tick;
                _dispatcherTimer.Start();

Dt_Tick can now update the UI thread.


        private void Dt_Tick(object sender, object e)
        {

From the naming convention, you might infer that _dispatcherTimer is a class level variable; that’s because it is. The reason is that you can stop the timer elsewhere in the code:

                _dispatcherTimer.Stop();

Load and Display a list of Images in Windows 10

The following is a quick tutorial on how to load a series of images from the machine and display them on screen. This is something that I’m working on for my next Store Application.

The XAML

Let’s start with the screen layout – the GridView control makes this quite an easy task in Windows 10:

            <GridView ItemsSource="{Binding Images}">
                <GridView.ItemTemplate>
                    <DataTemplate>
                        <Image Source="{Binding}" Stretch="Uniform" 
                               Width="100" Height="100"/>
                    </DataTemplate>
                </GridView.ItemTemplate>
            </GridView>

Binding

In this case, I have bound the view to a ViewModel; the relevant part of which looks like this:


        private ObservableCollection<BitmapImage> _images;
        public ObservableCollection<BitmapImage> Images
        {
            get
            {
                if (_images == null)
                {
                    _images = new ObservableCollection<BitmapImage>();
                }
                return _images;
            }
            set
            {
                _images = value;
                NotifyPropertyChanged();
            }
        }

Basically, just an observable collection of BitmapImage.

Load the Image

Here’s where we populate the list:


        private async void Load()
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".gif");

            StorageFile file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                var fileStream = await file.OpenAsync(FileAccessMode.Read);

                BitmapImage bi = new BitmapImage();

                bi.SetSource(fileStream);
                Images.Add(bi);

            }            
        }

Conclusion

I spent a short period of time wondering what had happened to the UniformGrid for Windows 10, but as you can see, the GridView just makes this job much easier.

OCR in Windows 10

Believe it or not, Windows 10 comes with OCR capabilities out of the box. It’s actually very easy to use as well; admittedly, it’s not the most sensitive in the world – but it does basically work. Here’s how you would scan in a bitmap image and recognise characters:

        public async string RecogniseOCR()
        {                        
            var ocrEngine = Windows.Media.Ocr.OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("en"));
            
            var file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\test.bmp");            
            using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                // Create image decoder.
                var decoder = await BitmapDecoder.CreateAsync(stream);

                // Load bitmap.
                var bitmap = await decoder.GetSoftwareBitmapAsync();

                // Extract text from image.
                OcrResult result = await ocrEngine.RecognizeAsync(bitmap);

                // Return recognized text.
                return result.Text;
            }
        }

I scanned this image:

OCRScan

And it found this:

OCRScan2

Like I said – not the most sensitive recognition in the world, but still, it’s there in Windows 10! What’s remarkable is that I only found it by accident – another example of Microsoft marketing missing a huge opportunity.

Targeting Windows 10 Desktop Device Family

Having upgraded to Windows 10 recently, I came across an idea for a new app. Part of what this app is supposed to do it allow scanning of an image. Whilst I found a number of helpful articles of the code to scan an image, they seemed to make an assumption that the reader knew how to target the Desktop Device Family.

Reference the Extension for Desktop Applications

Windows 10 has a number of specific extensions for specific targeted devices. The first step is to reference in the correct one:

Extensions

Change the target in you Package.appxmanifest file

If you have a look in the UI menu for this, you won’t find any way to change the targeted device family (at least I didn’t). So, you need to change the XML:

  <Dependencies>
<!--    <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
--> 
	  <TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0"/>
  </Dependencies>

Windows 10 – The Return of the Overrated Start Menu

Yesterday, for the first time, I saw Windows 10. I set it up in a VM inside Win 8. The following post in a combination of conjecture, opinions, and under researched hearsay.

First, let’s think about what I just said: I’m running a later version of Windows inside an earlier one. And it works.

9

Don’t mention 9! I mentioned it once, but I think I got away with it.

Start menu

The start menu never went anywhere for Win 8. You just press the Windows key and you’re in it (although it was more of a screen than a menu). Anyway, MS finally bowed to pressure, and it’s back:

start1

Looks good eh? Actually, after restarting it seemed to gather its thoughts:

start2

Anyway, as I understand the intention, if I were running this on a tablet, I’d be able to see the Win 8 start screen when I pressed the Windows Key. I can’t test that on a VM and, if I could, I’d be surprised if it worked properly for the TP.

Multiple Desktops

This is a neat feature: the ability to maintain more than one desktop. The way this appears to work is that you can open apps into any desktop, and then just switch between desktop to access them, or access them from the taskbar, and Windows will select the desktop they are on.

desktop

You appear to be able to maintain as many desktops as you like.

Search

There is a large magnifying glass on the taskbar, which brings up a huge, unwieldy, blank box with a small text search. Maybe this will be back on the charms bar for tablets, but the idea is that it will find stuff on your machine. It failed:

search

I don’t understand why this was separated from the start menu. Searching for, and running programs are basically the same thing. If I want to run word, I want to type “Word”; if I want to open a word document on my desktop, I want to type: “My word doc” and have it find it. Results seemed to be sporadic, sometimes it found what I expected, but generally it didn’t.

What happened to the charms bar?

It now seems to be a sub menu of each store window:

charmsbar

As I said earlier, I expect it will behave differently for the tablet and phone.

Universal Apps

These have been around for a while. They basically allow sharing of code between Windows store and Windows phone apps. As I understand it, these will now be effectively mandatory – you will have to produce a phone & store version, in the same way as you had to provide a snapped and filled version of your app.

Conclusion

The split desktop is nice, and the idea of having “One Windows” is a nice one. In fact, it’s effectively what I understood to be the driving force behind 8. It looks like it’s going to be a good OS, but I can’t see any killer features.

What I mean by that is this: imagine that you want to upgrade to Windows 10, and you put the idea to your boss. The first question they should ask is: “Why?”.

For Windows 8, the answer was simple: Hyper-V. An astoundingly useful and undersold feature.

Windows 10 doesn’t have that, and it needs it, because a lot of people are sticking on 7 and need a reason to upgrade – having the start menu back is not that reason.