Implementatie documentatie - Setting up API communication by REST services with TerraIndex for laboratories 

Page / - last modified by Nico Lemaire on 2025/05/06 15:49 

Setting up API communication by REST services with TerraIndex for laboratories 
last modified by Nico Lemaire
on 2025/05/06 15:49

Table of Contents
Digital Lab Exchange process
Firewall IP-Addresses of TerraIndex
Labdelivery (menu-card) files Exchange
Solution/Design
Get Customers (POST)
Request example
Response example
Get Products (POST)
Request example
Response example
Useraccount Checkup.
Solution/Design
Check ValidCredentials (POST)
Request example
Response example
Labassignment request delivery(POST)
Solution/Design
Create Order
Request example
Response example
Get Order status and Results XML and with PDF
Solution/Design
Request example Order Status
Response Status XML Example
Request example Order XML
Response Order XML Example
Request example Order PDF File
Response Order PDF Example
Customer wants to see real time information about the status in the interface
Solution/Design

•	Digital Lab Exchange process
•	Setting up Lab communication by REST services with TerraIndex
•	Firewall IP-Addresses of TerraIndex
•	Labdelivery (menu-card) files Exchange
•	Solution/Design
•	Get Customers (POST)
•	Request example
•	Response example
•	Get Products (POST)
•	Request example
•	Response example
•	Useraccount Checkup.
•	Solution/Design
•	Check ValidCredentials (POST)
•	Request example
•	Response example
•	Labassignment request delivery(POST)
•	Solution/Design
•	Create Order
•	Request example
•	Response example
•	Get Order status and Results XML and with PDF
•	Solution/Design
•	Request example Order Status
•	Response Status XML Example
•	Request example Order XML
•	Response Order XML Example
•	Request example Order PDF File
•	Response Order PDF Example
•	Customer wants to see real time information about the status in the interface
•	Solution/Design
Digital Lab Exchange process
The flow diagram gives a small overview of what the data flow of a lab assignment is.
Every block shows a step of the lab assignment process. From top to bottom these steps are:
 1.	Showing the laboratory and all the analyses that can be requested as an option to the user.
 2.	The user creating a lab assignment and sending it to the lab trough TerraIndex.
 3.	The lab delivering the analysis results back to the TerraIndex.
Lab exchange.svg Lab exchange.txt

==> TODO; add option to confirm order based on the Order price PDF

==> TODO; add option download labcertificate
Firewall IP-Addresses of TerraIndex
Our IP-addresses:
inbound Web.terraindex.com
137.116.199.164
outbound Test.terraindex.com
104.45.9.128
Production outbound (http)
40.115.34.64
Production outbound (ftp):
13.93.123.234
Test outbound (http, ftp)
13.73.138.173
Test outbound (ftp: eurofins, eurofins spain):
51.145.244.12
CD/CI outbound
40.114.238.16
Office outbound
213.124.115.132
Deliveryservice
Production: 13.93.123.234
Test: 51.145.244.12
Labdelivery (menu-card) files Exchange
Solution/Design
Action	TerraIndex	 	Laboratorium	Parameters/Message	Remarks	ResultCodes	
1	Sends a request to the function: GetCustomers().	>	 	WebserviceUsername (string), 
WebservicePassword (string),
CustomerUsername (string)	 	 	
2	 	 	Receives the request and check the customers this username and searches the dateLastChanged for this Customer.	 	 	 	
3	 	<=	Sends back the list of customers with the lastChangedTimestamp	ResultCode (),
ErrorMessage (string),
List<customer> , Customer:
CustomerCode (string),
CustomerName (string),
LabID (int),
LabName (string),
ChangedTimeStamp (DateTime)	We receive the dateTimestamp instead of sending it, so we always get the full list and we are also able to delete customercodes.	1 = Success,
2 = GeneralError,
3 = WrongSIKBVersion,
4 = InvalidCredentials,
5 = CustomerUsernameInvalid,
6 = CustomerUsernameNotValidForCustomerCode
7 = FileContentProblem,
8 = InvalidOrderId,
9 = OrderIdAlreadyApproved
10 = PDFNotAvailable	
4	Receives the list of Customers, and will check for each customer it needs to request a new/changed labdelivery file based on the ChangedTimestamp.	 	 	 	If a customer is not longer in this list, TerraIndex can remove this customercode from the customer database.	 	
5	Sends a request to the function: GetProductList() if it has changed.	>	 	WebserviceUsername (string), 
WebservicePassword (string),
CustomerUsername (string),
LabID (int),
CustomerCode (string),
LanguageCode (string, default 'nld' volgens ISO 639-3-codes),
SIKBVersion (string, default: '13.4.0'),
UseZipStream/UseZip (bool, default: 'false')	We start with dutch, then extend with multiple languages, TerraIndex is in the lead to request multiple languages.
TerraIndex uses: 'fra', 'nld', 'eng', 'spa', 'deu', 'ita', 'por', 'dan'
Besides SIKB 13.4.0, TerraIndex also supports 9.0.0/8.0.0 etc.
==> nle Do you want to mention these old versions?	 	
6	 	 	Reveives a request to create a labdelivery file in a certain version of SIKB. It will generate the file.	 	 	 	
7	 	<=	Sends back the SIKB file, as a Base64 encoded string, with or without using a zipstream.	ResultCode (),
ErrorMessage (string),
FileContent_Base64 (string),
UseZipStream/UseZip (bool, default: 'false')	 	1 = Success,
2 = GeneralError,
3 = WrongSIKBVersion,
4 = InvalidCredentials,
5 = CustomerUsernameInvalid,
6 = CustomerUsernameNotValidForCustomerCode
7 = FileContentProblem,
8 = InvalidOrderId,
9 = OrderIdAlreadyApproved
10 = PDFNotAvailable	
8	Receives the DeliveryFile and saves the file for import into customer database.	 	 	 	 	 	
9	Go back to step 5, for every Customer code, every language.	 	 	 	 	 	
10	Process the LabDeliveryFiles	 	 	 	 	 	
Get Customers (POST)
Request example
public GetCustomersCall.Response GetCustomers(string WebserviceUsername, string WebservicePassword, string CustomerUsername)
        {
            GetCustomersCall.Response set = new GetCustomersCall.Response();

            try
            {
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("userName", WebserviceUsername),
                    new KeyValuePair<string, string>("password", WebservicePassword),
                    new KeyValuePair<string, string>("customerUsername", CustomerUsername),
                });

                HttpResponseMessage response = _HttpClient.PostAsync(_HttpClient.BaseAddress + "/GetCustomers", content).Result;
                response.EnsureSuccessStatusCode();
                string responseMessage = response.Content.ReadAsStringAsync().Result;

                if (string.IsNullOrEmpty(responseMessage))
                {
                    throw new Exception("Empty response from: [" + _HttpClient.BaseAddress + " / GetCustomers" + "]");
                }
                using (var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseMessage)))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(GetCustomersCall.Response));
                    set = (GetCustomersCall.Response)serializer.Deserialize(ms);                 
                }
            }
            catch (Exception ex)
            {
                #region handle exception
                set.Status = new BusinessEntities.LabRestService.GetCustomersCall.ResponseStatus();
                set.Status.StatusCode = ((int)ResultCodes.GeneralError).ToString();               
                set.Status.ErrorMessage = "Exception occurred in GetCustomers (username: " + WebserviceUsername + ", password: " + WebservicePassword + ") with message: " + ex.Message;
                ex.Data.Add("WebserviceUsername", WebserviceUsername);
                ex.Data.Add("WebservicePassword", WebservicePassword);
                ex.Data.Add("CustomerUsername", CustomerUsername);
                ExceptionHandler.HandleException(ex);
                #endregion
            }
            return set;
        }
 	
POST https://<URL>/GetCustomers HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: 81.175.89.24
Content-Length: 115
Expect: 100-continue
userName=<webservice_username>&password=<Webservice_password>&customerUsername=<customer_username or token>	
Response example
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Response><Customers>
  <Customer LabId="1" LabName="Example Laboratorium" CustomerId="300" CustomerName="Adviesbureau De bodemkoning - Rotterdam" LastModifiedOnClient="2019-05-08T11:05:14.17+02:00" ></Customer>
  <Customer LabId="1" LabName="Example Laboratorium" CustomerId="656" CustomerName="Adviesbureau De bodemkoning - Delft" LastModifiedOnClient="2019-04-19T13:20:10.123+02:00" ></Customer>
</Customers>
<Status>
    <StatusCode>1</StatusCode>
    <StatusCodeDescription>OK</StatusCodeDescription>
    <ErrorMessage></ErrorMessage>
</Status>
</Response>
 	
Get Products (POST)
Request example
public GetProductsCall.Response GetProductList(string WebserviceUsername, string WebservicePassword, string CustomerUsername, string customerid, int labid, string sikbVersion, string languageCode)
        {
            GetProductsCall.Response set = new GetProductsCall.Response();
            try
            {
                bool useZipstream = true;
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("userName", WebserviceUsername),
                    new KeyValuePair<string, string>("password", WebservicePassword),
                    new KeyValuePair<string, string>("customerUsername", CustomerUsername),
                    new KeyValuePair<string, string>("languageCode", languageCode),
                    new KeyValuePair<string, string>("clientId", customerid),
                    new KeyValuePair<string, string>("sikbVersion", sikbVersion),
                    new KeyValuePair<string, string>("useZip", useZipstream.ToString() ),
                });
                HttpResponseMessage response = _HttpClient.PostAsync(_HttpClient.BaseAddress + "/GetProducts", content).Result;
                response.EnsureSuccessStatusCode();
                string responseMessage = response.Content.ReadAsStringAsync().Result;
                if (string.IsNullOrEmpty(responseMessage))
                {
                    throw new Exception("Empty response from: [" + _HttpClient.BaseAddress + " /GetProducts" + "]");
                }
                using (var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseMessage)))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(GetProductsCall.Response));
                    set = (GetProductsCall.Response)serializer.Deserialize(ms);
                }
                if (useZipstream && !string.IsNullOrEmpty(set.FileContent))
                {
                    //convert from base64 string back to normal
                    //first check for real Base64, by checking there is no 'xml'  in it
                    if (!set.FileContent.Contains("<labaanlevering"))
                    {
                        set.FileContent = ZipStreamHelper.DecompressBase64StringToString(set.FileContent);
                    }
                }
            }
            catch (Exception ex)
            {
                #region handle exception
                set.Status = new BusinessEntities.LabRestService.GetProductsCall.ResponseStatus();
                set.Status.StatusCode = ((int)ResultCodes.GeneralError).ToString();
                set.Status.ErrorMessage = "Exception occurred in GetProducts (username: " + WebserviceUsername + ", password: " + WebservicePassword + ") with message: " + ex.Message;
                ex.Data.Add("WebserviceUsername", WebserviceUsername);
                ex.Data.Add("WebservicePassword", WebservicePassword);
                ex.Data.Add("CustomerUsername", CustomerUsername);
                ex.Data.Add("sikbVersion", sikbVersion);
                ex.Data.Add("customerid", customerid);
                ex.Data.Add("languageCode", languageCode);
                ExceptionHandler.HandleException(ex);
                #endregion
            }
            return set;
        }	
POST https://<URL>/GetProducts HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: 81.175.89.24
Content-Length: 179
Expect: 100-continue
userName=<webservice_username>&password=<Webservice_password>&customerUsername=<customer_username or token>&languageCode=nld&clientId=300&sikbVersion=13.5.0&useZip=True	
Response example
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Response>
<FileContent> {SIKB FILE in ZIPSTREAM BASE64 format}</FileContent>
<Status>
<StatusCode>1</StatusCode>
<StatusCodeDescription>OK</StatusCodeDescription>
<ErrorMessage></ErrorMessage>
</Status></Response>	
Useraccount Checkup.
Solution/Design
With every call we will no longer send customer usernames and customer passwords. We want to use a fixed Machine 2 Machine username and password for TerraIndex. So we need to be able to quickly check whether the Customer username we want to use exists, and is bound to our TerraIndex fixed Machine 2 machine account.
WebserviceUsername (string),
WebservicePassword (string),
CustomerUsername (string)
Therefore we call a Webserice for ValidCredentials Check: 
Action	TerraIndex	 	Laboratorium	Parameters/Message	Remarks	ResultCodes	
1	Sends a request to the function: ValidCredentials().	>	 	WebserviceUsername (string),
WebservicePassword (string),
CustomerUsername (string)	We want to skip the Password of the customer, and we use the WebserviceUsername + WebservicePassword for real authentication.	 	
2	 	 	Receives the request and checks the combination of WebserviceUsername and WebservicePassword is Ok. Then checks the CustomerUsername is valid.	 	 	 	
3	 	<=	Sends back a Success of InvalidCredentials	ResultCode (),
ErrorMessage (string),	 	1 = Success,
2 = GeneralError,
3 = WrongSIKBVersion,
4 = InvalidCredentials,
5 = CustomerUsernameInvalid,
6 = CustomerUsernameNotValidForCustomerCode
7 = FileContentProblem,
8 = InvalidOrderId,
9 = OrderIdAlreadyApproved
10 = PDFNotAvailable	
Check ValidCredentials (POST)
Request example
public ValidCredentialsCall.Response ValidCredentials(string WebserviceUsername, string WebservicePassword, string CustomerUsername, string customerid)
        {
            ValidCredentialsCall.Response set = new ValidCredentialsCall.Response();
            try
            {
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("userName", WebserviceUsername),
                    new KeyValuePair<string, string>("password", WebservicePassword),
                    //new KeyValuePair<string, string>("clientId", customerid),   // Optional
                    new KeyValuePair<string, string>("customerUsername", CustomerUsername),
                });
                HttpResponseMessage response = _HttpClient.PostAsync(_HttpClient.BaseAddress + "/ValidCredentials", content).Result;
                response.EnsureSuccessStatusCode();
                string responseMessage = response.Content.ReadAsStringAsync().Result;
                if (string.IsNullOrEmpty(responseMessage))
                {
                    throw new Exception("Empty response from: [" + _HttpClient.BaseAddress + " / ValidCredentials" + "]");
                }
                using (var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseMessage)))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(ValidCredentialsCall.Response));
                    set = (ValidCredentialsCall.Response)serializer.Deserialize(ms);
                    return set;
                }
            }
            catch (Exception ex)
            {
                #region handle exception
                set.Status = new BusinessEntities.LabRestService.ValidCredentialsCall.ResponseStatus();
                set.Status.StatusCode = ((int)ResultCodes.GeneralError).ToString();
                set.Status.ErrorMessage = "Exception occurred in GetValidCredentials (username: " + WebserviceUsername + ", with message: " + ex.Message;
                ex.Data.Add("WebserviceUsername", WebserviceUsername);
                ex.Data.Add("WebservicePassword", WebservicePassword);
                ex.Data.Add("CustomerUsername", CustomerUsername);
                ExceptionHandler.HandleException(ex);
                #endregion
            }
            return set;
        }	
POST https://<URL>/ValidCredentials HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: 81.175.89.24
Content-Length: 125
Expect: 100-continue
userName=<webservice_username>&password=<Webservice_password>&clientId=<optional otherwise empty>&customerUsername=<customer_username or token>	
Response example
<?xml version="1.0" encoding="UTF-8" standalone="no"?><Response>
<Status>
<StatusCode>1</StatusCode>
<StatusCodeDescription>OK</StatusCodeDescription>
<ErrorMessage></ErrorMessage>
</Status>
</Response>	
Labassignment request delivery(POST)
Solution/Design
For this we create a Webservice for CreateOrder to create the order in the lab system.
After the creation, we would like to show an order overview of the laboratory in the future in PDF. The user can see the prices and can confirm or cancel.
Depending on the user's choice at the laboratory, to support this or not, TerraIndex calls the ApproveOrder or the CancelOrder.
For default we assume that we cannot do this yet, and TerraIndex sends needsApprovaIsSupported = false. If this becomes true in the future, the Lab can indicate whether or not it is necessary in the NeedsApprove field.
Action	TerraIndex	 	Laboratorium	Parameters/Message	Remarks	ResultCodes	
1	Sends a request to the function: CreateOrder().	>	 	WebserviceUsername (string),
WebservicePassword (string),
CustomerUsername (string),
FileContent_Base64 (string),
UseZipStream/UseZip (bool, default: 'false'),
CustomerCode (string),
SIKBVersion (string, default: '13.4.0'),
needsApprovalIsSupported (bool)	SIKB Version included, so labs can quickly check the version.
Besides SIKB 13.4.0, TerraIndex also supports 9.0.0.

Before sending the SIKB, validate to the XSD!
And to the XSLT?

needsApprovalIsSupported = false; means we dont get PDF with offerte. This will make is faster.
needsApprovalIsSupported = true; means lab will check the user setting to send a PDF Offerte back or not. (If the lab can support this.)	 	
2	 	 	Receives the request and checks the credentials.	 	 	 	
3	 	 	Credentials are valid, the Filecontent is checked on a valid Labassignment. When valid it will be processed and a OrderId is given.	 	Laboratorium saves the Sample GUIDs if it's SIKB 13 or higher.
Otherwise we use the idanlmons unique ID.	 	
 	 	 	Based on what customer, the order will be approved or the approve needs to be done in laboratorium system.	 	 	 	
4	 	<=	Sends back a Success with the new OrderId	ResultCode (),
ErrorMessage (string),
OrderId (string),
NeedsApprove (bool),
FileContent_Base64 (string),
UseZipStream/UseZip (bool, default: 'false'),	In the future labs will send back the PDF with the prices and some checks. To approve or cancel. For the first version this is not required yet and the fileContent remains empty.	1 = Success,
2 = GeneralError,
3 = WrongSIKBVersion,
4 = InvalidCredentials,
5 = CustomerUsernameInvalid,
6 = CustomerUsernameNotValidForCustomerCode
7 = FileContentProblem,
8 = InvalidOrderId,
9 = OrderIdAlreadyApproved
10 = PDFNotAvailable	
6	Receives the OrderId, and saves it.
 	 	 	 	Default for now laboratorium will send:
NeedsApprove = False,
PDF = Empty,
Zipstream = False,
 
In the future, do something with the PDF and show the PDF to users to Approve or Cancel.
This will be done by; NeedsApprove = true.

If NeedsApprove is False, the order is Processed and can't be changed in TI. Like it is now.

 	 	 	 	 	 	 	
 	IN THE FUTURE: APPROVEORDER	 	 	 	 	 	
7	Sends a request to the function: ApproveOrder().	=>	 	WebserviceUsername (string),
WebservicePassword (string),
CustomerUsername (string),
OrderId (string)	 	 	
8	 	 	Receives the approve and checks the credentials and the OrderId.	 	 	 	
9	 	<=	Sends back a Success with the new CertificateNr	ResultCode (),
ErrorMessage (string),
CertificateNr (string)	This process takes too long at some labs. Maybe this won't be workable...so maybe the CertificateNr return won't be possible. In this case, leave the CertificateNr empty. TerraIndex will read it from GetOrderStatus calls.	1 = Success,
2 = GeneralError,
3 = WrongSIKBVersion,
4 = InvalidCredentials,
5 = CustomerUsernameInvalid,
6 = CustomerUsernameNotValidForCustomerCode
7 = FileContentProblem,
8 = InvalidOrderId,
9 = OrderIdAlreadyApproved
10 = PDFNotAvailable	
10	Receives the CerificateNr and saves it.	 	 	 	 	 	
 	 	 	 	 	 	 	
 	IN THE FUTURE: CANCELORDER	 	 	 	 	 	
7	Sends a request to the function: CancelOrder().	>	 	WebserviceUsername (string),
WebservicePassword (string),
CustomerUsername (string),
OrderId (string)	 	 	
8	 	 	Receives the cancel and checks the credentials and the OrderId.	 	 	 	
9	 	<=	Sends back a Success 	ResultCode (),
ErrorMessage (string)	 	1 = Success,
2 = GeneralError,
3 = WrongSIKBVersion,
4 = InvalidCredentials,
5 = CustomerUsernameInvalid,
6 = CustomerUsernameNotValidForCustomerCode
7 = FileContentProblem,
8 = InvalidOrderId,
9 = OrderIdAlreadyApproved
10 = PDFNotAvailable	
10	Removes the OrderId and the IsSend to False	 	 	 	If OrderIsAleadyApproved, set the values to Approved and keep the OrderId and IsSend.	 	
 	 	 	 	 	 	 	
Create Order
Request example
public CreateOrderResponse.Response SendLabAssignment(string WebserviceUsername, string WebservicePassword, string CustomerUsername, string customerid, string sikbVersion, string assignmentXML, string languageCode, bool needsApprovalIsSupported = false)
        {
            CreateOrderResponse.Response set = new CreateOrderResponse.Response();
            try
            {
                bool useZipstream = true;
                MultipartFormDataContent content = new MultipartFormDataContent();
                //Add Formdata
                var formDataDictionary = new[]
                {
                    new KeyValuePair<string, string>("userName", WebserviceUsername),
                    new KeyValuePair<string, string>("password", WebservicePassword),
                    new KeyValuePair<string, string>("customerUserName", CustomerUsername),
                    new KeyValuePair<string, string>("clientId", customerid),
                    new KeyValuePair<string, string>("sikbVersion", sikbVersion),
                    new KeyValuePair<string, string>("languageCode", languageCode),
                    new KeyValuePair<string, string>("useZip", useZipstream.ToString() ),
                    new KeyValuePair<string, string>("needsApprovalIsSupported", needsApprovalIsSupported.ToString() ),
                    //new KeyValuePair<string, string>("orderXml", ZipStreamHelper.CompressToBase64String(assignmentXML)),
                    //new KeyValuePair<string, string>("orderXml", assignmentXML),
                };               
                foreach (var item in formDataDictionary)
                {
                    content.Add(new StringContent(item.Value), $"\"{item.Key}\"");
                }
                string filexml = string.Empty;
                if (useZipstream)
                {
                    filexml = ZipStreamHelper.CompressToBase64String(assignmentXML);
                }
                else
                {
                    filexml = assignmentXML;
                }
                //Add filecontent
                var fileContent = new ByteArrayContent(ZipStreamHelper.stringToByteArray(filexml));
                fileContent.Headers.ContentDisposition =
                        new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") //<- 'form-data' instead of 'attachment'
                        {
                            Name = "\"orderXml\"", // \" is needed so the message contains the quotes, wihtout it will fail
                            FileName = "\"VivaTerraIndexAssignment.xml\""
                        };
                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");               
                content.Add(fileContent);
                //Start sending
                HttpResponseMessage response = _HttpClient.PostAsync(_HttpClient.BaseAddress + "/CreateOrder", content).Result;
                response.EnsureSuccessStatusCode();
                string responseMessage = response.Content.ReadAsStringAsync().Result;
                if (string.IsNullOrEmpty(responseMessage))
                {
                    throw new Exception("Empty response from: [" + _HttpClient.BaseAddress + " /CreateOrder" + "]");
                }
                using (var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseMessage)))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(CreateOrderResponse.Response));
                    set = (CreateOrderResponse.Response)serializer.Deserialize(ms);
                }
                //Can contain a PDf with price information
                if (set.UseZip && !string.IsNullOrEmpty(set.FileContent))
                {
                    //convert from base64 string back to normal
                    set.FileContent = ZipStreamHelper.DecompressBase64StringToString(set.FileContent);                   
                }
            }
            catch (Exception ex)
            {
                #region handle exception
                set.Status = new BusinessEntities.LabRestService.CreateOrderResponse.ResponseStatus();
                set.Status.StatusCode = ((int)ResultCodes.GeneralError).ToString();
                set.Status.ErrorMessage = "Exception occurred in CreateOrder (username: " + WebserviceUsername + ") with message: " + ex.Message;
                ex.Data.Add("WebserviceUsername", WebserviceUsername);
                ex.Data.Add("WebservicePassword", WebservicePassword);
                ex.Data.Add("CustomerUsername", CustomerUsername);
                ex.Data.Add("sikbVersion", sikbVersion);
                ex.Data.Add("customerid", customerid);
                ExceptionHandler.HandleException(ex);
                #endregion
            }
            return set;
        }	
POST https://<URL>/CreateOrder HTTP/1.1
Content-Type: multipart/form-data; boundary="28a3e130-70c9-4a1a-b544-a802a1ade6ca"
Host: 81.175.89.24
Content-Length: 5010
Expect: 100-continue
--28a3e130-70c9-4a1a-b544-a802a1ade6ca
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="userName"
<Webservice_Username>
--28a3e130-70c9-4a1a-b544-a802a1ade6ca
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="password"
<Webservice_Password>
--28a3e130-70c9-4a1a-b544-a802a1ade6ca
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="customerUserName"
<Customer_Username or token>
--28a3e130-70c9-4a1a-b544-a802a1ade6ca
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="clientId"
300
--28a3e130-70c9-4a1a-b544-a802a1ade6ca
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="sikbVersion"
13.4.0
--28a3e130-70c9-4a1a-b544-a802a1ade6ca
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="languageCode"
nld
--28a3e130-70c9-4a1a-b544-a802a1ade6ca
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="useZip"
True
--28a3e130-70c9-4a1a-b544-a802a1ade6ca
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="needsApprovalIsSupported"
False
--28a3e130-70c9-4a1a-b544-a802a1ade6ca
Content-Disposition: form-data; name="orderXml"; filename="VivaTerraIndexAssignment.xml"
Content-Type: application/xml
<SIKB File in Zip stream Base64  encoding>
--28a3e130-70c9-4a1a-b544-a802a1ade6ca--	
Response example
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Response>
<OrderId>7113828</OrderId>
<NeedsApproval>True</NeedsApproval>
<FileContent></FileContent>
<Status>
    <StatusCode>1</StatusCode>
    <StatusCodeDescription>OK</StatusCodeDescription>
    <ErrorMessage></ErrorMessage>
</Status></Response>	
Get Order status and Results XML and with PDF
Solution/Design
TerraIndex will request per license/customer which results are ready. These are queried if the latest changes are newer than the last check. This way we never download too much unnecessarily and it can always be requested again.
Order status we support as minimal:
3 = Reportnumber is known, no results yet, but it's the official report certificate number. This is optional to send.
4 = Conceptual, temporary results avaiable, but not final yet. This is optional to send.
5 = Final results are available. This is required to send.
Action	TerraIndex	 	Laboratorium	Parameters/Message	Remarks	ResultCodes	
1	Sends a request to the function: GetCustomers().	>	 	WebserviceUsername (string), 
WebservicePassword (string),
CustomerUsername (string)	We want to skip the Password of the customer, and we introduce the WebserviceUsername + WebservicePassword.	 	
2	 	 	Receives the request and check the customers this username and searches the dateLastChanged for this Customer.	 	 	 	
3	 	<=	Sends back the list of customers to check for orderStatuses	ResultCode (),
ErrorMessage (string),
List<customer> , Customer:
CustomerCode (string),
CustomerName (string),
LabID (int),
LabName (string),
ChangedTimeStamp (DateTime)	We receive the dateTimestamp instead of sending it, so we always get the full list and we are also able to delete customercodes.	1 = Success,
2 = GeneralError,
3 = WrongSIKBVersion,
4 = InvalidCredentials,
5 = CustomerUsernameInvalid,
6 = CustomerUsernameNotValidForCustomerCode
7 = FileContentProblem,
8 = InvalidOrderId,
9 = OrderIdAlreadyApproved
10 = PDFNotAvailable	
4	Receives the list of Customers. Read the Timestamp this Customer is last checked for Results/Statuses.	 	 	 	 	 	
5	Send for each Customer a  call to retreive all orders statuses changes since a certain timestamp.
Function: GetOrderStatuses()	>	 	WebserviceUsername (string), 
WebservicePassword (string),
CustomerUsername (string),
CustomerCode (string),
LastCheckedTimestamp (DateTime)	TerraIndex keeps track of the last check timestamp for each license.	 	
6	 	 	Receives the request and check the orders that are changed since the timestamp for this Customer.	 	 	 	
7	 	<=	Sends back the list of orders with the status and lastChangedTimestamp	ResultCode (),
ErrorMessage (string),
OrderID (string),
LabassignmentGUID (GUID),
CertificateNumber (string)
OrderStatusSIKB (int),
Delayed (boolean),
ExpectedTimeStamp (DateTime),	OrderStatusSIKB is the SIKB Labassignment status.

Delayed is a boolean to tell the customer a order will be later ready then expected. The ExpectedTimestamp.
If Delayed for the firsttime, TerraIndex can send a notification to the users and show a different layout.

LabassignmentGUID is filled to support also Labassignments that are not from TerraIndex Ordered.	1 = Success,
2 = GeneralError,
3 = WrongSIKBVersion,
4 = InvalidCredentials,
5 = CustomerUsernameInvalid,
6 = CustomerUsernameNotValidForCustomerCode
7 = FileContentProblem,
8 = InvalidOrderId,
9 = OrderIdAlreadyApproved
10 = PDFNotAvailable	
8	Receives the list of Orders with status.
Update the CertificateNr if this is not already present in the labassignment. 	 	 	 	CertifcateNumber could be new here, if the lab wasn't able to fill it directly at the ApproveOrder.	 	
9	Send for each Order a call to retreive all results.
Function: GetOrderResults()	>	 	WebserviceUsername (string), 
WebservicePassword (string),
CustomerUsername (string),
CustomerCode (string),
OrderID (string),
SIKBVersion (string, default: '13.4.0')	Besides SIKB 13.4.0, TerraIndex also supports 9.0.0/8.0.0 etc.	 	
10	 	 	Receives the request and creates a SIKB results file based on the version that is requested.	 	 	 	
11	 	<=	Sends back the results of the orders.	ResultCode (),
ErrorMessage (string),
OrderId (string),
LabassignmentGUID (GUID),
FileContent_Base64 (string),
UseZipStream/UseZip (bool, default: 'false'),	 	1 = Success,
2 = GeneralError,
3 = WrongSIKBVersion,
4 = InvalidCredentials,
5 = CustomerUsernameInvalid,
6 = CustomerUsernameNotValidForCustomerCode
7 = FileContentProblem,
8 = InvalidOrderId,
9 = OrderIdAlreadyApproved
10 = PDFNotAvailable	
12	Receives the results and imports all results.	 	 	 	Import will be done to corresponding samples based on:
•	Find Project by ProjectGUID (as provided in the labassignment)
•	Find Project by ProjectCode (as provided in the Labassignment)
•	Find Project and Labassignment by LabassignmentGUID (as provided in the Labassignment)
•	Find Project (only if Project is not found yet) and Samples based on SampleGUID (as provided in the Labassignment) .
Sample GUIDs that are send to the lab in the labassignment version SIKB 13 or higher are required in the results for labassignment.
For lower version Labassignments the lab should return the 'old' idanlmons as SampleGUID in the XML.
•	Find Samples (only if Project is already found ) by SampleName
What is imported?
•	If Sample is found, the results in the XML are always all updated and/or inserted.
•	If Project is found, but the sample is not; The Sample and the results are inserted as new Sample. (If watersample; fake filtertube and fake measurementpoints are created)	 	
13	If OrderStatus is 'Completed/Reported' (SIKBID: 5)
Request the PDF certificate.
Function: GetOrderPDF()	>	 	WebserviceUsername (string), 
WebservicePassword (string),
CustomerUsername (string),
CustomerCode (string),
OrderID (string),	 	 	
14	 	 	Receives the request and creates the PDF for the Order.	 	 	 	
15	 	<=	Sends back the PDF of the order.	ResultCode (),
ErrorMessage (string),
OrderId (string),
LabassignmentGUID (GUID),
FileContent_Base64 (string),
UseZipStream/UseZip (bool, default: 'false'),	If the PDF is not available yet, please give the resultcode: PDFNotAvailable.	1 = Success,
2 = GeneralError,
3 = WrongSIKBVersion,
4 = InvalidCredentials,
5 = CustomerUsernameInvalid,
6 = CustomerUsernameNotValidForCustomerCode
7 = FileContentProblem,
8 = InvalidOrderId,
9 = OrderIdAlreadyApproved
10 = PDFNotAvailable	
12	Receives the PDF and stores it for reporting and downloading.	 	 	 	 	 	
Request example Order Status
public GetOrderStatusesCall.Response OrderStatuses(string WebserviceUsername, string WebservicePassword, string CustomerUsername, string customerid, DateTime? timestampSince)
        {
            GetOrderStatusesCall.Response set = new GetOrderStatusesCall.Response();
            string responseMessage = null;
            if (timestampSince == null) timestampSince = DateTime.Now.AddHours(-3); //Now, minus 3 hours
            var formattedTimestamp = System.Xml.XmlConvert.ToString((DateTime)timestampSince, System.Xml.XmlDateTimeSerializationMode.RoundtripKind);
            try
            {               
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("userName", WebserviceUsername),
                    new KeyValuePair<string, string>("password", WebservicePassword),
                    new KeyValuePair<string, string>("customerUsername", CustomerUsername),
                    new KeyValuePair<string, string>("clientId", customerid),
                    new KeyValuePair<string, string>("lastModified", formattedTimestamp),
                });
                HttpResponseMessage response = _HttpClient.PostAsync(_HttpClient.BaseAddress + "/GetOrderStatuses", content).GetAwaiter().GetResult();                
                responseMessage = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                response.EnsureSuccessStatusCode();
                if (string.IsNullOrEmpty(responseMessage))
                {
                    throw new Exception("Empty response from: [" + _HttpClient.BaseAddress + " /GetOrderStatuses" + "]");
                }
                using (var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseMessage)))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(GetOrderStatusesCall.Response));
                    set = (GetOrderStatusesCall.Response)serializer.Deserialize(ms);
                }                
            }
            catch (Exception ex)
            {
                #region handle exception
                set.Status = new BusinessEntities.LabRestService.GetOrderStatusesCall.ResponseStatus();
                set.Status.StatusCode = ((int)ResultCodes.GeneralError).ToString();
                set.Status.ErrorMessage = "Exception occurred in GetOrderStatuses (username: " + WebserviceUsername + ", password: " + WebservicePassword + ") with message: " + ex.ToString();
                ex.Data.Add("Response", responseMessage);
                ex.Data.Add("WebserviceUsername", WebserviceUsername);
                ex.Data.Add("WebservicePassword", WebservicePassword);
                ex.Data.Add("CustomerUsername", CustomerUsername);
                ex.Data.Add("customerid", customerid);
                ex.Data.Add("lastModified", formattedTimestamp);
                ex.Data.Add("Result", set);
                throw;
                #endregion
            }
            return set;
        }        
Response Status XML Example
      <?xml version="1.0" encoding="UTF-8" standalone="no"?>
            <Response>
                <Orders>
                    <Order>
                        <OrderStatus>Reported</OrderStatus>
                        <SIKBOrderId></SIKBOrderId>
                        <SIKBOrderStatus>5</SIKBOrderStatus>
                        <OrderId>4855422</OrderId>
                        <RapportNummer>12193838</RapportNummer>
                        <IsDelayed>False</IsDelayed>
                        <ExpectedOn>09/10/2015 17:15:00</ExpectedOn>
                    </Order>
                    <Order>
                        <OrderStatus>New</OrderStatus>
                        <SIKBOrderId></SIKBOrderId>
                        <SIKBOrderStatus>3</SIKBOrderStatus>
                        <OrderId>7106525</OrderId>
                        <RapportNummer>02808304-0749-41ae-96eb-d62b0365ebe4</RapportNummer>
                        <IsDelayed>False</IsDelayed>
                        <ExpectedOn></ExpectedOn>
                    </Order>
                    <Order>
                        <OrderStatus>New</OrderStatus>
                        <SIKBOrderId></SIKBOrderId>
                        <SIKBOrderStatus>3</SIKBOrderStatus>
                        <OrderId>7108954</OrderId>
                        <RapportNummer>10776137-ef99-4947-9a6a-9a3b32cd2dec</RapportNummer>
                        <IsDelayed>False</IsDelayed>
                        <ExpectedOn></ExpectedOn>
                    </Order>
                    <Order>
                        <OrderStatus>New</OrderStatus>
                        <SIKBOrderId></SIKBOrderId>
                        <SIKBOrderStatus>3</SIKBOrderStatus>
                        <OrderId>7110401</OrderId>
                        <RapportNummer>7881575c-bee2-409f-b304-9e472e7ac702</RapportNummer>
                        <IsDelayed>False</IsDelayed>
                        <ExpectedOn>11/10/2018 00:00:00</ExpectedOn>
                    </Order>
                </Orders>
                <Status>
                    <StatusCode>1</StatusCode>
                    <StatusCodeDescription>OK</StatusCodeDescription>
                    <AtmisErrorCode>0</AtmisErrorCode>
                    <ErrorMessage></ErrorMessage>
                </Status>
            </Response>
Request example Order XML
public GetOrderResultsCall.Response GetOrderResults(string WebserviceUsername, string WebservicePassword, string CustomerUsername, string customerid, string orderid, string sikbVersion)
        {
            GetOrderResultsCall.Response set = new GetOrderResultsCall.Response();
            string responseMessage = null;
            try
            {
                bool useZipstream = true;
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("userName", WebserviceUsername),
                    new KeyValuePair<string, string>("password", WebservicePassword),
                    new KeyValuePair<string, string>("customerUsername", CustomerUsername),                    
                    new KeyValuePair<string, string>("clientId", customerid),
                    new KeyValuePair<string, string>("orderId", orderid),
                    new KeyValuePair<string, string>("sikbVersion", sikbVersion),
                    new KeyValuePair<string, string>("useZip", useZipstream.ToString() ),
                });
                HttpResponseMessage response = _HttpClient.PostAsync(_HttpClient.BaseAddress + "/GetOrderResults", content).GetAwaiter().GetResult();                
                responseMessage = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                response.EnsureSuccessStatusCode();
                if (string.IsNullOrEmpty(responseMessage))
                {
                    throw new Exception("Empty response from: [" + _HttpClient.BaseAddress + " /GetOrderResults" + "]");
                }
                using (var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseMessage)))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(GetOrderResultsCall.Response));
                    set = (GetOrderResultsCall.Response)serializer.Deserialize(ms);
                }
                if (useZipstream && !string.IsNullOrEmpty(set.FileContent))
                {
                    //convert from base64 string back to normal
                    //first check for real Base64, by checking there is no 'xml'  in it
                    //If encoded, it wont contain either of the root XML tags of SIKB
                    if (!set.FileContent.Contains("FeatureCollectionIMSIKB0101") && !set.FileContent.Contains("labresultaat"))
                    {
                        set.FileContent = ZipStreamHelper.DecompressBase64StringToString(set.FileContent);
                    }
                }
            }
            catch (Exception ex)
            {
                #region handle exception
                set.Status = new BusinessEntities.LabRestService.GetOrderResultsCall.ResponseStatus();
                set.Status.StatusCode = ((int)ResultCodes.GeneralError).ToString();
                set.Status.ErrorMessage = "Exception occurred in GetOrderResults (username: " + WebserviceUsername + ", password: " + WebservicePassword + ") with message: " + ex.ToString();
                ex.Data.Add("Response", responseMessage);
                ex.Data.Add("WebserviceUsername", WebserviceUsername);
                ex.Data.Add("WebservicePassword", WebservicePassword);
                ex.Data.Add("CustomerUsername", CustomerUsername);
                ex.Data.Add("sikbVersion", sikbVersion);
                ex.Data.Add("customerid", customerid);
                ex.Data.Add("orderId", orderid);
                ex.Data.Add("Result", set);
                throw;
                #endregion
            }
            return set;
Response Order XML Example
        
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
       <Response>
                <FileContent>DhVn3Q1AA==</FileContent>  //BASE64 Zip Stream, SIKB0101 labresults xml file
                <Status>
                    <StatusCode>1</StatusCode>
                    <StatusCodeDescription>OK</StatusCodeDescription>
                    <AtmisErrorCode>0</AtmisErrorCode>    
                    <ErrorMessage></ErrorMessage>
                </Status>
            </Response>
Request example Order PDF File
              bool useZipstream = true;  // Always Supported, Keep it true!!
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("userName", WebserviceUsername),
                    new KeyValuePair<string, string>("password", WebservicePassword),
                    new KeyValuePair<string, string>("customerUsername", CustomerUsername),
                    new KeyValuePair<string, string>("clientId", customerid),
                    new KeyValuePair<string, string>("orderId", orderid),
                    new KeyValuePair<string, string>("useZip", useZipstream.ToString()), // Always Supported, Keep it true!!.
                    new KeyValuePair<string, string>("languageCode", languageCode)
                });
                HttpResponseMessage response = _HttpClient.PostAsync("GetOrderPdf", content).GetAwaiter().GetResult();                
                responseMessage = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                response.EnsureSuccessStatusCode();
Response Order PDF Example
            <Response>
                <OrderId>7113737</OrderId>
                <FileContent>
                            BASE64 encoded file
                </FileContent>
                <Status>
                    <StatusCode>1</StatusCode>
                    <StatusCodeDescription>OK</StatusCodeDescription>
                    <ErrorMessage></ErrorMessage>
                </Status>
            </Response>
Customer wants to see real time information about the status in the interface
Solution/Design
To always show up-to-date information in the TerraIndex interface when a user opens a lab assignment to see the status, we reuse part of the GetOrderStatus, but with a specific OrderID.
..NOT SUPPORTED YET...
Action	TerraIndex	 	Laboratorium	Parameters/Message	Remarks	ResultCodes	
1	Request the Order status for a single Order/Labassignment.
Function: GetOrderStatus()	>	 	WebserviceUsername (string), 
WebservicePassword (string),
CustomerUsername (string),
CustomerCode (string),
OrderID (string),	 	 	
2	 	 	Receives the request and gets the status for the Order.	 	 	 	
3	 	<=	Sends back the status of the order.	ResultCode (),
ErrorMessage (string),
OrderID (string),
LabassignmentGUID (GUID),
CertificateNumber (string)
OrderStatusSIKB (int),
Delayed (boolean),
ExpectedTimeStamp (DateTime),	OrderStatusSIKB is the SIKB Labassignment status.

Delayed is a boolean to tell the customer a order will be later ready then expected. The ExpectedTimestamp.
If Delayed for the firsttime, TerraIndex can send a notification to the users and show a different layout.

LabassignmentGUID is filled to support also Labassignments that are not from TerraIndex Ordered.	1 = Success,
2 = GeneralError,
3 = WrongSIKBVersion,
4 = InvalidCredentials,
5 = CustomerUsernameInvalid,
6 = CustomerUsernameNotValidForCustomerCode
7 = FileContentProblem,
8 = InvalidOrderId,
9 = OrderIdAlreadyApproved
10 = PDFNotAvailable	
4	Receives the status and shows in the interface the updated info.
Update the CertificateNr if this is not already present in the labassignment. 	 	 	 	CertifcateNumber could be new here, if the lab wasn't able to fill it directly at the ApproveOrder.