Archivi tag: windows

My developer/it pro toolkit for Windows (2021)

Every IT professional / programmer / developer has a toolkit to do be more productive. It’s the based on years of experience, tips from colleagues, friends, and experts.
This is my list of tools that I use more often. I don’t use every tool every day.

This is my first list and it will be interesting to see how this will evolve year over year.

Misc

Windows Terminal / If you are a terminal user this is for you. It’s a modern implementation of a terminal for Windows. Its main features include multiple tabs, panes, Unicode and UTF-8 character support, a GPU accelerated text rendering engine, and the ability to create your own themes and customize text, colors, backgrounds, and shortcuts.
Chocolatey / The Package Manager for Windows. Forget browsing to the website of your favorite tool, click download, open the setup, next-next-next-finish. Just write choco install mytool -y and you’re done!
Windows Subsystem for Linux / A complete GNU/Linux environment inside Windows. I use this to learn or explore Linux commands. It’s fast and without the overhead of a traditional virtual machine.
Notepad2 / A replacement for the standard notepad.exe. Syntax highlight support, super light and fast!
Visual Studio Code / Free. Built on open source. Runs everywhere. Free. Built on open source. Runs everywhere. A swiss-army knife for any code related activity.
Nightingale / A native Windows application REST client. An alternative to Postman. A lovely UI and smooth user experience.
PowerToys / A collection of tools to improve your Windows experience.
ZoomIt / It’s perfect to zoom on the screen and draw arrows, lines, and rectangles while doing screen sharing sessions.
Fork / a great UI for git.
Total Commander / A replacement of Windows File Explorer. Good old, feature rich and you can use it with just keyboard shortcuts. Blazing fast to rename, move or copy batch of files.
Markdown Monster / An IDE for your markdown files!
Fiddler / THE web debugger.
BeyondCompare / Compare directories, files, exe… If you have to compare something this is the tool you’re looking for.
SnagIt / screen capture on steroids
Procmon / Do you want to know every single detail of what happens in your registry, file system, and processes/thread activities? This is the tool that you’ll open to diagnose issues or behaviors happening on Windows.

Visual Studio Code Extensions

GitLens / Git superpowers in your VS Code.
Docker for VS Code / You can get IntelliSense when editing your Dockerfile and docker-compose.yml files, with completions and syntax help for common commands.
PowerShell / Bye bye PowerShell ISE.
RESTClient / Send HTTP request directly and view the response directly from VS Code. It can also generate code snippets to make HTTP call in the most common languages.

How to fix Windows 10 Broken Search Bar

If your Windows 10 Search Bar is broken you’re encountering an issue that is spreading to many Windows 10 users at the time of this writing.

This is NOT an official statement (I’m not responsible for any side effects caused by this) about how to fix but running this script inside a PowerShell session with administrator privileges and restarting the machine can solve your issue (it worked on my machine).

Get-AppXPackage -Name Microsoft.Windows.Cortana | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppXManifest.xml"}   

Clean your Windows 10 like a pro

The space on your hard drive is running low and you don’t know what to do. What to clean? Is there an app that can clean my PC?

The vast majority of Windows users rely on third party apps like CCleaner to do this job. Make yourself a favor: don’t do this. Windows has a built-in tool that can safely clean-up your PC and it’s called Disk Cleanup 4.png.

With the latest Windows 10 April 2018 Update (1803) the Disk Cleanup has been improved and you can now access it from the Settings.

1. Check you’re currently running Windows 10 1803

Open Run by right-clicking the Start Menu or with the keyboard shortcut Win+R. Then type winver and press Enter.

 

1

2. Remove Files

Open Settings by writing settings from the Start menu or press Win+X and then Settings. Choose the Storage section on the left and then click on Free up space now.

2

This feature will show you simple but well explained user interface where you can understand what you’re going to purge when you’ll press Remove files.

3

Happy cleaning!

WPF Prism concepts: regions

If you are a developer in the Microsoft environment and if you’re developing desktop apps, it’s likely that you’ve read something about Prism.  If you don’t then this is what Prism is about:

Prism is a framework for building loosely coupled, maintainable, and testable XAML applications in WPF, Windows 10 UWP, and Xamarin Forms. (from the Prism’s Official GitHub description)

The Prism documentation is very detailed but with this blog post we are more practical and examples-driven. If you want to dive into the details of Prism the official documentation is the best place.

Definition

A region is a placeholder in the shell of a Prism application for content that will be loaded at runtime. Regions are defined as UI elements like ContentControl, ItemsControl, TabControl or a custom control.

The content of a region is a view. We can access regions in a decoupled way by their name and they support dynamically adding or removing views.

Example with view discovery

So now it’s coding time!

The first thing we need is to setup our app to be a Prism-app. At this point we have a clean Prism-App.

Then, we create a region in our MainWindow. This is the XAML code.

<Window x:Class="XXXXX.Views.MainWindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"          xmlns:prism="http://prismlibrary.com/"                Title="MainWindow" Height="300" Width="300">
    <Grid>
        <ContentControl prism:RegionManager.RegionName="RegionA" />
    </Grid>
</Window>

We can see that the regions are defined as XAML attached properties. In the code above our region is called RegionA.

Now we have our region defined but no content to load into. We create a new user control in the Views subfolder and name it ViewA.xaml.

Immagine

In this class in the XAML part we write:

<UserControl x:Class="XXXXX.Views.ViewA"              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"              >
    <Grid>
        <TextBlock Text="View A" FontSize="38" />
    </Grid>
</UserControl>

That’s good! We have our region and a view. Now it’s time to tell Prism that RegionA is the target where to load the ViewA view. In the code-behind of the MainWindows.xaml we write:

using Prism.Regions;
using System;
using System.Windows;

namespace XXXXX.Views
{

    public partial class MainWindow : Window
    {
        public MainWindow(IRegionManager regionManager)
        {
            InitializeComponent();

            if (regionManager == null)
            {
                throw new ArgumentNullException(nameof(regionManager));
            }
            regionManager.RegisterViewWithRegion("RegionA", typeof(ViewA));
        }
    }
}

With the above code for the constructor we are registering that RegionA has to be populated with an instance of ViewA view. The region manager is passed as a parameter by the DI container (in our case Unity). This technique is called View Discovery. The result is:

Screenshot_1

Example with View Injection

Now we explore the View Injection technique that enables us to load and unload the content of a region dynamically at runtime.

We create a new view, ViewB, like we did for ViewA under the Views folder.

<UserControl x:Class="XXXXX.Views.ViewB"              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"            >
    <Grid>
        <TextBlock Text="View B" FontSize="38" Foreground="#FF0023FF" />
    </Grid>
</UserControl>

We edit the MainWindow to add another region and a button to fire our code:

<Window x:Class="XXXXX.Views.MainWindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"          xmlns:prism="http://prismlibrary.com/"                Title="MainWindow" Height="300" Width="300">
    <StackPanel>
        <ContentControl prism:RegionManager.RegionName="RegionA" />
  <Button Click="Button_Click" >Load region B</Button>
<Button Click="Button_Clear_Click" >Clear region B</Button>
<ContentControl prism:RegionManager.RegionName="RegionB" />
    </StackPanel>
</Window>

And the code behind

public partial class MainWindow : Window
    {

        private readonly IRegionManager _regionManager;
        private readonly IUnityContainer _container;

        public MainWindow(IRegionManager regionManager, IUnityContainer container)
        {
            InitializeComponent();
            //view discovery
            if (regionManager == null)
            {
                throw new ArgumentNullException(nameof(regionManager));
            }

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

            _regionManager = regionManager;
            _container = container;

            _regionManager.RegisterViewWithRegion(RegionNames.RegionA, typeof(ViewA));

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //We get from the container an instance of ViewB.
            var view = _container.Resolve<ViewB>();

            //We get from the region manager our target region.
            IRegion region = _regionManager.Regions["RegionB"];

            //We inject the view into the region.
            region.Add(view);
        }

  private void Button_Clear_Click(object sender, RoutedEventArgs e)
        {
            //We get from the region manager our target region.
            IRegion region = _regionManager.Regions["RegionB"];

            //Clears the content.
            region.RemoveAll();
        }

    }

What we’re doing here is to get our target region by using the RegionManager class.

The RegionManager class is responsible for creating and maintaining a collection of regions for the host controls. The RegionManager uses a control-specific adapter that associates a new region with the host control. The following illustration shows the relationship between the region, control, and adapter set up by the RegionManager. (Prism official docs)

When we have a reference of the region (RegionB in this case) we can add or remove content with the Add or the Remove/RemoveAll methods.

Screenshot_2

TL;DR

In this blog post we explored the concept of Region. Regions are useful conteiners to create our UI in a structured and dynamic way. We loaded content with the discovery and the injection technique.

In the next blog post we’ll study other Prism’s concepts.

Happy coding!

Reference

Prism official documentation (http://prismlibrary.readthedocs.io/en/latest/)
Prism Github page (https://github.com/PrismLibrary)

Prism UWP for beginners: navigation

In this post we’ll talk about the navigation with Prism in UWP. With navigation I mean the technique to go from one page to another of your app. The operation in UWP/XAML is tipically performed with the Frame class that’s available only in the code-behind of a Page because it inherits from Frame. This way we do not respect the MVVM pattern. Prism comes in our help providing a wrapper to the Frame class accessible from the ViewModel: it’s the NavigationService. This isn’t a very new name to us because we found it in the bootstrapper.

protected override Task OnInitializeAsync(IActivatedEventArgs args)
{
//...
Container.RegisterInstance(NavigationService);
//...
}

We saw it at the end of the bootstrap procedure in the OnLaunchApplicationAsync method, too.

protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
{
NavigationService.Navigate(PageNames.Main.ToString(), null);
return Task.FromResult(true); //This is a little trick because this method returns a Task.
}

To try the navigation system we create a SettingsPage in the View folder and then we’ll navigate to that page with a button in the MainPage.

Immagine

To go to there we need a command in the MainPageViewModel class and bind it in the MainPage view.

public class MainPageViewModel : ViewModelBase
{
public DelegateCommand GoToSettings { get; private set; }

//...
}

In the constructor we initialize the GoToSettings property.

public MainPageViewModel(ITwitterService twitterService, IWeatherService weatherService, INavigationService navigationService)
{

_navigationService = navigationService;

GoToSettings = new DelegateCommand(() =&gt;
{
_navigationService.Navigate("Settings", null);
});
}

In the constructor we added a parameter: the INavigationService reference. This new dependency will be handled by Unity container when resolving an instance of MainPageViewModel. The GoToSettingsCommand is composed by a single line of code where we call the Navigate method with the first argument that is the name of the page where we want to go and the second argument is to add additional information: since we have no additional data we write null.

In this example the Settings page allows us to change the backgorund image of the main page. We notice that in the upper left corner of the application a back. This is handeld by the UWP framwork when detects a navigation.

This back button can be different based on the device where the app is running: phone, tablet or pc. For example in a tablet with tablet mode enabled it will appear on the navigation bar at the botton of the device. In the MSDN we can find al the details.

Screenshot_2.png

When we click the back button we go back to the main page.

When navigating in our view-model we can use two methods to detect when we land into a page or when we leave a page. OnNavigatedTo is callaed when navigation in performed to a page. OnNavigatingFrom is called when navigating away from the page.

   public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary viewModelState)
        {
            base.OnNavigatedTo(e, viewModelState);

//Loading state custom logic.
        }

        public override void OnNavigatingFrom(NavigatingFromEventArgs e, Dictionary viewModelState, bool suspending)
        {
            base.OnNavigatingFrom(e, viewModelState, suspending);
//Save state logic.
        }

TL;DR

In this post we explored the basic concept about navigating with Prism in UWP App with the Navigation Service and the events that Prism offers to detect the transition from one page to another.

If you want to learn more you can refer to the Prism official website and MSDN. Happy coding!

Prism UWP posts

Prism UWP for beginners: setup

I want to learn Prism because it may be helpful in some future projects. To better understand how it works I need a target. I’d like to create a simple UWP app that displays my Twitter timeline and the local weather based on the GPS. Prism will help me to adopt the MVVM architeture and IoC/DI concepts. The MVVM and IoC/DI topics are out of the scope of this post.

Setup

I started a new UWP project with Visual Studio 2017 and then imported the Prism.Windows and Prims.Unity NuGet packages. Prism.Windows is the “core” library for the UWP techology and Prism.Unity is the IoC/DI container.

Screenshot_1.png

Conversion to Prism

I converted the Universal app to a Prism Universal app by configuring the bootstrapper. The bootstrapper is a required procedure by the Prism framework to properly initialize all the infrastructure. In vanilla UWP, the bootstrapper is the App class. I edited the App class so that it doesn’t inherit from the native Application class but from a Prism class called PrismUnityApplication.

This is the full App.xaml file.

<prismUnity:PrismUnityApplication x:Class="IC6.Buongiorno.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prismUnity="using:Prism.Unity.Windows"
RequestedTheme="Light">

</prismUnity:PrismUnityApplication>

 

This is the full App.xaml.cs file.

using System.Threading.Tasks;
using Microsoft.Practices.Unity;
using Prism.Unity.Windows;
using Prism.Windows.AppModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Resources;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using IC6.Buongiorno.Services.Twitter;
using IC6.Buongiorno.Services.Weather;

namespace IC6.Buongiorno
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App : PrismUnityApplication
{

public App()
{
InitializeComponent();
}

protected override UIElement CreateShell(Frame rootFrame)
{
var shell = Container.Resolve<Shell>();
shell.SetContentFrame(rootFrame);
return shell;
}

/// <summary>
/// Logic of app initialization.
/// This is the best place to register the services in Unity container.
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
protected override Task OnInitializeAsync(IActivatedEventArgs args)
{
System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>> OnInitializeAsync called.");

Container.RegisterInstance<ITwitterService>(new TwitterService());

Container.RegisterInstance<IWeatherService>(new WeatherService());

Container.RegisterInstance<IResourceLoader>(new ResourceLoaderAdapter(new ResourceLoader()));

Container.RegisterInstance(SessionStateService);

Container.RegisterInstance(NavigationService);

return base.OnInitializeAsync(args);
}

protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
{
NavigationService.Navigate(PageNames.Main.ToString(), null);

return Task.FromResult(true); //This is a little trick because this method returns a Task.
}
}
}

 

I created a Paged called Shell. The Prism definition of shell is:

The main window of an application where the primary UI content is contained.

Shell is called in the CreateShell method triggered by the Unity framework to create the main window of the application.

The OnInitializeAsync method is the place to initialize the Unity container. Here I registered my services. With registering I mean telling Unity that, for example, every time I need an ITwitterService it has to give me an instance of TwitterService. I also register the NavigationService and SessionStateService that I’ll explain in other posts.

I created the standard MVVM folders because Prism is convention based for some of its features.

image

I deleted the default MainPage.xaml file and created a new one in the Views directory as shown in the image above.

Inside OnLaunchApplicationAsync I called the NavigationService.Navigate method to navigate to the MainPage which accepts as first parameter the name of the page (the name of the View without the Page suffix): by passing as parameter the value “Main” Prism searches, in the Views folder, a page called MainPage.xaml. The second parameter is null because I didn’t have additional parameters to pass. The last statement is a little trick because this method returns a Task and I created a fake one with a constant true value.

TL;DR

I made my first steps with Prism in a UWP application: I created the shell and setup the bootstrapper.

Prism UWP posts

 

 

How to get started with Prism in 3 easy steps

In this post we explore the basics of Prism to create a mantainable and scalable WPF application.

IC368873.png

How to get started

  1. Download the nuget Prims.Xyz package for your Platform: in this example for WPF (Prims.WPF and Prism.Unity) with Visual Studio;
  2. Create a bootstrapper;
  3. Edit App.xaml and App.xaml.cs files;
  4. (Bonus point) Reorganize our project.

With this procedure we are setting the foundation for our Prism-enabled app.

1. Download

With the Manage Nuget tool in Visual Studio download the following packages: Prims.WPF and Prims.Unity. Visual Studio will take care of the process and at the end we’ll have these packages installed:

s1.png

2. Create a Bootstrapper

In our project we add a new Class. The name is not important but it has to derive from UnityBootstrapper.

using Microsoft.Practices.Unity;
using Prism.Unity;
using System.Windows;

namespace IC6.Prism
{
 class Bootstrapper : UnityBootstrapper
 {
   protected override DependencyObject CreateShell()
   {
    return Container.Resolve<MainWindow>();
   }

 protected override void InitializeShell()
   {
    Application.Current.MainWindow.Show();
   }
 }
}

3. Edit App.xaml and App.xaml.cs files.

In our project we edit the App.xaml to remove the StartupUri attribute since now that part of the initialization is handled by Prism with Unity.

<Application x:Class="IC6.Prism.App"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:local="clr-namespace:IC6.Prism">
 </Application.Resources>

 </Application.Resources>
</Application>

In the code behind file (App.xaml.cs) we override the OnStartup method to implement our custom startup logic that leverages the Bootstrapper.

using System.Windows;

namespace IC6.Prism
{
 public partial class App : Application
 {
   protected override void OnStartup(StartupEventArgs e)
   {
    base.OnStartup(e);

    var bootstrapper = new Bootstrapper();
    bootstrapper.Run();
   }
 }
}

4. Bonus point

Since we’re using Prism to get the most from MVVM pattern (and other features) we are going also to better organize our project. We delete the MainWindow.xaml and its code behind files from the solution, then we create a new folder called Views and finally create a new Window called MainWindow inside. This is the result.

s2.png

Back to school time

We’ve started this post with just code and not so much theory about what we are doing.

Why do we need a bootstrapper? A Prism application requires registration and configuration during the application startup process. This is known as bootstrapping the application. The Prism bootstrapping process includes creating and configuring a module catalog, creating a dependency injection container such as Unity, configuring default region adapter for UI composition, creating and initializing the shell view, and initializing modules.

In a traditional Windows Presentation Foundation (WPF) application, a startup Uniform Resource Identifier (URI) is specified in the App.xaml file that launches the main window.
In an application created with the Prism Library, it is the bootstrapper’s responsibility to create the shell or the main window. This is because the shell relies on services, such as the Region Manager, that need to be registered before the shell can be displayed.

Dependency Injection

Applications built with the Prism Library rely on dependency injection provided by a container. The library provides assemblies that work with Unity and it allows us to use other dependency injection containers. Part of the bootstrapping process is to configure. this container and register types with the container.

TL;DR

In this post we introduced Prims and made baby steps. With this approach we’re setting the architecure of our app to be scalable and mantainable. In the next posts we’ll go forward and learn other Prism foundamentals.

Readings

Dependency Injection: https://en.wikipedia.org/wiki/Dependency_injection

Prism GitHub homepage: https://github.com/PrismLibrary/Prism

Integrate Azure Cognitive Services in UWP app

Azure Cognitive Services are an amazing tool than enables developers to augment users’ experience using the power of machine-based intelligence. The API set is powerful and provides lots of features that are organized in categories: vision, speech, language, knowledge, search, and labs.image

In this post we learn how to leverage the Emotion API to get our user mood and set a background of our app accordingly.

Get API key

To get starded we need to get an API key to be able to access the Cognitive Services. So, let’s go to this address (https://azure.microsoft.com/en-us/try/cognitive-services/?api=emotion-api) and click on the Create button next to Emotion API.

image

After that the website will ask to accept the trial term of services and we accept:

image

After the login we get access to our keys:

image

Now we’re done with Azure web site and we can start coding.

Coding

We fire up Visual Studio and create a new UWP project.

image

To achieve our goal (get our user mood and change the background) where’re going to develop a simple UI where the user press a button, we take a picture of him/her, send that picture to Azure, and based on the result load a background image.

Before we write code we need to setup our application capabilities in the manifest and download some NuGet packages. We double click on the Package.appxmanifest file in Solution Explorer and Visual Studio, go to the Capabilities tab and check the webcam and microphone boxes.

image

Then we download the Microsoft.ProjectOxford.Emotion NuGet package that contains some helper classes to deal with the Azure Cognitive Services. In the Solution Explorer we right click and select Manage NuGet Packages. In the search box we type “Microsoft.ProjectOxford.Emotion”. We download the package.

image

With the following XAML we draw a simple UI with a Button to trigger the camera.

<Page x:Class="IC6.EmotionAPI.MainPage"       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"       xmlns:local="using:IC6.EmotionAPI"       xmlns:d="http://schemas.microsoft.com/expression/blend/2008"       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"       mc:Ignorable="d">

    <Grid Name="myGrid">
        <StackPanel>
            <Button Click="Button_Click">Take a camera picture</Button>

        </StackPanel>
    </Grid>
</Page>

At the handler of the click event we write


  private async void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                using (var stream = new InMemoryRandomAccessStream())
                {
                    await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                    stream.Seek(0);

                    var emotion = await MakeRequest(stream.AsStream());

                    if (emotion == null)
                    {
                        await new MessageDialog("Emotions non detected.").ShowAsync();

                        return;
                    }

                    var imgBrush = new ImageBrush();

                    if (emotion.Scores.Sadness &amp;amp;amp;gt; emotion.Scores.a)
                    {
                        imgBrush.ImageSource = new BitmapImage(new Uri(@"ms-appx://IC6.EmotionAPI/Assets/sad.jpg"));
                    }
                    else
                    {
                        imgBrush.ImageSource = new BitmapImage(new Uri(@"ms-appx://IC6.EmotionAPI/Assets/happy.jpg"));
                    }

                    myGrid.Background = imgBrush;

                }

            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message).ShowAsync();
            }
        }

In this method we’re leverging the power of the MediaCapture class that provides functionality for capturing photos, audio, and videos from a capture device, such as a webcam. The InitializeAsync method, which initializes the MediaCapture object, must be called before we can start previewing or capturing from the device.

In our exercise we’re going to put the MediaCapture initialization in the OnNavigatedTo method:

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

            if (_mediaCapture == null)
            {
                await InitializeCameraAsync();
            }

        }

InitializeAsync is a helper method we write to search for a camera and try to initialize it if we find one.

  private async Task InitializeCameraAsync()
        {

            // Attempt to get the front camera if one is available, but use any camera device if not
            var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Front);

            if (cameraDevice == null)
            {
                Debug.WriteLine("No camera device found!");
                return;
            }

            // Create MediaCapture and its settings
            _mediaCapture = new MediaCapture();

            var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };

            // Initialize MediaCapture
            try
            {
                await _mediaCapture.InitializeAsync(settings);
            }
            catch (UnauthorizedAccessException)
            {
                Debug.WriteLine("The app was denied access to the camera");
            }
        }

        ///
<summary>
        /// Attempts to find and return a device mounted on the panel specified, and on failure to find one it will return the first device listed
        /// </summary>

        /// <param name="desiredPanel">The desired panel on which the returned device should be mounted, if available</param>
        /// <returns></returns>
        private static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
        {
            // Get available devices for capturing pictures
            var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            // Get the desired camera by panel
            DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);

            // If there is no device mounted on the desired panel, return the first device found
            return desiredDevice ?? allVideoDevices.FirstOrDefault();
        }

Let’s focus on the MakeRequest method we called in the click event handler because here we make use of the Project Oxford library to detect emotions.

private async Task<Emotion> MakeRequest(Stream stream)
        {
            var apiClient = new Microsoft.ProjectOxford.Emotion.EmotionServiceClient("f1b67ad2720944018881b6f8761dff9a");
            var results = await apiClient.RecognizeAsync(stream);

            if (results == null) return null;

            return results.FirstOrDefault();
        }

We need to create an instance of the Microsoft.ProjectOxford.Emotion.EmotionServiceClient class. In the constructor we pass the key obtained from the Azure portal at the beginning of this post. Then, we call the RecognizeAsync method. Here we’re using the overload with the Stream parameter because we have our picture saved in memory. There is also an overload that accepts a URL string. With this call the Azure platform is now doing its magic and soon it’ll deliver the result. The RecognizeAsync returns an array of Emotion. An Emotion is made by a Rectagle reference and a Score reference. The Rectagle instance tells us the coorindates of the face detected while the Score instance tells us the confidence of every mood that Azure can detect: sadness, neutral, happiness, surprise, fear, and anger. Based on this data we can make “ifs” to do some funny things like changing the background of our main window.

TL; DR

In this post we learned how to detect the current mood of our user. We achieved that by using our front camera to take a picture and then make a call to Azure Emotion API to guess if our user is happy or not. We had to set the app manifest to inform the OS that we need to use the Webcam to ask the user for the privacy settings.

If you want to learn more about the MediaCapture class, visit MSDN (https://docs.microsoft.com/en-us/uwp/api/windows.media.capture.mediacapture) and the Azure Cognitive Services (https://azure.microsoft.com/en-us/services/cognitive-services/) website. The source code of the app developed in this post is available on my GitHub (https://github.com/phenixita/IC6.EmotionAPI).

Social

If you have questions you can use the comment section below or you can find me on Twitter! If you liked this post, share!

Servizio WCF ospitato nei Windows Services

Mi sono sempre chiesto la differenza tra ospitare un servizio WCF in IIS e nei Windows Services (services.msc, per capirsi). Così mi sono documentato e ho trovato quanto segue nell’MSDN.

image

Non contento ho fatto una prova completa dalla creazione del progetto all’installazione e interrogazione del servizio per capirci di più. Metto a disposizione il download della soluzione di Visual Studio 2015 che implementa questo esperimento.

Questi sono stati i passaggi.

  1. Nuovo progetto di tipo WCF Service Library
    1
  2. Ho rinominato con F2 i nomi dei file del progetto standard e del servizio che volevo implementare. Ho chiamato l’interfaccia ICalculatorService e la classe che lo implementa CalculatorService. Il servizio espone una funzionalità di somma di numeri con virgola.2
  3. Implementazione molto semplice nella classe CalculatorService.
    3
  4. Ho eseguito il progetto (F5) e mi sono imbattuto subito in un problema: AddressAccessDeniedException. Cercando su MSDN e StackOverflow ho capito che è un problema di privilegi. Per registrare un endpoint di ascolto bisogna avere permessi di amministratore.
    4
  5. Riavviato Visual Studio come amministratore e rieseguito il processo tutto parte senza problemi nell’host dei servizi.5
  6. E con il WCF test client le somme funzionano.6
  7. Viene il momento di creare un nuovo progetto per creare un Servizio Windows che ospiti il servizio WCF. Aggiungo quindi il progetto alla soluzione.7
  8. Un po’ di rinomina sui nomi del file e del servizio che chiamo WindowsCalculatorService rendono più chiaro il lavoro.8
  9. Aggiungo al progetto un installer per facilitare il lavoro di installazione del servizio. Clic destro, Add Installer.9
  10. Il bravo Visual Studio inserisce l’installer correttamente e vado a valorizzare con dei nomi sensati alcune proprietà tipo il nome del servizio con cui poi lo stesso comparirà nell’elenco dei servizi di Windows. C’è anche la possibilità di dare una descrizione (che io ho omesso).10
  11. Sostituisco il metodo Main() di Program.cs del progetto WindowsCalculatorService con queste righe di codice per permettere l’installazione semplicemente avviando l’exe e digitando una lettera: I installa, U disinstalla. 11
  12. Per fare funzionare questo trucchetto bisogna convertire il progetto in progetto Console andando nelle Proprietà del progetto stesso. 12
  13. Per far sì che il servizio WCF sia correttamente configurato quando ospitato dal servizio Windows bisogna riportare la configurazione dal file App.config del progetto WCF a quello del servizio di Windows. Attenzione! Riportare solo la sezione <system.serviceModel>! 13
  14. Per permettere l’installazione del servizio di Windows è necessario avere privilegi di amministratore quindi aggiungendo un file manifest alla soluzione WindowsCalculatorService (add item –> manifest file) vado a specificare level=requireAdministrator nell’apposita sezione <security> del file.14
  15. Modifico il WindowsCalculatorService.cs affinché quando viene avviato esegua il necessario per ospitare il nostro servizio WCF CalculatorService.
    21
  16. Compilo e avvio WindowsCalculatorService.exe e il sistema operativo propone l’UAC come giusto che sia.
    15
  17. Ottenuta la conferma il programma Console ci chiede se vogliamo installare o disinstallare. Ovviamente scrivo I ed installo.16
  18. L’installer del servizio vuole sapere con che utenza deve girare il nostro servizio. Inserisco le mie credenziali.
    17
  19. Ecco che il servizio compare correttamente nell’elenco dei servizi di Windows e lo avvio.18
  20. Avviando il WCF Test Client inserisco l’endpoint specificato nel file app.config.19
  21. Il servizio è operativo e funzionante!20

Voi avete esperienza con WCF? Io l’ho sempre usato per piccole cose e sempre in IIS ma dopo questa prova con i servizi di Windows credo che li userò sempre così. Sono più adatti ai miei scopi e, soprattutto, non richiede l’installazione di IIS.

Aggiornare un servizio di Windows via Powershell

Avete implementato un servizio di Windows e, come è consuetudine, avete scoperto un bug e lo avete risolto.

Ora bisogna aggiornare il servizio.

Siccome il mio codice ha spesso dei bug mi è capitato di dover ripetere più volte questo processo:

  • Compila la dll con la correzione;
  • Spegni il servizio nel server;
  • Sostituisci la dll;
  • Riavvia il servizio.

All’n-esima volta mi sono stufato e ho creato uno script powershell che recita:

Set-Service -Name MadLab.Router -ComputerName 125.0.0.254 -Status Stopped

Copy-Item -Path .\MadLab.Router.Servizio\bin\Release\* -Destination \\125.0.0.254\madlab-ame\MadLab.Router\ -Exclude *config*,*vshost*, *.pdb

Set-Service -Name MadLab.Router -ComputerName 125.0.0.254 -Status Running