The official Schematic C# library, supporting .NET Standard, .NET Core, and .NET Framework.
- Install the library using the .NET Core command-line interface (CLI) tools:
dotnet add package SchematicHQ.Clientor using the NuGet Command Line Interface (CLI):
nuget install SchematicHQ.ClientIssue an API key for the appropriate environment using the Schematic app.
Using this secret key, initialize a client in your application:
usingSchematicHQ;Schematicschematic=newSchematic("YOUR_API_KEY")A number of these examples use keys to identify companies and users. Learn more about keys here.
Create or update users and companies using identify events.
usingSchematicHQ.Client;usingSystem.Collections.Generic;usingOneOf;Schematicschematic=newSchematic("YOUR_API_KEY");schematic.Identify(keys:newDictionary<string,string>{{"email","wcoyote@acme.net"},{"user_id","your-user-id"}},company:newEventBodyIdentifyCompany{Keys=newDictionary<string,string>{{"id","your-company-id"}},Name="Acme Widgets, Inc.",Traits=newDictionary<string,OneOf<string,double,bool,OneOf<string,double,bool>>>{{"city","Atlanta"}}},name:"Wile E. Coyote",traits:newDictionary<string,OneOf<string,double,bool,OneOf<string,double,bool>>>{{"login_count",24},{"is_staff",false}});// to guarantee that all events are sent before the application exits, call this method before your program shuts downawaitschematic.Shutdown();This call is non-blocking and there is no response to check.
Track activity in your application using track events; these events can later be used to produce metrics for targeting.
Schematicschematic=newSchematic("YOUR_API_KEY");schematic.Track(eventName:"some-action",user:newDictionary<string,string>{{"user_id","your-user-id"}},company:newDictionary<string,string>{{"id","your-company-id"}});// to guarantee that all events are sent before the application exits, call this method before your program shuts downawaitschematic.Shutdown();This call is non-blocking and there is no response to check.
If you want to record large numbers of the same event at once, or perhaps measure usage in terms of a unit like tokens or memory, you can optionally specify a quantity for your event:
schematic.Track(eventName:"some-action",user:newDictionary<string,string>{{"user_id","your-user-id"}},company:newDictionary<string,string>{{"id","your-company-id"}},quantity:10);Although it is faster to create companies and users via identify events, if you need to handle a response, you can use the companies API to upsert companies. Because you use your own identifiers to identify companies, rather than a Schematic company ID, creating and updating companies are both done via the same upsert operation:
usingSchematicHQ.Client;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;Schematicschematic=newSchematic("YOUR_API_KEY");// Creating and updating companiesasyncTaskUpsertCompanyExample(){varresponse=awaitschematic.Companies.UpsertCompanyAsync(newUpsertCompanyRequestBody{Keys=newDictionary<string,string>{{"id","your-company-id"}},Name="Acme Widgets, Inc.",Traits=newDictionary<string,object>{{"city","Atlanta"},{"high_score",25},{"is_active",true}}});// Handle the response as neededConsole.WriteLine($"Company upserted: {response.Data.Name}");}You can define any number of company keys; these are used to address the company in the future, for example by updating the company's traits or checking a flag for the company.
You can also define any number of company traits; these can then be used as targeting parameters.
Similarly, you can upsert users using the Schematic API, as an alternative to using identify events. Because you use your own identifiers to identify users, rather than a Schematic user ID, creating and updating users are both done via the same upsert operation:
usingSchematicHQ.Client;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;Schematicschematic=newSchematic("YOUR_API_KEY");// Creating and updating usersasyncTaskUpsertUserExample(){varresponse=awaitschematic.Companies.UpsertUserAsync(newUpsertUserRequestBody{Keys=newDictionary<string,string>{{"email","wcoyote@acme.net"},{"user_id","your-user-id"}},Name="Wile E. Coyote",Traits=newDictionary<string,object>{{"city","Atlanta"},{"high_score",25},{"is_active",true}},Company=newDictionary<string,string>{{"id","your-company-id"}}});// Handle the response as neededConsole.WriteLine($"User upserted: {response.Data.Name}");}You can define any number of user keys; these are used to address the user in the future, for example by updating the user's traits or checking a flag for the user.
You can also define any number of user traits; these can then be used as targeting parameters.
When checking a flag, you'll provide keys for a company and/or keys for a user. You can also provide no keys at all, in which case you'll get the default value for the flag.
Schematicschematic=newSchematic("YOUR_API_KEY");boolflagValue=awaitschematic.CheckFlag("some-flag-key",company:newDictionary<string,string>{{"id","your-company-id"}},user:newDictionary<string,string>{{"user_id","your-user-id"}});If you need more detail about how a flag check was resolved, including any entitlement associated with the check, use CheckFlagWithEntitlement. This returns a response object with the flag value, the reason for the evaluation result, and entitlement details such as usage, allocation, and credit balances when applicable.
Schematicschematic=newSchematic("YOUR_API_KEY");varresp=awaitschematic.CheckFlagWithEntitlement("some-flag-key",company:newDictionary<string,string>{{"id","your-company-id"}},user:newDictionary<string,string>{{"user_id","your-user-id"}});Console.WriteLine($"Flag: {resp.FlagKey}, Value: {resp.Value}, Reason: {resp.Reason}");if(resp.Entitlement!=null){Console.WriteLine($"Entitlement type: {resp.Entitlement.ValueType}");Console.WriteLine($"Usage: {resp.Entitlement.Usage}, Allocation: {resp.Entitlement.Allocation}");Console.WriteLine($"Credit remaining: {resp.Entitlement.CreditRemaining}");}The CheckFlags method allows you to efficiently check multiple feature flags in a single operation. When you provide specific flag keys, it will only return the flag values for those flags, leveraging intelligent caching to minimize API calls.
Schematicschematic=newSchematic("YOUR_API_KEY");varcompany=newDictionary<string,string>{{"id","your-company-id"}};// Check specific flags by providing an array of flag keysvarresults=awaitschematic.CheckFlags(company:company,keys:new[]{"feature-flag-1","feature-flag-2","feature-flag-3"});foreach(varresultinresults){Console.WriteLine($"Flag {result.Flag}: {result.Value} ({result.Reason})");if(result.Value){// This flag is enabled}else{// This flag is disabled}}// Or check all available flags by omitting the keys parametervarallResults=awaitschematic.CheckFlags(company:company);foreach(varresultinallResults){Console.WriteLine($"Flag {result.Flag}: {result.Value}");}The Schematic .NET SDK includes built-in support for OpenFeature, allowing you to use Schematic's feature flags through the OpenFeature standard API.
usingOpenFeature;usingSchematicHQ.Client.OpenFeature;// Create and set the Schematic providervarprovider=newSchematicProvider("YOUR_API_KEY");awaitApi.Instance.SetProviderAsync(provider);// Get the OpenFeature clientvarclient=Api.Instance.GetClient();// Evaluate a boolean feature flagvarisEnabled=awaitclient.GetBooleanValue("your-flag-key",false);The Schematic provider supports company and user context through OpenFeature's evaluation context:
varcontext=EvaluationContext.Builder().Set("company",newStructure(newDictionary<string,Value>{["id"]=newValue("company-123"),["name"]=newValue("Acme Corp"),["plan"]=newValue("enterprise")})).Set("user",newStructure(newDictionary<string,Value>{["id"]=newValue("user-456"),["email"]=newValue("user@example.com"),["role"]=newValue("admin")})).Build();// Evaluate with contextvarisEnabled=awaitclient.GetBooleanValue("your-flag-key",false,context);The provider includes a method to track events:
varprovider=(SchematicProvider)Api.Instance.GetProvider();awaitprovider.TrackEventAsync("button_clicked",context,newDictionary<string,object>{["button_name"]="submit",["page"]="checkout"});Schematic can send webhooks to notify your application of events. To ensure the security of these webhooks, Schematic signs each request using HMAC-SHA256. The .NET SDK provides utility functions to verify these signatures.
When your application receives a webhook request from Schematic, you should verify its signature to ensure it's authentic:
usingSchematicHQ.Client.Webhooks.WebhookUtils;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;[ApiController][Route("api/[controller]")]publicclassWebhooksController:ControllerBase{[HttpPost("schematic")]publicasyncTask<IActionResult>HandleSchematicWebhook(){try{// Read the request bodystringbody;using(varreader=newStreamReader(Request.Body)){body=awaitreader.ReadToEndAsync();}// Extract headers into a dictionaryvarheaders=newDictionary<string,string>();foreach(varheaderinRequest.Headers){headers[header.Key]=header.Value;}// Each webhook has a distinct secret; you can access this via the Schematic appstringwebhookSecret="your-webhook-secret";// Verify the webhook signatureWebhookVerifier.VerifyWebhookSignature(body,headers,webhookSecret);// Process the webhook payload// ...returnOk();}catch(WebhookSignatureExceptionex){// Handle signature verification failurereturnUnauthorized(new{error=ex.Message});}catch(Exceptionex){// Handle other errorsreturnStatusCode(500,new{error="Internal server error"});}}}If you need to verify a webhook signature outside of the context of an HTTP request, you can use the VerifySignature method:
usingSchematicHQ.Client.Webhooks.WebhookUtils;publicboolVerifyWebhookManually(stringbody,stringsignature,stringtimestamp,stringsecret){try{WebhookVerifier.VerifySignature(body,signature,timestamp,secret);Console.WriteLine("Signature verification successful!");returntrue;}catch(WebhookSignatureExceptionex){Console.WriteLine($"Signature verification failed: {ex.Message}");returnfalse;}}There are a number of configuration options that can be specified by passing ClientOptions as a second parameter when instantiating the Schematic client.
The recommended way to configure caching is through the fluent helpers on ClientOptions or by setting ClientOptions.CacheConfiguration directly.
By default an in-memory cache will be configured, but you can customize it further if required:
usingSchematicHQ.Client;varoptions=newClientOptions().WithLocalCache(capacity:10000,ttl:TimeSpan.FromSeconds(1));Schematicschematic=newSchematic("YOUR_API_KEY",options);If you prefer to configure it explicitly, you can set CacheConfiguration yourself:
usingSchematicHQ.Client;usingSchematicHQ.Client.Cache;varoptions=newClientOptions{CacheConfiguration=newCacheConfiguration{ProviderType=CacheProviderType.Local,LocalCacheCapacity=10000,CacheTtl=TimeSpan.FromSeconds(1)}};You can also disable local caching entirely; bear in mind that, in this case, every flag check will result in a network request:
usingSchematicHQ.Client;varoptions=newClientOptions().WithLocalCache(capacity:0);Schematicschematic=newSchematic("YOUR_API_KEY",options);For distributed applications or when you want cache persistence across application restarts, use Redis:
usingSchematicHQ.Client;usingSchematicHQ.Client.Cache;varoptions=newClientOptions().WithRedisCache(newRedisCacheConfig{Configuration="redis.example.com:6379",KeyPrefix="schematic:",Database=0,CacheTTL=TimeSpan.FromMinutes(5)});Schematicschematic=newSchematic("YOUR_API_KEY",options);If you need more control over the connection, supply a ConfigurationOptions instance or a ConnectionMultiplexerFactory:
usingSchematicHQ.Client;usingSchematicHQ.Client.Cache;usingStackExchange.Redis;varredisOptions=ConfigurationOptions.Parse("redis-primary.example.com:6379,redis-replica.example.com:6379");redisOptions.AbortOnConnectFail=false;redisOptions.Ssl=true;varoptions=newClientOptions().WithRedisCache(newRedisCacheConfig{ConfigurationOptions=redisOptions,KeyPrefix="schematic:",Database=0,CacheTTL=TimeSpan.FromMinutes(10)});If you want to provide your own cache backend, implement ICacheProvider and assign it to ClientOptions.CacheProvider:
usingSchematicHQ.Client;usingSchematicHQ.Client.Cache;publicsealedclassMyCustomCache:ICacheProvider{// ...}varoptions=newClientOptions{CacheProvider=newMyCustomCache()};varschematic=newSchematic("YOUR_API_KEY",options);Custom caches are useful if you need specialized eviction, a different backing store, or additional observability around cache access.
You may want to specify default flag values for your application, which will be used if there is a service interruption or if the client is running in offline mode (see below):
usingSchematicHQ.Client;usingSystem.Collections.Generic;varoptions=newClientOptions{FlagDefaults=newDictionary<string,bool>{{"some-flag-key",true}}};Schematicschematic=newSchematic("YOUR_API_KEY",options);In development or testing environments, you may want to avoid making network requests to the Schematic API. You can run Schematic in offline mode by specifying the Offline option; in this case, it does not matter what API key you specify:
usingSchematicHQ.Client;varoptions=newClientOptions{Offline=true};Schematicschematic=newSchematic("",options);// API key doesn't matter in offline modeOffline mode works well with flag defaults:
usingSchematicHQ.Client;usingSystem.Collections.Generic;varoptions=newClientOptions{FlagDefaults=newDictionary<string,bool>{{"some-flag-key",true}},Offline=true};Schematicschematic=newSchematic("",options);boolflagValue=awaitschematic.CheckFlag("some-flag-key");// Returns trueYou can also set flag defaults dynamically after the client has been constructed using SetFlagDefault and SetFlagDefaults. This is useful in automated testing contexts, where you may want to specify per-test flag values:
usingSchematicHQ.Client;usingSystem.Collections.Generic;varoptions=newClientOptions{Offline=true};Schematicschematic=newSchematic("",options);// Set a single flag defaultschematic.SetFlagDefault("some-flag-key",true);// Or set multiple flag defaults at onceschematic.SetFlagDefaults(newDictionary<string,bool>{{"some-flag-key",true},{"another-flag-key",false}});boolflagValue=awaitschematic.CheckFlag("some-flag-key");// Returns trueSchematic API uses an Event Buffer to batch Identify and Track requests and avoid multiple API calls. You can set the event buffer flush period in options:
usingSchematicHQ.Client;varoptions=newClientOptions{DefaultEventBufferPeriod=TimeSpan.FromSeconds(5)};You may also want to use your custom event buffer. To do so, your custom event buffer has to implement IEventBuffer interface, and pass an instance to the Schematic API through options:
usingSchematicHQ.Client;varoptions=newClientOptions{EventBuffer=newMyCustomEventBuffer();//instance of your custom event buffer}You can override the HttpClient:
schematic=newSchematic("YOUR_API_KEY",newClientOptions{HttpClient= ...// Override the Http ClientBaseURL= ...// Override the Base URL})429 Rate Limit, and >=500 Internal errors will all be retried twice with exponential backoff. You can override this behavior globally or per-request.
varschematic=newSchematic("...",newClientOptions{MaxRetries=1// Only retry once});The SDK defaults to a 60s timeout. You can override this behaviour globally or per-request.
varschematic=newSchematic("...",newClientOptions{TimeoutInSeconds=20// Lower timeout});When the API returns a non-zero status code, (4xx or 5xx response), a subclass of SchematicException will be thrown:
usingSchematicHQ;try{schematic.Accounts.ListApiKeysAsync(...);}catch(SchematicExceptione){System.Console.WriteLine(e.Message)
System.Console.WriteLine(e.StatusCode)}Datastream is Schematic's real-time connection service that optimizes flag check performance and reliability. When enabled, the Schematic client maintains a WebSocket connection to our servers, which pushes down feature flag definitions, company data, and user data as needed.
- Improved Performance: Flag checks become near-instantaneous after the initial data load
- Reduced API Load: Minimizes HTTP requests to the Schematic API
- Real-time Updates: Flag changes are immediately pushed to your application
- Fault Tolerance: Falls back to standard API requests when needed
Important: Datastream is disabled by default. You must explicitly enable it in your client options:
usingSchematicHQ.Client;// Create options with Datastream enabledvaroptions=newClientOptions{UseDatastream=true// Enable Datastream};// Initialize client with optionsvarschematic=newSchematic("YOUR_API_KEY",options);You can customize Datastream's behavior through additional client options:
usingSchematicHQ.Client;usingSchematicHQ.Client.Cache;usingSchematicHQ.Client.Datastream;varoptions=newClientOptions{UseDatastream=true,DatastreamOptions=newDatastreamOptions{CacheTTL=TimeSpan.FromMinutes(10)}};varschematic=newSchematic("YOUR_API_KEY",options);DatastreamOptions currently controls Datastream-specific TTL behavior; the cache provider itself still comes from ClientOptions.CacheConfiguration (or CacheProvider for custom implementations).
The flag checking experience remains the same whether Datastream is enabled or not:
// Check a feature flag with Datastream enabledboolflagValue=awaitschematic.CheckFlag("premium-feature",company:newDictionary<string,string>{{"id","company-123"}},user:newDictionary<string,string>{{"email","user@example.com"}});// Use the flag resultif(flagValue){// Enable premium feature}else{// Use standard feature}The difference is that with Datastream enabled, after the initial data load, subsequent flag checks for the same company and user will be nearly instantaneous and won't require additional network requests.
Replicator mode is an advanced Datastream configuration that maintains a local replica of your Schematic data using a persistent cache layer. This mode provides enhanced performance and reliability for high-throughput applications.
usingSchematicHQ.Client;usingSchematicHQ.Client.Cache;usingSchematicHQ.Client.Datastream;varoptions=newClientOptions().WithRedisCache(newRedisCacheConfig{Configuration="localhost:6379",KeyPrefix="schematic-replica:",CacheTTL=TimeSpan.FromHours(24)}).WithReplicatorMode("https://health.your-app.com/schematic-replicator");varschematic=newSchematic("YOUR_API_KEY",options);usingSchematicHQ.Client;usingSchematicHQ.Client.Cache;usingSchematicHQ.Client.Datastream;usingStackExchange.Redis;varredisOptions=ConfigurationOptions.Parse("redis-primary.example.com:6379,redis-replica.example.com:6379");redisOptions.AbortOnConnectFail=false;redisOptions.Ssl=true;varoptions=newClientOptions().WithRedisCache(newRedisCacheConfig{ConfigurationOptions=redisOptions,KeyPrefix="schematic-replica:",CacheTTL=TimeSpan.FromHours(24)}).WithReplicatorMode("https://health.your-app.com/schematic-replicator");varschematic=newSchematic("YOUR_API_KEY",options);| Configuration Method | Description | Example |
|---|---|---|
.WithReplicatorMode(url) | Enables replicator mode and sets the health check endpoint URL | "https://health.example.com/replicator" |
.WithRedisCache(config) | Configures Redis as the cache provider for replicator data | Required for replicator mode |
While we value open-source contributions to this SDK, this library is generated programmatically. Additions made directly to this library would have to be moved over to our generation code, otherwise they would be overwritten upon the next generated release. Feel free to open a PR as a proof of concept, but know that we will not be able to schematic it as-is. We suggest opening an issue first to discuss with us!
On the other hand, contributions to the README are always very welcome!