The Granite State Hacker

Microsoft.Graph and Appointment Management

It’s been a minute since I’ve felt like there was some content to share of a coding variety, and ironically, I don’t have a minute to do it. So without further ado, I’ll dig right in.

In the management of Granite State Code Camp, I devised a way to connect with all the folks who had ever been a part of one of the events I’ve hosted in Teams. I sent a calendar invite as a 1:1 meeting initiation from myself to each of all the guests in the tenant, using Graph.

This goes back to 2020, when Granite State Code Camp rode out the pandemic as an online-only event, hosted entirely in Teams. Having hosted both GSCC and the Manchester Community College’s New Hampshire CyberSecurity Symposium in the same tenant every year since, there’s a good number of guests in the tenant that all represent a decent targeted mailing list for such events.

In the meantime, while Microsoft has done a fantastic job of touting CoPilot for Visual Studio, I found that Copilot had no understanding of the latest Graph libraries. How ironic that the immense greatness of Copilot stumbles on the immense greatness of new library updates, but that’s something to explore in another post.

While the invitation automation code is messy, and not clean enough for publishing, I was then in a situation where I had a bunch of calendar invitations, and it was really hard to figure out who had accepted, who had declined, and who had ignored.

So, I wrote a console utility to find and filter all the invitations, so that I could then follow up appropriately. This code will eventually become the basis of a re-write for the invitation itself, because I like the updates to the Graph API (which I didn’t use in the part that sends the invitations). Anyway, here’s the GitHub hosted Gist including the project file that shows the package/versions I used to arrive here.

Welcome to the Virtual Assistant Template
Tech in the 603, The Granite State Hacker

Welcome to the Virtual Assistant Template

I can’t believe I haven’t blogged this out, yet. I’ve been building chatbots for clients for years now, and presenting to the tech community on the topic at least as long.

Welcome to the Virtual Assistant Template

For a while, I was doing “Bot in a Day” workshops, all over the country. Held at Microsoft Technology Centers in places like Boston, Reston, Philly… I just realized the last one I did was over a year ago, now, in Irvine, California.

The reason we don’t need to do the day long workshops anymore is because everything we did (and more!) in “Bot in a Day” can now be done reliably and repeatably in minutes… We do this using the latest iteration of the “Enterprise Template”, now known as the “Virtual Assistant Template”.

Ok, so the one-time setup can be a bit longer than an hour… but that’s (mostly) one time. If you are a C# dev, especially in the ASP.NET Core space, you probably have most of the tools installed already, anyway.

Anyway, I’ve been doing variations on this “Bot in an Hour” theme, using Virtual Assistant Template, all over New England, and will soon be taking it on the road to Washington DC, where I’ll be doing the shtick for Ignite the Tour in February 2020.

So the Virtual Assistant Template is a very quick way to build out some meaty bones of an enterprise-grade chat bot, especially in C# (though a TypeScript version is also available).

I won’t try to do what its own documentation does well, at this point. Rather, I’ll point you to that documentation.

What is the Virtual Assistant Template (Microsoft)

OSS GitHub Repo

Here’s my presentation slides from Boston Code Camp, which was on November 23rd, 2019. It’s more complete than the stripped down version I presented as a workshop at Global AI Bootcamp 2019 today (December 14th) at MIT.

In addition to the “Welcome to the Virtual Assistant Template” presentation for Ignite the Tour, I’ll be doing a similar presentation for Granite State NH .NET Devs on December 19th at the Microsoft Store in Salem, NH.

Tech in the 603, The Granite State Hacker

C# and WebAssembly

I’m honored to be able to post in Matt GrovesAnnual C# Advent again this year, and today… December 22nd, 2018, is my second year contributing to it.

Last year I talked about ways to unload the main UI thread in WPF/.NET apps.

This year, I want to call attention to the Uno Platform tools I’ve been evangelizing for the past six months or so. 

Silverlight is dead – Long Live Uno Platform!

To understand this perspective, we’ll need to walk through some key terms….

What is Silverlight?silverlight

For those who don’t know, about ten years ago, Silverlight was the way to write C# and XAML to run in the web browser. It required a plug-in to run, much like Adobe Flash Player. Unfortunately, Microsoft announced the…. untimely demise of Silverlight in 2012. Silverlight, to some extent, seemed a more catchy term than other related technology names, so Microsoft used Silverlight as the name for mobile platforms that are also now depricated. As a result, it became almost synonymous with XAML.

What is XAML?

XAML, “eXtensible Application Markup Language” is the markup language behind a few great UI / UX layers in various Microsoft .NET-oid languages.  For those who’ve used it, it’s an addictively cool language family.  Using Visual Studio, Blend, and Adobe DX, you can create first-class UI.  With features like Storyboard animation, basic animation becomes child’s play. Composition makes fast, dynamic animations easy. Once you’ve gotten the basic idea of it, one finds themselves wanting to use it anywhere they can…  or at least that’s been my experience through WPF, Silverlight, Silverlight for Windows Phone, Silverlight for Windows Phone 8 / 8.1, Universal Windows Platform (UWP) and probably others.

The “code behind” XAML is typically C#, and historically .NET based.

What is Universal Windows Platform (UWP)?

UWP is the native platform of Windows 10.  It’s similar to classic .NET in a few ways.  First, UWP feels a lot like Windows Presentation Foundation (WPF) and .NET, being XAML and C# based, respectively.  It differs from classic .NET because it has a lot of fixes, both in terms of security and performance, that .NET can’t afford to apply for various reasons.  More simply put, .NET had some serious technical debt built up, so the easiest way to forgive that debt was to build a new platform based on the old languages.  Your XAML and C# skills are the same, but the namespaces and supporting framework libraries are different.

Don’t fret, though…  UWP runs natively on over 800 million devices (as of today, December 22nd, 2018), and that number continues to grow.  UWP is the native platform for all Windows 10 devices.  This means desktops, laptops, tablets, phones, HoloLenses, Xbox consoles, IoT embedded devices, and more. 

What is WebAssembly?webassembly

WebAssembly is a relatively new bytecode language specification… a virtual machine specification, similar to the Java Virtual Machine (JVM), that is fully supported by most modern major web browsers.  It allows near native performance in the same sandbox that javascript apps run in.  When you run javascript in a web page, the jit compiler in the browser converts the code into tokenized bytecode in order to execute it quicker.  WebAssembly improves on this significantly by pre-compiling the code.  Because the code is pre-complied, it doesn’t have to be sourced from javascript.  It can be compiled from just about any programming language.  Wasm, as it’s called, went from a specification just a few short years ago to being well supported in all major modern web browsers.

What is Uno Platform?uno platform

Uno Platform, for our purposes, is not really a new platform, but an extension to UWP. 

You write your UWP application for your Windows 10 devices the same way you always have.  Uno provides a mechanism to re-compile that UWP app to Web Assembly (and… by the way… using Xamarin tools, also to iOS… and also to Android!)

In a sense, Uno Platform is to UWP as Xamarin is (roughly) to classic .NET.

See the connection? 

Let’s do some math…

UWP = C# & XAML for Windows 10.  (800,000,000 devices)

Uno Platform += UWP for iOS (Millions more devices), Android (over a Billion devices), and WebAssembly (every modern major PC in the world)

Now factor in this…

.NET Core 3 += UWP for services

What does all that add up to? 

One skill set… 

UWP (C# & XAML) = FULL STACK, on all major platforms

From data access layer to REST API to UI canvas.

Wait a minute…  What about Xamarin?

Xamarin is the older way to do C# for cross platform / mobile.  

Coincidentally, just this past Thursday, Carl Barton, a Microsoft MVP for Xamarin presented the Xamarin Forms Challenge at the Windows Platform App Devs users group. The goal of the meetup was to demonstrate creating a simple app in C# and running it on as many platforms as we could in the hour.  He easily pushed ran the app on over a dozen platforms in the hour.

Uno Platform actually depends on Xamarin libraries to support iOS and Android. 

The main differences between Xamarin and Uno Platform are these:

  • Xamarin encourages you to use a Xamarin-specific dialect of XAML, including Xamarin Forms to express your cross platform UI.
  • If you already know & understand Microsoft’s UWP dialect of XAML, Uno Platform uses that dialect.
  • Xamarin enables you to produce binaries for dozens of different target platforms, reaching a billion or more devices.  These include .NET, UWP, iOS, Android, Tizen, Unity, ASP.NET, and many others.
  • Uno Platform only enables you to reach three additional binary output targets…  iOS, Android, and WebAssembly…. but WebAssembly can or likely will soon cover most of what Xamarin Forms covers.

I’ll leave it up to you which to choose, but for me, given the choice between Xamarin with several years of technical debt built up in a distinct dialect of XAML, and Uno Platform, using the fresher, native UWP dialect of XAML…  

Finally… 

Here’s the slides I presented most recently at the New England Microsoft Developers meetup in Burlington, Mass on December 6th (thanks again to Mathieu Filion of nventive for much of the content):

[office src=”https://onedrive.live.com/embed?cid=90A564D76FC99F8F&resid=90A564D76FC99F8F%211297452&authkey=AM6QZrb_6-9ltdE&em=2″ width=”402″ height=”327″]

Tech in the 603, The Granite State Hacker

Intro to Uno Platform

Uno’s free.  Uno is open-source.  Uno could seriously be the next significant disruption in mobile development.

Apologies that I neglected to hit on the conference call for the introductions.  We did get the bulk of the presentation recorded.

On the call:  Jerome Laban, Architect, and Francois Tanguay, CEO of nventive of Montreal, Quebec, Canada. Participants of the Windows Platform App Devs (including myself) were in the audience, asking questions.

To make up for the intro missed in the call, let me begin with the elephant in the room…

What’s “wrong” with Xamarin?

The relatively well known Microsoft tool set called Xamarin enables developers to write a dialect of C# and Xaml to target a variety of platforms including Windows, Windows Mobile, iOS, Android, MacOS and others.

For that reason, Xamarin’s currently a top choice for mobile developers around the world. Xamarin enables developers to target billions of devices.

The problem Xamarin presents is that Xamarin has become its own distinct dialect of .NET-based development.  Xamarin has its own distinct presentation layer called Xamarin Forms. Xamarin Forms as an employee skill set is not the same as a classic Windows developer set.  It’s not exactly the same as a Windows 10 developer skill set.  It’s a different platform, and requires developers that understand it.

Uno Platform reduces the skillset burden in this problem by converging the main skill set on Windows 10 development. Developers with an appreciation for the future of Windows development will definitely appreciate Uno Platform.

Windows Universal Platform (UWP) targets ALL flavors of Windows 10, including some unexpected ones, like Xbox One, and IoT devices running Windows 10 IoT Core.

Uno bridges UWP to iOS, Android, Web Assembly (Wasm), on top of Windows 10. This targets a huge and rapidly growing range of devices… (currently approaching around 3 BILLION… and that might be a low estimate.)

I’d embed the video, but Blogger’s giving me a hard time with the iframe-based embed code… please click this

Link to the video:

Intro to Uno Platform Skype conference recording.

The meetup:
Granite State Windows Platform App Devs
https://www.meetup.com/Granite-State-NH-WPDev/events/251284215/

Uno Platform’s site:
http://platform.uno

Tech in the 603, The Granite State Hacker

Locking Resources in C# for Read/Write Concurrency

In a previous project, I became a big fan of System.Threading.ReaderWriterLockSlim.  It was an excellent way to guard a resource against concurrency in a relatively flexible manner.  

C# has a lock(object) {} syntax for simple concurrency locks, but what if you have a resource that can sometimes be used concurrently, and other times, exclusively?

Enter System.Threading.ReaderWriterLockSlim.  This has a few handy methods on it for guarding code on a non-exclusive (Read) and exclusive (Write) mode, with an upgradeable lock, as well, so you don’t have to release a read lock in order to upgrade it.

This source works just as well in .NET as UWP.

I commented the code enough to try to make it so that someone familiar with ReaderWriterLockSlim and using(IDisposable){} would understand the rest, so without further ado…

https://gist.github.com/GraniteStateHacker/e608eecce2cb3dba0dbf4363b00e941f.js

Tech in the 603, The Granite State Hacker

Unloading the UI Thread in C# on Windows 10 + UWP

First I want to thank Matthew Groves for hosting the 1st known C# Advent (English).  I was honored to be able to grab the spot for Friday, December 22, 2017, which, happily, is the start of my Christmas holiday week, as well.

The crux of this post is that most visible performance issues in a Windows application come from the presentation layer.  Specifically, anything that puts load or wait states on the main “UI Thread” will make the app/application appear to hang or become unresponsive for periods of time. This post talks about strategies for getting load off the UI as much as possible, beyond the async/await mechanism in C#.  Most such load can be unloaded to a worker thread fairly easily.  Other tasks can be awaited together. In some cases, a UI component is involved, and it becomes necessary to manage load that, for that reason, reason MUST stay on the UI thread.

I remember when I was a kid hearing of projects for stock traders that handled hundreds of data update events every second and being totally intimidated by the thought of it.  I knew I’d “come of age” in technology when, in 2017, I worked with a focused team (known as “Blockheads”) to build such an app.  This latest generation “stock blotter” ran stable, without memory leakage, and with no apparent lag at tens of Gigabytes per second! These general ideas stem back to the project I worked on in 2016-2017 with BlueMetal for Fidelity Investments’ Equity Trading team, called Artis OMT.  Artis OMT has been on Fidelity’s Equity Trading floor for over a year now, and will soon reach a year of full deployment.  While Artis OMT was WPF, this post looks at similar performance ideas in a similar but different platform:  Windows 10 UWP (store apps).

Artis OMT didn’t start out able to handle 90Gigabytes of incoming data.  We had to use JetBrains tools to identify code that was bogging down or hanging the main UI thread.   That analysis, alone, is perhaps the subject of a different post, or more, some day.

When folks start thinking about UI Thread execution, the first thing most think of is Dispatcher.BeginInvoke().  This method is how you add workload to the UI thread.  I’m trying to talk about how to UNLOAD the UI thread, and/or manage your load so that the user won’t observe UI freezes or lockups.

Here, however, are a few relatively easy ways to really make use of the extra cores in your CPU, and make your apps appear to perform much better:


Task.Run(() => { … });

Classic depiction of processes running in sequence vs in parallel


The title of this says it all, really.  Push a workload off the current thread.  Use whenever you have long running processes that you don’t have to touch UI controls from.   If you have timing dependencies, you can manage them with Task.When, Task,Wait, or even better, Task.ContinueWith().  Examples below cover this a little more.



Batch remote service calls using Tasks and WhenAll()

Service calls are low hanging fruit.  So often I see code that makes calls in series, waiting on the results of one before making the next call, even though the two calls have no dependencies on each other…  it’s just so much easier to write the sequence case that folks let it hang.   await Task.WhenAll(…) is not as syntactically sweet, but still MUCH sweeter than having to set up an aggregate event.

///

/// Does one request at a time, holding up the entire process
/// at each step until it completes. Simpler code but….
/// Total time spent is the sum of all tasks’ time.
///
public async void GetContentinSequence(Session session)
{
    var dbContent = awaitGetDatabaseContent(session);
    var webContent = await GetWebContent(session);
    var userProfile = await GetUserProfile(session);
    var userContext = await GetUserContext(session);
}


///

/// Executes all requests simultaneously, letting the default task dispatcher do its thing.
/// total time spent is no more than the longest running individual task, all other things being equal.
///
public async void GetContentinParallel(Session session)
{
    var contextTask = GetDatabaseContent(session);
    var webContentTask = GetWebContent(session);
    var userProfileTask = GetUserProfile(session);
    var userContextTask = GetUserProfile(session);
    var stuff = new Task[] { contextTask, webContentTask, userProfileTask, userContextTask };
    await Task.WhenAll(stuff);
    var dbContent = contextTask.Result;
    var webContent = webContentTask.Result;
    var userProfile = userProfileTask.Result;
    var userContext = userContextTask.Result;
}

Here’s an example that makes this more clear:

var start = DateTimeOffset.Now;

var task1 = Task.Run(async () => { awaitTask.Delay(1000); });
var task2 = Task.Run(async () => { awaitTask.Delay(1500); }); //1.5 seconds
var task3 = Task.Run(async () => { await Task.Delay(1000); });
var task4 = Task.Run(async () => { awaitTask.Delay(1000); });
var tasks = new Task[] { task1, task2, task3, task4 };
Task.WhenAll(tasks).ContinueWith(t => { Debug.WriteLine(DateTimeOffset.Now – start); });



outputs something like:
00:00:01.5623681

As always, there’s some overhead with task switching.  You’ll notice that the time was just a few ticks longer than 1.5 seconds.

What if you can’t unload the UI thread?  what if your long running process must interact with controls like a huge grid that needs to calculate an aggregation of a data set that lives in it?   
Here’s an option…


DoEvents() erhhh… ummm…  await Task.Delay(…)

I once scrubbed references to Visual Basic from my CV and landed a job that had scrubbed VB from the job description.  I didn’t want to work for a company that would hire a “VB-Weenie” and they didn’t want to hire a “VB-Weenie”, either… but there was VB6 work to do. 

One thing that VB6 had going for it was a concept called DoEvents().   It enabled you to give up processing the current method to allow any pending events to execute. It would then return to finish the calling method.

In C#, the closest equivalent, nowadays, is “await Task.Yield()” or await.Task.Delay(…).

Most folks talk about using “await Task.Yield()” at the start of an awaitable method to make sure the whole method runs asynchronously.  There’s some sense to that.   More importantly, one can interrupt long running processes that must run on the UI in order to allow the UI to respond to user inputs.  In testing, I’ve seen that Task.Yield() often doesn’t allow enough room for redraws of the UI.  Likewise, setting a Task.Delay of a 1 tick timespan isn’t enough, either.  1 millisecond delay, however, does seem to suffice in my basic testing.

private async void LongRunningAggregatorOnUIThread(object sender, object e)

{

    await Task.Yield();
    timer.Stop();
    var timeoutRate = TimeSpan.FromMilliseconds(100);

    
    var timeout = DateTimeOffset.Now.Add(timeoutRate);
    var value = 0L;
    while (true)
    {
        value++;
        if (DateTimeOffset.Now >= timeout)
        {
            textbox.Text = value.ToString();
            await Task.Delay(1);
            timeout = DateTimeOffset.Now.Add(timeoutRate);
        }
    };
}



As always, use this very carefully.  This has overhead of its own, as well, that can cause performance issues…. including potential deadlocks.

Tech in the 603, The Granite State Hacker

Windows 10 IoT Core, C# & Azure IoT Hub for New England Microsoft Developers 12/7/2017

Just wanted to say thanks for inviting me to reprise my Boston Code Camp 28 presentation for the group last night (12/7).   I enjoy talking about development anywhere in the Microsoft stack, and I love that Windows 10 IoT Core + Azure IoT Hub spans a good range of it.  I have a bunch of other topics I’d be happy to share, especially in the Windows 10 domain. Check through this blog, I have a post for each that shares slides, but I know the presentation’s a big part of the value of them.

These slides are really only a tweak of the BOSCC28 slides with the NEMD group title. [office src=”https://onedrive.live.com/embed?cid=90A564D76FC99F8F&resid=90A564D76FC99F8F%211283616&authkey=AH0Ai1kfUL_6WKE&em=2&wdAr=1.7777777777777776″]

Tech in the 603, The Granite State Hacker

UWP Equivalent for HttpUtility.ParseQueryString

Getting ready for my LUIS presentation at the Granite State Windows 10 Platform Devs Users Group (@WPDevNH), it made sense to demo LUIS using UWP rather than .NET classic.  (Join us, 11/16 at the Microsoft Store in Salem, NH…  https://www.meetup.com/Granite-State-NH-WPDev/events/243099117/ )

For a demo related to LUIS querying, I needed an alternative to System.Web.HttpUtility.ParseQueryString.  (based on this demo:  https://docs.microsoft.com/en-us/azure/cognitive-services/LUIS/luis-get-started-cs-get-intent )

I did a simple decorator of a Dictionary, adding a constructor to parse using WwwFormUrlDecoder, and overriding the ToString() to put it back together…

I whipped one up relatively quickly, but decided this would be a decent quick post.  Here’s my alt code:

usingSystem.Collections;
usingSystem.Collections.Generic;
using System.Net;
using System.Text;
usingWindows.Foundation;
namespaceLUIS_Examples
{
    public class ParseQueryString : IDictionary<string, string>
    {
        private IDictionary<string, string> _internalDictionary = new Dictionary<string, string>();
        public ParseQueryString(string queryString) :
            base()
        {
            var decoder = new WwwFormUrlDecoder(queryString);
            foreach (var item in decoder)
            {
                _internalDictionary.Add(item.Name, item.Value);
            }
        }
        public override string ToString()
        {
            var sb = new StringBuilder();
            foreach (var aPair in _internalDictionary)
            {
                sb.AppendFormat(“{0}={1}”, WebUtility.UrlEncode(aPair.Key), WebUtility.UrlEncode(aPair.Value));
            }
            return sb.ToString();
        }
        public string this[string key] { get => _internalDictionary[key]; set { _internalDictionary[key] = value; } }
        public ICollection<string> Keys => _internalDictionary.Keys;
        public ICollection<string> Values => _internalDictionary.Values;
        public int Count => _internalDictionary.Count;
        public bool IsReadOnly => _internalDictionary.IsReadOnly;
        public void Add(string key, string value)
        {
            _internalDictionary.Add(key, value);
        }
        public void Add(KeyValuePair<string, string> item)
        {
            _internalDictionary.Add(item);
        }
        public void Clear()
        {
            _internalDictionary.Clear();
        }
        public bool Contains(KeyValuePair<string, string> item)
        {
            return _internalDictionary.Contains(item);
        }
        public bool ContainsKey(string key)
        {
            return _internalDictionary.ContainsKey(key);
        }
        public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
        {
            _internalDictionary.CopyTo(array, arrayIndex);
        }
        public IEnumeratorstring, string>> GetEnumerator()
        {
            return _internalDictionary.GetEnumerator();
        }
        public bool Remove(string key)
        {
            return _internalDictionary.Remove(key);
        }
        public bool Remove(KeyValuePair<string, string> item)
        {
            return _internalDictionary.Remove(item);
        }
        public bool TryGetValue(string key, out string value)
        {
            return _internalDictionary.TryGetValue(key, out value);
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable)_internalDictionary).GetEnumerator();
        }
    }
}

Tech in the 603, The Granite State Hacker

UWP Community Toolkit in the Wild

On August 17th, I reviewed use of the UWP Community Toolkit in practical application, used in several privately published apps. These apps were commissioned by Hewlett Packard to illustrate commercial uses of the HP Elite X3 Windows 10 Mobile phone. We checked out the code behind these apps with permission from HP.

The apps themselves focus on three core verticals:
1) Public Safety – apps to support officers in the field
2) Field Service – supporting a cable field service technician
3) Home Health – supporting a visiting care provider.

All show off Windows 10 UWP as a versatile platform, capable of easily adapting to phone, tablet, or desktop, as well as the HP Elite X3’s additional ability to support various hardware expansion jackets and docking options.

The UWP Community Toolkit is an open source project designed to make Windows 10 the easiest platform to build great apps for. More information can be found here:

http://www.uwpcommunitytoolkit.com/

The official UWP CTK demo app is here:
http://aka.ms/uwptoolkitapp

The presentation itself was all demos, digging in on the CTK toolkit sample app, looking at it in a locally cloned git repo, and showing how we used the same controls in the X3 demo apps.

The UWP CTK is a great set of tools to jumpstart Windows 10 Dev with.  

Our next meeting on September 21st, (2017) we’ll take a look at another great “Hit the ground running” UWP resource, the App Samples.