An Overview of Structured Logging with Serilog

Traditional logging techniques (such as writing lines of text to files) results in the loss of structure and semantics.

Structured logging enables richer, more semantic, structured log data to be created. But more importantly queried.

Serilog is an open source logging library that facilitates this structured logging.

Serilog can be used in the traditional way, for example writing to files, but it is designed to allow capture of structured data.

There are multiple provided “sinks” that route log data to a store; from unstructured data stores such as text files (single and rolling) to structured stores such as RavenDB. Multiple sinks can be configured so the same log event is written to both stores.

Writing to multiple sinks with Serilog

To create structured data, the logging code looks slightly different from traditional (unstructured) logging code. Once the logger is configured, to log an information level event we could write something like the following:

Log.Information("Log in succeeded for {UserId}. Authentication service took {LogInMilliseconds}.", userId, responseTime);

Here, a log event is being written that contains two pieces of structured, sematic data: UserId and LogInMilliseconds. If this message is written to an unstructured source (such as text file) then a simple string will be written. If a structured sink is used then the individual data items will be stored as well.

This means that this structured information can be richly queried, for example queries such as: “show me all the logins for user 42 where the login time exceeded 200ms” or “show me all the logins that took more than 1000ms”.

Check out the Serilog site for more info or my Modern Structured Logging With Serilog and Seq Pluralsight course.

You can start watching with a Pluralsight free trial.

SHARE:

Reducing MVVM Light Viewmodel Code with Fody Property Dependencies and Custom Property Changed Methods

In other previous articles I’ve written about Fody and this article we’ll see how we can use the PropertyChanged.Fody addin with MVVM Light viewmodels.

Windows Store app screenshot

The preceding screenshot shows the app in action: a name TextBox is twoway data-bound to the viewmodel, when a different name is typed, the TextBlock shows the uppercase version.

The user can also type a color into the color box and a bit of reflection happens to convert this string to a color from the Colors class.

Windows Store app screenshot with different bg color

The following code shows the (non Fody-fied) viewmodel:

More...

SHARE:

Using the Xbox Music API in Universal Windows Apps

The Xbox Music API can be used by third party developers (i.e. you and me) to search for artists, songs, albums, etc and also get access to actually play songs.

There are two flavours at present: “unauthenticated” and “authenticated”.

Authenticated access allow playing of full songs and working with user playlists. Playlist changes will automatically roam to user’s other devices. The full access to play full songs requires that the user has an Xbox Music Pass.

Unauthenticated access doesn’t allow access to user playlists, and streaming of music is restrict to 30 second previews.

At present anyone can get unauthenticated access via the Xbox Music RESTful API on Azure Marketplace. Authenticated access is currently limited, you need to apply for the pilot program. I’ve applied for this, hopefully I’ll be accepted so I can understand this part better.

Getting Started with Unauthenticated Access

We need an access key to allow our apps to able to use the (unauthenticated) API. To do this follow these instructions to register and create an application in Azure Marketplace. Don’t worry about the code samples at the bottom of the post, there’s a client API we can use instead.

So now you should have an application registered (you might have to enter some web address in the redirect URI – I’m not sure what this is for at this point).

More...

SHARE:

Consuming Server-Side SignalR Events in Universal Windows App Clients

In a previous article I wrote about creating server side SignalR timer events.

As part of my learning of SignalR I wanted to see how easy it would be to create a Universal Windows app consuming these server side events.

So first off I created a new blank Universal app:

creating universal app in Visual Studio screenshot

 

Next installed the SignalR NuGet package into both app projects: install-package Microsoft.AspNet.SignalR.Client

In the Windows 8.1 Store app project XAML I added a simple bound TextBlock that will display the server messages:

<Page
    x:Class="UpTimeUni.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UpTimeUni"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Viewbox>
            <TextBlock Text="{Binding Uptime}">please wait...</TextBlock>
        </Viewbox>
    </Grid>
</Page>

I also added similar XAML in the Windows Phone 8.1 main page.

More...

SHARE:

Using Server Side Timers and SignalR in ASP.NET MVC Applications

I thought it would be fun to create an “Internet uptime” page that you can see live here on Azure Websites. It shows how long the Internet (since ARPANET) has been around for.

image

Creating a Class that can be Managed by ASP.NET

The HostingEnvironment.RegisterObject method can be used to register an instance of an object that has its lifetime managed by the hosting environment.

To register an object it must implement the IRegisteredObject interface.

This interface defines a Stop method which gets called when ASP.NET needs to shutdown the app domain.

So, in the application start we can create an instance of our class and register it:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);

    HostingEnvironment.RegisterObject(new BackgroundUptimeServerTimer());
}

Creating a SignalR Hub to Send Messages from the Server to Client

Next we create a SignalR hub and the HTML.

So the hub class is called UptimeHub:

public class UptimeHub : Hub
{
}

We can get the server to call a client JavaScript method called “internetUpTime” in the HTML page and have this client code display the what’s been sent from the server timer.

The following shows the complete HTML for the page. Notice the “hub.client.internetUpTime = function (time) …” this function will get executed every time our server timer event fires.

More...

SHARE:

Vertically Center Div in Browser Window using Viewport-Relative Lengths

I found out about these units this week so I wanted to have a play with them.

The CSS units: vw, vh, vmin, and vmax allow sizes to be specified relative the the browser window size (or the “initial containing block”).

So 1 vw is equal to 1% of the viewport width and 1 vh is equal to 1% of the viewport height.

vmin and vmax return the smaller and larger respectively of vw or vh.

There is good support  for vw and vh in modern browsers with some partial support for vmax, overall about 55% of browsers offer full support, 20% partial support.

So for example to center a div vertically in the browser we could set its height to “50vh”  (50% of the viewport height) and set its top margin to be “25vh” (or a quarter of the viewport height), thus leaving a quarter below the div.

So here’s a screenshot of this in action in a tiny browser window (the white is the div):

image

And after resizing the browser:

More...

SHARE:

On Staying Positive and Subconscious Prejudices

So I was toying with an idea using SignalR on Azure.

In the client code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Internet Uptime</title>
</head>
<body>   
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
    <script src="/signalr/hubs"></script>
        
    <script>
        $(function () {
            var hub = $.connection.uptimeHub;            

            $.connection.hub.start();           

            hub.client.internetUpTime = function (time) {
                $('body').text(time);
                
            };           
        });
    </script>    
</body>
</html>

So when the server sends  an “internetUpTime” message, the <body> is being set to the content of the string sent from the server.

More...

SHARE:

Say Goodbye to Boring INotifyPropertyChanged Implementation in Universal Windows Apps with Fody

We need to implement INotifyPropertyChanged to allow bindings to be updated. For example in a simple viewmodel to add 2 numbers:

namespace UniFodyDemo
{    
    internal class CalculatorViewModel : INotifyPropertyChanged
    {
        private ICommand _addCommand;
        private string _firstNumber;
        private string _secondNumber;

        public CalculatorViewModel()
        {
            FirstNumber = "5";
            SecondNumber = "10";
            Result = "";

            AddCommand = new RelayCommand(Add);
        }


        // Use strings to simplify demo code (so no val converter)
        public string FirstNumber
        {
            get { return _firstNumber; }
            set
            {
                _firstNumber = value;
                OnPropertyChanged();
            }
        }

        public string SecondNumber
        {
            get { return _secondNumber; }
            set
            {
                _secondNumber = value;
                OnPropertyChanged();
            }
        }

        public string Result { get; set; }

        public ICommand AddCommand
        {
            get { return _addCommand; }
            private set
            {
                _addCommand = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void Add(object obj)
        {
            var a = int.Parse(FirstNumber);
            var b = int.Parse(SecondNumber);

            Result = (a + b).ToString();
        }

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

There’s more code here than we’d need if we didn’t have to implement INotifyPropertyChanged. Really the important things are the 3 properties that we bind to and the add command / method.

The XAML in both the Windows Store app and Windows Phone app looks like:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel Width="200">
        <TextBlock Text="{Binding FirstNumber, Mode=TwoWay}"></TextBlock>
        <TextBlock Text="{Binding SecondNumber, Mode=TwoWay}"></TextBlock>
        <Button Command="{Binding AddCommand}">Add</Button>
        <TextBlock Text="{Binding Result, Mode=TwoWay}"></TextBlock>
    </StackPanel>
</Grid>

Without implementing INotifyProperty changed, clicking the Add button won’t be of much use, we wont see the result.

The solution looks like the following, the shared project contains the viewmodel.

image

It would be great not have to write this same INotifyProperty stuff for everything we want to bind to/from. Using a NuGet package called PropertyChanged.Fody we can achieve this.

First this package needs to be installed into both the Windows Store and Windows Phone app projects. This is because the shared code in the viewmodel isn’t compiled in that shared project, rather the source code is compiled individually in both the Store/Phone projects.

Now the viewmodel can be simplified:

namespace UniFodyDemo
{
    [ImplementPropertyChanged]
    class CalculatorViewModel
    {
        public CalculatorViewModel()
        {
            FirstNumber = "5";
            SecondNumber = "10";
            Result = "";

            AddCommand = new RelayCommand(Add);
        }

        private void Add(object obj)
        {
            var a = int.Parse(FirstNumber);
            var b = int.Parse(SecondNumber);

            Result = (a + b).ToString();
        }
        

        // Use strings to simplify demo code (so no val converter)
        public string FirstNumber { get; set; }
        public string SecondNumber { get; set; }
        public string Result { get; set; }

        public ICommand AddCommand { get; private set; }
    }
}

Notice the [ImplementPropertyChanged] attribute which means INotifyPropertyChanged will be automatically implemented for us. Notice that it’s much easier to see what’s essential in the viewmodel without all the noise of INotifyPropertyChanged.

If we decompile the Windows store app we can see the implementation:

namespace UniFodyDemo
{
    internal class CalculatorViewModel : INotifyPropertyChanged
    {
        public ICommand AddCommand
        {
            get
            {
                return this.u003cAddCommandu003ek__BackingField;
            }
            private set
            {
                if (this.u003cAddCommandu003ek__BackingField == value)
                {
                    return;
                }
                this.u003cAddCommandu003ek__BackingField = value;
                this.OnPropertyChanged("AddCommand");
            }
        }

        public string FirstNumber
        {
            get
            {
                return this.u003cFirstNumberu003ek__BackingField;
            }
            set
            {
                if (String.Equals(this.u003cFirstNumberu003ek__BackingField, value, 4))
                {
                    return;
                }
                this.u003cFirstNumberu003ek__BackingField = value;
                this.OnPropertyChanged("FirstNumber");
            }
        }

        public string Result
        {
            get
            {
                return this.u003cResultu003ek__BackingField;
            }
            set
            {
                if (String.Equals(this.u003cResultu003ek__BackingField, value, 4))
                {
                    return;
                }
                this.u003cResultu003ek__BackingField = value;
                this.OnPropertyChanged("Result");
            }
        }

        public string SecondNumber
        {
            get
            {
                return this.u003cSecondNumberu003ek__BackingField;
            }
            set
            {
                if (String.Equals(this.u003cSecondNumberu003ek__BackingField, value, 4))
                {
                    return;
                }
                this.u003cSecondNumberu003ek__BackingField = value;
                this.OnPropertyChanged("SecondNumber");
            }
        }

        public CalculatorViewModel()
        {
            this.FirstNumber = "5";
            this.SecondNumber = "10";
            this.Result = "";
            this.AddCommand = new RelayCommand(new Action<object>(this, CalculatorViewModel.Add));
        }

        private void Add(object obj)
        {
            int num = Int32.Parse(this.FirstNumber);
            int num1 = Int32.Parse(this.SecondNumber);
            this.Result = (num + num1).ToString();
        }

        public virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged;
            if (propertyChangedEventHandler != null)
            {
                propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

So not only with Universal projects can we share code via the shared code project, adding Fody into the mix is even more awesome.

For a list of available addins or to contribute (or even create your own addin) check out the GitHub project site.

Also to learn more about Fody feel free to check out my Pluralsight course.

You can start watching with a Pluralsight free trial.

SHARE:

FeatureToggle 2.2Released

Release 2.2 of FeatureToggle is now available via NuGet.

This release adds a single new toggle: HttpJsonFeatureToggle.

This toggle gets it's enabled state from a JSON HTTP endpoint.

Configuration should be the url where the JSON configuration lives, e.g:

<add key="FeatureToggle.HttpJsonTrueToggle" value="http://localhost:8084/api/test/getenabled" />

As with all the toggles, if url is not available then an exception will be raised, rather than assuming either enabled or disabled.

The expected JSON that should be returned is in the form:  {"enabled": true} or  {"enabled": false}

Documentation here.

I’m thinking the next major release will be Version 3, planned changes here.

SHARE: