You are viewing the documentation for Digipost API Client 10.0, which is not the most recently released version. The newest version is 14.0 and can be browsed here.

Initial setup

The client library is available as a Nuget package. The client library (and associated Nuget package) is updated regularly as new functionality is added.

To install the Nuget package, follow these steps in Visual Studio/Rider:

  1. Select TOOLS -> Nuget Package Manager -> Manage Nuget Packages Solution…

  2. Search for Digipost.Api.Client. Multiple packages will appear. Install those necessary for you. Make sure you DON’T install the digipost-api-client packages. Those are .NET Framework libraries with an unfortunately similar name. If you’re looking for the .NET Framework documention, please see version 8.3. If you would like pre-releases of this package, make sure Include Prerelease` is enabled. Please refer to documentation for your version of Visual Studio for detailed instructions.
  3. Select which Digipost.Api.Client.X libraries you need and click Install for each.

Install and use enterprise certificate

SSL Certificates are small data files that digitally bind a cryptographic key to an organization's details. When installed on a web server, it activates the padlock and the https protocol (over port 443) and allows secure connections from a web server to a browser.

To communicate over HTTPS you need to sign your request with a enterprise certificate. The enterprise certificate can be loaded directly from file or from the Windows certificate store.

The following steps will install the certificate in the your certificate store. This should be done on the server where your application will run. For more information, please see the Microsoft Documentation.

The path and password to the certificate must be put somewhere safe.

The path on Windows is:

%APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json

On MacOS/Linux the path is:

~/.microsoft/usersecrets/<user_secrets_id>/secrets.json

Add the following UserSecretsId element to your .csproj file:

<PropertyGroup>
     <TargetFramework>netcoreapp2.1</TargetFramework>
     <UserSecretsId>enterprise-certificate</UserSecretsId>
</PropertyGroup>

This means that the element <user_secrets_id> in the path will be enterprise-certificate.

From the command line, navigate to the directory where the current .csproj file is located and run the following commands with your own certificate values:

dotnet user-secrets set "Certificate:Path:Absolute" "<your-certificate.p12>"
dotnet user-secrets set "Certificate:Password" "<your-certificate-password>"
Trust the Certificate on Windows:
  1. Double-click on the actual certificate file (CertificateName.p12)
  2. Save the sertificate in Current User or Local Machine and click Next. If you are running the client library from a system account, but debugging from a different user, please install it on Local Machine, as this enables loading it from any user.
  3. Use the suggested filename. Click Next
  4. Enter password for private key and select Mark this key as exportable … Click Next
  5. Choose Automatically select the certificate store based on the type of certificate
  6. Click Next and Finish
  7. Accept the certificate if prompted.
  8. When prompted that the import was successful, click Ok
Trust the Certificate on MacOS:
  1. Open Keychain Access
  2. Choose login keychain
  3. Press File and then Import
  4. Choose the enterprise certificate and add it
Trust the Certificate on Linux:

Download the root and intermediate certificates from Difi for your enterprise certificate provider. Note the renaming to have .crt ending for update-ca-certificates:

sudo cp Buypass_Class_3_Test4_Root_CA.pem /usr/local/share/ca-certificates/Buypass_Class_3_Test4_Root_CA.crt
sudo cp Buypass_Class_3_Test4_CA_3.pem /usr/local/share/ca-certificates/Buypass_Class_3_Test4_CA_3.crt
sudo update-ca-certificates

Create ClientConfig and DigipostClient:

// The actual sender of the message. The broker is the owner of the organization certificate 
// used in the library. The broker id can be retrieved from your Digipost organization account.
const int brokerId = 12345;
            
var broker = new Broker(brokerId);
var clientConfig = new ClientConfig(broker, Environment.Production);

var client = new DigipostClient(clientConfig, CertificateReader.ReadCertificate());

Where CertificateReader.ReadCertificate() is:

var pathToSecrets = $"{System.Environment.GetEnvironmentVariable("HOME")}/.microsoft/usersecrets/smoke-certificate/secrets.json";
_logger.LogDebug($"Reading certificate details from secrets file: {pathToSecrets}");
var fileExists = File.Exists(pathToSecrets);

if (!fileExists)
{
    _logger.LogDebug($"Did not find file at {pathToSecrets}");
}
            
var certificateConfig = File.ReadAllText(pathToSecrets);
var deserializeObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(certificateConfig);

deserializeObject.TryGetValue("Certificate:Path:Absolute", out var certificatePath);
deserializeObject.TryGetValue("Certificate:Password", out var certificatePassword);

_logger.LogDebug("Reading certificate from path found in secrets file: " + certificatePath);

return new X509Certificate2(certificatePath, certificatePassword, X509KeyStorageFlags.Exportable);

Load enterprise certificate from file

If there is a reason for not loading the certificate from the Windows certificate store, you can use the constructor taking in a X509Certificate2:

var clientConfig = new ClientConfig(broker, Environment.Production);
var enterpriseCertificate =
    new X509Certificate2(
        @"C:\Path\To\Certificate\Cert.p12",
        "secretPasswordProperlyInstalledAndLoaded",
        X509KeyStorageFlags.Exportable
    );

var client = new DigipostClient(clientConfig, enterpriseCertificate);

[Warning: This is technically supported on other operating systems than Windows, but we’ve not tested that thoroughly. Use at your own risk.] Load enterprise certificate from thumbprint in code

  1. Start mmc.exe (Click windowsbutton and type mmc.exe)
  2. Choose File -> Add/Remove Snap-in… (Ctrl + M)
  3. Mark certificate and click Add >
  4. If the certificate was installed in Current User choose My User Account and if installed on Local Machine choose Computer Account. Then click Finish and then OK
  5. Expand Certificates node, select Personal and open Certificates
  6. Double-click on the installed certificate
  7. Go to the Details tab
  8. Scroll down to Thumbprint
  9. Copy the thumbprint and load as shown below
 var clientConfig = new ClientConfig(broker, Environment.Production);
 var client = new DigipostClient(clientConfig, thumbprint: "84e492a972b7e...");

Send messages

Client configuration

ClientConfig is a container for all the connection specific parameters that you can set.

// The actual sender of the message. The broker is the owner of the organization certificate
// used in the library. The broker id can be retrieved from your Digipost organization account.
var broker = new Broker(12345);

// The sender is what the receiver of the message sees as the sender of the message.
// Sender and broker id will both be your organization's id if you are sending on behalf of yourself.
var sender = new Sender(67890);

var clientConfig = new ClientConfig(broker, Environment.Production);

var client = new DigipostClient(clientConfig, CertificateReader.ReadCertificate());

Send one letter to recipient via personal identification number

var message = new Message(
    sender,
    new RecipientById(IdentificationType.PersonalIdentificationNumber, "311084xxxx"),
    new Document(subject: "Attachment", fileType: "txt", path: @"c:\...\document.txt")
);

var result = client.SendMessage(message);

Other recipient types

There are other recipient types available to identify recipients of messages. Note that some recipient types may require special permissions to be set up in order to be used.

var recipient = new RecipientByNameAndAddress(
    fullName: "Ola Nordmann",
    addressLine1: "Prinsensveien 123",
    postalCode: "0460",
    city: "Oslo"
);

var primaryDocument = new Document(subject: "document subject", fileType: "pdf", path: @"c:\...\document.pdf");

var message = new Message(sender, recipient, primaryDocument);
var result = client.SendMessage(message);

Send one letter with multiple attachments

var primaryDocument = new Document(subject: "Primary document", fileType: "pdf", path: @"c:\...\document.pdf");
var attachment1 = new Document(subject: "Attachment 1", fileType: "txt", path: @"c:\...\attachment_01.txt");
var attachment2 = new Document(subject: "Attachment 2", fileType: "pdf", path: @"c:\...\attachment_02.pdf");

var message = new Message(
        sender,
        new RecipientById(IdentificationType.PersonalIdentificationNumber, id: "241084xxxxx"),
        primaryDocument
    ){Attachments = {attachment1, attachment2}};

var result = client.SendMessage(message);

Send letter with SMS notification

var primaryDocument = new Document(subject: "Primary document", fileType: "pdf", path: @"c:\...\document.pdf");

primaryDocument.SmsNotification = new SmsNotification(afterHours: 0); //SMS reminder after 0 hours
primaryDocument.SmsNotification.NotifyAtTimes.Add(new DateTime(2015, 05, 05, 12, 00, 00)); //new reminder at a specific date

var message = new Message(
    sender,
    new RecipientById(identificationType: IdentificationType.PersonalIdentificationNumber, id: "311084xxxx"),
    primaryDocument
);

var result = client.SendMessage(message);

Send letter with fallback to print if the user does not exist in Digipost

In cases where the recipient is not a Digipost user, it is also possible to use the recipient’s name and address for physical mail delivery.

var recipient = new RecipientByNameAndAddress(
    fullName: "Ola Nordmann",
    addressLine1: "Prinsensveien 123",
    postalCode: "0460",
    city: "Oslo"
);

var printDetails =
    new PrintDetails(
        printRecipient: new PrintRecipient(
            "Ola Nordmann",
            new NorwegianAddress("0460", "Oslo", "Prinsensveien 123")),
        printReturnRecipient: new PrintReturnRecipient(
            "Kari Nordmann",
            new NorwegianAddress("0400", "Oslo", "Akers Àle 2"))
    );

var primaryDocument = new Document(subject: "document subject", fileType: "pdf", path: @"c:\...\document.pdf");

var messageWithFallbackToPrint = new Message(sender, recipient, primaryDocument)
{
    PrintDetails = printDetails
};

var result = client.SendMessage(messageWithFallbackToPrint);

Send letter with fallback to print if the user does not read the message within a certain deadline

var recipient = new RecipientByNameAndAddress(
    fullName: "Ola Nordmann",
    addressLine1: "Prinsensveien 123",
    postalCode: "0460",
    city: "Oslo"
);

var printDetails =
    new PrintDetails(
        printRecipient: new PrintRecipient(
            "Ola Nordmann",
            new NorwegianAddress("0460", "Oslo", "Prinsensveien 123")),
        printReturnRecipient: new PrintReturnRecipient(
            "Kari Nordmann",
            new NorwegianAddress("0400", "Oslo", "Akers Àle 2"))
    );

var primaryDocument = new Document(subject: "document subject", fileType: "pdf", path: @"c:\...\document.pdf");

var messageWithPrintIfUnread = new Message(sender, recipient, primaryDocument)
{
    PrintDetails = printDetails,
    DeliveryTime = DateTime.Now.AddDays(3),
    PrintIfUnread = new PrintIfUnread(DateTime.Now.AddDays(6), printDetails)
};

var result = client.SendMessage(messageWithPrintIfUnread);

Send letter with higher security level

var primaryDocument = new Document(subject: "Primary document", fileType: "pdf", path: @"c:\...\document.pdf")
{
    AuthenticationLevel = AuthenticationLevel.TwoFactor, // Require BankID or BuyPass to open letter
    SensitivityLevel = SensitivityLevel.Sensitive // Sender information and subject will be hidden until Digipost user is logged in at the appropriate authentication level
};

var message = new Message(
    sender,
    new RecipientById(identificationType: IdentificationType.PersonalIdentificationNumber, id: "311084xxxx"),
    primaryDocument
);

var result = client.SendMessage(message);

Send letter with higher security level

var config = new ClientConfig("xxxxx", Environment.Production);
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

var primaryDocument = new Document(subject: "Primary document", fileType: "pdf", path: @"c:\...\document.pdf");

primaryDocument.AuthenticationLevel = AuthenticationLevel.TwoFactor; // Require BankID or BuyPass to open letter
primaryDocument.SensitivityLevel = SensitivityLevel.Sensitive; // Sender information and subject will be hidden until Digipost user is logged in at the appropriate authentication level

var message = new Message(
    new RecipientById(identificationType: IdentificationType.PersonalIdentificationNumber, id: "311084xxxx"), primaryDocument);

var result = client.SendMessage(message);

Identify recipient

Attempts to identify the person submitted in the request and returns whether he or she has a Digipost account. The person can be identified by personal identification number (PIN), Digipost address, or name and address.

If the user is identified, the ResultType will be DigipostAddress or PersonAlias. In cases where we identify the person, the data parameter will contain the given identification value.

User is identified and have a Digipost account:

ResultType: DigipostAddress
Data: "Ola.Nordmann#3244B"
Error: Null

User is identified but does not have a Digipost account:

ResultType: PersonAlias
Data: "azdixsdfsdffsdfncixtvpwdp#6QE6"
Error: Null

The PersonAlias can be used for feature lookups, instead of the given identify criteria.

Note: If you identify a person by PIN, the Digipost address will not be returned, since it is preferred that you continue to use this as identificator when sending the message.

If the user is not identified, the ResultType will be InvalidReason or UnidentifiedReason. See the Error parameter for more detailed error message.

The user is not identified because the PIN is not valid:

ResultType: InvalidReason
Data: Null
Error: InvalidPersonalIdentificationNumber

The user is not identified because we did not have a match from the identify criteria:

ResultType: UnidentifiedReason
Data: Null
Error: NotFound

Following is a example that uses personal identification number as identification choice.

var identification = new Identification(new RecipientById(IdentificationType.PersonalIdentificationNumber, "211084xxxxx"));
var identificationResponse = client.Identify(identification);

if (identificationResponse.ResultType == IdentificationResultType.DigipostAddress)
{
    //Exist as user in Digipost.
    //If you used personal identification number to identify - use this to send a message to this individual.
    //If not, see Data field for DigipostAddress.  
}
else if (identificationResponse.ResultType == IdentificationResultType.Personalias)
{
    //The person is identified but does not have an active Digipost account.
    //You can continue to use this alias to check the status of the user in future calls.
}
else if (identificationResponse.ResultType == IdentificationResultType.InvalidReason ||
         identificationResponse.ResultType == IdentificationResultType.UnidentifiedReason)
{
    //The person is NOT identified. Check Error for more details.
}

Send letter through Norsk Helsenett

The Digipost API is accessible from both internet and Norsk Helsenett (NHN). Both entry points use the same API, the only difference is that ClientConfig.Environment must be set to Environment.NorskHelsenett.

// API URL is different when request is sent from NHN
var config = new ClientConfig(new Broker(12345), Environment.NorskHelsenett);
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

var message = new Message(
    sender,
    new RecipientById(IdentificationType.PersonalIdentificationNumber, "311084xxxx"),
    new Document(subject: "Attachment", fileType: "txt", path: @"c:\...\document.txt")
);

var result = client.SendMessage(message);

Send invoice

It is possible to send invoice-metadata with a document. Documents with invoice-metadata enables the Send to Online Bank feature, which allows people to pay the invoice directly in Digipost.

var message = new Message(
    sender,
    new RecipientById(IdentificationType.PersonalIdentificationNumber, "211084xxxx"),
    new Invoice(
        subject: "Invoice 1",
        fileType: "pdf",
        path: @"c:\...\invoice.pdf",
        amount: new decimal(100.21),
        account: "2593143xxxx",
        duedate: DateTime.Parse("01.01.2016"),
        kid: "123123123")
);

var result = client.SendMessage(message);

Search for receivers

A central part of a user interface in the application that is integrating with Digipost is the possiblity to search for receivers. This is available via the search endpoint. A person can be found by simply searching by first name and last name, e.g. Ola Nordmann, or specified further by street address, postal code, city and organization name.

It is important to note that the search results returned do not necessarily include the receiver to which you actually wish to send. The search results returned are strictly based on the search query you have sent in. This equally applies when only one search result is returned. This means that the actual person to which you wish to send must be confirmed by a human being before the actual document i sent (typically in the senders application). If the goal is to create a 100% automated workflow then the identify recipient endpoint should be used (see Identify recipient use case).

var response = client.Search("Ola Nordmann Bellsund Longyearbyen");

foreach (var person in response.PersonDetails)
{
    var digipostAddress = person.DigipostAddress;
    var phoneNumber = person.MobileNumber;
}

Send on behalf of organization

In the following use case, Sender is defined as the party who is responsible for the actual content of the letter. Broker is defined as the party who is responsible for the technical transaction, which in this context means creating the request and being the party that is authenticated.

example

Sending on behalf of an organization is accomplished by setting Message.Sender to the id of the sender when constructing a message. The actual letter will appear in the receivers Digipost mailbox with the senders details (logo, name, etc.).

Remember to use the enterprise certificate of the broker to sign the message, not the one belonging to the sender. Also, the proper permissions need to be set by Digipost to send on behalf of an organization.

Let us illustrate this with an example. Let BrokerCompany be an organization with id 12345, and thumbprint of their certificate 84e492a972b7e…. They want to send on behalf of SenderCompany with organization id 67890.

var broker = new Broker(12345);
var sender = new Sender(67890);

var digitalRecipient = new RecipientById(IdentificationType.PersonalIdentificationNumber, "311084xxxx");
var primaryDocument = new Document(subject: "Attachment", fileType: "txt", path: @"c:\...\document.txt");


var clientConfig = new ClientConfig(broker, Environment.Production);

var message = new Message(sender, digitalRecipient, primaryDocument);

var result = client.SendMessage(message);

Send message with delivery time

A message can be sent with a delivery time. This means that a message can be sent at 11 AM, and be delivered to the recipient’s Digipost inbox at 3 PM the next day. Message.DeliveryTime is used for this purpose and is of type DateTime. This gives you a lot of flexibility on how to set the delivery time.

var message = new Message(
    sender,
    new RecipientById(IdentificationType.PersonalIdentificationNumber, "311084xxxx"),
    new Document(subject: "Attachment", fileType: "txt", path: @"c:\...\document.txt")
)
{
    DeliveryTime = DateTime.Now.AddDays(1).AddHours(4)
};

var result = client.SendMessage(message);

Send a message with extra computer readable data

Starting with version 8 of the Digipost API, messages can have extra bits of computer readable information that allows the creation of a customized, dynamic user experience for messages in Digipost. These extra bits of information are referred to as “Datatypes”.

All datatypes are sent in the same way. Each document can accommodate one datatype-object. An exhaustive list of available datatypes and their documentation can be found at digipost/digipost-data-types.

DataTypes are sent as an XML string in the document’s datatype field. You can build the XML yourself, or import our extension library Digipost.Api.Client.DataTypes. This library includes classes for each datatype, which can be serialized using SerializeUtil.Serialize(DataType), which gives you the XML string to append to the document. The expansion library is optional, but highly recommended if you’ll be working with DataTypes. The examples below will assume the usage of said library.

Send message with appointment datatype

Appointment represents a meeting set for a specific place and time. The following example demonstrates how to include such extra data:

var startTime = DateTime.Parse("2017-11-24T13:00:00+0100");
var appointment = new Appointment
{
    Start_Time = startTime.ToString("O"),
    End_Time = startTime.AddMinutes(30).ToString("O"),
    Address = new Address{ Street_Address = "Storgata 1", Postal_Code = "0001", City = "Oslo" }
};

string appointmentXml = SerializeUtil.Serialize(appointment);

var document = new Document(
    subject: "Your appointment",
    fileType: "pdf",
    path: @"c:\...\document.pdf",
    dataType: appointmentXml
);

// Create Message and send using the client as specified in other examples.

Send message with event datatype

Event represents a meeting set for a specific place, but covering multiple time spans. The following example demonstrates how to include such extra data:

var startTime = DateTime.Parse("2017-11-24T13:00:00+0100");

var timeInterval1 = new TimeInterval { Start_Time = DateTime.Today.ToString("O"), End_Time = DateTime.Today.AddHours(3).ToString("O") };
var timeInterval2 = new TimeInterval { Start_Time = DateTime.Today.AddDays(1).ToString("O"), End_Time = DateTime.Today.AddDays(1).AddHours(5).ToString("O") };

var barcode = new Barcode { Barcode_Value = "12345678", Barcode_Type = "insert type here", Barcode_Text = "this is a code", Show_Value_In_Barcode = true };
var address = new Address { Street_Address = "Gateveien 1", Postal_Code = "0001", City = "Oslo" };
var info = new Info { Title = "Title", Text = "Very important information" };
var link = new Link { Url = "https://www.test.no", Description = "This is a link" };

Event @event = new Event
{
    Start_Time = { timeInterval1, timeInterval2 },
    Description = "Description here",
    Address = address,
    Info = { info },
    Place = "Oslo City Røntgen",
    PlaceLabel = "This is a place",
    Sub_Title = "SubTitle",
    Barcode = barcode,
    BarcodeLabel = "Barcode Label",
    Links = { link }
};

string eventXml = SerializeUtil.Serialize(@event);

Document document = new Document(
    subject: "Your appointment",
    fileType: "pdf",
    path: @"c:\...\document.pdf",
    dataType: eventXml
);

// Create Message and send using the client as specified in other examples.

ExternalLink enhances a message in Digipost with a button which sends the user to an external site. The button can optionally have a deadline, a description and a custom text.

var externalLink = new ExternalLink
{
    Url = "https://example.org/loan-offer/uniqueCustomerId/",
    Description = "Please read the terms, and use the button above to accept them. The offer expires at 23/10-2018 10:00.",
    Button_Text = "Accept offer",
    Deadline = DateTime.Parse("2018-10-23T10:00:00+0200")
};

string linkXml = SerializeUtil.Serialize(externalLink);

var document = new Document(
    subject: "Your appointment",
    fileType: "pdf",
    path: @"c:\...\document.pdf",
    dataType: linkXml
);

// Create Message and send using the client as specified in other examples.

Receive messages

Client configuration

ClientConfig is a container for all the connection specific paramters that you can set.

// The actual sender of the message. The broker is the owner of the organization certificate 
// used in the library. The broker id can be retrieved from your Digipost organization account.
const int brokerId = 12345;
            
var broker = new Broker(brokerId);
var clientConfig = new ClientConfig(broker, Environment.Production);

var client = new DigipostClient(clientConfig, CertificateReader.ReadCertificate());

Get documents inbox

The inbox call outputs a list of documents ordered by DeliveryTime. Offset is the start index of the list, and limit is the max number of documents to be returned. The offset and limit are therefore not in any way connected to InboxDocument.Id.

The values offset and limit are meant for pagination so that one can fetch 100 and then the next 100.

var inbox = client.GetInbox(sender);

var first100 = inbox.Fetch(); //Default offset is 0 and default limit is 100

var next100 = inbox.Fetch(offset: 100, limit: 100);

We have now fetched the 200 newest inbox documents. As long as no new documents are received, the two API-calls shown above will always return the same result. If we now receive a new document, this will change. The first 100 will now contain 1 new document and 99 documents we have seen before. This means that as soon as you stumble upon a document you have seen before you can stop processing, given that all the following older ones have been processed.

Download document content

var inbox = client.GetInbox(sender);

var documentMetadata = (await inbox.Fetch()).First();

var documentStream = await inbox.FetchDocument(documentMetadata);

Delete document

var inbox = client.GetInbox(sender);

var documentMetadata = (await inbox.Fetch()).First();

await inbox.DeleteDocument(documentMetadata);

Logging

Debugging

Enabling Logging

The client library has the ability to log useful information that can be used for debug purposes. To enable logging, supply the DigipostClient with an implementation of Microsoft.Extensions.Logging.ILoggerFactory. This is Microsoft’s own logging API, and allows the user to chose their own logging framework.

Enabling logging on level DEBUG will output positive results of requests and worse, WARN only failed requests or worse, while ERROR will only occur on failed requests. These loggers will be under the Digipost.Api.Client namespace.

Implementing using NLog

There are numerous ways to implement a logger, but the following examples will be based on NLog documentation.

  1. Install the Nuget-packages NLog, NLog.Extensions.Logging and Microsoft.Extensions.DependencyInjection.
  2. Create an nlog.config file. The following is an example that logs to both file and console:
<?xml version="1.0" encoding="utf-8"?>

<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogFile="c:\temp\console-example-internal.log"
      internalLogLevel="Info">
    <!-- the targets to write to -->
    <targets>
        <!-- write logs to file -->
        <target xsi:type="File"
                name="fileTarget"
                fileName="${specialfolder:folder=UserProfile}/logs/digipost-api-client-dotnet/digipost-api-client-dotnet.log"
                layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}"
                archiveEvery="Day"
                archiveNumbering="Date"
                archiveDateFormat="yyyy-MM-dd"/>
        <target xsi:type="Console"
                name="consoleTarget"
                layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
    </targets>

    <!-- rules to map from logger name to target -->
    <rules>
        <logger name="*" minlevel="Trace" writeTo="fileTarget,consoleTarget"/>
    </rules>
</nlog>

In your application, do the following to create a logger and supply it to DigipostClient:

private static IServiceProvider CreateServiceProviderAndSetUpLogging()
{
    var services = new ServiceCollection();

    services.AddSingleton<ILoggerFactory, LoggerFactory>();
    services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
    services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));

    var serviceProvider = services.BuildServiceProvider();
    SetUpLoggingForTesting(serviceProvider);

    return serviceProvider;
}

private static void SetUpLoggingForTesting(IServiceProvider serviceProvider)
{
    var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();

    loggerFactory.AddNLog(new NLogProviderOptions {CaptureMessageTemplates = true, CaptureMessageProperties = true});
    NLog.LogManager.LoadConfiguration("./nlog.config");
}

static void Main(string[] args)
{
    ClientConfig clientConfig = null;
    
    var serviceProvider = CreateServiceProviderAndSetUpLogging();
    var client = new DigipostClient(clientConfig, CertificateReader.ReadCertificate(), serviceProvider.GetService<ILoggerFactory>());
}

Request and Response Logging

For initial integration and debugging purposes, it can be useful to log the actual request and response going over the wire. This can be enabled by doing the following:

Set the property ClientConfig.LogRequestAndResponse = true.

Warning: Enabling request logging should never be used in a production system. It will severely impact the performance of the client.

Error Handling

Error Handling

If you are communicating synchronously, the errors will be wrapped in an AggregateException. This is because a set of errors may have occured before you receive You can handle each exception within the aggregate by sending in an anonymous function to AggregateException.Handle():

try
{
    var messageDeliveryResult = api.SendMessage(message);	
}
catch (AggregateException ae)
{
    ae.Handle((x) =>
    {
        if (x is ClientResponseException)
        {
            Console.WriteLine("A client response exception occured!");
            return true;
        }
        return false;
    });
}

If you are using methods in the client library that has async in the name, it means that you are communicating asynchronously. To correctly identify errors that might happen, for example during sending a message, you can catch errors like you normally would in an application:

try
{
    var messageDeliveryResult = await api.SendMessageAsync(message);	
}
catch(ClientResponseException e)
{
    Console.WriteLine("A client response exception occured!");
}

Asynchronous communication with Digipost using the client library involves using methods with async in method name, like SendMessageAsync or IdentifyAsync.