Vue Basics – Moving Objects Around the Screen

I’ve recently been playing around with Vue. One of the things that I typically do when I’m learning some kind of front-end technology, is to work out how I might write a game in that technology – that usually tests the boundaries of what you can do. If you’re interested, this is a car game that I created in React.

Let’s start by having a look at what a bog standard “Hello World” app looks like in Vue:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Testing Vue</title>
    </head>
    <body>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
        
        <div id="app">
            <h1>{{ title }}</h1>
        </div>
        <script>
            new Vue({
                el: '#app',
                data: {
                    title: 'Hello World'
                }
            });
        </script>        
    </body>
</html>

Another way that you can write that, would be like this:

<p v-text="testdata"></p>

This kind of synthax actually lets you bind any property, for example:

<h1 v-bind:title="testdata"></h1>

That’s pretty much the bit that I was looking for; if you can bind the title, then you can bind the style; for example:

<div v-bind:style="location">test</div>

Inside the data section, I can expose a location; for example:

new Vue({
    el: '#app',
    data: {
        testdata: 'some data',
        location: 'width: 500px; height: 100px; left: 20px;border: 1px solid #000; position: absolute;'
                    
    },

Okay, so now we’re binding the style to a piece of data, so can we now do something like this:

data: {
    testdata: 'some data',
    posx: 100,
    location: 'width: 500px; height: 100px; left:' + this.posx + 'px; border: 1px solid #000; position: absolute;'
},

Unfortunately (or perhaps fortunately, I haven’t decided yet) not. Anything that changes needs to be in a separate section, called computed:

data: {
    testdata: 'some data',
    posx: 100                    
},
computed: {                    
    location: function() {
        return 'width:500px; height:100px; left:' + this.posx + 'px; border:1px solid #000; position: absolute;';
    } 
},

We’re actually nearly there now; all that’s missing is the thing that actually updates the variable, and therefore moves the div across the screen. The next thing we come across is the mounted method – this is a lifecycle event for each component, so we’ll need that to initialise our timer; now we can do this:

methods: {
    init() {
        setInterval(this.moveObject, 10);
    },
    moveObject() {
        this.posx += 1;                        
    }
},
mounted() {
    this.init();
}

It’s not hugely exciting, I’ll grant you, but moving an object around a screen is the basis for any game. For completeness, here’s the full code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Testing Vue</title>
    </head>
    <body>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
        <div id="app">
            <h1>{{ testdata }}</h1>
            <p v-text="testdata"></p>
            <div v-bind:style="location">test</div>
        </div>
        <script>
            new Vue({
                el: '#app',
                data: {
                    testdata: 'some data',
                    posx: 100                    
                },
                computed: {                    
                    location: function() {
                        return 'width:500px;height:100px; left:' + this.posx + 'px;border:1px solid #000; position: absolute;';
                    } 
                },
                methods: {
                    init() {
                        setInterval(this.moveObject, 10);
                    },
                    moveObject() {
                        this.posx += 1;                        
                    }
                },
                mounted() {
                    this.init();
                }
            });
            
        </script>        
    </body>
</html>

References

Vue.js Tutorial From Scratch – e01 – Introduction, Installation & Outputting Data

Viewing Server Variables in Asp.Net Core

In Asp.Net Core, you can view a list of data known as Server Variables. These are available when hosting inside IIS, and they give information about the request call and security.

You can view any one of these by adding some middleware to your Asp.Net Core project:

    app.Use(async (context, next) =>
    {
        var url = context.Features.Get<IServerVariablesFeature>()["URL"];

        await next.Invoke();
    }

You’ll need to be hosting inside IIS, and the code should go in the routing zone.

There is also a helper method for this, meaning you can do this instead:

    app.Use(async (context, next) =>
    {
        string a = context.GetServerVariable("URL");

        await next.Invoke();
    }

I then thought, why not just enumerate all the variables. You can see the list here.

I created a list of these:

    public static class ServerVariables
    {
        public static string[] Variables = new[]
        {
            "UNENCODED_URL",
            "URL",
            "QUERY_STRING",
            "REMOTE_ADDR",
            "ALL_HTTP",
            "AUTH_USER",
            "AUTH_TYPE",
            "REMOTE_USER",
            "SERVER_ADDR",
            "LOCAL_ADDR",
            "SERVER_PROTOCOL",
            "ALL_RAW",
            "REMOTE_HOST",
            "SERVER_SOFTWARE",
            "HTTP_RAW",
            "HTTP_COOKIE"
        };
    }

And then, in the middleware, just looped through them:

            app.Use(async (context, next) =>
            {                
                await context.Response.WriteAsync("<div>");
                foreach (var variable in ServerVariables.Variables)
                {
                    string result = context.GetServerVariable(variable);
                    await context.Response.WriteAsync($"<p>{variable}:    <b>{result}</b></p><br />");
                }

                await context.Response.WriteAsync("</div>");
                await next.Invoke();
            });

Remember that if you run this hosted in Kestrel, you’ll get nothing back.

References

https://docs.microsoft.com/en-us/previous-versions/iis/6.0-sdk/ms524602(v=vs.90)

Azure Service Bus – Scheduled Message Delivery

Azure Service Bus sets itself apart from other message brokers by the dizzying array of additional and useful features that it provides out of the box. This particular one is really useful for things like scheduled e-mails. Let’s say, for example, that you’re an event organiser, and you want to notify people a few days before the event. This feature enables you to tell Service Bus to simply send a message at that time (you could have a simple Azure function that then picked up the message and sent an e-mail).

If you’re new to Service Bus, or using it with .Net, then start here.

NuGet

The basic NuGet package you’ll need is here:

Microsoft.Azure.ServiceBus

Reading the Service Bus Message

For the purpose of this post, we’ll just set-up a basic console application that sends and receives the message; let’s start with the read:

private static Task ReadMessageEvent(string connectionString)
{
    var queueClient = new QueueClient(connectionString, QUEUE_NAME);

    var messageHandlerOptions = new MessageHandlerOptions(ExceptionHandler);
    queueClient.RegisterMessageHandler(handleMessage, messageHandlerOptions);

    return Task.CompletedTask;
}

private static Task ExceptionHandler(ExceptionReceivedEventArgs arg)
{
    Console.WriteLine("Something bad happened!");
    return Task.CompletedTask;
}

private static Task handleMessage(Message message, CancellationToken cancellation)
{
    string messageBody = Encoding.UTF8.GetString(message.Body);
    Console.WriteLine("Message received: {0}", messageBody);

    return Task.CompletedTask;
}

There’s not much to say here – this event will simply print a message to the console when it’s received.

Schedule the Service Bus Message

Now that we’ve set up a method to receive the messages, let’s send one. You could add this to the same console app (obviously it would have to occur after the Read!)

var queueClient = new QueueClient(connectionString, QUEUE_NAME);

string messageBody = $"{DateTime.Now}: Happy New Year! ({Guid.NewGuid()}) You won't get this until {dateTime}";
var message = new Message(Encoding.UTF8.GetBytes(messageBody));

long sequenceNumber = await queueClient.ScheduleMessageAsync(message, dateTime);
//await queueClient.CancelScheduledMessageAsync(sequenceNumber);

await queueClient.CloseAsync();

dateTime is simply the time that you wish to send the message; for example:

var dateTime = DateTime.UtcNow.AddSeconds(10)

Will send the message in 10 seconds.

The commented line above will then cancel the message from being sent – you only need to provide the sequence number (which you get from setting up the schedule in the first place).

References and A GitHub Example

For a working sample of this, please see here.

https://stackoverflow.com/questions/60437666/how-to-defer-a-azure-service-bus-message

Add certificate into WSL

I’ve recently been playing with WSL2, and one of the things that quickly bites you, is trying to move between your Linux distribution, and the main Windows system. In this particular instance, I had a certificate that I needed to apply to the WSL system.

The process turns out to be as follows

Copy cert to /usr/local/share/ca-certificates

For example, say your certificate was here:

c:\tmp\mycert.cer

You can copy this inside the WSL:

cp /mnt/c/tmp/mycert.cer /usr/local/share/ca-certificates

Once you’ve copied it here, run the update-ca-certificates command:

sudo update-ca-certificates

If it works, your certificate will be here:

/etc/ssl/certs

Notes

This was done on an Ubuntu distribution, but I’m not aware it would change based on that.

References

https://github.com/microsoft/WSL/issues/3161

Receiving Messages in Azure Service Bus

In this post I covered the basics of setting up a queue and sending a message to it. Here, I’m going to cover the options around receiving that message.

Essentially, there are two possibilities here: you can either set-up an event listener, or you can poll the queue directly, and receive the messages one at a time.

Option 1 – Events

The events option seems to be the one that Microsoft now prefer – essentially, you register a handler and then as the messages come in, you simply handle them inside an event. The code here looks something like this:

            var queueClient = new QueueClient(connectionString, "test-queue");

            var messageHandlerOptions = new MessageHandlerOptions(ExceptionHandler);
            queueClient.RegisterMessageHandler(handleMessage, messageHandlerOptions);

The event handlers:

        private static Task ExceptionHandler(ExceptionReceivedEventArgs arg)
        {
            Console.WriteLine("Something bad happened!");
            return Task.CompletedTask;
        }

        private static Task handleMessage(Message message, CancellationToken cancellation)
        {
            string messageBody = Encoding.UTF8.GetString(message.Body);
            Console.WriteLine("Message received: {0}", messageBody);

            return Task.CompletedTask;
        }

Option 2 – Polling

With this option, you simply ask for a message. You’ll need to use the approach for things like deferred messages (which I hope to cover in a future post):

            var messageReceiver = new MessageReceiver(connectionString, "test-queue", ReceiveMode.ReceiveAndDelete);            
            var message = await messageReceiver.ReceiveAsync();

            string messageBody = Encoding.UTF8.GetString(message.Body);            
            Console.WriteLine("Message received: {0}", messageBody);

Option 3 – Option 1, but cruelly force it into option 2

I thought I’d include this, although I would strongly advise against using it in most cases. If you wish, you can register an event, but force the event into a procedural call, so that you can await it finishing. You can do this by using the TaskCompletionSource. First, declare a TaskCompletionSource in your code (somewhere accessible):

private static TaskCompletionSource<bool> _taskCompletionSource;

Then, in handleMessage (see above), when you’ve received the message you want, set the result:

            if (message.CorrelationId == correlationId)
            {
                await client.CompleteAsync(message.SystemProperties.LockToken);

                _taskCompletionSource.SetResult(true);
            }

Finally, after you’ve registered the message handler, just await this task:

queueClient.RegisterMessageHandler(
                (message, cancellationToken) => handleMessage(correlationId, queueClient, message, cancellationToken), 
                messageHandlerOptions);

await _taskCompletionSource.Task;

References

Advanced Features with Azure Service Bus

Partial HTML

In Asp.Net Core server-side rendered HTML, you have the ability to use something called Partial Views. Essentially, these give you the ability to separate your View into, what some JS frameworks may call, components.

The way it works is incredibly simple. In your main page, you define some HTML, and reference the partial view – like so:

<div class="text-center">
    <div>
        <p>Merry Christmas - here's my partial view:</p>
    </div>
    <div>
        @await Html.PartialAsync("_MyPartial", Model.MyData)
    </div>
</div>

In your partial view, which is simply another cshtml file, you define the HTML fragment, along with the model; for example:

@model IEnumerable<MyDataType>

@foreach (var item in Model)
{
    <p>item.Data</p>
    <br />
}

References

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-5.0

Using Managed Identity With Azure KeyVault

One of the things that’s always irked me about Azure KeyVault is that, whilst it may indeed be a super secure store of information, ultimately, you need some way to access it – which means that you’ve essentially moved the security problem, rather than solved it.

However, after speaking to a colleague at work, I’ve been playing with the concept of using a Managed Identity for authentication. This does go some way to alleviate my concerns for interactive security. To be clear, my concerns are less that the system is less secure, but that because you’ve simply moved the keys to the castle, that you’re just not getting sufficient benefit for the added complexity.

Anyway, this post covers using Managed Identity to authenticate KeyVault locally with Visual Studio.

Install the config package

The first step is to install the NuGet package. This post is based on .Net Core 3.1; however, I believe that it’s the same for 5.0.

Install-Package Microsoft.Extensions.Configuration.AzureKeyVault

Change the CreateHostBuilder

In Program.cs, edit CreateHostBuilder:

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var configRoot = config.Build();

                    config.AddUserSecrets<Program>();

                    var azureServiceTokenProvider = new AzureServiceTokenProvider();
                    var keyVaultClient = new KeyVaultClient(
                        new KeyVaultClient.AuthenticationCallback(
                            azureServiceTokenProvider.KeyVaultTokenCallback));

                    config.AddAzureKeyVault(
                        $"https://{configRoot["KeyVaultName"]}.vault.azure.net/",
                        keyVaultClient,
                        new DefaultKeyVaultSecretManager());
                });

You’ll need to add the key vault name either in your appsettings.json, or you could keep it in a secrets file (although I don’t see why you would want to hide this). For example:

  "KeyVaultName": "my-keyvault"

Visual Studio Credentials

Finally, set your local credentials in Visual Studio:

Now you can simply read from the config, and it will pull the value from the KeyVault where it needs to:

myValue = Configuration.GetValue<string>("key-vault-secret");

References

https://docs.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-5.0

Sending a Service Bus Message Failed

While playing around with Azure Service Bus in .Net Core, I came across this error, and it had me stumped for a while:

Microsoft.Azure.ServiceBus.UnauthorizedException: ‘Put token failed. status-code: 401, status-description: InvalidSignature: The token has an invalid signature..’

Having had a look on the internet, everyone seemed to be of the opinion that such errors were caused by an invalid connection string. I checked my connection string a number of times and it seemed correct.

However, the sentiment is, in fact, the correct one. The actual cause of this was that I was using the connection string from a specific queue, while trying to connect to a topic. I’d copied the queue connection code, and for some reason, the connection string being different didn’t twig with me. Connection strings work in a hierarchical fashion. For example:

You can use the connection string from a namespace for all the queues and topics within that namespace; but you can only use the connection string for a queue only for that queue.

Add Configuration to a .Net Core Console Application

This is another of those blog posts that’s probably been done before, but I keep having to collate a few pieces of information.

What we’re going to do here is create a .Net Core Console application, that reads an appsettings.json file, and a local secrets file. I covered some of this in an earlier post around creating a test harness in a .Net Core application.

If you’re using the console, then start with a new console app:

dotnet new console

We’ll need a few NuGet packages, too:

Install-Package Microsoft.Extensions.Configuration
Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Configuration.UserSecrets

Wherever you’re reading the config, add the following snippet:

IConfiguration configuration = new ConfigurationBuilder()
               .AddJsonFile("appsettings.json", true, true)       
               .AddUserSecrets<Program>()
               .Build();

Since you’re bog standard console app doesn’t have an appsettings.json, you’ll need to add that; make sure you set the build action to “Copy if newer”:

And that’s it. To access the config, you can simply call:

Configuration.GetSection

If you wish to use GetValue then you’ll need the following package:

Install-Package microsoft.Extensions.Configuration.Binder

For example:

string connectionString = configuration.GetValue<string>("ServiceBusConnectionString");

References

https://www.twilio.com/blog/2018/05/user-secrets-in-a-net-core-console-app.html

Handling Events Inside an Azure Function

While writing an Azure function, I established a simple repository pattern using the standard IoC for Functions.

However, when I ran the project up, I started getting the following error:

System.ObjectDisposedException: ‘Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

Odd!

This was very unexpected. The path of code that led to this was a very basic Add, so I was confident that the object had not been intentionally disposed.

If a write caused this, then what about a read?

I tried reading from the context at the same point, and saw the same effect. Finally, I injected the DB Context into the function itself and called it from the first line of the function call, and it worked fine.

In fact, the issue was that I was trying to read from an Azure Service Bus here:

var client = new QueueClient(connectionStringBuilder, ReceiveMode.PeekLock); 
client.RegisterMessageHandler(handler, new MessageHandlerOptions(onException));

Before we continue, I realise that someone reading this will probably announce loudly: “You’re doing it wrong! You should use the Function Binding to read from a Service Bus Queue!” To that person, I reply loudly, and proudly: “Yes, you’re right – I’m doing it wrong!”

Back to the story. So, after I left, I saw … oops – wrong story.

The issue here is that the event is losing the context of the function, because the function can complete before the event fires.

However, it seems that I have solved this problem before. To fix this, you can simply use a TaskCompletionSource to set something up similar to the following:

private static TaskCompletionSource<bool> _tcs;

[FunctionName("MyFunction")]
public async Task Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer)
{
    _tcs = new TaskCompletionSource<bool>();

    var client = new QueueClient(connectionStringBuilder, ReceiveMode.PeekLock); 

    client.RegisterMessageHandler(handler, new MessageHandlerOptions(onException));

    await _tcs.Task;
}

private Task handler(Message message, CancellationToken cancellationToken)
{            
    _myService.AddData(someData);

    _tcs.SetResult(true);

    . . . 
}

Summary

As stated, if your problem is that you’re trying to use the service bus client, then you are probably doing it wrong. It’s something of a shame that the new Service Bus SDK doesn’t support a GetNextMessage() style syntax, but it doesn’t, and so you get forced into the Function Bindings (not that I have any specific issue with them).

However, there are many reasons why you may need or choose to use an event inside a function, and if you do, this is one possible way to do so.

It’s worth pointing out that the above solution will only work for the first call of the event. If you have multiple calls then you’ll need to somehow determine when the last one has occurred.

References

https://www.pmichaels.net/2020/09/19/creating-and-using-an-azure-service-bus-in-net-core/