Click or drag to resize
Page 4: Create a Local Copy of the Provider Database
Run Tiny Ember+
Create the Project
  1. Start Visual Studio 2015.

  2. Create a new Console Application project that uses the .NET Framework 4.5.

  3. Add references to Lawo and Lawo.EmberPlusSharp, see Page 1: Prerequisites.

Using Declarations

Replace the default using declarations with the following:

C#
using System;
using System.Linq;
using System.Net.Sockets;
using System.Threading.Tasks;

using Microsoft.VisualStudio.TestTools.UnitTesting;
using S101;
using Threading.Tasks;
TCP Connection and S101

Before we can retrieve data from the provider we first need to create a connection and then establish the S101 protocol. Since these first steps will be mostly the same whenever we'd like to connect to a provider, we'll put them into a handy method:

C#
private static async Task<S101Client> ConnectAsync(string host, int port)
{
    // Create TCP connection
    var tcpClient = new TcpClient();
    await tcpClient.ConnectAsync(host, port);

    // Establish S101 protocol
    // S101 provides message packaging, CRC integrity checks and a keep-alive mechanism.
    var stream = tcpClient.GetStream();
    return new S101Client(tcpClient, stream.ReadAsync, stream.WriteAsync);
}
Root Class

Next, we need to create a new nested class, an object of which will henceforth represent the root of our local copy of the provider database.

C#
// Note that the most-derived subtype MyRoot needs to be passed to the generic base class.
private sealed class MyRoot : DynamicRoot<MyRoot>
{
}
Note Note

The library requires the creation of such a class for the fully dynamic use case although it isn't technically necessary. We will go into the rationale for this later.

Main Method

We can now connect to any provider with the following code:

C#
private static void Main()
{
    // This is necessary so that we can execute async code in a console application.
    AsyncPump.Run(
        async () =>
        {
            // Establish S101 protocol
            using (S101Client client = await ConnectAsync("localhost", 9000))

            // Retrieve *all* elements in the provider database and store them in a local copy
            using (Consumer<MyRoot> consumer = await Consumer<MyRoot>.CreateAsync(client))
            {
                // Get the root of the local database.
                INode root = consumer.Root;

                // For now just output the number of direct children under the root node.
                Console.WriteLine(root.Children.Count);
            }
        });
}
Note Note

The call to AsyncPumpRun(FuncTask) is only necessary because there is no direct support for async methods in a Console Application. In GUI applications (e.g. Windows Forms, WPF, Windows Store) the async methods are typically called directly from an async void event handler.

Proceed to Page 5: Iterate over the Local Database.