Last updated: 2019-03-19

Hello World Log Event sample (C#)

This page describes how to create a Log Event from scratch using Visual Studio and C#.

If you want to get started even faster, then download the FileWriterSample that you should use together with the Pickup Service

graph LR roProject(1. Create new Project)-->roNuGet(2. Add NuGet reference) roNuGet --> roCustomCode(3. Set Log Event Properties)

Step 1: Create a new Visual Studio Project

Using any Visual Studio version create a new Project (we recommend that you create a library so you can reuse the code in a reusable component)
Create New Project
Create New Project

Make sure to select .NET Framework 4.5 or later

Step 2: Manage NuGet package for the LogAPI

Now, You need to tell Visual Studio NuGet Package manager where to look for NuGet packages.

  1. From the Tools menu | NuGet Package Manager | Package Manager Settings...
    NuGet Package Manager Settings

  2. Add a new named entry with the following properties

    1. Name - Nodinite Public Packages (or whatever you would like to call our package source)
    2. Source - https://packages.nodinite.com/nuget
      Nodinite Package source
  3. From within your project add a NuGet reference by right clicking on the project/solution and select Manage NuGet Packages...
    Add NuGet package reference

  4. Add a NuGet Reference to IM.Libraries.Contracts.RestApi
    IM.Libraries.Contracts.RestApi

If you are using Nodinite, make sure to use 5.x version or later and if you are using Nodinite use 4.x version

Step 3: Add custom code

We will now create the Log Event

The Log Event has three distinct parts:

  1. Event details
  2. Payload
  3. Context properties
graph TD subgraph Log Event subgraph 1. Details roED[fal:fa-bolt Event Details
LogDateTime = 2018-05-03 13:37:00+02:00
EndPointName = https://api.nodinite.com/...
MessageType=Invoice
...] end subgraph 2. Payload ro[fal:fa-envelope Message
Body=base64EncodedMessage] end subgraph 3. Context Properties roKey[fal:fa-key Key Values
InvoiceNo = 123
CorrelationId=456
...] end end

Now in Visual Studio, type LogEvent and add the appropriate using statement by pressing CTRL key followed by the . (dot) key.
TypeLogEvent

In the top of your .cs file the following using statement should now exist:

using IM.Libraries.Contracts.RestApi.Log;

Using Statement for the Log Event

Create the LogEvent

Now lets create a method that creates and returns the LogEvent

private LogEvent CreateNodiniteLogEvent()
{
    return new LogEvent()
    {                
    };
}

Mandatory fields

There are some mandatory fields that you must provide. These are further documented in the JSON Log Event user guide.


// Required values 
LogAgentValueId = 42,
EndPointName = "INT101: Receive Hello World Log Events",
EndPointUri = "C:\\temp\\in",
EndPointDirection = 0,
EndPointTypeId = LogEventEndPointType.File,
OriginalMessageTypeName = "Hello.World.File/1.0",
LogDateTime = DateTime.UtcNow

Optional Fields example

Below is a fully populated Log Event example

// Required values 
LogAgentValueId = 42,
EndPointName = "INT101: Receive Hello World Log Events",
EndPointUri = "C:\\temp\\in",
EndPointDirection = 0,
EndPointTypeId = LogEventEndPointType.File,
OriginalMessageTypeName = "Hello.World.File/1.0",
LogDateTime = DateTime.UtcNow,

// Optional values
EventDirection = LogEventEventDirection.ExternalIncoming,
ProcessingUser = "DOMAIN\\user",
SequenceNo = 0,
EventNumber = 0,
LogText = "File OK",
ApplicationInterchangeId = "",
LocalInterchangeId = null,
LogStatus = 0,
ProcessName = "My Process",
ProcessingMachineName = "localhost",
ProcessingModuleName = "INT101-HelloWorld-Application",
ProcessingModuleType = "FilePickup",
ServiceInstanceActivityId = null,
ProcessingTime = 80,

// Add Body (payload)
Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { orderid = "123", name = "John Doe" })),

// Add arbitrary Context
Context = new Dictionary<string, string> {
    { "CorrelationId", "064205E2-F7CF-43A6-B514-4B55536C2B67" },
    { DefaultContextProperties.Filename, "Hello.txt" }
}

How do I validate a Log Event?

Below is a sample method that can help you validate your Log Event

private static void ValidateLogEvent(LogEvent logEvent)
{
    if (!logEvent.IsValid(out List<LogReceiptErrorMessage> errorMessages))
    {
        Console.WriteLine("Log Event is not valid!");
        foreach (var errorMessage in errorMessages)
        {
            Console.WriteLine("{0}\t\t{1}", errorMessage.Title, errorMessage.Message);
        }
    }
    else
    {
        Console.WriteLine("Log Event OK!");
    }
}

Create, Validate and write Log Event to file example

Below is the full example

using IM.Libraries.Contracts.RestApi.Log;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Nodinite.Samples
{
    public class SampleLogEvent
    {
        private LogEvent CreateNodiniteLogEvent()
        {
            return new LogEvent()
            {
                // Required values 
                LogAgentValueId = 42,
                EndPointName = "INT101: Receive Hello World Log Events",
                EndPointUri = "C:\\temp\\in",
                EndPointDirection = 0,
                EndPointTypeId = LogEventEndPointType.File,
                OriginalMessageTypeName = "Hello.World.File/1.0",
                LogDateTime = DateTime.UtcNow,

                // Optional values
                EventDirection = LogEventEventDirection.ExternalIncoming,
                ProcessingUser = "DOMAIN\\user",
                SequenceNo = 0,
                EventNumber = 0,
                LogText = "File OK",
                ApplicationInterchangeId = "",
                LocalInterchangeId = null,
                LogStatus = 0,
                ProcessName = "My Process",
                ProcessingMachineName = "localhost",
                ProcessingModuleName = "INT101-HelloWorld-Application",
                ProcessingModuleType = "FilePickup",
                ServiceInstanceActivityId = null,
                ProcessingTime = 80,

                // Add Body (payload)
                Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { orderid = "123", name = "John Doe" })),

                // Add arbitrary Context
                Context = new Dictionary<string, string> {
                    { "CorrelationId", "064205E2-F7CF-43A6-B514-4B55536C2B67" },
                    { DefaultContextProperties.Filename, "Hello.txt" }
                }

            };
        }

        private void ValidateLogEvent(LogEvent logEvent)
        {
            if (!logEvent.IsValid(out List<LogReceiptErrorMessage> errorMessages))
            {
                Console.WriteLine("Log Event is not valid!");
                foreach (var errorMessage in errorMessages)
                {
                    Console.WriteLine("{0}\t\t{1}", errorMessage.Title, errorMessage.Message);
                }
            }
            else
            {
                Console.WriteLine("Log Event OK!");
            }
        }

        public void CreateValidateAndWriteLogEventToFile()
        {
            LogEvent logEvent = CreateNodiniteLogEvent();
            ValidateLogEvent(logEvent);

            string jsonString = logEvent.ToJson();

            using (StreamWriter file = File.CreateText(string.Format("LogEvent_{0}.json", Guid.NewGuid())))
            {
                file.WriteLine(jsonString);
            }
        }        
    }
}

Make sure to customize the code snippet above according to your log needs. Avoid hard coding and use config file and/or parameters to dynamically set the properties.

The file written in the example above should be consumed by the Pickup Service. Make sure to read more in the Asynchronous Logging user guide.


Next Step