Setting up the SDK
The following steps illustrate how you can initialize the SDK after the installation of the Data Exchange .NET SDK is completed. In addition to the provided steps, you can also initialize the SDK to your specific requirements by incorporating additional steps, configurations, or modifications to the default setup.
Initializing the SDK using the default setup
Use the default setup provided by the Data Exchange .NET SDK out of the box to initialize the SDK. The following code sample illustrates the default method of initializing the SDK.
Register an App (if not done already) and note down the values of ClientId, ClientSecret, and CallBack and pass them to the client object. This grants access to the Data Exchange functionality, offering methods for retrieving and updating both data and metadata associated with Data Exchanges. Client initialization now returns a structured response object from which the actual client instance must be extracted using .Value. This enables structured error handling and access to metadata about the response.
string AuthClientID = "Your App Client id";
string AuthClientSecret = "Your App Client Secret";
string AuthCallBack = "Your App CallBack URL";
SDKOptionsDefaultSetup SdkOptionsDefaultSetup = new SDKOptionsDefaultSetup()
{
ClientId = AuthClientID,
ClientSecret = AuthClientSecret,
CallBack = AuthCallBack,
ConnectorName = "Revit-Connector",
ConnectorVersion = "1.0.0",
HostApplicationName = "Revit",
HostApplicationVersion = "2023.0.1"
};
Handling Port Conflicts with Fallback URLs
When users sign in, the SDK opens a browser and listens on a local port (specified in CallBack) to receive the OAuth callback. If another application is already using that port, authentication fails with a PortInUseException.
You can specify fallback redirect URLs to improve reliability. The SDK will try each URL in order until it finds an available port:
using System.Collections.Generic;
var options = new SDKOptionsDefaultSetup()
{
ClientId = "your-client-id",
ClientSecret = "your-client-secret",
CallBack = "http://localhost:8080/",
FallbackRedirectUrls = new List<string>
{
"http://localhost:9090/",
"http://localhost:3000/"
},
ConnectorName = "Revit-Connector",
ConnectorVersion = "1.0.0",
HostApplicationName = "Revit",
HostApplicationVersion = "2023.0.1"
};
⚠️ Portal Registration Required
All callback URLs (primary and fallback) must be registered as valid redirect URIs in your APS application settings before use.
If all configured ports are in use, the SDK throws AllCallbackPortsInUseException. Handle this to show a meaningful error message:
try
{
IClient client = new Client(options);
}
catch (AllCallbackPortsInUseException ex)
{
// All configured callback ports are busy
Console.WriteLine($"Authentication failed: {ex.Message}");
Console.WriteLine($"Attempted URLs: {string.Join(", ", ex.AttemptedUrls)}");
}
catch (PortInUseException ex)
{
// Single port in use (when no fallbacks configured)
Console.WriteLine($"Port in use: {ex.Message}");
}
The Applications that use the authentication provider of SDK must initialize the client in an async manner as this will open the browser for authentication and should be enclosed in a try-catch block as shown in the following code sample.
// Asynchronous
try
{
IClient Client = await Task.Run(() => new Client(SdkOptionsDefaultSetup));
}
catch (Exception ex)
{
}
// Synchronous
try
{
IClient Client = new Client(SdkOptionsDefaultSetup);
}
catch (Exception ex)
{
}
It is important that when the SDK throws any exception, the connector should catch it and display an appropriate message along with the exception details on the UI.
For instance, if the callback URL’s port is already in use by another process, the SDK will throw a custom exception called PortInUseException. The connector code, where the SDK is being initialized, should catch this exception and display a relevant message accordingly.
Creating a Logger object
Create an ILogger Interface object and use it across the application to log the messages in the log file. The ILogger Interface object enables the logging of events, messages, and errors during execution, offering valuable insight for application debugging, monitoring, and maintenance.
var AppWorkspaceDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string AppBasePath = Path.Combine(AppWorkspaceDirectory, "YourApplicationName");
var LogDirectoryPath = Path.Combine(AppBasePath, "logs");
ILogger Logger = new Log(LogDirectoryPath);
Logging errors with context
ILogger.Error has three overloads: Error(Exception exception), Error(string message, string caller = null), and Error(string message, Exception exception, string caller = null). Use the third overload whenever you catch an exception you want to explain — it records your own diagnostic message and the exception together, instead of forcing a choice between “log what happened” and “log why it matters.”
Passing only the exception loses the calling context that made the failure meaningful (what were you trying to do when it happened?). Passing only a string loses the actual error details (stack trace, inner exception, exception type) needed to diagnose it. Together, they give you both.
try
{
await elementDataModel.SyncExchangeDataAsync(exchangeIdentifier);
}
catch (Exception ex)
{
// Records both a diagnostic message and the full exception details in one call.
Logger.Error($"Failed to sync exchange {exchangeIdentifier.ExchangeId}", ex);
// Handle or rethrow according to your connector's error-handling policy.
throw;
}
The caller parameter is optional — the SDK captures the calling method name automatically via [CallerMemberName], so you only need to pass it explicitly if you’re logging on behalf of a different method than the one you’re currently in (for example, from a shared error-handling helper).
Duplicate-safe by design: if you pass the same exception instance to Error more than once — for example, because it’s re-caught and logged again further up the call stack — the SDK records it only once. You don’t need to guard against double-logging the same exception yourself.
Creating Auth object
Register an App (if not done already) and note down the values of ClientId, ClientSecret, and CallBack. Pass these values to the IAuth object, and this step will authenticate the connector SDK. The Logger object is optional and can be added only if needed.
string AuthClientID = "Your App Client id";
string AuthClientSecret = "Your App Client Secret";
string AuthCallBack = "Your App CallBack URL";
var AuthOption = new AuthOptions
{
ClientId = AuthClientID,
ClientSecret = AuthClientSecret,
CallBack = AuthCallBack,
Logger = Logger
};
IAuth Auth = new Auth(AuthOption);
Note: AuthOptions also supports the FallbackRedirectUrls property for handling port conflicts. See Handling Port Conflicts with Fallback URLs for details and examples.
Note: When the SDK opens the browser for sign-in, users may see an OAuth consent screen listing the permissions the app is requesting. This is expected behavior. See Before You Begin for a description of the requested permissions.
Creating Storage object
Create an object of the IStorage Interface. IStorage is a key-value cache on the local file system that survives restarts. The SDK uses it internally to avoid re-fetching data it has already retrieved, such as exchange details and schema definitions, and your connector can use the same cache for state it wants to keep between sessions.
IStorage Storage = new Storage(AppBasePath);
Most connectors construct the object, hand it to the client, and never touch it again. Read on if you store your own state in the cache or implement IStorage against a different backing store.
Changed in 8.0.0:
AddandSaverequire agroupparameter. Calls written against an earlier release that omit it do not compile. See Storage entries are scoped to a group.
How entries are stored
Entries are addressed by a key, optionally within a group. A group is a folder on disk, so grouping is how you keep one logical set of entries separate from another and clean them up together.
Writing is a two-step operation, and this is the part most worth understanding:
Add(key, value, group)puts an entry in the in-memory collection. On its own it never touches disk.Save(key, group)commits that one entry. It writes the value most recently added under the key, or deletes the stored entry when the key was passed toRemove. It does nothing when the key is not present.
An entry you add but never save stays in memory and is gone when the process exits. The same applies to deletion: Remove takes the entry out of memory, but the file remains on disk until you save the same key.
There is no call that flushes the whole cache. Save the specific key you own, and your write never waits on unrelated pending writes — a small settings entry does not get held up behind a large exchange payload that some other part of the SDK happens to have queued.
Add and Save both require a group. Prefix the groups you own with something specific to your connector so your entries stay separate from the SDK’s. Save throws IOException when the entry cannot be written or removed, leaving the previously persisted value intact.
Get reads the in-memory value by default. Pass includeInMemoryCache: false to skip memory and read what is currently committed to disk.
Storage synchronizes its own reads and writes, so you can call it from multiple threads without adding a lock of your own.
What you can store, and how to name keys
Values are serialized to JSON and written gzip-compressed to <group>/<key>.gz under the path you passed to the constructor. Two consequences are worth planning around:
- Values must survive a JSON round trip. Plain data — strings, numbers, collections, and your own data-holding classes — is fine. Streams, file handles, and delegates are not. A value that cannot be serialized fails when you save it, not when you add it.
- Serialized data embeds .NET type names. Renaming, moving, or re-namespacing a cached type means existing entries no longer deserialize into it. Treat a cache miss after an upgrade as expected and fall back to re-fetching, rather than assuming a stored entry is always readable.
The key becomes the file name, and the SDK does not sanitize it. Keys must be valid file names on every platform you support, so encode any identifier that can contain /, \, or : before you use it as a key. Group names become folder names and follow the same rule.
Your connector shares this cache with the SDK, which stores its own exchange and schema data here. Prefix the keys and groups you own with something specific to your connector so you cannot collide with SDK entries or with another connector using the same workspace path.
Nothing expires or evicts entries. Whatever you write stays until you remove it, so delete the state you own when it stops being relevant.
Example: remembering state per project
A connector wants to reopen with the exchanges the user had loaded, without querying the service again on every launch. Keying each record by project, and grouping them under a name the connector owns, keeps this state separate from the SDK’s own entries.
// Prefixed with the connector name so it cannot collide with SDK groups.
private const string LoadedExchangesGroup = "contoso-loaded-exchanges";
// Project identifiers can contain characters that are not legal in a file name.
private static string ToKey(string projectId) =>
Convert.ToBase64String(Encoding.UTF8.GetBytes(projectId)).Replace('/', '_');
// Record the loaded exchanges when the user closes a project.
public void SaveLoadedExchanges(string projectId, List<string> exchangeIds)
{
this.storage.Add(ToKey(projectId), exchangeIds, LoadedExchangesGroup);
this.storage.Save(ToKey(projectId), LoadedExchangesGroup);
}
// Restore them the next time that project opens.
public List<string> GetLoadedExchanges(string projectId)
{
return this.storage.Get<List<string>>(ToKey(projectId), LoadedExchangesGroup)
?? new List<string>();
}
// Discard the record when the user disconnects the project.
public void ForgetProject(string projectId)
{
this.storage.Remove(ToKey(projectId), LoadedExchangesGroup);
this.storage.Save(ToKey(projectId), LoadedExchangesGroup);
}
Get returns the default for the type when no entry exists, so treat a null result as “nothing cached yet” rather than an error — including after an upgrade that changed the cached type. Note the Save call in ForgetProject: without it the entry disappears from memory but the file stays on disk, and the stale record returns the next time the connector starts.
Setting the workspace path
Provide a non-empty application workspace path when you construct Storage. Mesh translation derives its output directory from this path and no longer falls back to %TEMP%. See Mesh translation and output paths.
Creating HostingProvider object
Create an object of IHostingProvider Interface. The IHostingProvider provides functionalities for accessing Hubs, Projects, Folders, and many more within Forma (formerly Autodesk Construction Cloud) using the API and facilitates the connection to Forma APIs.
IHostingProvider HostingProvider = new ACC(Logger, () => Auth.GetAuthToken());
Creating Geometry configuration object
Create an object of the GeometryConfiguration Object, the Geometry configuration instance is used to configure GUSDK configurations such as STEPProtocol, STEPTolerance, etc.
GeometryConfiguration GeometryConfiguration = new GeometryConfiguration()
{
STEPProtocol = STEPProtocol.ConfigurationControlledDesign,
STEPTolerance = 0.001,
UseConversionApiForGeometryTranslation = true, // Optional: use the ConversionAPI translation path (default: true).
ConversionBatchSize = 10000, // Optional: geometry assets per conversion batch (default: 10000).
SyncUploadConcurrency = 20, // Optional: maximum parallel sync uploads, 1-35 (default: 20).
TuneThreadPool = true // Optional: raise process-wide thread pool minimums (default: true).
} ;
UseConversionApiForGeometryTranslation, ConversionBatchSize, SyncUploadConcurrency, TuneThreadPool, and AllowUserRenderStyleOverride are tunables on GeometryConfiguration. Each defaults to a value that preserves prior behavior or reflects internal testing, so most connectors never need to set them.
Choosing the geometry translation path
UseConversionApiForGeometryTranslation selects which implementation the SDK uses to translate geometry: the out-of-process ConversionAPI (a gRPC-backed service) when true, or the legacy in-process GUSDK Client APIs when false. It is a bool with a default of true.
Heads-up — legacy GUSDK Client APIs will be deprecated: the SDK will deprecate the legacy in-process GUSDK Client API path in an upcoming release. There is no action to take today — the default (
true) already selects the ConversionAPI path — but if your connector explicitly sets this tofalse, plan to move off that setting before the legacy path is removed.
The ConversionAPI path is also a prerequisite for newer geometry capabilities as they ship — for example, correct STEP export for mirrored (reflected) instance geometry depends on this path being active. Staying on the default keeps your connector ready for capabilities like this without further configuration changes.
Follow this guidance when you set UseConversionApiForGeometryTranslation:
- Leave it at the default
trueunless you have a specific reason to use the legacy path. - Set it to
falseonly as a temporary fallback if you hit a regression on the ConversionAPI path that the legacy path does not exhibit — and plan to remove that override before legacy GUSDK Client APIs are deprecated.
Tuning geometry conversion batch size
Sync runs in phases: the SDK first converts your connector’s authored geometry (STEP, OBJ, or in-memory meshes) into the format a Data Exchange requires, then uploads the converted result. ConversionBatchSize controls how many geometry assets the SDK converts per batch during the conversion phase. Each batch becomes one call to the geometry conversion service, which bounds how much geometry that service holds in memory at once; smaller values may reduce peak memory but increase the number of calls and total conversion time.
The value is an int with a default of 10000. There is no clamped range — a value of 0 or negative falls back to the default rather than throwing:
| Value assigned | Effective value |
|---|---|
0 or negative |
10000 |
| positive | unchanged |
Follow this guidance when you set ConversionBatchSize:
- Leave it at the default
10000unless you measure excessive memory use, or an out-of-memory error, during the conversion phase of a large-model sync (before upload begins).10000preserves the effective batch size the SDK used before this setting became functional in 8.0.0. - Lower it if a large-model sync — one with a large number of geometry assets — runs out of memory during conversion. A smaller batch trades more, smaller service calls (and a longer conversion phase) for a lower peak memory footprint. Peak memory also depends on geometry complexity and asset size, not batch size alone.
- Raising it above the default rarely helps for typical large models, since call overhead is usually small relative to conversion time itself.
var geometryConfig = new GeometryConfiguration()
{
UseConversionApiForGeometryTranslation = true, // Default; use the ConversionAPI translation path.
ConversionBatchSize = 2000 // Lower for large models that run out of memory during conversion.
};
Upgrading from a version before 8.0.0:
ConversionBatchSizewas not applied prior to 8.0.0 — the conversion phase always used a fixed batch of 10,000 regardless of this setting. If your connector explicitly setsConversionBatchSizeto any positive value other than10000— including5000, the former property default — that value had no effect before 8.0.0. Starting in 8.0.0 the setting is honored, so test large-model sync after upgrading if this applies to you; the value may behave differently than before for the first time.
Tuning sync upload concurrency
SyncUploadConcurrency controls the maximum number of sync API batches uploaded to the exchange concurrently during a data exchange sync. When you sync a model, the SDK splits its assets, relationships, and schemas into batches. It serializes those batches sequentially but uploads them in parallel to overlap network I/O and maximize throughput. SyncUploadConcurrency is the upper bound on how many of those uploads are in flight at any moment. Internally, it acts as a single concurrency gate (a semaphore) on the upload path: a higher value allows more simultaneous network requests, and a lower value reduces network pressure and the number of in-flight payloads.
The value is an int with a default of 20 and a valid range of 1 to 35, inclusive. The SDK silently clamps an out-of-range value into that range and does not throw an exception:
| Value assigned | Effective value |
|---|---|
0 or negative |
1 |
1 to 35 |
unchanged |
36 or higher |
35 |
Follow this guidance when you set SyncUploadConcurrency:
- Leave it at the default
20unless you have a specific, measured reason to change it. Internal testing across connectors confirmed20as the best general-purpose default. - Raising it toward
35mainly benefits small or fast models, where more parallel uploads complete sooner. It provides little benefit for large models, where conversion time, not upload concurrency, dominates. - Do not treat it as a memory-control lever. In the current architecture, it does not reduce memory usage.
- Lowering it can help in constrained or unreliable network environments by reducing the number of simultaneous in-flight requests.
var geometryConfig = new GeometryConfiguration()
{
SyncUploadConcurrency = 30 // Raise parallel uploads (clamped to 1-35).
};
Tuning the thread pool
TuneThreadPool controls whether the SDK raises the process-wide .NET ThreadPool minimum-thread settings during client initialization. It is a bool with a default of true, and it affects the whole host process.
By default, the .NET thread pool grows slowly, creating roughly one new thread every 500 milliseconds. Under the CPU-intensive geometry conversions that the SDK performs on large models, that slow ramp-up can starve the pool of the threads it needs for I/O completion callbacks. This can surface as an error such as There were not enough free threads in the ThreadPool to complete the operation. When TuneThreadPool is true, the SDK raises the minimum thread counts so the pool creates threads eagerly instead of waiting through the slow ramp, which reduces the risk of this starvation. The SDK only ever raises the minimums. It never lowers them below what the host has already configured.
Because this setting changes a process-wide value, set TuneThreadPool to false when:
- The host application manages the thread pool itself and you do not want the SDK to change a process-wide setting, or
- The SDK shares its process with other components that should not be affected by a global thread-pool change.
This opt-out exists so that hosts retain full control of their own runtime tuning. Follow this guidance when you set TuneThreadPool:
- Leave it at the default
truefor standalone connectors and any host that does not already tune the thread pool. This is the recommended setting for large-model reliability. - Disabling it does not by itself cause errors, but it removes a safeguard against thread-pool starvation during heavy geometry conversion.
var geometryConfig = new GeometryConfiguration()
{
TuneThreadPool = false // The host manages the thread pool itself.
};
Overriding file-derived render styles
When you attach a BRep file such as STEP or IFC to an element, that file usually carries its own color and transparency. You can also pass a RenderStyle of your own to CreateFileGeometry. AllowUserRenderStyleOverride decides which of the two wins.
The default is false, and it means the file wins. The style translated out of the source file is used, and the render style you supplied is a fallback applied only when the file produced no style at all. This is the right behavior almost always: the authoring application knows what color the geometry is, and your connector should not silently repaint it.
Set it to true only when you know the host exports incorrect style information. Your supplied render style then replaces the translated style for the whole body, including any per-face styles the file defined.
var geometryConfig = new GeometryConfiguration()
{
// The host exports incorrect color and transparency, so the
// connector supplies the correct style instead.
AllowUserRenderStyleOverride = true
};
This setting is process-wide for the client. There is no per-geometry switch, so turning it on affects every BRep file your connector translates.
When you need this
The case this exists for is a host whose exporter loses style information. MicroStation is the known example: exporting BRep geometry to STEP writes every body as opaque white, discarding the color and transparency the user actually applied. The connector has the correct values and passes them to CreateFileGeometry, but with the default setting the SDK keeps the white opaque style from the file, and the exchange loads looking nothing like the source model.
// The connector knows the real appearance of this component.
var glazing = new RenderStyle(
name: "Glazing",
rgba: new RGBA(120, 180, 210, 255),
transparency: 0.35);
var geometry = ElementDataModel.CreateFileGeometry(
filePath: "curtain-wall.stp",
format: GeometryFormat.Step,
renderStyle: glazing);
With AllowUserRenderStyleOverride left at false, the exported STEP reports opaque white and that is what consumers see — the glazing style is discarded because the file produced a style. With it set to true, glazing is applied instead and the panel renders as intended.
Before turning this on, confirm the problem is the exporter rather than your own style data. If the file carries correct colors and you enable the override, you replace good style information with whatever your connector supplied, and per-face detail in the source file is lost.
Quick reference
| Property | Type | Default | Range / Values | Scope | Change when |
|---|---|---|---|---|---|
UseConversionApiForGeometryTranslation |
bool |
true |
true / false |
Per client | Almost never — legacy GUSDK Client APIs are being deprecated; only as a temporary fallback for a ConversionAPI regression |
ConversionBatchSize |
int |
10000 |
Any positive int; 0 or negative falls back to 10000 |
Per sync (conversion path) | A large-model sync runs out of memory during conversion, before upload |
SyncUploadConcurrency |
int |
20 |
1–35 (auto-clamped) |
Per sync (upload path) | Tuning upload parallelism for small or fast models, or for constrained networks |
TuneThreadPool |
bool |
true |
true / false |
Process-wide | The host already manages the thread pool, or the process is shared |
AllowUserRenderStyleOverride |
bool |
false |
true / false |
Per client | The host exports incorrect color or transparency in BRep files, and your connector supplies the correct render style |
Creating SDKOptions object
Pass the values of the objects from the preceding steps to the SDKOptions object. It provides an option to DataExchange SDK such as Authentication, Storage, Hosting, logger, and so on.
var sdkOptions = new SDKOptions
{
AuthProvider = Auth,
Storage = Storage,
SourceProvider = new SourceProvider.SourceProvider(),
ContractProvider = new ContractProvider.ContractProvider(),
HostingProvider = HostingProvider,
Logger = Logger,
ConnectorName = "Revit-Connector",
ConnectorVersion = "1.0.0",
HostApplicationName = "Revit",
HostApplicationVersion = "2023.0.1",
WarmupServices = true // Optional: pre-warm geometry translation at init (default: false)
};
Pre-warming the geometry translation service
WarmupServices controls whether the geometry translation service is started during SDK initialization or on the first call that needs it. Set it to true if your users would notice latency on the first geometry translation call and your flow has some wall-clock time between SDK init and that first call (for example, a UI where the user selects folders or names an exchange). Leave it at the default false for scripted or test-like flows that translate immediately after init.
Note: Connectors built on
SDKOptionsDefaultSetupgetWarmupServices = trueapplied by default. Set it tofalseexplicitly if you want to opt out.
Creating Client object
Pass the SdkOptions object to the IClient interface, this grants access to the Data Exchange functionality, offering methods for retrieving and updating both data and metadata associated with Data Exchanges.
The Applications that use the authentication provider of SDK must initialize the client in an async manner as this will open the browser for authentication and should be enclosed in a try-catch block as shown in the following code sample.
// Asynchronous
try
{
IClient Client = await Task.Run(() => new Client(SdkOptions));
}
catch (Exception ex)
{
}
// Synchronous
IClient Client = new Client(SdkOptions);