Category Archives

Installing #mvvmlight for .NET Standard 1.0

.NET, MVVM, Technical stuff, Universal Windows Platform UWP, WPF, Xamarin
2 Comments

I just released the new MVVM Light preview version for .NET Standard 1.0. I also published an article in the MVVM Light documentation describing the installation of the .NET Standard 1.0 version of MVVM Light as well as the changes needed to existing applications.

Hopefully you find this helpful.

This is a pre-release version and I am eager to hear your feedback. If you have any issue during the uninstallation process, installation process or while using MVVM Light for .NET Standard 1.0, send me an email at Laurent@galasoft.ch for assistance.

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)

Share on Facebook

Setting the device brightness on Windows with WPF

.NET, Technical stuff, Windows 10, Windows 7, Windows 8, Work, WPF
3 Comments

I am working on a project which I can’t really detail, but one aspect caused me a few headaches. Finally I reached out to the Windows team at Microsoft and got great help from Katie Anderson who works on the brightness team. This was quite tricky, and we had to have a couple of roundtrips before we managed to find a way that worked.

Well, why?

In the application I am working on, it is necessary for the user to set the device brightness from the application itself. You might wonder why, because most Windows devices have hard keys to set the monitor brightness. For example on a Surface, you can use the Fn-Del and Fn-Backspace key combinations to alter the brightness of the screen. Or you can of course swipe from the right side and use the Brightness button to change the value in the Action Center.

However on that particular project, the user doesn’t have access to the keyboard, nor to the Action Center. This is a kind of kiosk scenario if you will where many of the Windows features are deactivated by policies, and no hard keyboard is provided. I had to find a way to do this programmatically.

First approach: Not so good

At first I thought I would have my application’s main window run in full screen and set a black Rectangle on top of everything, and change the Rectangle’s opacity in my code. That worked well but of course it wouldn’t work if other applications were in the foreground (yes, I forgot to mention, it’s a kiosk app which can start other apps and put them in the foreground…).

Second approach: Better but not great

OK, no problems I thought, let’s have my app open a modal full screen window which is always on top. I will then have this window made insensitive to touch or mouse clicks with the following code. Finally, this window will have the black Rectangle and be on top of everything all the time.

public static class WindowsServices
{
    private const int GwlExstyle = -20;
    private const int WsExTransparent = 0x00000020;

    public static void SetWindowExTransparent(IntPtr hwnd)
    {
        var extendedStyle = GetWindowLong(hwnd, GwlExstyle);
        SetWindowLong(hwnd, GwlExstyle, extendedStyle | WsExTransparent);
    }

    [DllImport("user32.dll")]
    static extern int GetWindowLong(IntPtr hwnd, int index);

    [DllImport("user32.dll")]
    static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);
}

This worked OK but somehow it was not satisfying. I really wanted to have a solution where my app would modify the actual device brightness. There are a few reasons why the client also wanted that, and so I started to investigate deeper. Unfortunately, Bing searches (and the equivalent Google searches) didn’t really return anything satisfactory.

Using Powershell

After searching a bit, I got a first clue that what I wanted to achieve was doable: You can query and modify the device brightness from Powershell with the following script:

CODE TO GET THE BRIGHTNESS INSTANCE

PS C:> Get-Ciminstance -Namespace root/WMI -ClassName WmiMonitorBrightness

CODE TO SET THE BRIGHTNESS

PS C:\Users\lbugn> $monitor = Get-WmiObject -ns root/wmi -class wmiMonitorBrightNessMethods
PS C:\Users\lbugn> $monitor.WmiSetBrightness(50,10)

If you run these commands in Powershell, you will marvel at the result: Yes it does work and the screen’s brightness is modified. Great Scott, I am on the right track! The key to this is the WMI (Windows Management Interface) class WmiMonitorBrightness.

Converting to .NET

The next step was obvious: I needed to convert the Powershell script to some usable .NET code. Unfortunately, easier said than done. This is where I reached out to Microsoft for help and thankfully Katie really followed through and after a few iterations we got it to work.

First she used the WMI Code Creator tool to convert the Powershell script to .NET. I had no idea that such a tool existed, but then again I never had to dive so deep in the entrails of Windows. Unfortunately when running the code that the tool created (which I won’t post here to avoid confusion), I got some errors. One more roundtrip to Redmond (via email) and Katie found the way: The following code will indeed modify the brightness of the screen, yay!!

public static class WindowsServices
{
    private static ManagementObject _brightnessInstance;
    private static ManagementBaseObject _brightnessClass;

    static WindowsServices()
    {
        // Querying the Windows service to get the Brightness API.
        var searcher = new ManagementObjectSearcher(
            "root\\WMI", 
            "SELECT * FROM WmiMonitorBrightness");

        var results = searcher.Get();
        var resultEnum = results.GetEnumerator();
        resultEnum.MoveNext();
        _brightnessClass = resultEnum.Current;

        // We need to create an instance to use the Set method!
        var instanceName = (string)_brightnessClass["InstanceName"];
        _brightnessInstance = new ManagementObject(
            "root\\WMI",
            "WmiMonitorBrightnessMethods.InstanceName='" + instanceName + "'",
            null);
    }

    public static int GetDeviceCurrentBrightness()
    {
        // Getting the current value.
        var value = _brightnessClass.GetPropertyValue("CurrentBrightness");
        var valueString = value.ToString();
        return int.Parse(valueString); // Direct cast fails.
    }

    public static void SetDeviceBrightness(int newValue)
    {
        if (newValue < 0)
        {
            newValue = 0;
        }

        if (newValue > 100)
        {
            newValue = 100;
        }

        var inParams = _brightnessInstance.GetMethodParameters("WmiSetBrightness");
        inParams["Brightness"] = newValue;
        inParams["Timeout"] = 0;
        _brightnessInstance.InvokeMethod("WmiSetBrightness", inParams, null);
    }
}

I made a small sample here which gets the current value of the screen brightness and then increases it by 10% every time you click on a button. When you reach 100%, it goes back to zero on the next click. Simple enough, and does the trick.

I hope that this will be useful to a reader looking for the same feature. I’d love to be the first one to ever blog about this. I doubt that I am, and probably someone will point me to the article that I never found :) but seriously, I really couldn’t find any mention of something like that on the whole WWW.

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)

Share on Facebook
 

Two millions #mvvmlight downloads

.NET, MVVM, Technical stuff, Universal Windows Platform UWP, Work, WPF, Xamarin, XAML
3 Comments

Sometimes between last week and this week, we crossed a threshold: Two millions MVVM Light downloads.

I don’t have many metrics about MVVM Light, because the toolkit itself is not instrumented in any way. You get the raw binaries without added sugar :) So the only numbers I can rely on are the number of downloaded copies, either on Nuget or as the VSIX extension for Visual Studio. Obviously this doesn’t say much about the number of applications created with MVVM Light, since once the VSIX is downloaded, every File / New Project command creates a new app without any download. Still, it’s been interesting to see the evolution in downloads since I started to track the numbers.

Recently, I had a memory on my Facebook wall reminding me that 2 years ago, I was posting about 500’000 downloads, just before my Visual Studio Live sessions in Las Vegas. Two years later I was in Vegas again, for VS Live again, and about to cross two millions. Clearly the curve went up quite a bit. I tried to analyze what was the most significant change, and I think the port to Xamarin definitely played a significant role there. I also saw an uptake in interest in conference submissions since MVVM Light is truly cross platform, especially since Xamarin Evolve 2014 where I had a session. Since then a lot more sessions were given about Building Truly Universal Applications with MVVM Light, and quite a few full rooms too.

Tracking the downloads

As I mentioned, it is difficult to track downloads in a significant manner. There are automated build stations that will restore Nuget packages every so often. On the other hand there are people who download the Visual Studio extension once and create new applications without downloading anything. The only significant metric, I guess, is the evolution in downloads over time. Here is a chart (click to enlarge):

2017-03-21_11-13-37

Right now I track downloads on the following pages:

What’s coming

Currently I am working on the following topics:

  • A post about Working with MVVM Light in Visual Studio 2017. This is a pretty long post, which will also end up in the documentation pages. It will also explain how the sample applications (created by the templates) work and what features they demonstrate.
  • Improving the project template for WPF. I want to add more features there and be on par with what I have for Windows 10, iOS and Android.
  • Adding a project template for iPad and iOS Universal.
  • MVVM Light for Xamarin Pluralsight course. No ETA on this at the moment, sorry.

And of course the backlog is still active! Don’t hesitate to send your feedback :)

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

#Microsoft #Experiences in Paris: Code and slides

.NET, Conferences, HoloLens, MVVM, Technical stuff, Windows 10, Work, WPF, Xamarin, XAML
No Comments

Last week I had the pleasure of taking the TGV from Zurich to Paris, and after a quick 4 hours of comfortable travel, to make my way to the Porte Maillot and the Palais des Congrès.

TL;DR: All slides and source code is available from here.

A podcast

After a good night sleep I made my way to the speakers lounge and prepared the last steps for my talk. Then I took a moment to head to the meeting room where the Live Tiles podcast was being recorded. A band of podcasters got together and talked about the future of Microsoft. It was so nice to “see these familiar voices” in action. Even nicer when Christophe (Toss .NET) and Denis saw me and pulled me in to talk about HoloLens and our experiences with this device. You can hear the recording here, my contribution starts at 36:30.

My talk: Really universal apps with Xamarin and MVVM Light

My talk was titled (in French) “Construisons des applications vraiment universelles avec Windows, Xamarin and MVVM Light”. This favorite topic of mine shows how you can structure an application to share a maximum of code without any compromises. You can build healthy layers of Model and ViewModel, unit test them so you can feel secure about not breaking anything with future changes. Then you can build a thin layer of real native user interface for any supported framework with XAML or Xamarin (Windows Presentation Foundation, Windows 10 Universal, Xamarin.iOS, Xamarin.Android). And if you are in an enterprise scenario and looking for maximum productivity, you can also of course use Xamarin.Forms and render the same UI to all supported platforms.

The MVVM Light Toolkit assists you in these tasks, notably by providing a Data Binding framework for Xamarin.iOS and Xamarin.Android, as well as components that make it very easy to connect a list control to an ObservableCollection, with automatic refresh in case the collection changes. This open source toolkit is in it’s version 5.3, has been downloaded almost 1.7 million times and is even used by Microsoft to build parts of Windows 10.

I was really pleased when I headed to my conference room and saw a long queue in front of the entrance. I gave my talk to a standing room of about 270 people, and loved the interaction during and after the talk. A lot of very positive feedback, and we stayed and talked until the hostess kicked us out of the room :)

Thank you to everyone who came and made this a memorable moment. You will find all the details of the talk, the slides and the source code from this portal.

Some tea

Before I made my way to the Palais des Congrès, I took a pit stop at one of the most wonderful shops on Earth: the Mariage Frères tea store. This old fashioned store is stock full of amazing teas from all over the world. It’s a must-visit if you are a tea enthusiast or if you just want to spend a moment living in an atmosphere of luxury and pleasure.

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Slides and code samples for VS Live Redmond

HoloLens, MVVM, Technical stuff, Universal Windows Platform UWP, VSLive, Windows 10, Work, WPF, Xamarin, XAML
No Comments

VS Live just took place in Redmond, and I had a great time. I had three sessions in one day, and I was really exhausted in the evening, but it was absolutely worth it. Speaking in Building 33 (the conference center on Microsoft campus) was an amazing experience. I have spent so many hours in this building, listening to amazing speakers of Microsoft and others, during MVP summits and other events… so really it was quite magical to be on the speaker side this time, in room St Helens.

vsliveredmond

Thanks to every one who came to my talks! I hope it was informative and useful, and that it encourages you to try those technologies and techniques.

Here are the pages for the talks I gave:

Windows Presentation Foundation (WPF) 4.6
Windows Presentation Foundation is what people are using to build real applications for the enterprise, the industry, the workplace, and for every situation where Windows 10 Universal isn’t quite ready yet. Far from being dead, WPF is 10 years old this year, and it’s still alive and kicking. It gives Universal Applications a run for their money. In this session, you’ll learn what is new in Windows Presentation Foundation, where it’s going in the future, and what you can achieve with WPF that Universal Application developers can only dream of. We’ll also see how these two roads cross and how existing WPF applications can be brought to Windows 10 using the Centennial bridge. Finally we’ll discover new features and tools recently implemented for WPF developers.

Windows 10 – The Universal Application: One App To Rule Them All?
Windows 10 and the Universal Windows Platform offer a lot of productivity and flexibility around targeting the broad set of devices that run Windows. As a developer, you have a lot of choice–from building a single binary that is identical on all devices, through to an app that adapts to the type of device and on to the point of building an entirely different app for each class of device. What’s the right thing to do? How should you think about building the “One App to Rule Them All?” What are the design and implementation trade-offs you need to consider? This session dives into these areas with a hands-on approach and shows what it really means to be building apps across families of Windows devices that have different capabilities. We will also talk about bridges (and especially the iOS Bridge to Windows 10), and new platforms such as Continuum and HoloLens (with live demos).

Building Truly Universal Applications with Windows 10, Xamarin and MVVM
With Windows 10 supporting an unprecedented number of platforms and form factors (from IOT to phones to tablets to laptops and desktops to XBOX and SurfaceHub, and even the new HoloGraphic computer HoloLens), the name ‘Windows 10 Universal application’ is fairly accurate. But to be honest, shouldn’t a truly Universal application run on Windows 7, iOS and Android devices too? Thankfully, this is possible thanks to a clever architecture pattern named Model-View-ViewModel, the .NET portable class libraries and the Xamarin frameworks. With these tools, we can structure an application so that most of the code is shared across all the platforms, and then build truly native UI that adapts without any compromises to the device it runs on. In this session, we will understand exactly how such universal applications are built. Laurent Bugnion, a XAML/C# expert, Microsoft and Xamarin MVP who started making universal applications before it was even a thing, will show you practical knowledge with a lot of demos. Come listen from the creator of the popular MVVM Light Toolkit how this powerful but simple library can be leveraged to help you target more users than you ever dreamed of!

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Slides and sample code for my presentations at #VSLive Boston

.NET, Conferences, Universal Windows Platform UWP, VSLive, Windows 10, Work, WPF, XAML
2 Comments

Thanks to everyone who came to my sessions at VSLive Boston. I had a great time. I hope it was informative and useful. I am aware that you take time out of your job to come and see us speak and I really hope that you found it worth your time.

I had two sessions:

Windows 10 – The Universal Application: One App To Rule Them All?

You can find the slides and sample code for this session here. This page also links to a video showing how Windows 10 Universal apps work on HoloLens!

Windows Presentation Foundation (WPF) 4.6

Here are the slides and sample code.

Thanks again for your warm welcome in Boston!! I even had some time to visit the city and had a blast in the historical places.

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Slides and sample code for #XamarinEvolve and #Techorama

.NET, MVVM, Techorama, WPF, Xamarin, XAML
4 Comments

These past weeks have been busy with travel and speaking. After the wonderful time in San Francisco for Build 2016, I had a few precious weeks to prepare for Xamarin Evolve (Orlando, FL) and Techorama (Mechelen, Belgium). I just came back and here is the time to post the slides, sample code, and for Xamarin Evolve we even have a video of the talk!

Xamarin Evolve

2016-01-03_19-25-58

Evolve took place in tropical Orlando, and it was pretty nice to see sun, warm temperature and even some pool time on the day after the conference ended. I had a great time there. I talked about the DataBinding system in MVVM Light, which applies to Xamarin.iOS and Xamarin.Android. This critical part of all MVVM applications is there to ensure the connection between the ViewModel layer (typically in a portable class library and shared across all platforms) and the View layer. In Xamarin.Forms and on Windows, we don’t need an external databinding framework because we already have these (this is what you use when you write Text=”{Binding MyProperty}” in XAML). But in Android and iOS, there is no such concept, and this is where the MVVM Light platform-specific extensions come handy.

Here is the abstract (which was modified by Xamarin themselves… I normally don’t really use this marketing-y tone ;):

An In-Depth Study of the MVVM Light Databinding System

Living in the dark ages and still wiring up properties manually between your user interface and data source? Databinding is a technique to automatically synchronize a user interface with it’s data source and can vastly simplify how your app displays and interacts with data. While databinding is available out of the box for Xamarin.Forms and Windows applications, additional components are needed in Xamarin.Android and Xamarin.iOS. In this session, learn how to leverage databinding in your cross-platform applications as you master MVVM Light databinding and the MVVM pattern.

I created a page for this presentation on my website. There you will find the slides, video recording as well as the sample code.

Note: At the moment, some of the Xamarin Evolve videos are not working properly. Xamarin is informed. Thanks for your patience.

Techorama

techorama

Techorama is one of my favorite conferences, created by the community for the community after the cancellation of TechDays Belgium. Gill, Pieter and Kevin created a hell of a show, which grew to host more than 1000 visitors these days. The venue is awesome too, it is a movie theater and we get to project our slides and code on a huge screen. This year there were quite a few renowned speakers from the US and the whole world in fact. Even though I got to spend only one night at home after coming back from Orlando before flying again, which was quite tiring and a bit stressful, I was really looking forward to go to Mechelen. I hope you enjoyed my session there about WPF. It was a fun session where I talked about the differences between WPF and the Windows 10 Universal platform, about new development in WPF (especially tools such as the Visual Tree, the Live Property Explorer, and XAML Edit and Continue), about the Windows Bridge “Project Centennial” which takes a classic Windows app and “packs” it to transform it into a Universal application. We finished with an exciting demo of a new feature shown at Xamarin Evolve the week before: the Xamarin Workbooks, which allow you to create a rich document (using Markdown) with titles, subtitles, images etc, and allows including snippets of C# that will be executed by the Xamarin Inspector tool. Because the tool supports Android, iOS and WPF, it was a great find and it fitted well in my session which aimed to show that WPF is still very current and state of the art. So I happily changed my presentation to include it in the demos.

Windows Presentation Foundation (WPF) 4.6

Windows Presentation Foundation is what people are using to build real applications for the enterprise, the industry, the workplace, and for every situation where Windows 10 Universal is not quite ready yet. Far from being dead, WPF is 10 years old this year, alive and kicking, and gives Universal Applications a run for their money! In this session, Laurent Bugnion, a Microsoft Windows Developer MVP and Microsoft Regional Director, WPF expert since 2006, will show you what is new in Windows Presentation Foundation, where it is going in the future, and what you can achieve with WPF that Universal Application developers can only dream of.

The presentation’s page is on my website, and will give you access to the slides and the demo source code. Make sure to check the last couple of slides for more resources!

One more thing

I recently discovered (not sure how I missed that) that my session about Windows 10 UWP at the Future Decoded conference in London last year had been recorded. I added the video to the presentation’s page. So in case you want to know how to adapt your UWP app on multiple platforms, this is where you can go!

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
 

Slides and samples for my talks

.NET, Technical stuff, Universal Windows Platform UWP, Windows 10, Work, WPF, XAML
No Comments

Right before and after the MVP summit in Bellevue / Redmond, I had the chance and honor to speak at a number of events. Here are the slides and sample code for these sessions.

Xamarin University

MVVM Light and Xamarin (guest lectures): The Xamarin University is a subscription based service by Xamarin, and as such the guest lectures’ material is only available to subscribed members. If you are a subscribed member, please go to my presentation page which links to Xamarin’s guest lectures page. After logging in, you will be able to find the material you can download. There is a screen recording, the slides as well as the sample code in there.

Read the rest of this entry »

Upcoming speaking engagements and travels!

.NET, IdentityMine, MVVM, Technical stuff, Visual Studio, Windows 10, Work, WPF, Xamarin, XAML
1 Comment

Wow it’s autumn already! When did that happen? The Summer was very busy, with a lot of super interesting work at IdentityMine, the release of MVVM Light V5.2, and preparation for an upcoming article in MSDN Magazine (more about that later) and even some work on some personal apps I wanted to port to Windows 10 and improve.

In the coming few weeks, I have some travel coming up, with speaking engagements. Here is the list below, and I will update it if something new comes up. I really hope to have a chance to see you at one of these talks, and if you do come, please come say hi and let’s chat!

Read the rest of this entry »

Re-enabling the CommandManager feature with RelayCommand in MVVM Light V5

.NET, MVVM, Technical stuff, WPF, XAML
12 Comments

In October, I published V5 of the MVVM Light Toolkit. Amongst other things, this is the first version where the main assemblies (GalaSoft.MvvmLight and GalaSoft.MvvmLight.Extras) are portable class libraries (PCL). This is good for you because you can now develop PCLs that reference MVVM Light and use its components. It’s good for me too, because it creates less clutter when I want to support multiple Windows frameworks (and boy, do I support them! All XAML frameworks are officially supported by MVVM Light V5 as well as Xamarin.iOS, Xamarin.Android and Xamarin.Forms!)

For you who are using MVVM Light as your framework of choice in an application, it should mean much change. In WPF 4 and WPF 4.5, however, there is a catch: The CommandManager will stop working after you upgrade MVVM Light to V5. What you will observe is that your UI elements (buttons, etc) will stop getting disabled/enabled when the RelayCommand’s CanExecute delegate returns false.

Read the rest of this entry »