Yandex Cloud
Search
Contact UsGet started
  • Blog
  • Pricing
  • Documentation
  • All Services
  • System Status
    • Featured
    • Infrastructure & Network
    • Data Platform
    • Containers
    • Developer tools
    • Serverless
    • Security
    • Monitoring & Resources
    • ML & AI
    • Business tools
  • All Solutions
    • By industry
    • By use case
    • Economics and Pricing
    • Security
    • Technical Support
    • Customer Stories
    • Start testing with double trial credits
    • Cloud credits to scale your IT product
    • Gateway to Russia
    • Cloud for Startups
    • Education and Science
    • Yandex Cloud Partner program
  • Blog
  • Pricing
  • Documentation
© 2025 Direct Cursus Technology L.L.C.
Yandex IoT Core
    • All tutorials
    • Working with Yandex IoT Core from an Android device in Java
    • Working with Yandex IoT Core in C#
    • Working with Yandex IoT Core in Java
    • Writing data from a device into a database
    • Status monitoring of geographically distributed devices
    • Monitoring sensor readings and event notifications
    • Testing message delivery
    • Emulating multiple IoT devices
  • Access management
  • Pricing policy
  • Terraform reference
  • Monitoring metrics
  • Audit Trails events
  • Release notes
  • FAQ

In this article:

  • Getting started
  • Create the required Yandex IoT Core resources
  • Create a registry and add a certificate to it
  • Create a device and add a certificate to it
  • Connect to Yandex IoT Core
  • Get authenticated in Yandex IoT Core
  • Authentication using certificates
  • Authenticating by username and password
  • Establish a connection
  • Subscribe to a topic and get messages
  • Send a message
  • Terminate the connection
  1. Tutorials
  2. Working with Yandex IoT Core in C#

Working with Yandex IoT Core in C#

Written by
Yandex Cloud
Updated at April 9, 2025
  • Getting started
  • Create the required Yandex IoT Core resources
    • Create a registry and add a certificate to it
    • Create a device and add a certificate to it
  • Connect to Yandex IoT Core
  • Get authenticated in Yandex IoT Core
    • Authentication using certificates
    • Authenticating by username and password
  • Establish a connection
  • Subscribe to a topic and get messages
  • Send a message
  • Terminate the connection

In this tutorial, you will learn how to connect to Yandex IoT Core using the Paho library written in C#. The tutorial assumes that you know how to develop apps on .NET in C#.

Note

For the source code discussed in the tutorial, visit GitHub. Interactions with Yandex IoT Core are encapsulated in the YaClient class that you can use in your projects.

Once connected, you can:

  • Send messages.
  • Subscribe a device or registry to receive messages.

To connect to Yandex IoT Core and start messaging:

  • Create the required Yandex IoT Core resources:
    • Create a registry and add a certificate to it.
    • Create a device and add a certificate to it.
  • Connect to Yandex IoT Core.
  • Authenticate in Yandex IoT Core:
    • Authentication using certificates.
    • Authentication by username and password.
  • Establish a connection.
  • Subscribe to a topic and receive messages.
  • Send a message.
  • Terminate the connection.

Getting started

  1. If you do not have the Yandex Cloud CLI yet, install and initialize it.
  2. Download and install a development environment for .Net, e.g., Microsoft Visual Studio.

Create the required Yandex IoT Core resources

Create a registry and add a certificate to it

If you already have a certificate, start with the second step.

  1. Create a certificate for the registry (skip this step if you already have a registry certificate):

    openssl req -x509 \
      -newkey rsa:4096 \
      -keyout registry-key.pem \
      -out registry-cert.pem \
      -nodes \
      -days 365 \
      -subj '/CN=localhost'
    
  2. Create a registry:

    yc iot registry create --name my-registry
    
  3. Add a certificate to the registry:

    yc iot registry certificate add \
      --registry-name my-registry \ # Registry name.
      --certificate-file registry-cert.pem # Path to the public part of the certificate.
    

Create a device and add a certificate to it

If you already have a certificate, start with the second step.

  1. (Optional) Create a certificate for the device:

    openssl req -x509 \
      -newkey rsa:4096 \
      -keyout device-key.pem \
      -out device-cert.pem \
      -nodes \
      -days 365 \
      -subj '/CN=localhost'
    
  2. Review a list of the registries where you can create a device or create a new registry.

  3. Create a device:

    yc iot device create --registry-name my-registry --name my-device
    
  4. Add a certificate to the device:

    yc iot device certificate add \
      --device-name my-device \ # Device name.
      --certificate-file device-cert.pem # Path to the public part of the certificate.
    

Connect to Yandex IoT Core

Before connecting, configure the connection parameters using the following code:

// Setting up a TLS connection
MqttClientOptionsBuilderTlsParameters tlsOptions = new MqttClientOptionsBuilderTlsParameters
{
  SslProtocol = SslProtocols.Tls12,
  UseTls = true
};

// Enabling the server validation event handler
tlsOptions.CertificateValidationCallback += CertificateValidationCallback;

// Setting up the connection parameters
var options = new MqttClientOptionsBuilder()
    .WithClientId($"Test_C#_Client_{Guid.NewGuid()}")
    .WithTcpServer(MqttServer, MqttPort)
    .WithTls(tlsOptions)
    .WithCleanSession()
    .WithCredentials(id, password)
    .WithKeepAlivePeriod(TimeSpan.FromSeconds(90))
    .WithKeepAliveSendInterval(TimeSpan.FromSeconds(60))
    .Build();

var factory = new MqttFactory();
IMqttClient mqttClient = factory.CreateMqttClient();

// Enabling the data receipt event handler
mqttClient.UseApplicationMessageReceivedHandler(DataHandler);

// Enabling the event handler for connections to Yandex IoT Core
mqttClient.UseConnectedHandler(ConnectedHandler);

// Enabling the event handler for losing connections to Yandex IoT Core
mqttClient.UseDisconnectedHandler(DisconnectedHandler);

Where:

  • MqttClientOptionsBuilderTlsParameters: Class that specifies the TLS usage parameters when connecting to Yandex IoT Core.
  • MqttClientOptionsBuilder: Constructor class that sets the connection options. You can use the default settings, but we recommend setting the WithKeepAlivePeriod and WithKeepAliveSendInterval parameters. The values of these parameters determine:
    • Rate of sending the PINGREQ commands.

    • Client response time to a broken connection.

      The lower the above parameters, the sooner the client will find out that the connection was terminated abnormally. However, this increases the frequency of billable PINGREQ commands.

Get authenticated in Yandex IoT Core

There are two authentication methods:

  • Using X.509 certificates.
  • Using a username and password.

Authentication using certificates

When authenticating with X.509 certificates, it is most convenient to use PKCS#12 certificates in PFX format. To generate a certificate in PKCS#12 format from PEM certificates, run the command:

openssl pkcs12 -export -out cert.pfx -inkey key.pem -in cert.pem

To load certificates in your project, use the following code:

X509Certificate2 certificate = new X509Certificate2(certPath);

The client certificate used for authentication on the server is specified when setting up a TLS connection:

X509Certificate2 certificate = new X509Certificate2(certPath);
List<byte[]> certificates = new List<byte[]>();
certificates.Add(certificate.Export(X509ContentType.SerializedCert));

// Setting up a TLS connection
MqttClientOptionsBuilderTlsParameters tlsOptions = new MqttClientOptionsBuilderTlsParameters
{
  Certificates = certificates,
  SslProtocol = SslProtocols.Tls12,
  UseTls = true
};

The certificate used for server authentication is used in the server validation event handler:

private static X509Certificate2 rootCrt = new X509Certificate2("rootCA.crt");

private static bool CertificateValidationCallback(X509Certificate cert, X509Chain chain, SslPolicyErrors errors, IMqttClientOptions opts)
{
  try
  {
    if (errors == SslPolicyErrors.None)
    {
      return true;
    }

    if (errors == SslPolicyErrors.RemoteCertificateChainErrors)
    {
      chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
      chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
      chain.ChainPolicy.ExtraStore.Add(rootCrt);

      chain.Build((X509Certificate2)rootCrt);
      // Comparing certificate thumbprints
      var res = chain.ChainElements.Cast<X509ChainElement>().Any(a => a.Certificate.Thumbprint == rootCrt.Thumbprint);
      return res;
    }
  }
  catch { }

  return false;
}

Authenticating by username and password

Authentication with a username and password in Yandex IoT Core requires the TLS protocol. To do this, use the MqttClientOptionsBuilderTlsParameters class:

// Setting up a TLS connection
MqttClientOptionsBuilderTlsParameters tlsOptions = new MqttClientOptionsBuilderTlsParameters
{
  SslProtocol = SslProtocols.Tls12,
  UseTls = true
};

// Enabling the server validation event handler
tlsOptions.CertificateValidationCallback += CertificateValidationCallback;

In the connection settings, use the WithCredentials method to specify the username (registry or device id) and password:

// Setting up the connection parameters
var options = new MqttClientOptionsBuilder()
    .WithClientId($"Test_C#_Client_{Guid.NewGuid()}")
    .WithTcpServer(MqttServer, MqttPort)
    .WithTls(tlsOptions)
    .WithCleanSession()
    .WithCredentials(id, password)
    .WithKeepAlivePeriod(TimeSpan.FromSeconds(90))
    .WithKeepAliveSendInterval(TimeSpan.FromSeconds(60))
    .Build();

Establish a connection

Establish a connection to Yandex IoT Core using the following code:

mqttClient.ConnectAsync(options, CancellationToken.None);

Subscribe to a topic and get messages

Use a callback function to receive messages:

...
  mqttClient.UseApplicationMessageReceivedHandler(DataHandler);
...

private Task DataHandler(MqttApplicationMessageReceivedEventArgs arg)
{
  return Task.CompletedTask;
}

Subscribe to a topic using the following code. In the SubscribeAsync method, specify the topic (topic) you want to subscribe to and the QoS level (qos).

mqttClient.SubscribeAsync(topic, qos);

Send a message

Send a message using the following code. In the PublishAsync method, specify the topic you want to send a message to, the message text, and the preferred quality of service level (qos).

mqttClient.PublishAsync(topic, "Your message text.", qos);

Handle connection loss events and track message delivery using callback functions:

...
  mqttClient.UseConnectedHandler(ConnectedHandler);
  mqttClient.UseDisconnectedHandler(DisconnectedHandler);
...

private Task ConnectedHandler(MqttClientConnectedEventArgs arg)
{
  return Task.CompletedTask;
}

private static Task DisconnectedHandler(MqttClientDisconnectedEventArgs arg)
{
  return Task.CompletedTask;
}

Terminate the connection

Disconnect from Yandex IoT Core using the following code:

mqttClient.DisconnectAsync();

Was the article helpful?

Previous
Working with Yandex IoT Core from an Android device in Java
Next
Working with Yandex IoT Core in Java
© 2025 Direct Cursus Technology L.L.C.