.NET community was never known as a strong proponent of the open source software. Traditionally, it gravitates towards the full stack solutions provided by Microsoft or well-known vendors of the commercial components.

With introduction of NuGet, open sourcing .NET, Roslyn and intentional push to Open Source from Microsoft, situation seems changing. However, Open Source is not a way of life for the majority of the .NET developers. To verify that, I did a couple of OSS-related presentations for the local .NET user groups. I was not (unfortunately) surprised to see that besides some really well-known libraries, not many OSS projects are known for the attendees.

To spread the good words about existing .NET Open Source projects, from time to time I am going to introduce one OSS library which I found useful.

Project of the week

For the first week, instead of the library I’d like to introduce two initiatives – First Timers Only and Up For Grabs. Both projects aim to help to find a project for the first contribution and based on the tags assigned by the repository maintainers. The idea is to suggest a simple isolated feature/defect fix to help newcomers to learn the submission process.

If you are a project maintainer, check your repository and mark the appropriate stories with tags. If you never contributed to an open source project – it’s time to try!

Will talk next week.

How to save WriteableBitmap as PNG file, solution for a UserVoice request

API to save WriteableBitmap to PNG is one of the top UserVoice requests for Universal Windows Platform. While such API does not exist in the same way as WriteableBitmap SaveJpeg() extension method, there are two workarounds.

If you are allowed (or willing) to use a third-party library, WriteableBitmapEx provides ability to save bitmap as PNG.

In case you’d like to stay free of external libraries, you can use the following solution, based on the UWP APIs:

WriteableBitmap bitmap = new WriteableBitmap(50, 50);
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(
                                 new Uri("ms-appx:///Assets/MyBitmap.jpg"));

using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
    await bitmap.SetSourceAsync(fileStream);
}

FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("PNG File", new List { ".png" });
StorageFile destFile = await picker.PickSaveFileAsync();

using (IRandomAccessStream stream = await destFile.OpenAsync(FileAccessMode.ReadWrite))
{
    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
    Stream pixelStream = bitmap.PixelBuffer.AsStream();
    byte[] pixels = new byte[pixelStream.Length];
    await pixelStream.ReadAsync(pixels, 0, pixels.Length);

    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                (uint) bitmap.PixelWidth, (uint) bitmap.PixelHeight, 96.0, 96.0, pixels);
    await encoder.FlushAsync();
}

This code creates WritebaleBitmap from a JPG image loaded from the assets. Than it requests a name for the converted file and uses BitmapEncoder to convert bitmap to PNG and save it.

Usage of Clipboard in Universal Windows apps

Clipboard access was one of the features missed during the transition of Windows Phone 8.x development platform from Silverlight to Windows Runtime. As the result, it was one of the most requested feature on the Windows Platform UserVoice site.

Universal Windows Platform bring this feature back for both desktop and phone apps and it is facilitated by Clipboard class.

Adding information to the clipboard require two steps – creation of DataPackage object and assignment of this object as a clipboard content.

var dataPackage = new DataPackage();
dataPackage.SetText("http://lunarfrog.com");
Clipboard.SetContent(dataPackage);

DataPackage supports various data formats, including plain text, HTML, links and images. The same DataPackage class is used to share data between the Universal apps, and in this scenario, it allows setting a data provider, callback function that will be called when data is requested. In case of the clipboard, data provider function can be setup too, but it will be called as soon as the Clipboard.SetContent() function is invoked.

The same Clipboard class is used to retrieve the clipboard content.

DataPackageView dataPackageView = Clipboard.GetContent();
if (dataPackageView.Contains("Text"))
{
    string text = await dataPackageView.GetTextAsync();
}

In this case GetContentMethod returns an instance of DataPackageView class, a read-only DataPackage view. Available types can be evaluated using Contains function (as in the example) or by iterating AvailableFormats property.

That is it – Clipboard API is simple and straightforward to use; it allow to share information not only between the Universal apps but also between them and the Classic desktop apps.

What is new for file system access in Windows 10

With the upcoming release of Windows 10, Windows developers will get an access to Universal Windows Platform (UWP) that extends WinRT platform with new capabilities and UIs. Previously, I described several places on the local drive and external storages simply accessible by modern Windows apps. UWP apps inherit all that capabilities but also can be enhanced by utilizing new folders.

Publisher Cache Folder

From now, apps from the same publisher can share files between each other using ApplicationData.Current.GetPublisherCacheFolder. This folder shall not be used for critical data, as it is not backedup or roamed and at any moment can be cleared by the user. Before use, shared folder shall be registered in the app manifest. Files created in the cache stays there until at least one publisher app still installed.

Files are physically located in %user_folder%\AppData\Local\Publishers\%PublisherID%\%folder%

Local Cache Folder

Another folder, ApplicationData.Current.LocalCacheFolder, allows caching files locally, for particular app, without including them into backup or roaming operations. Files are physically located in %user_folder%\AppData\Local\Publishers\%ID%\LocalCache\

Bonus: Showing folder in File Explorer

New Windows.System.Launcher method - LaunchFolderAsync(IStorageFolder) – allows launching of File Explorer with the content of the provided folder. Overloaded version of LaunchFolderAsync accepts second parameter which let developers to control Explorer’s display options.

Universal Windows Platform includes multiple new and improved UI controls - you can join Canadian Dev Connection blog to learn more. Also, don’t forget to join Windows 10 release celebration at a Microsoft Store near you!

Getting started with F200, Intel RealSense 3D camera

Natural user interface is a hot topic these days: Kinect, Leap, HoloLenses… Recently, Intel joined other players with their RealSense 3D technology. For now, it is represented by F200 camera only (as part of RealSense Developer Kit), but soon should appear in notebooks and all-in-one devices.

F200 consists of several components: color camera, depth camera with IR light source and microphone array. It allows performing face tracking and recognition, hand/object tracking and voice recognition.

RealSense Dev Kit

Setting up environment

F200 camera shall be connected to PC using USB3 port – OS does not detect camera connected via USB2. Other requirements include 64-bit Windows 8.1 and Intel processor with SSE4.2 instruction set support. It is recommended to use 4th generation of Core processors, but at least some of the 2nd and 3rd generation processors in combination with RealSense SDK ver4 are capable to support F200.

RealSense SDK is available at Intel RealSense portal and support development using C++, C#/Unity and Java. SDK includes redistributable modules, documentation and samples.

In most of the cases provided sample just work, but from time to time (at least for me), camera initialization failing. In this case killing of Intel RealSense Depth Camera Manager Service may solve the problem.

Developing for F200

SDK provides access to raw sensor data as well as several algorithms for predefined data processing, for example face tracking or gesture recognition.

Simple RealSense application includes the following steps:

Next paragraphs demonstrate use of SDK to detect two gestures – “thumb up” and “thumb down”.

Access RealSense subsystem

PXCMSession is an entry point that provides access to all SDK’s I/O and algorithm modules. For predefined usages, such as gesture recognition, another interface provides simplified access – PXCMSenseManager


_senseManager = PXCMSenseManager.CreateInstance();

Configure and begin data acquisition

F200 color and depth sensors can acquire images in different resolutions (for example 320x240, 640x480, 1920x1080, etc.) and in the same time, different algorithms are designed to work with different image sizes. When multiple algorithms are required to work together, resolution negotiation can be performed manually or automatically, using EnableXXX functions of PXCMSenseManager


_senseManager.EnableHand();
_senseManager.EnableEmotion();

Enabled modules require configuration. The following example demonstrate configuration of Hand module for detecting “thumb up” and “thumb down” gestures:


var handManager = _senseManager.QueryHand();
_handConfig = handManager.CreateActiveConfiguration();
_handConfig.EnableGesture("thumb_up");
_handConfig.EnableGesture("thumb_down");
_handConfig.EnableAllAlerts();
_handConfig.ApplyChanges();

Next step is to begin acquisition:


_senseManager.Init();

Process acquired data

Depending on application’s architecture, data can be processed in for-loop, using callback function or task/thread. The following example demonstrate usage of Task:


private void ProcessInput(CancellationToken token)
{
   // Wait for available data
   while (!token.IsCancellationRequested &&
         _senseManager.AcquireFrame(true) >= pxcmStatus.PXCM_STATUS_NO_ERROR) 
   {
      try
      {
         var handQuery = _senseManager.QueryHand(); 
         if (handQuery != null)
         {
            var handData = handQuery.CreateOutput(); // Get processing results
            handData.Update();
 
            PXCMHandData.GestureData gestureData;
            if (handData.IsGestureFired("thumb_down", out gestureData))
            {
               Dispatcher.Invoke(ThumbDown);
            }
            else if (handData.IsGestureFired("thumb_up", out gestureData))
            {
               Dispatcher.Invoke(ThumbUp);
            }
            handData.Dispose();
         }
      }
      finally 
      {
         _senseManager.ReleaseFrame();
      }
   }
}

As the result, UI is updated when one of the enabled gestures is detected.

Gestures is detected

Dispose SDK objects

C# SDK is a managed wrapper around native C++ code, so all SDK objects shall be disposed using Dispose() method.


_handConfig.Dispose();
_senseManager.Dispose();

Links

Full source code for this simple application is available at GitHub and the following posts will describe more complicated use cases.

Learn new software development skills with Microsoft Virtual Academy

Holiday season is here and for many of us it means more spare time and opportunity to learn new thing or deeper existing knowledge. My personal plan is to use Microsoft Virtual Academy for refreshing me game development skills.

With over 2000 free courses in 14 languages, MVA is a good option for staying up-to-date with the technologies and frameworks. Over 30 million videos already viewed in 2014 by 2.5 million users and my pre-New Year resolution is to watch

Happy Holidays!

Day One of Connect() event announcements

If you did not have time to follow today’s event, read all related posts and twits, here is a quick recap of the announcements.

.NET go open-source

Links

WPF is alive

Links

The Roadmap for WPF

Visual Studio 2015, Blend and MSDN benefits

Links

Upcoming changes to .NET ecosystem and Connect(); event

A couple of my recent talks and blog posts for Canadian Developer Connection blog describe upcoming features of .NET and new exciting tools such as project Roslyn, C# 6 and .NET Native compiler. These changes represent just a small subset of changes approaching .NET developers.

Last week, among others Microsoft MVPs, I had a chance to sneak peak some of the features that are not announced yet. Hopefully, I don’t need to keep silence for too long, as this information will be released pretty soon, during Connect(); event on November 12 and 13.

As a .NET developer you don’t want to miss this event, so check it out online.

Canadian MVP Consumer Camp

I wanted to let everyone know about a great event that Microsoft is organizing at the Microsoft Store at Square One Shopping Centre in Mississauga – the first Canadian MVP Consumer Camp on Thursday, May 29th from 4pm to 9pm. I will be there with my fellow MVPs answering tech questions, showing off demos and the unique features of Microsoft devices. There will be prize draws, Q&A sessions, snacks and refreshments.

MVPs are recognized exceptional, independent community leaders who share their passion, technical expertise, and real-world knowledge of Microsoft products with others. We speak at events, answer questions online, and have awesome technical blogs! I will be there with quite a few MVPs from across Canada!

Do you have any questions about Surface, Windows, Office, Windows Phone or Xbox? Do you want to learn about how to get the most out of your gadgets? There will be an MVP there who can provide answers! Hope to see you there!

Register here!

Build 2014 - Three announcements, one goal to make your apps faster

While the first day of Build 2014 conference brought information about upcoming releases of Windows and Windows Phone, day two demonstrated that .NET is still relevant in the world of devices, services and apps. Roslyn, an open-sources C#/VB compiler, and .NET Foundation received enough attention in the conference reviews unlike three technical announcements – .NET Native, RyuJIT and SIMD processor instructions support – that are intended to make .NET applications faster.

.NET Native

.NET Native is a set of tools to compile C# application to native code. It allows bypassing traditional step of intermediate language (IL) code translation during run-time and improves application’s performance. According to Microsoft, popular Windows Store apps start up to 60% faster and use 15-20% less memory when compiled with .NET Native.

Additional benefits of .NET Native are code obfuscation and simplified deployment. Compiled application does not include IL code and cannot be decompiled as simply as traditional .NET application. It also include all required parts of the target .NET framework and does not require .NET on user’s system.

Currently .NET Native is in a preview state and available for Windows Store apps only, may become available for desktop applications later.

Link: http://msdn.microsoft.com/en-US/vstudio/dotnetnative

RyuJIT

RyuJIT is a brand new x64 .NET JIT compiler that was created to make .NET application compilation faster. Available as a Community Preview, it already demonstrates better performance, less memory usage and faster startup for .Net applications. CTP version is limiter to x64 architecture and may have some issues, but in the future RyuJIT will become a single JIT compiler for .NET. It is a good time to test it by yourself!

Link: http://blogs.msdn.com/b/dotnet/archive/2013/09/30/ryujit-the-next-generation-jit-compiler.aspx

SIMD

Single instruction, multiple data (SIMD) set of processor instructions allows to apply the same operation to multiple data items simultaneously. For 3D, scientific and other calculation-intensive applications, these instructions can bring significant performance improvements. While SIMD instructions supported in Intel’s processors since Pentium 3, .NET applications was not able to benefit from this feature so far.

With introduction of RyuJIT, Microsoft also announced availability of SIMD support for .NET, implemented using Microsoft.Bcl.Simd NuGet package.

NuGet package: http://www.nuget.org/packages/Microsoft.Bcl.Simd

Code sample: http://code.msdn.microsoft.com/SIMD-Sample-f2c8c35a

Next posts Previous posts