> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ditto.live/llms.txt
> Use this file to discover all available pages before exploring further.

# C#

> You can integrate the Ditto SDK into C# projects to develop for platforms, including mobile apps for iOS and Android, desktop apps, Linux-enabled server systems, and more.

To install the C# SDK:

<Steps>
  <Step>
    Confirm that you meet the minimum requirements. ([Prerequisites](#prerequisites))
  </Step>

  <Step>
    Install the Ditto SDK. ([Installing Dependencies](#installing-dependencies))
  </Step>

  <Step>
    Set up your app permissions. ([Configuring Permissions](#configuring-permissions))
  </Step>

  <Step>
    Add Ditto to your app. ([Initializing Ditto](#initializing-ditto))
  </Step>

  <Step>
    (Optional) Declare a foreground service (Android only). ([Declaring a Foreground Service](#declaring-a-foreground-service-android-only))
  </Step>
</Steps>

## Prerequisites

Following are the minimum requirements that must be met before attempting to install Ditto:

* <a href="https://dotnet.microsoft.com/en-us/download/dotnet/8.0" target="_blank">.NET 8 or higher</a>
* <a href="https://dotnet.microsoft.com/en-us/platform/support/policy/maui" target="_blank">.NET 8 or higher if you are targeting .NET MAUI</a>

## Installing Dependencies

To use the Ditto SDK in your project, you’ll need to install the appropriate NuGet package.

<Info>
  If using a package manager other than NuGet, the official package manager for .NET, the command syntax to install Ditto may differ from the following snippet. For more information, see the official Nuget documentation > <a href="https://www.nuget.org/packages/Ditto/" target="_blank">Ditto .NET</a>
</Info>

<CodeGroup>
  ```shell:NuGet Package Manager theme={null}
  Install-Package Ditto -Version 5.0.0
  ```

  ```shell:.NET CLI theme={null}
  dotnet add package Ditto --version 5.0.0
  ```

  ```xml: csproj theme={null}
  <PackageReference Include="Ditto" Version="5.0.0" />
  ```
</CodeGroup>

## Configuring Permissions

To set up your environment for your target platform:

<Tabs>
  <Tab title="iOS Target">
    For apps targeting iOS; for example, MAUI, once you've added the Ditto package dependency,
    configure permissions and ensure your app continues syncing while running in the background,
    including when the end-user device is locked, by enabling background modes.

    <Steps>
      <Step>
        Open the `Info.Plist` file for your project.
      </Step>

      <Step>
        Add the following key-value pairs, and then, if desired, modify each string value:

        ```xml XML theme={null}
        <key>NSBluetoothAlwaysUsageDescription</key>
        <string>Uses Bluetooth to connect and sync with nearby devices</string>
        <key>NSLocalNetworkUsageDescription</key>
        <string>Uses WiFi to connect and sync with nearby devices</string>
        <key>NSBonjourServices</key>
        <array>
        <string>_http-alt._tcp.</string>
        </array>
        ```
      </Step>

      <Step>
        Enable Bluetooth Background Modes:

        ```xml XML theme={null}
        <key>UIBackgroundModes</key>
        <array>
        <string>bluetooth-central</string>
        <string>bluetooth-peripheral</string>
        </array>
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="Android Target">
    For apps targeting Android, once you've added the Ditto package dependency, configure the necessary permissions:

    <Steps>
      <Step>
        Open the `AndroidManifest.xml` file typically located in the `src/main/` directory of your project.
      </Step>

      <Step>
        Add the necessary permissions to ensure your app has the permissions required by Ditto:

        <Info>
          For instructions on how to modify the following configuration for permissions requests; for example, prevent your app from requesting unnecessary permissions on newer OS versions or ensure compatibility with both older and newer OS versions, see [Customizing Permissions]().
        </Info>

        ```xml XML theme={null}
        <manifest
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <uses-permission android:name="android.permission.BLUETOOTH"
        android:maxSdkVersion="30" />
        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
        android:maxSdkVersion="30" />
        <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE"
        tools:targetApi="s" />
        <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"
        tools:targetApi="s" />
        <uses-permission android:name="android.permission.BLUETOOTH_SCAN"
        android:usesPermissionFlags="neverForLocation"
        tools:targetApi="s" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
        android:maxSdkVersion="32" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
        android:maxSdkVersion="30" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
        <uses-permission
        android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
        <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
        <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES"
        android:usesPermissionFlags="neverForLocation"
        tools:targetApi="tiramisu" />
        ```
      </Step>
    </Steps>

    ### Customizing Permissions

    To modify the behavior of permission requests for the Android target:

    <Steps>
      <Step>
        Add the following namespace attribute to the root `<manifest>` tag of your `AndroidManifest.xml` file:

        ```xml theme={null}
        xmlns:tools="http://schemas.android.com/tools"
        ```
      </Step>

      <Step>
        To request permissions on all OS versions of Android:

        ```xml theme={null}
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
        tools:remove="android:maxSdkVersion" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
        tools:remove="android:maxSdkVersion" />
        ```
      </Step>

      <Step>
        To limit permissions request, use the following attributes as desired:

        * [tools:targetApi]()
        * [android:maxSdkVersion]()
      </Step>
    </Steps>

    #### tools:targetApi

    The `tools:targetApi` attribute allows you to specify that a permission should only be requested on devices running a specified Android API level or *higher*.

    By limiting permissions requests, you prevent errors that result from asking permissions on devices running older OS versions of Android.

    #### android:maxSdkVersion

    With the `android:maxSdkVersion` attribute, you can customize to only initiate a permission request on devices running a specified Android API level or lower.

    Setting to a specified API level or lower helps avoids unnecessary permissions requests on devices running newer OS versions of Android.
  </Tab>

  <Tab title="Mac Catalyst Target">
    For apps targeting macOS via Mac Catalyst, once you've added the Ditto package dependency,
    you'll need to request permission for Bluetooth and local networking access.

    <Steps>
      <Step>
        Open the `Info.plist` file for your Mac Catalyst target.
      </Step>

      <Step>
        Add the following key-value pairs to request access to Bluetooth and local networking:

        ```xml XML theme={null}
        <key>NSBluetoothAlwaysUsageDescription</key>
        <string>Uses Bluetooth to connect and sync with nearby devices</string>
        <key>NSLocalNetworkUsageDescription</key>
        <string>Uses WiFi to connect and sync with nearby devices</string>
        <key>NSBonjourServices</key>
        <array>
        <string>_http-alt._tcp.</string>
        </array>
        ```
      </Step>
    </Steps>
  </Tab>
</Tabs>

### Requesting Permissions at Runtime

In addition to being declared, some permissions need to be requested from the user at runtime. To ensure your app has the required permissions for sync, use the `DittoSyncPermissions` helper class from the Ditto SDK.
This helper class simplifies the process of requesting end-user permissions at runtime with a single method call for all necessary permissions.

Ensure `Sync.Start()` is invoked after permissions have been requested.

```csharp C# theme={null}
public async Task CheckPermissions()
{
    await DittoSyncPermissions.RequestPermissionsAsync();
    ditto.Sync.Start();
}
```

## Initializing Ditto

Once you’ve installed the Ditto SDK, set the debug level you want Ditto to log messages for, create a new Ditto identity, and set up Ditto exception handling for data sync operations:

```csharp C# theme={null}
using DittoSDK;

var databaseId = "YOUR_DATABASE_ID";
var config = new DittoConfig(
    databaseId: databaseId,
    connect: DittoConnect.Server($"https://{databaseId}.cloud.ditto.live")
);

var ditto = await Ditto.OpenAsync(config);

ditto.Auth.ExpirationHandler = async (ditto, secondsRemaining) => {
    var result = await ditto.Auth.LoginAsync("YOUR_PLAYGROUND_TOKEN", Authenticator.DevelopmentProvider);
    if (result.Error != null) {
        Console.WriteLine($"Auth error: {result.Error}");
    }
};

ditto.Sync.Start();
```

## Declaring a Foreground Service (Android Only)

A [foreground service](https://developer.android.com/develop/background-work/services/fgs) allows your app to continue syncing data with Ditto while running in the background. A foreground service is not required to use Ditto, but without it your app will stop syncing whenever it is in the background.

To declare the foreground service, add the following to your `AndroidManifest.xml`:

```xml theme={null}
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" tools:targetApi="upside_down_cake" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" tools:targetApi="tiramisu" />

<application ...>
    <service
        android:name="live.ditto.transports.foregroundservice.DefaultDittoForegroundService"
        android:exported="false"
        android:foregroundServiceType="connectedDevice"
        android:stopWithTask="true">
        <meta-data android:name="notificationChannelName" android:value="Background Data Sync" />
        <meta-data android:name="notificationChannelId" android:value="BackgroundDataSyncId" />
        <meta-data android:name="smallIcon" android:resource="@drawable/small_app_icon" />
        <meta-data android:name="notificationTitle" android:value="Syncing Data" />
        <meta-data android:name="notificationText" android:value="Syncing data across connected devices" />
        <meta-data android:name="notificationId" android:value="1001" />
    </service>
</application>
```

Make sure you customize the service metadata--it will be displayed to the user in the foreground service notification. Note that your `small_app_icon` drawable must be monochrome white.

The foreground service will be automatically started and stopped on `ditto.Sync.Start()` and `ditto.Sync.Stop()`, respectively.

## Next Steps

Learn how to build a task list app built on .NET and integrated with Ditto by going to the [.NET MAUI](/sdk/latest/quickstarts/dotnet-maui) or [.NET TUI](/sdk/latest/quickstarts/dotnet-console) quickstart apps.
