Request

Response

    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"
            };
    
    Show More

    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"
    };
    
    Show More

    ⚠️ 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}");
    }
    
    Show More

    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)
            {
            
            }
    
    Show More

    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;
    }
    
    Show More

    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);
    
    Show More

    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, this Interface provides functionality for storing data in a cache-like manner.

            IStorage Storage = new Storage(AppBasePath);
    

    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).
                } ;
    
    Show More

    UseConversionApiForGeometryTranslation, ConversionBatchSize, SyncUploadConcurrency, and TuneThreadPool 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 to false, 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 true unless you have a specific reason to use the legacy path.
    • Set it to false only 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 assignedEffective value
    0 or negative 10000
    positive unchanged

    Follow this guidance when you set ConversionBatchSize:

    • Leave it at the default 10000 unless you measure excessive memory use, or an out-of-memory error, during the conversion phase of a large-model sync (before upload begins). 10000 preserves the effective batch size the SDK used before this setting became functional in 7.6.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 7.6.0: ConversionBatchSize was not applied prior to 7.6.0 — the conversion phase always used a fixed batch of 10,000 regardless of this setting. If your connector explicitly sets ConversionBatchSize to any positive value other than 10000 — including 5000, the former property default — that value had no effect before 7.6.0. Starting in 7.6.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 assignedEffective 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 20 unless you have a specific, measured reason to change it. Internal testing across connectors confirmed 20 as the best general-purpose default.
    • Raising it toward 35 mainly 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 true for 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.
                };
    

    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

    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)
            };
    
    Show More

    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.

    Only geometry translation is pre-warmed today; other SDK services start on demand regardless of this setting.

    Note: Connectors built on SDKOptionsDefaultSetup get WarmupServices = true applied by default. Set it to false explicitly 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);  
    
    Show More