.NET SDK Integration
Complete integration workflow for the 7G .NET SDK - from NuGet installation to your first authenticated, type-safe API call in 15-20 minutes.
Audience: .NET developers (C#, F#, VB.NET) building applications on .NET 6.0+ who want automatic token management, type safety, and rapid development.
This guide covers: NuGet installation, authentication with automatic token refresh, type-safe querying with FilterField<T>, and production integration patterns.
What You'll Learn
This guide provides a complete workflow for .NET SDK integration. Estimated completion: 15 minutes.
By the end of this guide, you'll have:
- Installed the SDK via NuGet and authenticated successfully
- Made your first type-safe query with automatic token refresh
- Used FilterField<T> fluent filtering
- Understood SDK error handling (exceptions + Result checking)
This guide covers:
- NuGet installation and SDK initialization
- Authentication workflow with automatic token refresh (30 seconds before expiry)
- Type-safe querying and response handling
- Production integration patterns (DI, HttpClientFactory)
For comprehensive depth, this guide delegates to concept pages:
Why .NET SDK Integration?
- Automatic token management - SDK refreshes tokens 30 seconds before expiry
- Type safety - Strongly-typed DTOs, filters, and responses with IntelliSense
- Fluent filtering - FilterField<T> with implicit conversions for concise queries
- Production ready - Supports DI, HttpClientFactory, and connection pooling
Prerequisites
You'll need:
- .NET 6.0 or later (.NET 6, 7, 8, or 9)
- NuGet package manager (dotnet CLI or Visual Studio)
- 7G API credentials (username and password)
- IDE with IntelliSense (Visual Studio, VS Code with C# extension)
Package Information
Package Name: SevenG.API.SDK
Current Version: 1.0.7
Target Frameworks: .NET 6.0, .NET 7.0, .NET 8.0, .NET 9.0
Key Dependencies: System.IdentityModel.Tokens.Jwt (for JWT exp claim parsing)
Public Endpoints (No Authentication Required)
Only 4 endpoints can be called before logging in (SDK automatically includes Authorization header for all others after login):
/User/Login- Initial authentication/User/Status- API status check/Common/Lookup- Lookup data retrieval/Common/HealthCheck- Health monitoring
All other 71 endpoints require authentication via LoginAsync first.
Installation
Install the 7G .NET SDK via NuGet using your preferred method:
# Install via .NET CLI (recommended)
dotnet add package SevenG.API.SDK
# Restore packages
dotnet restoreAdd Using Directives
After installation, add these using statements to your C# files:
using SevenG.API.SDK;
using SevenG.API.SDK.DTO;
using System.Text.Json; // For response deserializationNuGet Source
The SDK is available on the public NuGet repository. No additional package sources required.
Verify Installation
Confirm the SDK is installed and accessible:
using SevenG.API.SDK;
var client = new SevenGClient(SevenGEnvironment.Test);
Console.WriteLine("✓ SDK installed successfully!");Choose Your Environment
The SDK uses the SevenGEnvironment enum for clean, type-safe environment selection - no URL string management required.
| Environment | Enum Value | Purpose |
|---|---|---|
| Production | SevenGEnvironment.Production |
Live production data and operations |
| Test | SevenGEnvironment.Test |
Integration testing and validation (staging environment) |
| Lab | SevenGEnvironment.Lab |
Features and sandbox testing (staging environment) |
SevenGEnvironment.Test or SevenGEnvironment.Lab) for initial integration and testing. Switch to Production only when your integration is validated and ready for live operations.
SDK Features Overview
The 7G .NET SDK provides enterprise-grade features that eliminate boilerplate and accelerate development.
1. Automatic Token Management
HTTP/REST Approach
- Manually track token expiry timestamp
- Manually calculate when to refresh (5 minutes before expiry)
- Manually implement refresh logic
- Conservative timing buffer to prevent mid-request expiration
SDK Approach
SDK automatically manages tokens transparently:
var response = await client.BizEntity.GetAsync(filter);
// SDK automatically (before every request):
// 1. Checks: Does token expire in < 30 seconds?
// 2. If yes: Refreshes token automatically
// 3. Then: Makes your request with valid tokenWhy 30 Seconds Before Expiry?
The SDK reads the JWT exp claim using JwtSecurityTokenHandler for exact expiry time. This precise timing (30 seconds) ensures minimal token waste while maintaining zero-downtime operation.
HTTP/REST users should use 5-minute timing for manual refresh due to implementation variance and network latency. See the HTTP Integration Guide for details.
2. Strongly-Typed Everything
// No compile-time validation
var json = @"{
'name': 'Smith Super Fund',
'bizEntityTypID': 4 // Typo! Won't be caught until runtime
}";
var response = await httpClient.PostAsync("/BizEntity", new StringContent(json));3. Fluent Filtering with FilterField<T>
// Implicit conversions for cleaner syntax
var filter = new BizEntityFilter
{
BizEntityTypeID = 4, // int → FilterField<int> { Equal = 4 }
BizEntityStatusID = 1, // Active entities only
PageSize = 50
};
var response = await client.BizEntity.GetAsync(filter);4. Dependency Injection Ready
Two constructor patterns for maximum flexibility:
// SDK creates and manages HttpClient internally
var client = new SevenGClient(SevenGEnvironment.Test);
// Quick setup for console apps, scripts, utilitiesUnderstanding SDK Responses
The SDK returns two response structures:
APIResponse (73 endpoints)
All operational SDK methods return this structure:
{
"result": true, // Success indicator - ALWAYS CHECK THIS
"message": "", // Error details (empty on success)
"recordCount": 25, // Records in response
"data": [...] // Response payload (dynamic object)
}TokenResponse (Authentication only)
Only LoginAsync and RefreshTokenAsync return this structure:
{
"accessToken": "eyJx...",
"refreshToken": "cZk..."
}Critical: Always Check response.Result == true
Business logic errors (validation, not found, conflicts) return result: false. Always verify response.Result before processing response.Data.
Deserializing Response.Data
The Data property is object (dynamic). Convert to strongly-typed collections:
using System.Text.Json;
var response = await client.BizEntity.GetAsync(filter);
if (!response.Result)
{
Console.WriteLine($"Error: {response.Message}");
return;
}
// Deserialize dynamic Data to List<BizEntityDTO>
var entities = JsonSerializer.Deserialize<List<BizEntityDTO>>(
JsonSerializer.Serialize(response.Data)
);
foreach (var entity in entities)
{
Console.WriteLine($"{entity.BizEntityID}: {entity.Name}");
}Authentication - SDK Workflow
The SDK handles authentication automatically. You login once, and the SDK manages token refresh seamlessly.
Step 1: Initialize Client
Create a SevenGClient instance:
using SevenG.API.SDK;
// SDK creates HttpClient internally
var client = new SevenGClient(SevenGEnvironment.Test);Pattern 1: Quick setup (console apps, scripts). Pattern 2: Production (HttpClientFactory, connection pooling).
Step 2: Login
Authenticate to receive JWT tokens:
using SevenG.API.SDK;
var client = new SevenGClient(SevenGEnvironment.Test);
var tokens = await client.Auth.LoginAsync("your-username", "your-password");
Console.WriteLine("✓ Logged in successfully");
Console.WriteLine($"Access Token: {tokens.AccessToken.Substring(0, 20)}...");
// SDK stores tokens automatically - ready to make API calls!The SDK reads the JWT exp claim to determine exact expiry, stores both tokens, and auto-injects Authorization header for all future requests.
Step 3: Automatic Token Refresh
SDK automatically refreshes tokens 30 seconds before expiry. No manual tracking required:
// Just keep making requests - SDK handles refresh automatically
var response1 = await client.BizEntity.GetAsync(filter);
// ... 19 minutes pass ...
var response2 = await client.BizEntity.GetAsync(filter); // SDK auto-refreshed tokens
Step 4: Handle Authentication Errors
Authentication errors throw InvalidOperationException:
try
{
var client = new SevenGClient(SevenGEnvironment.Test);
await client.Auth.LoginAsync(username, password);
// Make requests (token refresh automatic)
var response = await client.BizEntity.GetAsync(filter);
// Check API response
if (!response.Result)
{
Console.WriteLine($"API Error: {response.Message}");
return;
}
Console.WriteLine("Success!");
}
catch (InvalidOperationException ex) when (ex.Message.Contains("Access token not set"))
{
Console.WriteLine("Authentication required - call LoginAsync first");
}
catch (InvalidOperationException ex) when (ex.Message.Contains("refresh token"))
{
Console.WriteLine("Session expired - re-login required");
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Authentication error: {ex.Message}");
}Your First GET Request
Make your first type-safe query using FilterField<T> fluent filtering and experience automatic token management.
Example: Get First 10 SMSF Entities
using SevenG.API.SDK;
using SevenG.API.SDK.DTO;
using System.Text.Json;
// Initialize client
var client = new SevenGClient(SevenGEnvironment.Test);
// Authenticate
await client.Auth.LoginAsync("your-username", "your-password");
// Create filter
var filter = new BizEntityFilter
{
BizEntityTypeID = 4, // Use Common/Lookup to find TypeIDs
PageSize = 10
};
// Make request (SDK automatically includes Authorization header)
var response = await client.BizEntity.GetAsync(filter);
if (!response.Result)
{
Console.WriteLine($"Error: {response.Message}");
return;
}
// Deserialize to strongly-typed list
var entities = JsonSerializer.Deserialize<List<BizEntityDTO>>(
JsonSerializer.Serialize(response.Data)
);
// Process results
Console.WriteLine($"Retrieved {entities.Count} SMSF entities:");
foreach (var entity in entities)
{
Console.WriteLine($"- [{entity.BizEntityID}] {entity.Name}");
if (entity.Accounts != null)
{
Console.WriteLine($" Accounts: {entity.Accounts.Count}");
}
}Success!
You've made your first authenticated SDK call. The SDK automatically included the Authorization header and handled token validation.
What's Happening Behind the Scenes
When you call client.BizEntity.GetAsync(filter), the SDK executes this sequence automatically:
- Check and refresh token if needed (
await _authClient.EnsureValidTokenAsync()) - Convert filter object to query string (
QueryBuilder.ToQueryString(Model)) - Make HTTP GET request with Authorization header auto-injected
- Parse response with fallbacks (
MessageParser.ParseResponseAsync) - Return APIResponse with Result, Message, RecordCount, Data