

¡Se AWS SDK para .NET ha publicado la versión 4 (V4) del\$1

Para obtener información sobre los cambios más importantes y la migración de sus aplicaciones, consulte el [tema sobre migración](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html).

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

# Envío de notificaciones desde la nube mediante Amazon Simple Notification Service
<a name="sns-apis-intro"></a>

**nota**  
La información de este tema es específica de los proyectos basados en .NET Framework y en la AWS SDK para .NET versión 3.3 y anteriores.

 AWS SDK para .NET Es compatible con Amazon Simple Notification Service (Amazon SNS), que es un servicio web que permite a las aplicaciones, los usuarios finales y los dispositivos enviar notificaciones al instante desde la nube. Para obtener más información, consulte [Amazon SNS](https://aws.amazon.com/sns/).

## Enumeración de temas de Amazon SNS
<a name="sns-list-example"></a>

En el siguiente ejemplo se muestra cómo enumerar sus temas de Amazon SNS, las suscripciones a cada tema y los atributos de cada tema. En este ejemplo se usa el valor predeterminado [AmazonSimpleNotificationServiceClient](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SNS/TSNSClient.html).

```
// using Amazon.SimpleNotificationService;
// using Amazon.SimpleNotificationService.Model;

var client = new AmazonSimpleNotificationServiceClient();
var request = new ListTopicsRequest();
var response = new ListTopicsResponse();

do
{
  response = client.ListTopics(request);

  foreach (var topic in response.Topics)
  {
    Console.WriteLine("Topic: {0}", topic.TopicArn);

    var subs = client.ListSubscriptionsByTopic(
      new ListSubscriptionsByTopicRequest
      {
        TopicArn = topic.TopicArn
      });

    var ss = subs.Subscriptions;

    if (ss.Any())
    {
      Console.WriteLine("  Subscriptions:");

      foreach (var sub in ss)
      {
        Console.WriteLine("    {0}", sub.SubscriptionArn);
      }
    }

    var attrs = client.GetTopicAttributes(
      new GetTopicAttributesRequest
      {
        TopicArn = topic.TopicArn
      }).Attributes;

    if (attrs.Any())
    {
      Console.WriteLine("  Attributes:");

      foreach (var attr in attrs)
      {
        Console.WriteLine("    {0} = {1}", attr.Key, attr.Value);
      }
    }

    Console.WriteLine();
  }

  request.NextToken = response.NextToken;

} while (!string.IsNullOrEmpty(response.NextToken));
```

## Envío de un mensaje a un tema de Amazon SNS
<a name="sns-send-message-example"></a>

En el siguiente ejemplo se muestra cómo enviar un mensaje a un tema de Amazon SNS. El ejemplo toma un argumento, el ARN del tema de Amazon SNS.

```
using System;
using System.Linq;
using System.Threading.Tasks;

using Amazon;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

namespace SnsSendMessage
{
    class Program
    {
        static void Main(string[] args)
        {
            /* Topic ARNs must be in the correct format:
             *   arn:aws:sns:REGION:ACCOUNT_ID:NAME
             *
             *  where:
             *  REGION     is the region in which the topic is created, such as us-west-2
             *  ACCOUNT_ID is your (typically) 12-character account ID
             *  NAME       is the name of the topic
             */
            string topicArn = args[0];
            string message = "Hello at " + DateTime.Now.ToShortTimeString();

            var client = new AmazonSimpleNotificationServiceClient(region: Amazon.RegionEndpoint.USWest2);

            var request = new PublishRequest
            {
                Message = message,
                TopicArn = topicArn
            };

            try
            {
                var response = client.Publish(request);

                Console.WriteLine("Message sent to topic:");
                Console.WriteLine(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught exception publishing request:");
                Console.WriteLine(ex.Message);
            }
        }
    }
}
```

Consulte el [ejemplo completo](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/.dotnet/example_code_legacy/SNS/SnsSendMessage.cs), que incluye información sobre cómo compilar y ejecutar el ejemplo desde la línea de comandos, en adelante GitHub.

## Envío de un mensaje SMS a un número de teléfono
<a name="sns-send-sms-example"></a>

En el siguiente ejemplo se muestra cómo enviar un mensaje SMS a un número de teléfono. El ejemplo acepta un argumento, el número de teléfono, que debe estar en cualquiera de los dos formatos descritos en los comentarios.

```
using System;
using System.Linq;
using System.Threading.Tasks;
using Amazon;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

namespace SnsPublish
{
    class Program
    {
        static void Main(string[] args)
        {
            // US phone numbers must be in the correct format:
            // +1 (nnn) nnn-nnnn OR +1nnnnnnnnnn
            string number = args[0];
            string message = "Hello at " + DateTime.Now.ToShortTimeString();

            var client = new AmazonSimpleNotificationServiceClient(region: Amazon.RegionEndpoint.USWest2);
            var request = new PublishRequest
            {
                Message = message,
                PhoneNumber = number
            };

            try
            {
                var response = client.Publish(request);

                Console.WriteLine("Message sent to " + number + ":");
                Console.WriteLine(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught exception publishing request:");
                Console.WriteLine(ex.Message);
            }
        }
    }
}
```

Consulte el [ejemplo completo](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/.dotnet/example_code_legacy/SNS/SnsPublish.cs), que incluye información sobre cómo compilar y ejecutar el ejemplo desde la línea de comandos, en adelante GitHub.