Category Archives

Travels in October and November

Azure, Microsoft, Technical stuff, Visual Studio, Work, Xamarin
No Comments

These coming few weeks will be quite busy with conferences and other meetings. Here is where you might have the occasion to see me:

  • I am currently in Boston, where I will support Scott Guthrie’s Red Shirt Tour on October 19. Ultimately, Scott is my boss (‘s boss’s boss’s boss) as well as someone I have admire ever since I met him in person 10 years ago. The event is all about Azure with Scott showing demos and code across all of Azure, Visual Studio, Xamarin and more.
  • After Boston, I will be in New York City on October 20th. This is another stop of the Azure Red Shirt Tour.
The Red Shirt Dev Tour NYC edition will be livestreamed!! Join us at http://aka.ms/rstlive

  • Before going back home, I will have the privilege and pleasure to fly down to Lima, Peru on October 25th and 26th. There, I will participate to the MVP Connection event, organized by Microsoft for its Most Valuable Professionals. Unfortunately, due to travel constraints, I won’t have time to participate in any public event there, but I will most certainly do my best to come back at another occasion and speak in public.

At the MVP Connection event, I will have an hour to speak about a few exciting topics including Azure Functions and Xamarin, the Azure Mobile Center and the Xamarin Live Player. Of course I will also be available for questions and discussions around Azure, Xamarin, Windows, MVVM Light and more.

After a few days at home, I will continue with travel:

  • I will fly to Hyderabad, India and participate to another MVP Connection event on November 3rd and 4th where I will be honored to speak about the same topics as in Lima. There too, I will be available for questions and discussions, and meeting as many MVPs as I can :) Unfortunately I don’t have other stops in India in November, but I am already thinking of coming back next year!

Then I still have two conferences in November:

  • I am super happy that I can travel to Malmö, Sweden this year again and speak at the Oredev conference on November 10. I spoke there once in 2011 [TODO CHECK] and never could again because the conference was always conflicting with the Microsoft MVP summit. At Oredev, I will be speaking about HoloLens and show developers how to get started with Mixed Reality programming. This should work well with my dear friend Rene Schulte’s talk at the same conference, which is scheduled just after mine and will dig quite a lot deeper into the topic.

  • To conclude the travel in November, I will spend a couple of days in Sofia, Bulgaria on November 16th and 17th. There, I will have the honor of keynoting the ISTA conference. From their website: “Innovations in Software Technologies and Automation (ISTA) is an annual, international conference, devoted to the latest trends in software development and test automation. We are committed to support the development of quality standards in the field with focus on new technologies and best practices.” Sounds like a very exciting conference in a dynamic city of software. I had the pleasure to speak in Sofia before and was always impressed by the quality of the attendees!

I hope that I have a chance to meet some of you, dear readers, at one or the other event. Make sure to follow me on Twitter to get the details of my travels, and by all means come say hi!

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook

Flexibility is great until it isn’t… Careful with these Azure Tables!!

Azure, Azure Storage Explorer, Azure Tables, Technical stuff, Work
5 Comments

As part of my ongoing discovery of Azure features and services, I am working on a few applications and samples that use various features of Azure such as Azure Functions, Azure Tables and more. Recently I had a bug in one of my applications, a link shortener that takes in a link in the form http://gslb.ch/5t and returns another longer link, in this case https://expertday.forxamarin.com.

The application uses an HTTP Module that detects the short domain gslb.ch and performs the table lookup. This is straightforward enough. Where things become interesting is that by deploying this solution on Azure and switching Application Insights on, I get some feedback on who is clicking what. For instance, the short link above has a few possible variations. http://gslb.ch/5t is used for Twitter, as indicated by the trailing T. I could also use http://gslb.ch/5f for Facebook, http://gslb.ch/5l for LinkedIn, you get the idea. It allows me to see where the majority of my community is active, which is interesting information.

Using analytics

As part of the service, I also have the possibility to add some analytics information for the destination system. For some Microsoft links, we use analytics like the following:

“?WT_mc_id=redshirtdevtour-twitter-lbugnion”

This type of analytics is used for the Red Shirt Tour taking place this Fall, where Scott Guthrie is visiting 5 locations in the USA and talking about Azure with a LOT of demos. If you haven’t done so yet, you should really check it out, some great content for free, and a chance to meet a lot of the Cloud Developer Advocates, including myself in Boston and NYC. Sometimes I want to use analytics, and sometimes I don’t, so I have foreseen a boolean column for this in the database, as shown below.

Using Azure Tables for storage

I found one small issue that cost me a few head scratches. You see, I use Azure Tables for the storage of the link information. This is quick to use and super easy to maintain. As time goes, I might port it to CosmosDB but for now, this works well.

From the Azure Tables page: “A NoSQL key-value store for rapid development using massive semi-structured datasets”. This is a very flexible, schema-less system. It means that you can easily add new entries in a table, and create new properties on the fly, for example with the Microsoft Azure Storage Explorer which I documented earlier. In my case, here is a screenshot of the table:

2017-10-01_11-05-22
(Click for full size)

As you can see, the last column is titled SkipAnalytics. If true, the analytics portion described above is omitted from the long link. Obviously I made this value a boolean as shown in the class code:

public class ShortenedLinkEntity : TableEntity
{
    public string LongLink { get; set; }
    public string Alias { get; set; }
    public string Channel { get; set; }
    public string EventName { get; set; }
    public bool SkipAnalytics { get; set; }
    public string LinkAlias { get; set; }
}

The entities are retrieved with the following code. In this example, I hardcoded the index “5”, which corresponds to the RowKey column in the table shown above.

var account = CloudStorageAccount.Parse(Constants.ConnectionString);
var tableClient = account.CreateCloudTableClient();
var linksTable = tableClient.GetTableReference(LinksTableName);
await linksTable.CreateIfNotExistsAsync();

var retrieveOperation = TableOperation.Retrieve<ShortenedLinkEntity>(
    "partition",
    "5");
var operation = await linksTable.ExecuteAsync(retrieveOperation);
var link = operation.Result as ShortenedLinkEntity;
return link;

The code above starts by creating a CloudStorageAccount corresponding to the connection string I obtained from the Azure Storage Explorer as shown here (Primary Connection String):

2017-10-01_11-20-54

Then I create a CloudTableClient which I use to retrieve the CloudTable for the short links. To retrieve the entity itself, I use here the TableOperation.Retrieve method, which is very fast and convenient if you happen to know the PartitionKey and the RowKey for a given entity. Since in my code the RowKey is the index passed in the URL (here “5”), it is easy.

That sounds great, so where’s the issue?

Here is the bug: I wanted to add a new row. Eventually I will have a client for this (planning to develop it with Xamarin, of course, so I can use it on Windows, iOS, Android) but right now I add rows directly in the Azure Storage Explorer. Let’s see if you can spot the issue.

First I add a new entity in the table. Notice that I don’t enter a value for the SkipAnalytics column, this is an error that I will fix later.

2017-10-01_11-25-29

2017-10-01_11-26-21

Then I see ooops I forgot the SkipAnalytics column, let’s correct that now by selecting the row and clicking the Edit button.

2017-10-01_11-32-01

Note that the empty columns are missing from this dialog. This is because as I explained, the entities stored in Azure Tables can take any shape, there is no strict schema. Freedom is great but in that case it will cause a small issue. Let’s add the missing SkipAnalytics column by pressing the Add Property button.

2017-10-01_11-33-47

Looking good right? Now if I press Update, the entity is updated in the Table. I can then run the code to retrieve the entity in my web application and… SkipAnalytics is false. Why???

Did you spot the issue?

Let’s go back to the place where I edited the entity.

2017-10-01_11-33-48

Wait… how can the column SkipAnalytics be a string? All the other rows use Boolean for this value in the table!! Well here you go, this is the issue. Because of the added freedom, I can have an object with a SkipAnalytics value of type bool, and another object in the same table where the SkipAnalytics value is of type string. When I retrieve the value in a strongly typed language like C#, I don’t get an error, but the value “true” maps to the Boolean false. Ugh…

Unfortunately, (1) the Azure Explorer doesn’t perform a check when you add an entity, (2) the Azure Table doesn’t have a problem storing what we would consider incompatible values and (3) there is no exception when the entity is retrieved and the values are mapped to the corresponding entity. This creates a bug in the application that can be quite difficult to understand.

What now?

For now, I didn’t ask the team yet why this is possible. I’d love to know if this is by design or if they would consider it a flaw of the system. What do you guys think? Personally I would be happier if the Azure Storage Explorer would prevent me from doing that. Maybe an update in the future? If and when I get a reply from the team, I will update this post with what I learn.

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)

Share on Facebook

Writing, writing, writing…

.NET, Azure, Azure Functions, Cloud Developer Advocate, Microsoft, Technical stuff, Work, Xamarin
No Comments

One thing I love in my new job is that I can just sit down anywhere on Earth, grab my Surface Pro and produce content (articles, samples, etc) or learn new things just as if I was home. I just came back from Singapore and had a great time there talking at the Xamarin “MonkeyFest” conference. But it was also a busy time producing content and I am so happy that things are starting to fall into place.

Here are a few highlights:

  • I just published a few new articles (see below). As I am discovering new features of Azure, I want to share with you all. I decided to write in markdown (just like docs.microsoft.com) and publish on GitHub. Why GitHub? Well first of all this is of course the destination for developers. The markdown renderer is pretty good, it is easy and fast to create and publish good quality content. At some point this documentation might migrate to another location, but for now it makes sense to have it on Github. Also, and maybe most importantly, I like that the source code and the corresponding articles are all grouped together, for example my sample-azure-coinvalue application.
  • As I was writing, I noticed that a few topics are going to be recurrent in all my samples. So I went ahead and created the following repo: sample-azure-general. In this repo, I will document recurring processes in Azure, such as creating a trial account, Creating and testing Azure Functions in Visual Studio, Publishing functions to Azure, etc etc etc.
  • In parallel I am also working on new samples and should be able to publish more soon. So stay tuned to this blog or to my Twitter account. Yes for now the list of samples is very lean but now that everything is starting to be coherent, I want to add new content regularly!

Please help me help you!

I’d really like you all to be able to tell me what is the most important for you. And so in this spirit I want to start with two features:

Available articles:

At the moment you can find the following content in sample-azure-general:

Hopefully this is helpful to all of you, and I hope that we can get the discussion running. Microsoft is literally paying me to help you understand Azure, cross-platform, Windows, .NET and more and I love that job. So please please please don’t be shy and let me know what you need. We want to help!

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook

My talks in September

.NET, Azure, Azure Functions, Microsoft, MVVM, Work, Xamarin
No Comments

I don’t know about you but I had an amazing summer. I had the amazing luck of spending time in beautiful places in the Philippines, Iceland and then 2 great weeks in Seattle and Redmond. Having started to work with Microsoft on August 1st, it was great to be on campus in Redmond as a blue badge.

Apart from sitting down with my new team, meeting my new manager and old friends on campus, I also delivered two sessions at the Visual Studio Live conference. The event took place at the Microsoft conference center (Building 33) and was as packed as usual with great speakers and very competent attendees. This year was special for me because my two talks took place in the Cascade room, which is a really nice auditorium with all the comfort. I also had a lovely time interacting with attendees at the traditional Birds of a Feather lunch, where a table is assigned to a speaker and attendees can go around the room, sit down, ask questions or just chat.

You can find the slides, source code and all the information about my two talks on my website:

Amsterdam: MVVM Cross Hackfest

My next engagement is the closing event of the MVVM Cross Hackfest taking place in Amsterdam on September 2nd. The .NET Open Source foundation is sponsoring this event with others, where the aim is to encourage new contributors to help open source projects. For MVVM Cross, the event is the occasion to port this popular framework to .NET Standard. While the project lasts 2 weeks, September 2 will be the last day with a celebration, some lightning talks and a party.

At this occasion, I will speak about Azure Functions (which are really awesome). My Microsoft colleague Mike James will also be there and speak about other Azure services. The rest of the lightning talks will be held by MVVM Cross contributors. You can see the program here. My session’s abstract is the following:

Azure Functions and Xamarin

One of the most exciting recent additions to Microsoft Azure is called Functions and allows the developer to quickly build and deploy code to the cloud without complicated setup. Also dubbed “serverless computing”, Azure Functions can be triggered by timers, HTTP calls or database operations, and can communicate with other Azure services or mobile and desktop applications such as those made with Xamarin. In this lightning talk, Laurent Bugnion, Cloud Developer Advocate for Microsoft, will give you an introduction to Azure Functions and get you started with this exciting aspect of modern computing.

Singapore: MonkeyFest

A little later in the month, I will fly to Singapore to attend the MonkeyFest conference which is a Xamarin event organized for the first time in the beautiful south east Asian city. There is a nice team of speakers speaking on a variety of topics. The entrance tickets can be purchased for 19 Singapore dollars, which is very cheap for such a quality show! We hope to see a lot of attendees at Microsoft Singapore!

Building truly Universal applications with Windows, Xamarin, MVVM and Azure

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!

Come say hi!

I hope that I will have the occasion to see a lot of you out there. I have more talks coming up in November – but that is for another post. Please come say hi!

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)

Share on Facebook

Joining Microsoft

IdentityMine, Microsoft, MVP, MVVM, Personal, Universal Windows Platform UWP, Valorem, Work, Xamarin, XAML
16 Comments

Well here is a post I didn’t quite expect to write… but the best things in life are unexpected. I am thrilled and proud to announce that as of August 1st 2017, I joined the Cloud and Enterprise group (aka Azure) at Microsoft.

My role will be a Senior Cloud Developer Advocate and I will explain in this post what it is I will do! I guess an FAQ format is most appropriate here, so here goes:

Are you moving to the USA?

No, I am staying put in Zurich Switzerland, my home for the past 23 years. While I don’t exclude living in the US at some point in the future, now is not that time and I will stay close to the friends and family I have in Switzerland. The role is global, and I will be travelling about the same amount than I am now, including coming to Redmond about 3-4 times a year and going to events worldwide.

It’s really interesting to see all the new people joining the team and I can’t wait to hear more about who else will get on board. Because it is a global role, we will have local offices around the world (in exciting places such as London, Shanghai, Bangalore etc). I really hope I will have a chance to be present at events in places where I couldn’t go yet, especially in Asia and South America. While I am super happy about all the talks I gave in Europe and the USA, I feel that it’s time to go “advocate” in more places now. Can’t wait to create that content and teach.

What will you do?

This is the most interesting part! This group is helping to redefine how we engage with developers on a big scale and be an empathetic advocate to the product engineers building the tools, services, APIs and other tech you use on a daily basis!

If you follow Twitter, you might have seen quite a few very talented people joining the Developer Advocate group. These people have very diverse skills, from web to open source to Linux to Docker and more. Even though I will be “advocating” Azure, my main expertise is going to be with Xamarin development and cloud-connected mobile app experiences, and of course MVVM. XAML has been a primary interest for more than 10 years now, and Xamarin is a technology and a team that I worked with for the past 4 years now. I am really enthusiast about working with these technologies even more intensively now, and most importantly to teach people worldwide how to use them.

Who is employing you? Who is your boss?

Because I am living in Switzerland, technically I will be an employee of Microsoft Switzerland. But I am reporting to Tim Heuer (a great friend!) who is based in Redmond. Our team is a part of the engineering group in Azure and reports up through Scott Guthrie. It’s kind of a hybrid situation, and I expect to be regularly in Wallisellen in the Microsoft Switzerland offices, as well as in Redmond for team meetings a few times a year.

What makes you most excited about this job?

Difficult to answer. When I received the call three months ago, and heard about the amazing job description, I thought it was just great for me. In a later call, I heard that Tim Heuer would be my boss and that was an amazing cherry on a fantastic cake. I have to admit that the thought of getting into Microsoft at this time, under Satya Nadella and Scott Guthrie, is making me very happy. It is a great time for Microsoft and especially Azure. I started getting more and more interested in Azure after I joined the Microsoft Regional Directors group. This group of experts is composed of very experienced people who have strategic roles in various firms, big and small. A large portion of the discussions have been focused on Azure, which led me to understand how important this technology is. There are just so many applications and the pace of innovation is quite breathtaking. I have a huge respect for everyone I will be working with, and especially of course for Scott Guthrie, who I have met many times over the past 10 years. He is as nice as he seems but most importantly, he is really, really clever and drives innovation amongst his people. I am delighted to be a part of this new adventure.

What do you regret the most?

I will certainly miss working for Valorem and especially all my friends. I met some of you guys 10 years ago, and we have been working together as a team for more than 8 years. I will be forever grateful to the IdentityMine team who gave me a chance in 2008 and decided to create a whole branch in Switzerland just for me. I think in retrospect it was a win-win, just look at all the amazing projects we realized!

But maybe most painful of all is the fact that I will have to resign from the MVP awards (both Microsoft and Xamarin) and the Regional Director program. Of course the joke is that joining Microsoft is the best reason for losing these awards, but I will really miss the amazing community of peers, some them who grew to become more than dear friends, a family.

Of course the good news is that I will continue to see many of you at conferences and other events around the globe. I will also continue to participate to some of the distribution lists and so we will be able to keep in touch. And as always, if you come to Zurich, let me know and we’ll have a fondue! (or something…).

Will something change for MVVM Light?

Short answer: No.

Slightly longer answer: Microsoft is very open regarding open source. I retain the full ownership of the project and I expect to be working on it about the same amount of time than I do now (of course on my free time). In the next few weeks you will see a move to Github as well as a version for .NET Standard so keep watching this space for updates.

What’s next?

Well while today is officially my first day at Microsoft, it is also Switzerland’s national day (Happy 726th birthday Switzerland!) and so my first day will be tomorrow. I have the new employee orientation (NEO yay) at the Swiss HQ in Wallisellen near Zurich. I expect that I will get my blue badge as well as a ton of information. At some point I should also get a new laptop (I was given a choice between a PC and a Mac and selected a Surface Pro 4 because I still love the Surface form factor, especially when I travel). Then I will spend a few days in Redmond next week, and connect with some of the team. Really impatient to get started!

I am sure I will have a lot more to say about all this in the next few days, so stay tuned!

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Solving the #Xamarin error “Unable to copy appname.dll…”

.NET, Technical stuff, Visual Studio, Work, Xamarin
No Comments

If you recently updated Xamarin to the latest stable version in Visual Studio 2015 or Visual Studio 2017, you might have encountered an annoying error when trying to build:

Unable to copy appname.dll from obj to bin because it is being used by another process

This error typically happens the second time that you try to build after you start Visual Studio. The first time everything works OK, then suddenly you cannot build anymore. Cleaning the solution doesn’t help, the only “fix” is to restart Visual Studio which is of course really annoying when you are developing.

This error is known, as shown by the Bugzilla issue #56275. There is also an old forum discussion on the Xamarin forums, which is a bit confusing because it might be a recurring error in the Xamarin updates.

Fortunately, the Bugzilla discussion also carries a workaround. This is a Visual Studio extension that you can install, which should fix the issue. I also talked to Microsoft about this and got confirmation that the error is fixed in a future release of Visual Studio. The engineer who replied to me also gave me a VSIX to fix the issue. I am not entirely sure what the difference is with the one in the Bugzilla issue, so I will just copy it here for your convenience. As far as I can tell, both VSIX files work well.

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Using the Windows Template Studio with #MVVMLight

.NET, Build, MVVM, Technical stuff, Universal Windows Platform UWP, Visual Studio, Windows 10, Work
1 Comment

Here is a story of a great collaboration between Microsoft and the community.

Last year in August, as I was speaking at VS Live in Redmond, I was asked by my friend Clint Rutkas for coffee because he had an idea he wanted to run by me. Now if you know Clint, that is usually really intriguing and I was really excited to hear about his idea.

Clint told me about the project he was thinking of starting. This was just conceptual at the time, but his idea made a lot of sense: Why not make the process of creating a new Universal Windows application a lot easier. Why not help people with all the tedious tasks that you get right after File, New, Project.

Usually when you get started, you need to add a bunch of pages and helpers to your application. The Blank application template is just that, blank. In MVVM Light, I added a project template for the supported frameworks (Universal Windows Platform, Xamarin.iOS, Xamarin.Android, Windows Presentation Foundation, Silverlight).

2017-05-24_11-09-27
The MVVM Light templates in Visual Studio 2017

However creating a meaningful project template is really difficult. You are constantly navigating between “too much content” and “too little content”. If you have too much, the developer ends up having to remove a whole lot of code, which is tedious. If you have too little, then the developer needs to spend time adding the basics, as well as sometimes having to look for guidance on how to do common things like navigation, dialogs, a Settings page, etc.

Building a wizard

Of course I thought of building a wizard to help people getting started. This is not easy though. First of all, the Visual Studio automation can be complex. You need to support multiple versions of Studio, and the extensibility model changes from version to version, so that is a big commitment. And this is where Microsoft has a huge advantage, they own the extensibility model, they know in advance is something is going to change, and they have the resource to create and maintain the code. And since the WTS is open source and available on Github, you can also contribute, and help make this project even better.

Installing the Windows Template Studio

Before you get started, you will need to add the Windows Template Studio (WTS) to Visual Studio 2017. Thankfully this is really very easy. In Visual Studio 2017, just select Tools, Extensions and Updates. Click the Online item on the left, and enter Windows Template Studio in the search box on the top right.

2017-05-24_09-47-08
The Extensions and Updates dialog with WTS

In Visual Studio 2017, you are now required to close the application to install the extension, so after the download is complete, close Studio and it will get installed.

Getting started

2017-05-24_11-16-46

The WTS starts in the File, New, Project dialog. Under the usual Universal Windows templates, you will see the entry for the WTS. Select it, give a name to your new application and press OK.

The project type

2017-05-24_11-19-16
The project type and framework dialog

The next screen is about the foundation of your app. You can select a type of navigation (currently you can select an app with a navigation pane, or an app with tabs), or simply a blank template without navigation.

The framework

Then comes the framework selection. This is where you will notice MVVM Light front and center. The other options at the moment are Code Behind, or a basic “no-name” MVVM implementation which can be useful in situations where the usage of 3rd party frameworks is completely forbidden.

The pages

2017-05-24_11-20-12
The pages dialog

The next step is probably the one I am the most excited about. It is usually so tedious to add the same pages over and over in every application I create. Here, you can choose to add pages such as blank page, map page, master/details, web view, settings etc. I can’t stress enough how much of a time saver this step is.

Note that the studio also supports you in finding out which licenses the 3rd party frameworks use. For example, if you add a Settings page which uses JSON.Net for the serialization of the settings, a link to the license is added to the Summary pane on the right, and so you don’t have any surprise.

The features

The features dialog is as exciting. With one click, you can add new experiences to your application such as Suspend/Resume, Background tasks, notifications, live tiles and more.

2017-05-24_11-54-40
The features dialog

This is probably the easiest way to offer a fully featured application to your users.

Why only MVVM Light at this time?

Microsoft ran numbers of the Nuget downloads and saw a confirmation that MVVM Light is the most widely used framework to build MVVM applications on Windows. In addition, its modularity and simplicity of use makes it a prime candidate for the first version of the WTS. However this is an open source project and so the developers of other projects (such as my good friends at the Prism or MVVM Cross projects) are already working to add support for their own framework in the WTS.

What about other application types?

At the moment, the WTS only works for Universal Windows applications. However nothing would prevent it to be updated for other application types. Personally I would welcome Xamarin support! And here we can predict that this will probably happen sooner or later, supported by the community of open source developers. I can see a lot of advantages in adding support for Xamarin or even WPF desktop applications. So I encourage everyone to head to Github and start contributing!

Resources

Here are some videos and links to get started:

I hope that you also see the potential of this great tool and that you will contribute.

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Live blogging the Microsoft Build keynote, day 2 #msbuild

.NET, Build, Conferences, Technical stuff, Universal Windows Platform UWP, Visual Studio, Windows 10, Work, Xamarin, XAML
No Comments

And the show continues on day 2! In this post, I will be live blogging the Microsoft Build keynote on day 2. This should be a very exciting event with focus on client development, Windows and Mixed Reality. Get ready!!

Live blogging the Microsoft Build keynote, day 1 #msbuild

.NET, Build, Conferences, HoloLens, Technical stuff, Universal Windows Platform UWP, Visual Studio, Windows 10, Work, Xamarin, XAML
No Comments

Build day 1 is a wrap and you can find all the live notes taken during the keynote in this post!

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