Skip to content

Commit 531151f

Browse files
authored
Merge pull request #280902 from memontic-ms/memontic/acs-download-media
Add download media quickstart
2 parents a917e57 + 602b7d8 commit 531151f

File tree

7 files changed

+544
-110
lines changed

7 files changed

+544
-110
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
title: Download WhatsApp message media
3+
titleSuffix: An Azure Communication Services Messages quickstart
4+
description: In this quickstart, you learn how to download the media received in a WhatsApp message with Azure Communication Services Messages.
5+
author: memontic-ms
6+
manager: camilo.ramirez
7+
services: azure-communication-services
8+
ms.author: memontic
9+
ms.date: 07/15/2024
10+
ms.topic: quickstart
11+
ms.service: azure-communication-services
12+
---
13+
14+
# Quickstart: Download WhatsApp message media
15+
16+
Azure Communication Services enables you to send and receive WhatsApp messages. In this quickstart, you learn how to download the media payload received in a WhatsApp message.
17+
18+
Use case: A business receives a WhatsApp message from their customer that contains an image. The business needs to download the image from WhatsApp in order to view the image.
19+
20+
[!INCLUDE [Download WhatsApp media messages with .NET](./includes/download-media/download-media-net.md)]
21+
22+
## Next steps
23+
24+
In this quickstart, you tried out the Advanced Messaging for WhatsApp SDK. Next you might also want to see the following articles:
25+
26+
- [Send WhatsApp Messages using Advanced Messages](../../../quickstarts/advanced-messaging/whatsapp/get-started.md)
27+
- [Handle Advanced Messaging Events](./handle-advanced-messaging-events.md)
28+
- [Send WhatsApp Template Messages](../../../concepts/advanced-messaging/whatsapp/template-messages.md)

articles/communication-services/quickstarts/advanced-messaging/whatsapp/get-started.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@ author: memontic-ms
66
manager: camilo.ramirez
77
services: azure-communication-services
88
ms.author: memontic
9-
ms.date: 02/29/2024
9+
ms.date: 07/15/2024
1010
ms.topic: quickstart
1111
ms.service: azure-communication-services
1212
ms.custom: devx-track-extended-java, devx-track-js, devx-track-python
1313
zone_pivot_groups: acs-js-csharp-java-python
1414
---
1515

16-
# Quickstart: Send WhatsApp Messages using Advanced Messages
16+
# Quickstart: Send WhatsApp messages using Advanced Messages
1717

1818
Azure Communication Services enables you to send and receive WhatsApp messages. In this quickstart, get started integrating your app with Azure Communication Advanced Messages SDK and start sending/receiving WhatsApp messages. Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.
1919

@@ -37,5 +37,5 @@ Azure Communication Services enables you to send and receive WhatsApp messages.
3737

3838
In this quickstart, you tried out the Advanced Messaging for WhatsApp SDK. Next you might also want to see the following articles:
3939

40-
- [Handle Advanced Messaging Events](./handle-advanced-messaging-events.md)
41-
- [Send WhatsApp Template Messages](../../../concepts/advanced-messaging/whatsapp/template-messages.md)
40+
- [Handle Advanced Messaging events](./handle-advanced-messaging-events.md)
41+
- [Send WhatsApp template messages](../../../concepts/advanced-messaging/whatsapp/template-messages.md)
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
---
2+
title: Include file
3+
description: Include file
4+
services: azure-communication-services
5+
author: memontic
6+
ms.service: azure-communication-services
7+
ms.date: 07/15/2024
8+
ms.topic: include
9+
ms.custom: include file
10+
ms.author: memontic
11+
---
12+
13+
#### [Connection String](#tab/connection-string)
14+
15+
For simplicity, this quickstart uses a connection string to authenticate. In production environments, we recommend using [service principals](../../../identity/service-principal.md).
16+
17+
Get the connection string from your Azure Communication Services resource in the Azure portal. On the left, navigate to the `Keys` tab. Copy the `Connection string` field for the primary key. The connection string is in the format `endpoint=https://{your Azure Communication Services resource name}.communication.azure.com/;accesskey={secret key}`.
18+
19+
:::image type="content" source="../media/get-started/get-communication-resource-connection-string.png" lightbox="../media/get-started/get-communication-resource-connection-string.png" alt-text="Screenshot that shows an Azure Communication Services resource in the Azure portal, viewing the 'Connection string' field in the 'Primary key' section.":::
20+
21+
Set the environment variable `COMMUNICATION_SERVICES_CONNECTION_STRING` to the value of your connection string.
22+
Open a console window and enter the following command:
23+
```console
24+
setx COMMUNICATION_SERVICES_CONNECTION_STRING "<your connection string>"
25+
```
26+
After you add the environment variable, you might need to restart any running programs that will need to read the environment variable, including the console window. For example, if you're using Visual Studio as your editor, restart Visual Studio before running the example.
27+
28+
For more information on how to set an environment variable for your system, follow the steps at [Store your connection string in an environment variable](../../../create-communication-resource.md#store-your-connection-string-in-an-environment-variable).
29+
30+
To instantiate a `NotificationMessagesClient`, add the following code to the `Main` method:
31+
```csharp
32+
// Retrieve connection string from environment variable
33+
string connectionString =
34+
Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
35+
36+
// Instantiate the client
37+
var notificationMessagesClient = new NotificationMessagesClient(connectionString);
38+
```
39+
40+
#### [Microsoft Entra ID](#tab/aad)
41+
42+
You can also authenticate with Microsoft Entra ID using the [Azure Identity library](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/identity/Azure.Identity).
43+
44+
The [`Azure.Identity`](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/identity/Azure.Identity) package provides various credential types that your application can use to authenticate. You can choose from the various options to authenticate the identity client detailed at [Azure Identity - Credential providers](/dotnet/api/overview/azure/identity-readme#credentials) and [Azure Identity - Authenticate the client](/dotnet/api/overview/azure/identity-readme#authenticate-the-client). This option walks through one way of using the [`DefaultAzureCredential`](/dotnet/api/overview/azure/identity-readme#defaultazurecredential).
45+
46+
The `DefaultAzureCredential` attempts to authenticate via [`several mechanisms`](/dotnet/api/overview/azure/identity-readme#defaultazurecredential) and might obtain its authentication credentials if you're signed into Visual Studio or Azure CLI. However, this option walks you through setting up with environment variables.
47+
48+
To create a `DefaultAzureCredential` object:
49+
1. To set up your service principle app, follow the instructions at [Creating a Microsoft Entra registered Application](../../../identity/service-principal.md?pivots=platform-azcli#creating-a-microsoft-entra-registered-application).
50+
51+
1. Set the environment variables `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, and `AZURE_TENANT_ID` using the output of your app's creation.
52+
Open a console window and enter the following commands:
53+
```console
54+
setx AZURE_CLIENT_ID "<your app's appId>"
55+
setx AZURE_CLIENT_SECRET "<your app's password>"
56+
setx AZURE_TENANT_ID "<your app's tenant>"
57+
```
58+
After you add the environment variables, you might need to restart any running programs that will need to read the environment variables, including the console window. For example, if you're using Visual Studio as your editor, restart Visual Studio before running the example.
59+
60+
1. To use the [`DefaultAzureCredential`](/dotnet/api/overview/azure/identity-readme#defaultazurecredential) provider, or other credential providers provided with the Azure SDK, install the `Azure.Identity` NuGet package and add the following `using` directive to your *Program.cs* file.
61+
```csharp
62+
using Azure.Identity;
63+
```
64+
65+
1. To instantiate a `NotificationMessagesClient`, add the following code to the `Main` method.
66+
```csharp
67+
// Configure authentication
68+
var endpoint = new Uri("https://<resource name>.communication.azure.com");
69+
var credential = new DefaultAzureCredential();
70+
71+
// Instantiate the client
72+
var notificationMessagesClient =
73+
new NotificationMessagesClient(endpoint, credential);
74+
```
75+
76+
#### [AzureKeyCredential](#tab/azurekeycredential)
77+
78+
You can also authenticate with an AzureKeyCredential.
79+
80+
Get the endpoint and key from your Azure Communication Services resource in the Azure portal. On the left, navigate to the `Keys` tab. Copy the `Endpoint` and the `Key` field for the primary key.
81+
82+
:::image type="content" source="../media/get-started/get-communication-resource-endpoint-and-key.png" lightbox="../media/get-started/get-communication-resource-endpoint-and-key.png" alt-text="Screenshot that shows an Azure Communication Services resource in the Azure portal, viewing the 'Connection string' field in the 'Primary key' section.":::
83+
84+
Set the environment variable `COMMUNICATION_SERVICES_KEY` to the value of your connection string.
85+
Open a console window and enter the following command:
86+
```console
87+
setx COMMUNICATION_SERVICES_KEY "<your key>"
88+
```
89+
After you add the environment variable, you might need to restart any running programs that will need to read the environment variable, including the console window. For example, if you're using Visual Studio as your editor, restart Visual Studio before running the example.
90+
91+
For more information on how to set an environment variable for your system, follow the steps at [Store your connection string in an environment variable](../../../create-communication-resource.md#store-your-connection-string-in-an-environment-variable).
92+
93+
To instantiate a `NotificationMessagesClient`, add the following code to the `Main` method:
94+
```csharp
95+
// Retrieve key from environment variable
96+
string key =
97+
Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_KEY");
98+
99+
// Configure authentication
100+
var endpoint = new Uri("https://<resource name>.communication.azure.com");
101+
var credential = new AzureKeyCredential(key);
102+
103+
// Instantiate the client
104+
var notificationMessagesClient =
105+
new NotificationMessagesClient(endpoint, credential);
106+
```
107+
108+
---
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
---
2+
title: Include file
3+
description: Include file
4+
services: azure-communication-services
5+
author: memontic-ms
6+
ms.service: azure-communication-services
7+
ms.subservice: messages
8+
ms.date: 07/15/2024
9+
ms.topic: include
10+
ms.custom: include file
11+
ms.author: memontic
12+
---
13+
14+
```csharp
15+
using System;
16+
using System.Collections.Generic;
17+
using System.IO;
18+
using System.Threading.Tasks;
19+
using Azure;
20+
using Azure.Communication.Messages;
21+
22+
namespace AdvancedMessagingDownloadMediaQuickstart
23+
{
24+
class Program
25+
{
26+
public static async Task Main(string[] args)
27+
{
28+
Console.WriteLine("Azure Communication Services - Download WhatsApp message media");
29+
30+
// Authenticate the client
31+
string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
32+
NotificationMessagesClient notificationMessagesClient =
33+
new NotificationMessagesClient(connectionString);
34+
35+
await DownloadMediaWithStreamAsync(notificationMessagesClient);
36+
await DownloadMediaToFileAsync(notificationMessagesClient);
37+
38+
Console.WriteLine("\n\nPress any key to exit.");
39+
Console.ReadKey();
40+
}
41+
42+
public static async Task DownloadMediaWithStreamAsync(NotificationMessagesClient notificationMessagesClient)
43+
{
44+
// MediaId GUID of the media received in an incoming message.
45+
// Ex. "00000000-0000-0000-0000-000000000000"
46+
var mediaId = "<MediaId>";
47+
48+
Response<Stream> fileResponse;
49+
try
50+
{
51+
// Download media to stream
52+
fileResponse = await notificationMessagesClient.DownloadMediaAsync(mediaId);
53+
54+
Console.WriteLine(fileResponse.ToString());
55+
}
56+
catch (RequestFailedException e)
57+
{
58+
Console.WriteLine(e);
59+
return;
60+
}
61+
62+
// File extension derived from the MIME type in the response headers.
63+
// Ex. A MIME type of "image/jpeg" would mean the fileExtension should be ".jpg"
64+
var contentType = fileResponse.GetRawResponse().Headers.ContentType;
65+
string fileExtension = GetFileExtension(contentType);
66+
67+
// File location to write the media.
68+
// Ex. @"c:\temp\media.jpg"
69+
string filePath = @"<FilePath>" + "<FileName>" + fileExtension;
70+
Console.WriteLine(filePath);
71+
72+
// Write the media stream to the file
73+
using (Stream outStream = File.OpenWrite(filePath))
74+
{
75+
fileResponse.Value.CopyTo(outStream);
76+
}
77+
}
78+
79+
private static string GetFileExtension(string contentType)
80+
{
81+
return MimeTypes.TryGetValue(contentType, out var extension) ? extension : string.Empty;
82+
}
83+
84+
private static readonly Dictionary<string, string> MimeTypes = new Dictionary<string, string>
85+
{
86+
{ "application/pdf", ".pdf" },
87+
{ "image/jpeg", ".jpg" },
88+
{ "image/png", ".png" },
89+
{ "video/mp4", ".mp4" },
90+
// Add more mappings as needed
91+
};
92+
93+
public static async Task DownloadMediaToFileAsync(NotificationMessagesClient notificationMessagesClient)
94+
{
95+
// MediaId GUID of the media received in an incoming message.
96+
// Ex. "00000000-0000-0000-0000-000000000000"
97+
var mediaId = "<MediaId>";
98+
99+
// File extension derived from the MIME type received in an incoming message
100+
// Ex. A MIME type of "image/jpeg" would mean the fileExtension should be ".jpg"
101+
string fileExtension = "<FileExtension>";
102+
103+
// File location to write the media.
104+
// Ex. @"c:\temp\media.jpg"
105+
string filePath = @"<FilePath>" + "<FileName>" + fileExtension;
106+
Console.WriteLine(filePath);
107+
108+
try
109+
{
110+
// Download media to file
111+
Response response = await notificationMessagesClient.DownloadMediaToAsync(mediaId, filePath);
112+
113+
Console.WriteLine(response.ToString());
114+
}
115+
catch (RequestFailedException e)
116+
{
117+
Console.WriteLine(e);
118+
return;
119+
}
120+
}
121+
}
122+
}
123+
```

0 commit comments

Comments
 (0)