Category Archives: .NET

.NET Framework

Calling the Azure Event Hub REST-API – from UWP, WPF and any other .NET (Core) Client

To push events into Azure Event Hub you can use the Nuget-package WindowsAzure.ServiceBus (https://www.nuget.org/packages/WindowsAzure.ServiceBus/). That package works pretty straight forward, but there’s one problem:

It has been built for the .NET Framework. It is not available for .NET Core, which means you cannot use that package for example in an Universal Windows Platform (UWP) app or in a Xamarin-Forms app or in any other app that does not run on top of the full .NET Version.

But how do push events to your Azure Event Hub from an UWP-app? This question is exactly the one I had. I want to push events with sensor data from a Raspberry PI 3 to Azure Event Hub. And as the Raspberry PI 3 is running Windows IoT, I want to use an UWP-app. (Side note: I know there’s an Azure IoT Hub, but Event Hub can be interesting, as for specific scenarios it could be cheaper, and maybe it is given already in your architecture).

To access the Event Hub from an UWP-app, you can use

  • use an Open Source-library. I tried a few, but they didn’t work on the latest build I was running
  • use the REST-API of Azures Event Hub. And this is what this blog-post is about.

When you read about the REST-API, you’ll find out that there are two URIs to send an Event: With or without publisher name (or device Name, whatever you name it):

  • https://{servicebusNamespace}.servicebus.windows.net/{eventHubPath}/messages
  • https://{servicebusNamespace}.servicebus.windows.net/{eventHubPath}/publishers/{publisherId}/messages

Now the challenge is that you need to handle the security with the Shared Access Signature Token. Somehow you Need to generate that token, and to do this, you also need to find out about your event hub namespace, your event hub name, your shared access key and finally hashing that stuff into a Shared Access Signature etc. And this seems to be complicated in an UWP. I haven’t found a trivial solution on the web, so I thought I build a generator for that token for you and for me.

Yesterday night when my wife and the kids where sleeping I switched Visual Studio to the Dark-theme – feeling like Batman – and I started to create a WPF-application that generates everything you need to access the REST-API of your Azure Event Hub. All you need to do is:

  1. Enter your Event Hub Connection String (you find that one on the Azure Portal)
  2. Enter a Token Lifetime (specify when the token will expire)
  3. Optionally Enter a Publisher Name (this can be a device name. Or you keep it empty to make REST-calls without publisher name)

The tool I created is called Event Hub Rest Client Generator, and it looks like this:

calling-the-azure-event-hub-rest-api-from-uwp-wpf-and-any-other-net-core-client_1

Now let’s see how to use it. The first thing is to access your connection string on the Azure Portal under http://manage.windowsazure.com. When you open up your event hub, you’ll see a link called “View Connection String”.

calling-the-azure-event-hub-rest-api-from-uwp-wpf-and-any-other-net-core-client_2

When you click the link, you find your connection strings (If you don’t see any, you need to configure SAS in your event hub). Now let’s copy one of these connection strings.

calling-the-azure-event-hub-rest-api-from-uwp-wpf-and-any-other-net-core-client_3

Let’s paste the connection string into the Event Hub Rest Client Generator and let’s specify a publisher name. Then the Generator will look like this:

calling-the-azure-event-hub-rest-api-from-uwp-wpf-and-any-other-net-core-client_4

As you can see, you get all the details, like for example the Shared Access Signature (of course including the HCMA SHA256 Hashvalue). You even get a generated sample class that is using the HttpClient to do REST-calls to your event hub. So you can just use that class to get started in your UWP-app to push events to Azure Event Hub via the REST-API.

The Event Hub Rest Client Generator is free, Open-Source and available on Github. Download the tool here:

https://github.com/thomasclaudiushuber/EventHub.RestClientGenerator/releases

Have fun and thanks for reading,

Thomas

Wow, Microsoft acquired Xamarin!

Xamarin_Blue_Logo

To develop mobile applications today you have many options

  • you can do it native in Swift/Objective C for iOS, in Java for Android or in C# for Windows Mobile
  • you can build a web-app with popular JavaScript-Frameworks like Angular and use Apache Cordova to deploy it to your devices
  • you can build it native in C# by using Xamarin

With the Xamarin-approach you can share your C# libraries between iOS, Android and C#. You can even build the User Interface just once with Xamarin Forms. And the great thing is what you finally get: A full native app for the corresponding platform.

Already last year at Microsoft’s Build conference I and many others expected that Microsoft might announce that they acquired Xamarin. But it didn’t happen. But today, Microsoft let cat out of the bag.

Microsoft acquired Xamarin

That’s great news for us developers. Think about the awesome integration we will have in Visual Studio to build mobile apps for all platforms. And I’m sure that the toolset – which is already today really awesome – will be enhanced and integrated very well. Read more details about the acquisition on Scott Gu’s blog:

https://weblogs.asp.net/scottgu/welcoming-the-xamarin-team-to-microsoft

Render just the first line of a TextBlock

Sometimes you want a TextBlock to just display one line. For example if you have a huge virtualized ListView that contains many data items and in the DataTemplate you’re using a TextBlock. When the TextBlock has different height, the virtualization leads to some not so nice behavior when scrolling:
The Thumb of the ScrollBar changes its size while scrolling, as the final extend size is not known, as the items in the ListView have different sizes because of multiple lines.

So when you have virtualization, you might want to display your multiline messages in a master-detail-way. Select a single-line-item in the ListView and display the multiline message somewhere else.

But now the problem is, how to tell the TextBlock to render just the first line? Note that I want to adjust the rendering. I don’t want to adjust the strings with a converter or whatever. Just the rendering! :-)

The TextBox has for the single-line-scenario a MaxLines-Property. But the TextBlock does not have this property.
The TextBlock also does not allow to override its MeasureOverride-method to measure the line height and do custom stuff, as this method is marked as sealed in the TextBlock class.

So how could you display only the first line of a TextBlock like this:

<TextBlock TextWrapping="NoWrap">
  Text with
    <LineBreak/>
  multiple
    <LineBreak/>
  lines
</TextBlock>

To render just the first line, I use a little trick. I place the TextBlock from above together with a hidden TextBlock with just one line in a Grid. Then I can bind the real TextBlock’s Height to the ActualHeight of the hidden one-line-TextBlock. Here the XAML-code, works like a charm.

<Grid>
  <TextBlock x:Name="txtOneLineDummy" 
             Text="One line" 
             Visibility="Hidden" 
             VerticalAlignment="Top"/>
  <TextBlock TextWrapping="NoWrap" 
             Height="{Binding ElementName=txtOneLineDummy,Path=ActualHeight}">
    Text with
      <LineBreak/>
    multiple
      <LineBreak/>
    lines
  </TextBlock>
</Grid>

Note that you could place the hidden one-liner-TextBlock also somewhere else, especially if you have thousands of records that would use a TextBlock via a DataTemplate

Creating a background application with WPF

Sometimes you need to have an application running in the background. Then you don’t want your MainWindow to be visible all the time. Instead you just want to have an icon in the notification area that allows the user to open up the MainWindow and to exit the application. In WPF you can do this easily with the help of Windows Forms’ NotifyIcon-class.

Just add references to System.Windows.Forms and System.Drawing to your WPF-project. Add also an icon-file (.ico) to your project resources. To do this just open the Resources.resx-file in the Properties-folder of your project. Select the Icon-resource and click the Add Resource button. I’ve named it MyIcon.

AddIconToResources

Then go to the App.xaml.cs and implement it like below. The trick is to never close the MainWindow, as a closed Window cannot be shown again. Instead cancel the closing and just hide it.

using System.ComponentModel;
using System.Windows;
 
namespace BackgroundApplication
{
 
    public partial class App : Application
    {
        private System.Windows.Forms.NotifyIcon _notifyIcon;
        private bool _isExit;
 
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            MainWindow = new MainWindow();
            MainWindow.Closing += MainWindow_Closing;
 
            _notifyIcon = new System.Windows.Forms.NotifyIcon();
            _notifyIcon.DoubleClick += (s, args) => ShowMainWindow();
            _notifyIcon.Icon = BackgroundApplication.Properties.Resources.MyIcon;
            _notifyIcon.Visible = true;
 
            CreateContextMenu();
        }
 
        private void CreateContextMenu()
        {
            _notifyIcon.ContextMenuStrip =
              new System.Windows.Forms.ContextMenuStrip();
            _notifyIcon.ContextMenuStrip.Items.Add("MainWindow...").Click += (s, e) => ShowMainWindow();
            _notifyIcon.ContextMenuStrip.Items.Add("Exit").Click += (s, e) => ExitApplication();
        }
 
        private void ExitApplication()
        {
            _isExit = true;
            MainWindow.Close();
            _notifyIcon.Dispose();
            _notifyIcon = null;
        }
 
        private void ShowMainWindow()
        {
            if (MainWindow.IsVisible)
            {
                if (MainWindow.WindowState == WindowState.Minimized)
                {
                    MainWindow.WindowState = WindowState.Normal;
                }
                MainWindow.Activate();
            }
            else
            {
                MainWindow.Show();
            }
        }
 
        private void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            if (!_isExit)
            {
                e.Cancel = true;
                MainWindow.Hide(); // A hidden window can be shown again, a closed one not
            }
        }
    }
}

Now go in addition to the App.xaml and remove the Startup-Uri, so that when you start the application, only the NotifyIcon is added to the notification area

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

Done

Download the sample-project here: Background application

The future of Windows Presentation Foundation (WPF) and what’s coming next

In 2006 I started working with the first preview versions of the Windows Presentation Foundation with my Trivadis fellow Christoph Pletz. We wrote 2007 the very first German article about MVVM and 2008 I published my first book with the title “Windows Presentation Foundation – the ultimate handbook”.

Since then the consultants of Trivadis and I did a ton of big WPF-projects for several customers. During the last year with the hype around AngularJS and HTML5 many customers asked about the future of WPF. Today I’m happy to announce that Microsoft respective the WPF Team shared their roadmap about that bright future. Find it here:

http://blogs.msdn.com/b/dotnet/archive/2014/11/12/the-roadmap-for-wpf.aspx

I’m very happy to see that Microsoft invested quite a lot of effort into performance-optimization for the next version. Also the Visual Diagnostics tools in the article with the Live Visual Tree and Live Property Explorer look quite promising. Below a screenshot taken from the article above:

VisualDiagnostics3

Even Blend has been completely redesigned and supports now differnt things like for example Solution Folders and better Source Control support.

With that next release of WPF I’ll for sure update my book about WPF and bring out a fourth edition next year.

Thomas

Microsoft TechDays 2013 Basel

Thanks to all who joined my sessions at TechDays in Basel. Also a big thanks to Microsoft Switzerland for organizing this great and successful event. I really enjoyed the two days of networking with awesome people.

Please find the slides and demos of my talks on my homepage by selecting the talk:

http://www.thomasclaudiushuber.com/talks.php

If you were not able to attend TechDays in Basel, you can just watch my talks here (they’re in German. Find other talks on on channel9):

 

Feel free to ask any questions about the topics by commenting here or just send me an email.

Thomas

Received Microsoft MVP award 2013

Wow, on 1st of July I’ve received my very first Microsoft MVP (Most Valuable Professional) award. I received it in the area “Client Development”.

MVP_FullColor_ForScreen

Thanks to all the people out there in the .NET/C#/XAML-community, thanks to all the readers of my books, articles and blog-posts, thanks to the participants of my public talks, thanks to the colleagues at Trivadis and thanks to Microsoft Switzerland for their great support. In the end I want to thank my family and all the friends and people supporting me in any technical and non-technical way. You’re awesome!

More about the MVP award you can read on
http://mvp.microsoft.com/

My personal MVP profile is here:
http://mvp.microsoft.com/en-us/mvp/Thomas%20Claudius%20Huber-5000162

Keep on codin’
Thomas

Dragging Elements in Windows Store Apps

In Windows Store Apps there are three kinds of Touch-Events:

  • Gesture Events – those are high-level-events like Tapped or RightTapped.
  • Pointer-Events – low-level-events like PointerPressed, PointerMoved, PointerReleased.
  • Manipulation-Events – low-level-events for multi-touch actions like rotate, scale or transform an element.

Pointer-Events consolidate Touch-, Pen- and Mouse-Input. So on the UIElement-class from WinRT you wont find Mouse-Events known from WPF/Silverlight like MouseLeftButtonDown.

In my upcoming Windows Store Apps I want to show how Elements can be dragged/moved with Pointer-Events. You can download the code of the sample here:

MovingElements, or in German ElementeVerschieben-Sample

The app looks like below. By touching an empty space in the yellow area, an Image is inserted. The image can be grabbed with a finger or with the mouse-cursor and moved around. The app works also with multiple fingers. You can grab multiple images at once and move them around.

MovingElementsWinRT

If you´ve feedback to the code, feel free to comment. Smiley 

As I´m really busy the next weeks/months with the writing of the Windows Store Apps-book, I´m not able to give you big support on the code. Use it or not.

Thomas

Windows Store-apps with XAML and C# – blog series

Since yesterday evening Winodws 8 RTM is out for developers. This blogpost is the start of a blog-series about developing Windows Store-apps with XAML and C#. The series consists of some informational and some “how-to” posts:

More topics will come. If you’ve topics not listed above you want to read about, write a comment on this post.

The first post about XAML will be written till saturday evening

Thomas

TechDays 2011 – Demos online

Thanks to all who attended in my session at TechDays 2011 in Basel. My Live-Demo is available via the link below.

TechDays Basel – LiveDemo – Download here

The .zip-File contains a .bak-File that you can restore via SQL Server Management Studio by chosing “Restore Database” from the contextmenu when right-clicking on “databases” in Object Explorer.