USA
800 691 9120
UK
01225 704844
We use cookies on our website to analyze website usage and to help secure the website against misuse. Advertising and functional cookies are not used in our site or our web application products.
By clicking “Accept Essential Cookies Only”, you consent to us placing these cookies.
Download the Visual Studio API Samples Project
This guide provides comprehensive documentation for integrating with the xAssets API, including working code examples derived from the official APIExample project.
There are two ways to execute API calls in xAssets Applications
The option to embed API functionality within transformations requires no programming expertise and does not need to be hosted on a computer, since the programs will exist within your xAssets database, and xAssets Engineers will write the scripts for you. These scripts can still be triggered from an external program.
When using restful calls, all methods automatically route through to one of three interfaces:
One restful call is needed to get an authorization token, and this is then used in subsequent restful calls to get data and run queries from the database. API get commands are listed below.
Using restful calls, you explicitly call the web services interface as follows:
These methods are described in detail in the API Interface section.
This section links to methods which are most commonly used.
Most tasks can be achieved within transformations, which can run on a schedule, a trigger, or be manually launched from any menu item. This includes notifications, emailing reports, imports, exports, data manipulation and integration to other local and cloud applications.
Get operations are called using the API Interface Function named "CommandProcessor".
SaveSpecial operations are specialized save methods called using the Restful API Interface Function named "SaveSpecial". SaveSpecial and Save operations are only available through the restful API from version 7.3.43 or later.
In order to save XML, which was retrieved from a table or API method, and then modified, use the WebSaveXML function.
The example programs provided include the most commonly used interface methods.
The xAssets API provides programmatic access to your asset management data. It supports multiple connection methods and allows you to:
This guide focuses on practical implementation using the provided helper classes and working examples.
The xAssets API supports four connection types:
| Type | Enum Value | Description | Recommended |
|---|---|---|---|
RESTful |
Restful = 1 |
HTTP-based REST API using bearer tokens | Yes - Standard API use |
WebSocket |
Sockets = 2 |
Persistent WebSocket connection (WSS) | Yes - Real-time/persistent connections |
SOAP |
SOAP = 3 |
Legacy SOAP/XML web service | No - Backward compatibility only |
SOAP AD |
SOAPActiveDirectory = 4 |
SOAP with Active Directory authentication | No - Backward compatibility only |
Install-Package Newtonsoft.Json
Install-Package System.Net.WebSockets
Add the provided helper classes to your project:
xAssetsAPIConnection.vb (or .cs) - Main API connection classWebSocketClient.vb (or .cs) - WebSocket communication handlerJSONRecord.vb (or .cs) - JSON helper classAdd required imports:
Imports System.Security
Imports System.Xml
Imports Newtonsoft.Json.Linq
using System.Security;
using System.Xml;
using Newtonsoft.Json.Linq;
For RESTful and WebSocket connections, use an API Key:
' Create connection
Dim cs As New xAssetsAPIConnection(
Nothing, ' proxy (Nothing for no proxy)
xAssetsAPIConnection.ConnectionTypeEnum.Restful, ' connection type
"mydatabase", ' database name
44301, ' port
"mycompany.hosted.xassets.net", ' hostname
"https", ' scheme
"") ' subdirectory
' Convert API key to SecureString
Dim apiKey As String = "your-api-key-guid-here"
Dim securePassword As New SecureString()
For Each ch As Char In "" ' API key auth uses empty password
securePassword.AppendChar(ch)
Next
' Connect
cs.Connect(apiKey, securePassword)
If cs.Connected Then
Console.WriteLine("Connected successfully!")
End If
// Create connection
var cs = new xAssetsAPIConnection(
null, // proxy
xAssetsAPIConnection.ConnectionTypeEnum.Restful, // connection type
"mydatabase", // database name
44301, // port
"mycompany.hosted.xassets.net", // hostname
"https", // scheme
""); // subdirectory
// Convert API key to SecureString
string apiKey = "your-api-key-guid-here";
var securePassword = new SecureString();
// API key auth uses empty password
// Connect
cs.Connect(apiKey, securePassword);
if (cs.Connected)
{
Console.WriteLine("Connected successfully!");
}
For legacy SOAP connections:
Dim cs As New xAssetsAPIConnection(
Nothing,
xAssetsAPIConnection.ConnectionTypeEnum.SOAP,
"mydatabase", 443, "myserver", "https", "")
Dim password As New SecureString()
For Each ch As Char In "mypassword"
password.AppendChar(ch)
Next
cs.Connect("myusername", password)
For domain-authenticated SOAP connections:
' When username contains backslash, AD auth is used automatically
Dim username As String = "DOMAIN\username"
Dim password As New SecureString()
For Each ch As Char In "$challengeresponse$" ' Special token for AD auth
password.AppendChar(ch)
Next
cs.Connect(username, password)
The following classes are provided for your use and can be included directly in your project:
| File | Description |
|---|---|
xAssetsAPIConnection.vb/.cs |
Main API connection wrapper supporting all connection types |
WebSocketClient.vb/.cs |
WebSocket communication handler for persistent connections |
JSONRecord.vb/.cs |
Simple JSON object wrapper using Newtonsoft.Json |
These files are available in both VB.NET and C# in the SourceFiles folder.
All connection types implement the IConnector interface:
Interface IConnector
ReadOnly Property Connected As Boolean
ReadOnly Property DataPath As String
Property WebAddress As String
Function DatabaseList() As String()
Sub Connect(username As String, password As SecureString)
Sub Disconnect()
Function Query(queryname As String, parameters As String, Optional format As String = "XML") As String
Function Command(cmd As String, ParamArray arguments() As String) As String
Function Save(xml As String) As String
Sub SaveFile(filename As String, b() As Byte, ispcxfile As Boolean)
Function SaveSpecial(command As String, xml As String, additionalquerystring As String,
output As String, ParamArray arguments() As String) As String
Function Restful(output As String, fmt As String, command As String, subcommand As String,
xml As String, additionalquerystring As String, ParamArray arguments() As String) As String
End Interface
' Run a saved query called "All Assets"
Dim xml As String = cs.Query("All Assets", "")
Console.WriteLine(xml)
// Run a saved query called "All Assets"
string xml = cs.Query("All Assets", "");
Console.WriteLine(xml);
Parameters are passed as a query string prefixed with p?:
' Get assets for custodian with ID = 11
Dim paramsxml As String = "p?custodianid=11"
Dim xml As String = cs.Query("Assets With a Specified Custodian", paramsxml)
// Get assets for custodian with ID = 11
string paramsxml = "p?custodianid=11";
string xml = cs.Query("Assets With a Specified Custodian", paramsxml);
' Find all custodians with "Owen" in their name
Dim paramsxml As String = "p?searchfor=owen"
Dim xml As String = cs.Query("Custodian Search", paramsxml)
The Command method executes CommandProcessor commands directly.
' Get asset with ID = 2
Dim xml As String = cs.Command("AssetXML", "EDIT", "2")
// Get asset with ID = 2
string xml = cs.Command("AssetXML", "EDIT", "2");
' Get assets with IDs 1, 2, 3, 4, 5
Dim xml As String = cs.Command("AssetXML", "LIST_ALL", "FIXEDLIST", "1,2,3,4,5")
' Create a new asset with default field values
Dim xml As String = cs.Command("AssetXML", "NEW", "1",
"DatePurchased", Now.ToString("dd-MMM-yyyy HH:mm:ss"),
"StatusID", "2")
// Create a new asset with default field values
string xml = cs.Command("AssetXML", "NEW", "1",
"DatePurchased", DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss"),
"StatusID", "2");
' Get the XML tag name for the "Notes" field
Dim notesTag As String = cs.Command("FieldTag", "Notes")
' Returns something like "A45" (the actual tag depends on your configuration)
' Get the custodian ID for "Joe Bloggs"
Dim custodianId As String = cs.Command("GetCustodianID", "Joe Bloggs")
' Get list of available transformations
Dim xml As String = cs.Command("LookupDBTransform", "", "NOSUBS", "")
' Get list of saved queries (without parameter requirements)
Dim xml As String = cs.Command("LookupSavedSelect", "", "", "", "NOPARAMS")
The Save method persists XML data back to the database.
' Get an asset
Dim xml As String = cs.Command("AssetXML", "EDIT", "2")
' Get the tag name for the Notes field
Dim notesTag As String = cs.Command("FieldTag", "Notes")
' Load into XmlDocument and modify
Dim doc As New XmlDocument()
doc.LoadXml(xml)
For Each nodRecord As XmlNode In doc.DocumentElement.ChildNodes
Dim nodNotes As XmlNode = nodRecord.SelectSingleNode(notesTag)
If nodNotes IsNot Nothing Then
nodNotes.InnerText = "Updated by API at " & Now.ToString("dd-MMM-yyyy HH:mm:ss")
End If
Next
' Save back to database
Dim result As String = cs.Save(doc.OuterXml)
Console.WriteLine("Save result: " & result)
// Get an asset
string xml = cs.Command("AssetXML", "EDIT", "2");
// Get the tag name for the Notes field
string notesTag = cs.Command("FieldTag", "Notes");
// Load into XmlDocument and modify
var doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlNode nodRecord in doc.DocumentElement.ChildNodes)
{
XmlNode nodNotes = nodRecord.SelectSingleNode(notesTag);
if (nodNotes != null)
{
nodNotes.InnerText = "Updated by API at " + DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss");
}
}
// Save back to database
string result = cs.Save(doc.OuterXml);
Console.WriteLine("Save result: " + result);
' Create new asset XML with default fields
Dim xml As String = cs.Command("AssetXML", "NEW", "1",
"DatePurchased", Now.ToString("dd-MMM-yyyy HH:mm:ss"),
"StatusID", "2")
' Modify the XML to set additional fields
Dim doc As New XmlDocument()
doc.LoadXml(xml)
Dim rec As XmlNode = doc.DocumentElement.ChildNodes(0)
rec.SelectSingleNode("A20").InnerText = "Test Asset Created by API"
xml = doc.OuterXml
' Save to database - returns "AssetID=123" format
Dim result As String = cs.Save(xml)
Dim newAssetId As String = result.Substring(8) ' Extract ID from "AssetID=123"
Console.WriteLine("New Asset ID: " & newAssetId)
The SaveSpecial method executes complex operations.
Dim assetId As String = "123" ' Asset ID to dispose
Dim xml As String =
"<BulkDisposal_T>" &
"<BulkDisposal_R>" &
"<a>1</a>" &
"<b>0</b>" &
"<D39>" & Now.ToString("dd-MMM-yyyy HH:mm:ss") & "</D39>" &
"<FixedList></FixedList>" &
"<AID>" & assetId & "</AID>" &
"<SID>6</SID>" & ' 6 = Sold
"<BID>1</BID>" &
"<B1ID></B1ID>" &
"<ValueToDispose></ValueToDispose>" &
"<WriteDownCurrencyCode></WriteDownCurrencyCode>" &
"<WriteDown>100%</WriteDown>" &
"<SaleProceedsCurrencyCode></SaleProceedsCurrencyCode>" &
"<SaleProceeds></SaleProceeds>" &
"<SaleExpensesCurrencyCode></SaleExpensesCurrencyCode>" &
"<SaleExpenses>0.00</SaleExpenses>" &
"<SBID>7</SBID>" &
"<PurgeFlag>0</PurgeFlag>" & ' 0 = Dispose, 1 = Delete
"<Transfer></Transfer>" &
"<Transfer1></Transfer1>" &
"<Transfer2></Transfer2>" &
"<Transfer3></Transfer3>" &
"</BulkDisposal_R>" &
"</BulkDisposal_T>"
Dim result As String = cs.SaveSpecial("specialbulkdisposal", xml, "", "", {})
Console.WriteLine("Disposal result: " & result)
The only difference from disposal is setting PurgeFlag to 1:
' Same XML as above but with:
' "<PurgeFlag>1</PurgeFlag>" ' 1 = Delete/Purge
Dim result As String = cs.SaveSpecial("specialbulkdisposal", xml, "", "", {})
Dim transformName As String = "API Example Transform - Get All Assets PDF"
Dim xmlParameters As String = "" ' Empty if no parameters required
Dim additionalQueryString As String = ""
Dim output As String = ""
Dim result As String = cs.SaveSpecial("specialdbtransformrun", xmlParameters,
additionalQueryString, output, transformName)
' Result format: "special=reportview\uploads\report.pdf"
If result.StartsWith("special=reportview") Then
Dim reportPath As String = result.Substring(8) ' Path after "special="
Console.WriteLine("Report generated at: " & reportPath)
End If
Dim incidentId As String = "456"
Dim issueKey As String = "PT-1"
Dim summary As String = "Computer stopped working"
Dim notes As String = "The computer won't boot, fan is running full speed"
Dim reporterName As String = "Joe Bloggs"
Dim result As String = cs.SaveSpecial("SpecialTaskAssetLinkAdd", "", "", "",
{incidentId, "", "", "1", issueKey,
summary, notes, reporterName})
Dim xml As String = cs.Query("All Assets", "")
Dim doc As New XmlDocument()
doc.LoadXml(xml)
For Each record As XmlNode In doc.DocumentElement.ChildNodes
' Access fields by their tag names
Dim assetId As String = record.SelectSingleNode("AID")?.InnerText
Dim description As String = record.SelectSingleNode("A20")?.InnerText
Console.WriteLine($"Asset {assetId}: {description}")
Next
string xml = cs.Query("All Assets", "");
var doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlNode record in doc.DocumentElement.ChildNodes)
{
string assetId = record.SelectSingleNode("AID")?.InnerText;
string description = record.SelectSingleNode("A20")?.InnerText;
Console.WriteLine($"Asset {assetId}: {description}");
}
When you have parameters in XML format, convert them to query string format:
Private Function XmlToParameters(xmlString As String) As String
Dim doc As New XmlDocument()
doc.LoadXml(xmlString)
Dim nv As NameValueCollection = HttpUtility.ParseQueryString("")
For Each node As XmlNode In doc.DocumentElement.ChildNodes
nv(node.Name) = node.InnerText
Next
Return "p?" & nv.ToString()
End Function
' Usage:
' Dim params As String = XmlToParameters("<param><custodianid>11</custodianid></param>")
' Results in: "p?custodianid=11"
For RESTful and WebSocket connections, you can request JSON output instead of XML:
' Get all assets as JSON
Dim json As String = cs.Query("All Assets", "", "JSON")
Console.WriteLine(json)
// Get all assets as JSON
string json = cs.Query("All Assets", "", "JSON");
Console.WriteLine(json);
Note:JSON output is only available with RESTful and WebSocket connection types.
For RESTful and WebSocket connections, large files are uploaded in 1MB chunks:
Dim filePath As String = "C:\path\to\largefile.zip"
' The Restful method handles chunking automatically
Dim result As String = cs.Restful("all", "json", "upload", "", "", "", filePath)
Console.WriteLine("Upload result: " & result)
' Create a byte array (e.g., from a string)
Dim text As String = "Hello World"
Dim bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(text)
' Compress if needed
Using ms As New MemoryStream()
Using gzip As New GZipStream(ms, CompressionMode.Compress)
gzip.Write(bytes, 0, bytes.Length)
End Using
bytes = ms.ToArray()
End Using
' Upload
cs.SaveFile("myfile.txt.gz", bytes, False)
// Create a byte array
string text = "Hello World";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);
// Compress if needed
using (var ms = new MemoryStream())
{
using (var gzip = new GZipStream(ms, CompressionMode.Compress))
{
gzip.Write(bytes, 0, bytes.Length);
}
bytes = ms.ToArray();
}
// Upload
cs.SaveFile("myfile.txt.gz", bytes, false);
' After running a transformation that generates a file:
Dim result As String = cs.SaveSpecial("specialdbtransformrun", "", "", "", "My Report")
If result.StartsWith("special=reportview") Then
Dim downloadPath As String = result.Substring(8).Replace("\", "/")
' For WebSocket connections, use the download command
If connectionType = "SOCK" Then
Dim base64Content As String = cs.Command("download", downloadPath)
Dim fileBytes() As Byte = Convert.FromBase64String(base64Content)
File.WriteAllBytes("C:\output\report.pdf", fileBytes)
Else
' For REST connections, download via HTTP
Dim webPath As String = cs.DataPath & "/" & downloadPath
Dim client As New WebClient()
client.DownloadFile(webPath, "C:\output\report.pdf")
End If
End If
Private Sub RunTransformation(transformDesc As String, xmlParameters As String)
Dim result As String = cs.SaveSpecial("specialdbtransformrun", xmlParameters,
"", "", transformDesc)
If result.StartsWith("special=reportview") Then
' Download and open the report
Dim target As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "report.pdf")
Dim downloadPath As String = result.Substring(8).Replace("\", "/")
Dim webPath As String = cs.DataPath & "/" & downloadPath
Dim client As New WebClient()
client.DownloadFile(webPath, target)
' Launch in default application
Process.Start(New ProcessStartInfo() With {
.FileName = "explorer",
.Arguments = """" & target & """"
})
Else
Console.WriteLine("Transformation result: " & result)
End If
End Sub
To get the transformation output as data (instead of a file):
' Add output=transformationresult to get data instead of file path
Dim result As String = cs.SaveSpecial("specialdbtransformrun", "",
"output=transformationresult", "raw",
"My Data Transform")
Console.WriteLine(result) ' Contains the transformation output
' Get the custodian ID for the reporter
Dim reporterId As String = cs.Command("GetCustodianID", "Joe Bloggs")
' Create incident
Dim xml As String = cs.Command("AssetServiceHistoryXML", "NEW",
"AssetServiceRef", "PT-1",
"AssetServiceDesc", "Computer stopped working",
"ServiceTypeID", "35", ' 35 = Incident Management
"ServiceStatusID", "2", ' 2 = NEW
"ServicePriorityID", "1", ' 1 = Low priority
"CallerID", reporterId,
"DateRaised", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss+00:00"))
Dim result As String = cs.Save(xml)
Dim incidentId As String = result.Substring(8)
Console.WriteLine("Created incident: " & incidentId)
Dim incidentId As String = "456" ' Parent incident ID
Dim xmlComment As String = cs.Command("AssetServiceHistoryXML", "NEW",
"AssetServiceDesc", "x",
"Notes", "Additional details about the issue...",
"ParentAssetServiceHistoryID", incidentId,
"ServiceTypeID", "35",
"ServiceStatusID", "2")
Dim result As String = cs.Save(xmlComment)
' This finds assets matching the incident text
Dim result As String = cs.Command("GetAssetsForIncident",
{"PT-1", ' Issue key
"Computer stopped working", ' Summary
"Won't boot, fan loud", ' Notes
"Joe Bloggs"}) ' Reporter
Dim json As JObject = JObject.Parse(result)
Console.WriteLine(json.ToString(Formatting.Indented))
If your network requires a proxy server:
' Create proxy settings
Dim proxy As New xAssetsAPIConnection.ProxyRegistryData() With {
.ProxyURL = "http://proxy.company.com",
.ProxyPort = 8080,
.ProxyUserName = "proxyuser",
.ProxyPassword = New NetworkCredential("", "proxypassword").SecurePassword,
.UseDefault = "0" ' 0=Manual, 1=DefaultCredentials, 2=CredentialCache, 3=NetworkCredentials
}
' Create connection with proxy
Dim cs As New xAssetsAPIConnection(
proxy,
xAssetsAPIConnection.ConnectionTypeEnum.Restful,
"mydatabase", 44301, "myserver", "https", "")
' Or set proxy after creation
cs.SetProxy(proxy)
| UseDefault Value | Behavior |
|---|---|
"0" |
Use manual credentials (ProxyUserName/ProxyPassword) |
"1" |
Use WebProxy.UseDefaultCredentials = True |
"2" |
Use CredentialCache.DefaultCredentials |
"3" |
Use CredentialCache.DefaultNetworkCredentials |
proxy.ProxyBypass = "localhost;*.internal.com;10.*" ' Semicolon-separated
proxy.ProxyLocalByPass = "1" ' Bypass proxy for local addresses
Try
Dim xml As String = cs.Query("All Assets", "")
' Process results...
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message)
If ex.InnerException IsNot Nothing Then
Console.WriteLine("Inner: " & ex.InnerException.Message)
End If
End Try
The xAssetsAPIConnection class automatically handles session timeouts (error codes 1031 and 1035) by reconnecting. However, you may want to implement additional handling:
Try
Dim xml As String = cs.Query("All Assets", "")
Catch ex As Win32Exception
Select Case ex.NativeErrorCode
Case 1031, 1035
' Session expired - already handled by auto-reconnect
' But if you get here, reconnect failed
Console.WriteLine("Session expired and could not reconnect")
Case Else
Console.WriteLine("Error " & ex.NativeErrorCode & ": " & ex.Message)
End Select
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message)
End Try
Try
cs.Connect(apiKey, password)
Catch ex As WebSocketException
Select Case ex.ErrorCode
Case 258
Console.WriteLine("Invalid address or port")
Case 1168
Console.WriteLine("Server not available")
Case Else
Console.WriteLine("WebSocket error: " & ex.Message)
End Select
End Try
| Method | Description |
|---|---|
Connect(username, password) |
Establish connection with credentials |
Disconnect() |
Close the connection |
Query(queryname, parameters, format) |
Execute a saved query |
Command(cmd, arguments) |
Execute a CommandProcessor command |
Save(xml) |
Save XML data to database |
SaveFile(filename, bytes, ispcxfile) |
Upload a file as byte array |
SaveSpecial(command, xml, querystring, output, arguments) |
Execute a SaveSpecial operation |
Restful(output, format, command, subcommand, xml, querystring, arguments) |
Execute a REST API call |
DatabaseList() |
Get list of available databases |
| Property | Description |
|---|---|
Connected |
True if session is active |
Database |
Current database name |
ConnectionType |
Current connection type enum |
WebAddress |
Server URL |
DataPath |
Path for file downloads |