Some features of this SDK are still in development. Consult with our online support team if you run into issues using this SDK in a production environment.

Sinch .NET SDK for Conversation

The Sinch Conversation .NET SDK allows you to quickly interact with the Conversation API from inside your .NET applications. The fastest way to get started with the SDK is to check out our getting started guides. There you'll find all the instructions necessary to download, install, set up, and start using the SDK.

Syntax

When using the .NET SDK, the code representing requests and queries sent to and responses received from the Conversation API are structured similarly to those that are sent and received using the Conversation API itself.

Note:

This guide describes the syntactical structure of the .NET SDK for the Conversation API, including any differences that may exist between the API itself and the SDK. For a full reference on Conversation API calls and responses, see the Conversation REST API Reference.

The code sample on the side of this page is an example of how to use the .NET SDK to send a text message on the SMS channel of a Conversation API app. The SDK code and Conversation API call that accomplishes the same task are displayed below for reference and comparison (note that this REST API example uses Basic Authentication instead of OAuth2):

SDKREST API
Copy
Copied
using System.Text.Json;
using Sinch;
using Sinch.Conversation;
using Sinch.Conversation.Messages.Send;
using Sinch.Conversation.Messages.Message;
using Sinch.Conversation.Common;

var sinch = new SinchClient("YOUR_project_id",
    "YOUR_access_key",
    "YOUR_access_secret",
    // ensure you set the Conversation region. 
    options => options.ConversationRegion = ConversationRegion.Us);

var response = await sinch.Conversation.Messages.Send(new SendMessageRequest
{
    Message = new AppMessage(new TextMessage("Hello! Thank you for using the Sinch .NET SDK to send an SMS.")),
    AppId = "YOUR_app_id",
    Recipient = new Identified
    {
        IdentifiedBy = new IdentifiedBy
        {
            ChannelIdentities = new List<ChannelIdentity>
            {
                new ChannelIdentity
                {
                    AppId = "YOUR_app_id",
                    Identity = "RECIPIENT_number",
                    Channel = new ConversationChannel("SMS")
                }
            }
        }
    },
    ChannelProperties = new Dictionary<string, string> { { "SMS_SENDER", "YOUR_sms_sender" } }
});

Console.WriteLine(JsonSerializer.Serialize(response, new JsonSerializerOptions()
{
    WriteIndented = true
}));
Copy
Copied
// Find your App ID at dashboard.sinch.com/convapi/apps
// Find your Project ID at dashboard.sinch.com/settings/project-management
// Get your Access Key and Access Secret at dashboard.sinch.com/settings/access-keys
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text;
using System.Text.Json;
using System.Net.Http.Headers;

public class Program
{
  public static async Task Main()
  {
    System.Net.Http.HttpClient client = new();

    string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("YOUR_access_key:YOUR_access_secret"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(@"Basic", base64String);

    string json = JsonSerializer.Serialize(new
    {
      app_id = "YOUR_app_id",
      recipient = new {
        identified_by = new {
          channel_identities = new[] {
            new {
              channel = "SMS",
              identity = "RECIPIENT_number"
            }
          },
        }
      },
      message = new {
        text_message = new {
          text = "This is a text message."
        }
      },
      channel_properties =  new {
        SMS_SENDER = "YOUR_sms_sender"
      } 
    });

    using StringContent postData = new(json, Encoding.UTF8, "application/json");
      var ProjectId = "YOUR_project_id";
      var Region = "us";
    using HttpResponseMessage request = await client.PostAsync("https://" + Region + ".conversation.api.sinch.com/v1/projects/" + ProjectId + "/messages:send", postData);
    string response = await request.Content.ReadAsStringAsync();

    Console.WriteLine(response);
  }
}

This example highlights the following required to successfully make a Conversation API call using the Sinch .NET SDK:

Client

When using the Sinch .NET SDK, you initialize communication with the Sinch backend by initializing the .NET SDK's main client class. This client allows you to access the functionality of the Sinch .NET SDK.

Initialization

Before initializing a client using this SDK, you'll need three pieces of information:

  • Your Project ID
  • An access key ID
  • An access key Secret
These values can be found on the Access Keys page of the Customer Dashboard. You can also create new access key IDs and Secrets, if required.
Note:
If you have trouble accessing the above link, ensure that you have gained access to the Conversation API by accepting the corresponding terms and conditions.

To start using the SDK, you need to initialize the main client class with your credentials from your Sinch dashboard.

Note:

For testing purposes on your local environment it's fine to use hardcoded values, but before deploying to production we strongly recommend using environment variables to store the credentials.

Copy
Copied
using Sinch;

var sinch = new SinchClient("YOUR_project_id",
                            "YOUR_access_key", 
                            "YOUR_access_secret");
You can also implement the client using ASP.NET dependency injection. SinchClient is thread safe, so it's fine to add it as a singleton:
Copy
Copied
builder.Services.AddSingleton<ISinchClient>(x => new SinchClient(
    builder.Configuration["YOUR_project_id"],
    builder.Configuration["YOUR_access_key"],
    builder.Configuration["YOUR_access_secret"]));

Conversation domain

The Sinch .NET SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, Sinch.Conversation.[Endpoint_Category].[Method()].

Endpoint categories

In the Sinch .NET SDK, Conversation API endpoints are accessible through the client (either a general client or a Conversation-specific client). The naming convention of the endpoint's representation in the SDK matches the API:

  • Messages
  • Apps
  • Contacts
  • Events
  • Transcoding
  • Capability
  • TemplatesV2
  • Webhooks
  • Conversations

For example:

Copy
Copied
var response = await sinch.Conversation.Messages.Send(new SendMessageRequest
{
    Message = new AppMessage(new TextMessage("Hello! Thank you for using the Sinch .NET SDK to send an SMS.")),
    AppId = "YOUR_app_id",
    Recipient = new Identified
    {
        IdentifiedBy = new IdentifiedBy
        {
            ChannelIdentities = new List<ChannelIdentity>
            {
                new ChannelIdentity
                {
                    AppId = "YOUR_app_id",
                    Identity = "RECIPIENT_number",
                    Channel = new ConversationChannel("SMS")
                }
            }
        }
    },
    ChannelProperties = new Dictionary<string, string> { { "SMS_SENDER", "YOUR_sms_sender" } }
});

Messages endpoint category

The Messages category of the .NET SDK corresponds to the messages endpoint. The mapping between the API operations and corresponding methods are described below:
API operationSDK method
Send a messageSend
Get a messageGet
Delete a messageDelete
List messagesList
Update a message's metadataUpdate

Apps endpoint category

The Apps category of the .NET SDK corresponds to the apps endpoint. The mapping between the API operations and corresponding methods are described below:
API operationSDK method
List all apps for a given projectList
Create an appCreate
Get an appGet
Delete an appDelete
Update an appUpdate

Contacts endpoint category

The Contacts category of the .NET SDK corresponds to the contacts endpoint. The mapping between the API operations and corresponding methods are described below:
API operationSDK method
List contactsList or ListAuto
Create a contactCreate
Get a contactGet
Delete a contactDelete
Update a contactUpdate
Merge two contactsMerge
Get channel profileGetChannelProfile

Conversations endpoint category

The Conversations category of the .NET SDK corresponds to the conversations endpoint. The mapping between the API operations and corresponding methods are described below:
API operationSDK method
List conversationsList or ListAuto
Create a conversationCreate
Get a conversationGet
Delete a conversationDelete
Update a conversationUpdate
Stop conversationStop
Inject a messageInjectMessage
Inject an eventInjectEvent

Events endpoint category

The Events category of the .NET SDK corresponds to the events endpoint. The mapping between the API operations and corresponding methods are described below:
API operationSDK method
Send an eventSend
Get an eventGet
Delete an eventDelete
List eventsList or ListAuto

Transcoding endpoint category

The Transcoding category of the .NET SDK corresponds to the messages:transcode endpoint. The mapping between the API operations and corresponding methods are described below:
API operationSDK method
Transcode a messageTranscode

Capability endpoint category

The Capability category of the .NET SDK corresponds to the capability endpoint. The mapping between the API operations and corresponding methods are described below:
API operationSDK method
Capability lookupLookup

Webhooks endpoint category

The Webhooks category of the .NET SDK corresponds to the webhooks endpoint. The mapping between the API operations and corresponding methods are described below:
API operationSDK method
List webhooksList
Create a new webhookCreate
Get a webhookGet
Update an existing webhookUpdate
Delete an existing webhookDelete

TemplatesV2 endpoint category

The TemplatesV2 category of the .NET SDK corresponds to the Templates-V2 endpoint. The mapping between the API operations and corresponding methods are described below:
API operationSDK method
List all templates belonging to a project IDList
Creates a templateCreate
Lists translations for a templateListTranslations
Updates a templateUpdate
Get a templateGet
Delete a templateDelete

Request and query parameters

Requests and queries made using the .NET SDK are similar to those made using the Conversation API. Many of the fields are named and structured similarly. When translating field names from the Conversation API to the .NET SDK, remember that many of the API field names are in camelCase. In the .NET SDK, field names are in PascalCase. This pattern change manages almost all field name translations between the API and the SDK. For example:

SDKJSON
Copy
Copied
AppId = "YOUR_app_id"
Copy
Copied
"app_id": "{APP_ID}"
Note that the fields have the same name. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding .NET method. For example, consider this example in which the get method of the message class is invoked:
SDKJSON
Copy
Copied
var response = await sinch.Conversation.Messages.Get(
    messageId = "YOUR_message_id",
    messagesSource = "CONVERSATION_SOURCE"
    )
    
Copy
Copied
url = "https://us.conversation.api.sinch.com/v1/projects/" + project_id + "/messages/" + YOUR_message_id

payload = {
    "messages_source": "CONVERSATION_SOURCE"
}
When using the Conversation API, message_id would be included as a path parameter, and messages_source would be included as a query parameter in the JSON payload. With the .NET SDK, both parameters are included as arguments in the get method.

Responses

Response fields match the API responses. They are delivered as .NET objects.

We'd love to hear from you!
Rate this content:
Still have a question?
 
Ask the community.