Monthly Archives: January 2021

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