import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/docs/ui/accordion"


export const exampleFile = 'dotnet-guide-examples'
# Bento .NET Guide

This guide covers installing the Bento .NET SDK, configuring the client, and the main operations: tracking events, managing subscribers, and sending transactional emails from your .NET application.


  

  

  

  


### Reference

  # [API Reference](#api-reference)
  # [Troubleshooting](#troubleshooting)
  # [FAQ](#faq)


## Getting Started


  
    
**1. Package Installation**

    
      ## Installation

      Download and extract the ZIP file containing the .NET SDK:

      
    

    
**2. Client Configuration**

    
      ## Basic Setup

      To initialize the Bento client, you'll need your Site UUID, Publishable Key, and Secret Key from your Bento account.
      You can find your keys in your [Bento Team](https://app.bentonow.com/account/teams). To see your keys, click
      `Your Private API Keys`. If you do not see a Publishable key and Secret Key, click `Generate Key` to
      create a set.

      
    
  


## Beginner Guide


## Tracking Your First Event

Events record actions users take in your application, like signing up or making a purchase.

#### Adding subscribers via events
Events are the preferred way to add subscribers. One call records the event and kicks off any workflows and
automations tied to it.

#### Enriching events with data
Events can carry contextual data alongside the action itself. This can be used in emails via
[liquid tags](/docs/liquid_guide) or in segmentation. For instance, when recording a purchase event, you can include detailed
transaction information such as:

| Detail                                                   | Liquid tag                                                                                                                                         |
|----------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|
| Product details |                  |
| Purchase amount |                  |
| Transaction ID  |                  |
| Payment method  |  |

### Practical Example
When a customer completes a purchase, you can track this as an event while including all relevant purchase details. This
approach enables you to:

- Trigger specific post-purchase workflows
- Launch targeted follow-up automations
- Track lifetime value (LTV) metrics
- Create personalized communications based on purchase history


## Managing Subscribers

If you need to manage subscribers directly there are a set of convenience methods available to you. Add, update, and
unsubscribe subscribers with these simple methods. Currently, you cannot remove subscribers via the API, but you can
remove them from the dashboard `People > All Users`.


  <summary>
    
  </summary>
  <content>

    
    
  </content>


#### Adding Individual Subscribers
Please note, while these methods make it easy to manage a subscriber, the Bento recommended way to add **a** subscriber
is via an `event`. This allows you to kick off sequences and automations, while also recording the "event" at the same
time (1 API call).

#### Adding Multiple Subscribers
Importing or modifying multiple subscribers should be handled via the [bulk methods](/docs/examples/nodejs#subscriber-updates),
instead of looping over these calls multiple times.


## Common Use Cases

Here are some common scenarios with ready-to-use code:

  <summary>
    
  </summary>
  <content>
    
    
  </content>


## Intermediate Guide


## Custom Fields and Tags

Bento allows you to store custom data about your users through fields and segment them with tags:

  <summary>
    
  </summary>
  <content>
    
    
    
  </content>


## Using Custom Fields & Tags
While custom fields and tags can be used to segment subscribers, most Bento users find that namespaced tags provide a more
effective and easier-to-maintain solution for most segmentation use cases.

#### Namespaced Tags
Namespaced tags follow this format: `namespace`:`detail`
For example, if you offer three subscription plans, you could create these tags:
* `subscription:basic`
* `subscription:pro`
* `subscription:enterprise`

We recommend applying these tags either through an automated flow or via bulk updates.


> **Recommended**
> Tags do not need to be namespaced, but for many customers the organization pays off by using namespaced tags when
>   it makes sense.


#### Fields
Fields are perfect for storing information about your subscribers, such as their language, timezone,
or other relevant details. By using fields, you can easily segment subscribers based on their specific needs and
preferences, allowing you to tailor your marketing efforts and messaging to each group.

The primary difference between
fields and namespaced tags is that fields are not limited to a specific detail and do not need to be predefined. You can
store any type of data in a field, including strings, numbers, or even objects. This flexibility makes fields a powerful
tool for storing data.

#### Best Practices
For optimal organization, consider using tags for segmentation while storing more detailed user information in custom
fields. Many successful implementations use a strategic combination of both approaches.


## Tracking Purchase Events

When recording purchase events, you must include a `unique:` key as part of the tracking data. This requirement prevents
duplicate transactions from being recorded in your analytics.

Most users find it beneficial to use their internal cart or order number as the `unique:` key. This approach simplifies
future lookups and maintains consistency across your systems. The `unique:` key value you provide is accessible through
liquid tags when creating custom email templates, allowing for personalized transactional messaging based on specific
purchase details.

Tracking purchases is a great way to monitor customer lifetime value (LTV) and identify recurring customers. Bento reports
on the LTV of each subscriber, allowing you to identify high-value customers and tailor your marketing efforts accordingly.


## Advanced Guide


## Batch Operations

For efficiency, we suggest using batch operations when integrating with Bento. These methods allow for single or bulk
operations on subscribers and events, improving the performance and scalability of your integration. They also cover more
than 80% of the API use cases for most customers.


## Transactional Emails

Bento allows you to send personalized transactional emails for time-sensitive, direct communications. These emails serve
specific functional purposes rather than marketing objectives.


  
    #### Ideal Transactional Email Use Cases
    * User onboarding (confirmation etc)
    * Password reset notifications
    * Sign-in verification links
    * Order confirmations and details
    * Account notifications
  

  
    #### NOT Ideal Transactional Email Use Cases
    * CC / BCC recipients
    * Emails that require an attachment (we suggest always using links for emails for best deliverability)
    * Marketing of any kind
    * Promotional content
    * Newsletters
  


#### From Address Requirements
The sender address used in your transactional emails must be configured as an Author email within your Bento settings.
Please note that generic addresses such as "~[no-reply@domain.com](mailto:no-reply@domain.com)~" or similar non-personal
addresses are not currently supported.

#### Important Distinction
**Transactional** emails are designed for **essential communications** that facilitate specific **user actions** or provide
critical information.


> 🚨 **Important**
> Transactional emails should **not** be used as substitutes for **marketing** campaigns or **promotional**
>   content.


## Subscriber Updates

Many organizations joining Bento already have an established subscriber base that requires bulk updates over time. These
updates commonly include setting field data and managing tags across multiple subscribers. We recommend these
methods for all subscriber updates, single or bulk.


> These methods cover more than 80% of the API use cases for most customers.


#### Choosing the Right Update Method:


The SDK offers multiple approaches for creating subscribers in Bento, each suited to different scenarios.

#### Preferred Method: Events

The recommended way to create subscribers is via events in response to user activity. This approach activates
automations, workflows, and can contain data enrichment.


  <summary>
    
  </summary>
  <content>
    
  </content>


#### Alternative Methods

For scenarios where you need to create subscribers independently of user actions:

  
**1. Single Subscriber Creation**

  
    Use this method when you need to quickly create a single subscriber with minimal data:

    

    
> ⚠️ **Warning**
> This endpoint is rate-limited and not suitable for loops or bulk creation. Use only for individual subscriber creation.


  
  
**2. Multiple Or Enriched Subscriber Creation**

  
    For creating multiple subscribers or including additional fields:

    

    Best Practices for Batch Imports:
    * Though the API supports up to 1,000 subscribers per call, we recommend batches of 200-300 for optimal performance when dealing with extensive data.
    * Include all relevant custom fields in the initial import to minimize follow-up updates.
    * For very large imports (10,000+ subscribers), consider implementing a queue system with delay between batches.

  


#### Updating Subscribers
Depending on your requirements, several approaches are available for updating subscriber information.

#### Event-Based Updates (Preferred)
When updates occur in response to user actions, tracking events is the recommended approach:


> Because you can apply as many changes via automations / workflows as you want this is the most flexible method.
>   It doesn't require code or deployment changes, and can be completely handled in Bento.


#### Alternative Update Methods

For updates outside of user-triggered actions:

  
**1. Single Attribute Updates**

  
    For quickly updating a specific attribute on a single subscriber:
    
      <summary>
        
      </summary>
      <content>
        
        
      </content>
    

    
> ⚠️ **Warning**
> The Command API is not recommended for multiple updates or bulk operations. Given its heavy rate limit, use the Batch API instead.

  
  
**2. Batch Updates**

  
    For updating multiple subscribers or multiple fields at once, use the batch import method:

    

    Recommendations:
    * Even for single-subscriber updates, consider using the batch import method when multiple fields need updating.
    * The batch import performs an "upsert" operation. It creates subscribers that don't exist and updates those that do.
    * This approach provides the most flexibility as your use cases evolve, whether you need to add more changes or modify multiple users simultaneously.

  


#### Specialized Update Operations
For specific update scenarios, the SDK offers dedicated methods:


  <summary>
    
  </summary>
  <content>

    
    
  </content>


## Utility Features

These utilities handle common secondary use cases like email validation and blacklist checks.


  <summary>
    
  </summary>
  <content>
    
    
    

  </content>


## API Reference


### Core API

- **Client** - Main entry point for using the SDK (`bento.Client`)
- **Configuration** - Set up through the `bento.Config` struct with API keys and settings
- **Cancellation** - Async methods accept `CancellationToken` for cancellation and timeouts
- **Data Types** - Structured request/response types in the root package (`bento.EventData`, `bento.SubscriberInput`, etc.)
- **Error Handling** - Predefined error types (`ErrInvalidConfig`, `ErrInvalidEmail`, etc.) for specialized error handling


### Convenience Methods


#### Core API


| Use Case                                                                         | C# SDK Method                                                                                                                                                                                  |
|----------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|  Add a new subscriber                   |      |
| Update data for an existing subscriber  |  |
| Track a custom event                    |                        |

### Modules

#### Batch
| Use Case                                                              | Method                                                                                                                                                                                         | API Reference                                                                                                                                       |
|-----------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|
| Import multiple subscribers  |  | [Import Subscribers](/docs/subscribers#import-subscribers) |
| Import multiple events       |                                  | [Import Events](/docs/events_api#create-events)            |
| Send emails                  |                          | [Send Emails](/docs/emails_api#create-emails)              |

#### Experimental
| Use Case                                                            | Method                                                                                                                                                                                 | API Reference                                                                                                                                   |
|---------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------|
| Validate email address     |          | [Validate Email](/docs/utility#validate-email)         |
| Predict gender from name   |                  | [Gender Guess](/docs/utility#guess-gender)             |
| Get IP geolocation         |            | [IP Geolocation](/docs/utility#geolocate-ip-address)   |
| Check domain/IP blacklist  |  | [Blacklist Check](/docs/utility#search-blacklists)     |
| Moderate content           |      | [Content Moderation](/docs/utility#content-moderation) |

#### Fields
| Use Case                                                 | Method                                                                                                                                                       | API Reference                                                                                                                       |
|----------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------|
| Get all fields  |                | [Get Fields](/docs/fields#get-fields)      |
| Create a field  |  | [Create Fields](/docs/fields#create-field) |

#### Subscribers
| Use Case                                                      | Method                                                                                                                                                                                     | API Reference                                                                                                                                   |
|---------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------|
| Find subscriber      |                | [Find Subscriber](/docs/subscribers#find-subscriber)   |
| Create a subscriber  |  | [Create Subscriber](/docs/subscribers#find-subscriber) |

#### Tags
| Use Case                                               | Method                                                                                                                                           | API Reference                                                                                                                    |
|--------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------|
| Get all tags  |            | [List Tags](/docs/tags_api#get-tags)    |
| Create a tag  |  | [Create Tag](/docs/tags_api#create-tag) |

#### Broadcasts
| Use Case                                                          | Method                                                                                                                                                                                             | API Reference                                                                                                                                    |
|-------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|
| Get all broadcasts       |                                      | [Get Broadcasts](/docs/broadcasts#get-broadcasts)       |
| Create a broadcast       |                | [Create Broadcast](/docs/broadcasts#create-broadcast)   |
| Create batch broadcasts  |  | [Create Broadcasts](/docs/broadcasts#create-broadcasts) |

#### Stats
| Use Case                                                    | Method                                                                                                                                                                       | API Reference                                                                                                                               |
|-------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------|
| Get site stats     |                          | [Get Site Stats](/docs/stats#get-site-stats)       |
| Get segment stats  |  | [Get Segment Stats](/docs/stats#get-segment-stats) |
| Get report stats   |      | [Get Report Stats](/docs/stats#get-report-stats)   |


## Troubleshooting


#### Common Errors

|                                                            |                                                                   |
|------------------------------------------------------------|-------------------------------------------------------------------|
| `Not Authorized` | Check your API keys and ensure they have appropriate permissions  |
| `Rate Limited`   | Implement backoff/retry logic for batch operations                |
| `Network Errors` | Check internet connectivity and API endpoint availability         |
| `Exceptions`     | Double check you are using a valid `Author` & the payload format. |


#### Debugging Tips

|    |                                                                                          |
|----|------------------------------------------------------------------------------------------|
| 1. | Configure logging in your .NET application to capture API responses                      |
| 2. | Check `response.Success` and inspect `response.Error` when a call fails                  |
| 3. | For batch operations, start with smaller batches to isolate issues                       |


## FAQ


  
    Can I use this SDK in a frontend environment?
    
      No, this SDK is designed for server-side .NET applications as it requires secret API keys that should never be
      exposed to clients. If you wish to track events from the frontend, consider using our JavaScript SDK or create an
      ASP.NET Core endpoint that securely handles tracking authenticated user actions.
    
  

  
    How do I handle rate limiting?
    
      Implement exponential backoff with .NET's retry patterns when you encounter rate limit responses. You can use
      libraries like Polly or implement your own retry logic with HttpClient:

      
    
  

  
    What's the maximum batch size for importing subscribers or events?
    
      Up to 1,000 subscribers or events can be imported in a single batch operation. We recommend batches of 200-300 for
      optimal performance. For large imports, consider using .NET's async patterns and Task.WhenAll for parallel processing:

      
    
  

  
    How do I track anonymous users?
    
      Currently, the SDK requires an email address for all tracking. Anonymous tracking support is planned for future
      releases.
    
  

  
    Which .NET versions are supported?
    
      The SDK requires .NET 8.0 or higher to support the latest features and security improvements. We recommend using the latest stable version of .NET for optimal performance and security.
    
  

  
    How can I contribute to the SDK?
    
      We welcome contributions! Check the GitHub repository at [github.com/bentonow/bento-dotnet-sdk](https://github.com/bentonow/bento-dotnet-sdk)
      for contribution guidelines. You can submit pull requests, report issues, or suggest new features.
      For direct assistance, join our community Discord server.
    
  

  
    How do I handle timeouts and cancellation tokens?
    
      The SDK uses HttpClient with proper async/await patterns and supports CancellationToken for timeout management. You can configure timeouts in your application:

      
    
  

  
    Can I use the SDK with Azure Functions or other serverless environments?
    
      Yes, the SDK is compatible with .NET serverless environments like Azure Functions and AWS Lambda. For best performance, configure the SDK during application startup using dependency injection to reuse HttpClient connections:

      

      For bulk operations, be mindful of function execution time limits and consider breaking large batches into smaller chunks.