Examples

The following examples may help you to get started quickly.

Using WebConnect with C#

C# has multiple possibilities to connect with WebConnect such as HttpClient, WebRequest, etc.
In the following example we will use the HttpClient of Microsoft. The example can be compiled in Visual Studio 2010 or later.

Install the Web API Client Libraries

Use NuGet Package Manager to install the Web API Client Libraries package.
From the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Microsoft.AspNet.WebApi.Client

Create basic structure

The Main function calls an async method named RunAsync and then blocks until RunAsync completes.

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml.XPath;

namespace WebConnectClient
{
    class Program
    {
        static void Main()
        {
            RunAsync().Wait();

            Console.WriteLine("Press enter to end the application...");
            Console.ReadLine();
        }
        static async Task RunAsync()
        {
            // TODO - Initialize HttpClient
        }
    }
}

Create and Initialize HttpClient

We create a new HttpClient and set some of it's properties, like the 'Accept' and 'Authorization' header.

static async Task RunAsync()
{
    try
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://venice.unit4.com/WebConnect/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                Convert.ToBase64String(Encoding.ASCII.GetBytes("User:Password")));

            // TODO - Send requests
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
}

Sending HTTP requests

We'll send a few requests and process the answer.

// Get from dossier 'Demo' a customer card with number '1' and subnumber '0'.
HttpResponseMessage response = await client.GetAsync("api/Demo/Customer?NumberPair=1\t0");

if (!response.IsSuccessStatusCode)
    Console.WriteLine("Get customer card failed.");
else
{
    // Get the response xml.
    string xml = await response.Content.ReadAsStringAsync();

    // Display the customer name.
    using (var stream = new StringReader(xml))
    {
        var xpath = new XPathDocument(stream);
        var navigator = xpath.CreateNavigator();
        var nameNode = navigator.SelectSingleNode("Response/Customers/Customer/Fields/Name");
        if (nameNode != null)
            Console.WriteLine("Retrieved customer card '" + nameNode.Value + "'.");
    }
}

// Create a new customer card in dossier 'Demo'.
string json =
    "{" +
    "  \"Request\": {" +
    "    \"Customers\": {" +
    "      \"Customer\": [" +
    "        {" +
    "          \"Fields\" : {" +
    "            \"Name\": \"My customer NV\"," +
    "            \"VatNum\": \"BE 0427.604.308\"," +
    "            \"LegalForm\": \"NV\"" +
    "          }" +
    "        }" +
    "      ]" +
    "    }" +
    "  }" +
    "}";

using (StringContent content = new StringContent(json, Encoding.UTF8, "application/json"))
{
    response = await client.PostAsync("api/Demo/Customer", content);
}

// Display the result.
if (!response.IsSuccessStatusCode)
    Console.WriteLine("Create customer card failed.");
else
{
    // Gets the response xml.
    string xml = await response.Content.ReadAsStringAsync();

    // Retrieve the system number
    string sysNum = null;
    using (var stream = new StringReader(xml))
    {
        var xpath = new XPathDocument(stream);
        var navigator = xpath.CreateNavigator();
        var sysNumNode = navigator.SelectSingleNode("Response/Customers/Customer/Fields/SysNum");
        if (sysNumNode != null)
            sysNum = sysNumNode.Value;
    }

    if (sysNum == null)
        return;

    // Display the result.
    Console.WriteLine("Customer card with system number '" + sysNum + "' created.");
    Console.WriteLine("Press enter to update the Customer card...");
    Console.ReadLine();

    // Update in dossier 'Demo' the info of the customer card
    // with systemnumber sysNum (created in the previous call).
    json =
        "{" +
        "  \"Request\": {" +
        "    \"Customers\": {" +
        "      \"Customer\": [" +
        "        {" +
        "          \"Fields\" : {" +
        "            \"Info\": \"The customer card was brought up to date.\"" +
        "          }" +
        "        }" +
        "      ]" +
        "    }" +
        "  }" +
        "}";

    using (StringContent content = new StringContent(json, Encoding.UTF8, "application/json"))
    {
        response = await client.PutAsync("api/Demo/Customer?SystemNumber=" + sysNum, content);
    }

    // Display the result.
    if (!response.IsSuccessStatusCode)
        Console.WriteLine("Update customer card failed.");
    else
        Console.WriteLine("Customer card with system number '" + sysNum + "' updated.");

    Console.WriteLine("Press enter to delete the customer card...");
    Console.ReadLine();

    // Delete in dossier 'Demo' the customer card with systemnumber sysNum.
    response = await client.DeleteAsync("api/Demo/Customer?SystemNumber=" + sysNum);

    // Display the result.
    if (!response.IsSuccessStatusCode)
        Console.WriteLine("Delete customer card failed.");
    else
        Console.WriteLine("Customer card with system number '" + sysNum + "' deleted");
}

Using WebConnect with VB

This example can be compiled in Visual Studio 2010 or later.

Install the Json.NET Library

Use NuGet Package Manager to install the Json.NET package.
From the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Newtonsoft.Json

Request class

Making a request and processing the answer requires a fair amount of code. To simplify the different requests we'll use the Request class. It uses the HttpWebRequest object internally to send a request and to process the answer.

Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Xml.XPath
Module WebConnect
    Public Class RequestResponse
        'The http status code.
        Public Property StatusCode As HttpStatusCode

        'The requested
        Public Property Message As String
    End Class

    Public Class Request
        Private ReadOnly _request As HttpWebRequest

        Public Sub New(ByVal method As String, ByVal url As String, ByVal userName As String, ByVal password As String)
            _request = WebRequest.Create(url)
            _request.Method = method
            _request.Credentials = New NetworkCredential(userName, password)
            _request.Accept = "application/xml"
        End Sub

        Function Send(Optional content As String = Nothing, Optional contentType As String = "") As RequestResponse
            Dim answer As RequestResponse = New RequestResponse()

            If Not IsNothing(content) Then
                'Specify the format of the body.
                _request.ContentType = contentType
                'Add the body text to the request.
                Dim requestBody As Byte() = Encoding.UTF8.GetBytes(content)
                _request.ContentLength = requestBody.Length
                Using stream As Stream = _request.GetRequestStream()
                    stream.Write(requestBody, 0, requestBody.Length)
                End Using
            End If

            Try
                'Send the request and get the response.
                Using response As HttpWebResponse = _request.GetResponse()
                    If Not IsNothing(response) Then
                        answer.StatusCode = response.StatusCode
                        Dim Stream As Stream = response.GetResponseStream()
                        If Not IsNothing(Stream) Then
                            Using reader As StreamReader = New StreamReader(Stream)
                                answer.Message = reader.ReadToEnd()
                            End Using
                        End If
                    Else
                        Console.WriteLine("Request.Send - response = Nothing")
                    End If
                End Using
            Catch webEx As WebException
                Try
                    Using stream As Stream = webEx.Response.GetResponseStream()
                        If Not IsNothing(stream) Then
                            Using reader As StreamReader = New StreamReader(stream)
                                answer.Message = reader.ReadToEnd()
                            End Using
                        End If
                    End Using
                    Dim response = DirectCast(webEx.Response, HttpWebResponse)
                    If Not IsNothing(response) Then
                        answer.StatusCode = response.StatusCode
                    End If
                Catch ex As Exception
                    Console.WriteLine("Request.Send - exception: " + ex.Message)
                End Try
            End Try
            Return answer
        End Function
    End Class	
End Module

Sending HTTP requests

We'll send a few requests and process the answer.

Sub Main()	
    Try
        Dim username As String = "User"
        Dim password As String = "Password"

        'Get from dossier 'Demo' a customer card with number '1' and subnumber '0'.
        Dim url As String = "https://venice.unit4.com/WebConnect/api/Demo/Customer?NumberPair=1" & vbTab & "0"
        Dim request As Request = New Request("GET", url, username, password)
        Dim response As RequestResponse = request.Send()

        'Display the result.
        If response.StatusCode() <> HttpStatusCode.OK Then
            Console.WriteLine("Get customer card failed.")
        Else
            Using stream As StringReader = New StringReader(response.Message())
                Dim xpath As XPathDocument = New XPathDocument(stream)
                Dim navigator As XPathNavigator = xpath.CreateNavigator()
                Dim nameNode As XPathNavigator = navigator.SelectSingleNode("Response/Customers/Customer/Fields/Name")
                If Not IsNothing(nameNode) Then
                    Console.WriteLine("Retrieved customer card '" & nameNode.Value & "'.")
                End If
            End Using
        End If

        'Create a new customer card in dossier 'Demo'.
        Dim json =
            "{" +
            "  ""Request"": {" +
            "    ""Customers"": {" +
            "      ""Customer"": [" +
            "        {" +
            "          ""Fields"" : {" +
            "            ""Name"": ""My customer NV""," +
            "            ""VatNum"": ""BE 0427.604.308""," +
            "            ""LegalForm"": ""NV""" +
            "          }" +
            "        }" +
            "      ]" +
            "    }" +
            "  }" +
            "}"
        url = "https://venice.unit4.com/WebConnect/api/Demo/Customer"
        request = New Request("POST", url, username, password)
        response = request.Send(json, "application/json")

        'Display the result.
        If response.StatusCode() <> HttpStatusCode.OK Then
            Console.WriteLine("Customer post failed.")
        Else
            Dim sysNum As String = Nothing
            Using stream As StringReader = New StringReader(response.Message)
                Dim xpath As XPathDocument = New XPathDocument(stream)
                Dim navigator As XPathNavigator = xpath.CreateNavigator()
                Dim sysNumNode As XPathNavigator = navigator.SelectSingleNode("Response/Customers/Customer/Fields/SysNum")
    
                If Not IsNothing(sysNumNode) Then
                    sysNum = sysNumNode.Value
                End If
            End Using

            If IsNothing(sysNum) Then
                Return
            End If

            'Display the result.
            Console.WriteLine("Customer card with system number '" & sysNum & "' created.")

            Console.WriteLine("Press enter to update the Customer card...")
            Console.ReadLine()

            'Update in dossier 'Demo' the info of the customer card
            'with systemnumber sysNum (created in the previous call).
            json =
                "{" +
                "  ""Request"": {" +
                "    ""Customers"": {" +
                "      ""Customer"": [" +
                "        {" +
                "          ""Fields"" : {" +
                "            ""Info"": ""The customer card was brought up to date.""" +
                "          }" +
                "        }" +
                "      ]" +
                "    }" +
                "  }" +
                "}"

            url = "https://venice.unit4.com/WebConnect/api/Demo/Customer?SystemNumber=" & sysNum
            request = New Request("PUT", url, username, password)
            response = request.Send(json, "application/json")

            'Display the result.
            If response.StatusCode() <> HttpStatusCode.OK Then
                Console.WriteLine("Update customer card failed.")
            Else
                Console.WriteLine("Customer card with system number '" & sysNum & "' updated.")
            End If

            Console.WriteLine("Press enter to delete the customer card...")
            Console.ReadLine()

            'Delete in dossier 'Demo' the customer card with systemnumber sysNum.
            url = "https://venice.unit4.com/WebConnect/api/Demo/Customer?SystemNumber=" & sysNum
            request = New Request("DELETE", url, username, password)
            response = request.Send()

            'Display the result.
            If response.StatusCode() <> HttpStatusCode.OK Then
                Console.WriteLine("Delete customer card failed.")
            Else
                Console.WriteLine("Customer card with system number '" & sysNum & "' deleted.")
            End If
        End If

        Console.WriteLine("Press enter to end the application...")
        Console.ReadLine()
    Catch ex As Exception
        Console.WriteLine("Exception: " + ex.Message)
        Console.ReadLine()
    End Try
End Sub