.NET SDK
Learn more about the Keyfax Web API .NET SDK.
To use the Keyfax Web API .NET SDK to interact with the Keyfax Web API end points you will first need to add an assembly reference to the Keyfax.WebApi.Sdk.dll file from your existing C# or VB.NET .NET project. The Keyfax.WebApi.Sdk.dll assembly targets .NET Framework 4.8 so your project will also need to target .NET Framework 4.8 to reference this assembly.
Once you've added an assembly reference to Keyfax.WebApi.Sdk.dll you can then begin using the various methods provided with the Keyfax Web API .NET SDK as demonstrated below. The main KeyfaxClient class exists within the Keyfax.WebApi.Sdk.Basic.v1 namespace so you will likely need to use or import this namespace into your existing classes as shown below...
C#
At the top of your C# class...
using Keyfax.WebApi.Sdk.Basic.v1;
VB.NET
At the top of your VB.NET class...
Imports Keyfax.WebApi.Sdk.Basic.v1
All further code examples will only be provided in C# however it is of course also possible to use the Keyfax Web API .NET SDK from a VB.NET project.
Obtaining Initial Keyfax Web API Keys
Before you can start calling the Keyfax Web API end points you must first obtain an API and signing key. These keys are required to verify requests into the Keyfax Web API. You can obtain these keys programmatically via the Keyfax Web API by calling GET /api/v1/key?hostName=Dev, GET /api/v1/key?hostName=Test or GET /api/v1/key?hostName=Live. If you can't programmatically obtain your keys via the Keyfax Web API for any reason please contact Omfax support for assistance with generating and providing your initial Keyfax Web API keys.
To obtain initial keys you can only call GET /api/v1/key once for each supplied host name. Once keys have been generated for the supplied host name this request will fail and return a 400 Bad Request response. In addition for initial key generation to succeed for the supplied host name a WebApi/KeyGen element must exist within the kfServerConfig.xml file within the Keyfax web application with a hostName attribute matching the supplied host name. As this request will only succeed the very first time it's important you save or make a note of the returned API keys before attempting to call this end point again.
To obtain initial keys hosts can make a request to GET /api/v1/key?hostName=Dev. If no existing keys exist for the supplied host name then the very first request to GET /api/v1/key will always return new keys that can be used for subsequent verified Keyfax Web API requests. The following C# code example shows how to use the Keyfax Web API .NET SDK to programmatically obtain initial keys for a host named "Dev" and save these newly generated Keyfax Web API keys locally within the host environment for subsequent Keyfax Web API requests...
// Configure client, no host name, API key or signing key are required when generating initial keys
var client = new KeyfaxClient(c =>
{
c.BaseUrl = "https://keyfaxurl.com/Interview/";
});
// Call GET /api/v1/key to obtain initial Keyfax Web API keys.
var hostName = "Dev"; // The host name to create the keys for
var response = await client.GetKeyAsync(hostName);
if (response.Success)
{
if (response.Data != null)
{
// Save keys locally for future use
var newKeys = await KeyStore.SaveKeysAsync(new ApiKeys()
{
HostName = response.Data.HostName,
ApiKey = response.Data.ApiKey,
SigningKey = response.Data.SigningKey
});
}
}
else
{
// Initial keys could not be created, the reason will be available within the response body
Console.WriteLine($"{response.StatusCode} - {response.Body}");
}In the above code example we are generating new API keys for a host named "Dev". The supplied host name allows you to generate unique keys for different environments that may be accessing the same Keyfax Web API. By default Keyfax comes pre-configured with 3 default host names "Dev", "Test", & "Live".
For initial key generation to succeed for the supplied host name a WebApi/KeyGen element must exist within the kfServerConfig.xml file within the Keyfax web application with a hostName attribute matching the host name supplied to GET /api/v1/key. The following configuration demonstrates a valid entry within kfServerConfig.xml for our "Dev" host...
<KFServerConfig>
<WebApi>
<KeyGen hostName="Dev" WebHookUrl="http://hosturl.com/KeyfaxApiKeyWebHook.aspx" Email="[email protected]"/>
</WebApi>
</KFServerConfig>When calling GET /api/v1/key If keys are generated and returned successfully a 201 Created status code will be returned and the Host Name, API key and Signing Key required to verify requests into the Keyfax Web API will be presented within the response body.
To assist the KeyStore class used within the code example above to save the Keyfax Web API keys locally on the file system is provided below. It's important to note that hosts would typically implement their own method for storing Keyfax Web API keys. For example you may choose to save these keys to your database or within a more secure key vault solution.
/// <summary>
/// A simple example key store. For demonstration purposes only.
/// </summary>
public static class KeyStore
{
// Keys are saved locally to this file
private const string KeysFileName = "keys.txt";
/// <summary>
/// Get previously saved keys from the local key store.
/// </summary>
/// <returns></returns>
public async static Task<ApiKeys> GetKeysAsync()
{
var directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var path = Path.Combine(directory, KeysFileName);
try
{
var fileText = string.Empty;
if (File.Exists(path))
{
using (var sr = new StreamReader(path))
{
fileText = await sr.ReadToEndAsync();
}
}
if (!string.IsNullOrEmpty(fileText))
{
// We save the key as a plain text file in this example like so...
// {hostName}:{apiKey}:{signingKey}
var fileParts = fileText.Split(':');
// Ensure expected length
if (fileParts.Length == 3)
{
return new ApiKeys()
{
HostName = fileParts[0],
ApiKey = fileParts[1],
SigningKey = fileParts[2]
};
}
}
}
catch
{
throw; // re-throw any exceptions
}
// keys not found or invalid
return null;
}
/// <summary>
/// Save keys to a plain text file on the local file system.
/// This is for demonstration purposes only and keys should be stored in a more secure manner.
/// </summary>
/// <param name="hostName">The Keyfax host name.</param>
/// <param name="apiKey">The Keyfax API key</param>
/// <param name="signingKey">The Keyfax Signing key</param>
/// <returns></returns>
public async static Task<ApiKeys> SaveKeysAsync(ApiKeys keyData)
{
var directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var path = Path.Combine(directory, KeysFileName);
try
{
using (var sw = new StreamWriter(path))
{
await sw.WriteLineAsync($"{keyData.HostName}:{keyData.ApiKey}:{keyData.SigningKey}");
}
}
catch
{
throw; // re-throw any exceptions
}
// Return saved keys
return await GetKeysAsync();
}
}The simple ApiKeys POCO referenced by the key store example above is shown below...
public class ApiKeys
{
public string HostName { get; set; }
public string ApiKey { get; set; }
public string SigningKey { get; set; }
}Once you've obtained an initial API & Signing Key for the supplied host name you can then use these keys and host name to make verified requests into the Keyfax Web API using the .NET SDK.
Configuring the .NET SDK
When using the main KeyfaxClient class provided with the Keyfax Web API .NET SDK to make verified requests you must supply a URL, host name, API key & Signing key. You would typically configure the KeyfaxClient class once and then use the methods provided by this class to make any number of requests into the Keyfax Web API.
The following C# code demonstrates how to configure the Keyfax Web API .NET SDK KeyfaxClient class...
using Keyfax.WebApi.Sdk.Basic.v1
...
var client = new KeyfaxClient(c =>
{
c.BaseUrl = "https://keyfaxurl.com/Interview/";
c.HostName = "Dev";
c.ApiKey= "YourAPIKey";
c.SigningKey = "YourSigningKey";
});A description of each property is provided below...
BaseUrl
The BaseUrl is always required. This is the full absolute URL to your Keyfax web application. For example http://localhost:8080/Interview/, http://web-server/Interview/ or http://dnsname.com/Interview/.
HostName
IMPORTANT The host name is case-sensitive and should be consistent casing across all requests into the Keyfax Web API. If you create keys for a host named "Dev" and attempt to verify a request using a host name of "DEV" this request will fail even if the supplied API and signing key are valid as the host name casing does not match.
The host name will be used to determine which API keys are used to verify the request. The host name also controls how Keyfax Web API keys are initially created & reset if compromised. A WebApi/KeyGen element with a matching hostName attribute must be configured within the Keyfax kfServerConfig.xml file for key creation & resets to work correctly.
Typical values for the host name would include: Live, Test, Dev etc.
API & Signing Key
To verify certain requests you must provide your API & signing keys when configuring the Keyfax .NET SDK client.
Launching Keyfax
IMPORTANT The start-up data you provide to Keyfax should be customized to suit your environment & host integration. The start-up data presented here in these examples is minimal and for demonstration purposes only. Please contact Omfax Systems for assistance with configuring your specific integration to fully leverage the Intelligent Scripting capabilities within Keyfax.
After configuring the Keyfax Web API KeyfaxClient class as shown above you can then call methods on this class to return strongly typed .NET objects from the Keyfax Web API end points. For example to return launch data for Keyfax you can call the PostStartUpDataAsync method supplying valid start-up data as demonstrated in the following C# example...
public async void GetKeyfaxLaunchDetails()
{
// Configure client, hard coded for demonstration purposes only
var client = new KeyfaxClient(c =>
{
c.BaseUrl = "https://keyfaxurl.com/Interview/";
c.HostName = "Dev";
c.ApiKey = "6b1261ff-2472-4c5a-82c2-f7f96176de70";
c.SigningKey = "98f8NgUHbRmyyqA9t3QpNPj8OZ9cfCmsXQs33JFF2Lzl8WE7F2/XSQuEQzDQ/i/qOhlQW8oCLpSd5ge30G3uWw==";
});
// Build sample start-up data, this data would need to be customized based on
// the host and Keyfax configuration, this is only provided for demonstration purposes
var startUpData = new StartUpData()
{
Mode = new StartUpDataItem()
{
Value = "ROL"
},
UserName = new StartUpDataItem()
{
Value = "administrator"
},
Password = new StartUpDataItem()
{
Value = "Global"
},
Company = new StartUpDataItem()
{
Value = "ROL_Live",
},
ScriptSet = new StartUpDataItem()
{
Value = "ROL"
}
};
// Make the request to POST api/v1/startup to obtain launch data
var result = await client.PostStartUpAsync(startUpData);
// Was the request successful?
if (result.Success)
{
// Ensure the request returned launch data
if (result.Data != null)
{
// Just provided for demonstration purposes
Console.WriteLine("Launch Guid: " + result.Data.Guid);
Console.WriteLine("Launch Company: " + result.Data.Company);
Console.WriteLine("Launch Url: " + result.Data.LaunchUrl);
}
}
}Using the returned LaunchUrl you can then launch a Keyfax session within the users default web browser or within an embedded web browser or frame within your application. The Guid and Company information returned from this request can be used later to obtain results for the launched Keyfax session via the POST /api/v1/results end point.
Obtaining Keyfax Results
When a user completes or cancels a script within Keyfax this completes the launched Keyfax session. Results for the launched Keyfax session can be obtained from a host system via a call to POST /api/v1/results or by using the PostResultsAsync method provided within the .NET SDK. The following C# code demonstrates how to obtain results for a previously launched Keyfax session using the Keyfax Web API .NET SDK...
public async void GetKeyfaxResults()
{
// Hard coded for demonstration purposes only
var client = new KeyfaxClient(c =>
{
c.BaseUrl = "https://keyfaxurl.com/Interview/";
c.HostName = "Dev";
c.ApiKey = "6b1261ff-2472-4c5a-82c2-f7f96176de70";
c.SigningKey = "98f8NgUHbRmyyqA9t3QpNPj8OZ9cfCmsXQs33JFF2Lzl8WE7F2/XSQuEQzDQ/i/qOhlQW8oCLpSd5ge30G3uWw==";
});
// Internally calls POST /api/v1/results supplying required Guid & Company to obtain Keyfax results
// The Guid & Company are hard coded for demonstration purposes only
// The Guid & Company would normally be obtained via the Keyfax launch details
var result = await client.PostResultsAsync(new StartUpResult()
{
Guid = "GuidReturnedFromPostStartUpAsync",
Company = "CompanyReturnedFromPostStartUpAsync"
});
// Was the request successful?
if (result.Success)
{
// Ensure the request returned data
if (result.Data != null)
{
// Iterate each property in our results and display
foreach (var prop in result.Data)
{
Console.WriteLine("Key: " + prop.Key);
Console.WriteLine("Value: " + prop.Value);
}
}
}
}Available SDK Methods
A brief summary of each method available within the Keyfax Web API .NET SDK is provided below.
GetStartUpAsync(GET /api/v1/startup) Returns minimal example start-up data for the current master configuration.PostStartUpAsync(POST /api/v1/startup) Post start-up data to Keyfax to obtain launch resultsPostResultsAsync(POST /api/v1/results) Post launch results to Keyfax to obtain diagnostic results.GetTokenAsync(GET /api/v1/token) Obtain a valid JSON Web Token for client sideBearerauthentication.GetKeyAsync(GET /api/v1/key) Obtain initial API & Signing Keys forBasicauthentication.PostKeyAsync(POST /api/v1/key) Generate new API & Signing Keys forBasicauthentication.
Known Issues
When working with the Keyfax Web API .NET SDK you may encounter one or more of the following errors or warnings.
Could not load file or assembly 'System.Net.Http.Formatting
The full error message is shown below...
{"Could not load file or assembly 'System.Net.Http.Formatting, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.":"System.Net.Http.Formatting, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"}Please ensure you've added the dependencies required by Keyfax.WebApi.Sdk.dll to your project as detailed within the section below.
.NET SDK dependencies
It may be necessary to add one or more of the following NuGet packages to your project to fully leverage the Keyfax Web API .NET SDK. If adding these packages is necessary please ensure you add the versions shown below.
Microsoft.AspNet.WebApi.Client(5.2.7)Microsoft.AspNet.WebApi.Core(5.2.7)Newtonsoft.Json(7.0.1+)
Last updated