Skip to content

Commit 5f1d351

Browse files
authored
Merge pull request #229959 from ddematheu2/url-shortener-tutorial
url shortener tutorial
2 parents 266f14c + a9c90a7 commit 5f1d351

File tree

4 files changed

+446
-0
lines changed

4 files changed

+446
-0
lines changed
Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,223 @@
1+
---
2+
title: include file
3+
description: include file
4+
author: ddematheu2
5+
manager: shahen
6+
services: azure-communication-services
7+
ms.author: dademath
8+
ms.date: 03/29/2023
9+
ms.topic: include
10+
ms.service: azure-communication-services
11+
---
12+
13+
## Sample code
14+
15+
You can find the completed code for this tutorial on [GitHub](https://github.com/Azure-Samples/communication-services-dotnet-quickstarts/tree/main/sms-url-shortener).
16+
17+
## Prerequisites
18+
19+
- An active Azure subscription. [Create an account for free](https://azure.microsoft.com/free/?ref=microsoft.com&utm_source=microsoft.com&utm_medium=docs&utm_campaign=visualstudio).
20+
- An active Azure Communication Services resource. For more information, see [Create an Azure Communication Services resource](../../quickstarts/create-communication-resource.md).
21+
- An Azure Communication Services phone number. [Get a phone number](../../quickstarts/telephony/get-phone-number.md). You need to [verify your phone number](../../quickstarts/sms/apply-for-toll-free-verification.md) so it can send messages with URLs.
22+
- Deployed [AzUrlShortener](https://github.com/microsoft/AzUrlShortener). Click [Deploy to Azure](https://github.com/microsoft/AzUrlShortener/wiki/How-to-deploy-your-AzUrlShortener) button for quick deploy.
23+
- [*Optional*] Deploy the [Admin web app](https://github.com/microsoft/AzUrlShortener/blob/main/src/Cloud5mins.ShortenerTools.TinyBlazorAdmin/README.md) to manage and monitor links in UI.
24+
- For this tutorial, SMS requests are routed to an Azure Function. You could always use an existing service, different framework like express or just run the tutorial as a C# console app. To follow this tutorial with an Azure Function, see instructions to set it up: [Azure Function for C#](https://learn.microsoft.com/azure/azure-functions/create-first-function-vs-code-csharp).
25+
26+
## Architecture overview
27+
28+
In this tutorial, the focus is to set up a middleware that orchestrates requests to send SMS and the shortening of URLs through the Azure URL Shortener service. It interacts with Azure Communication Services to complete the sending of the SMS.
29+
30+
![Diagram for architecture overview.](../media/url-shortener/url-shortener-architecture.png)
31+
32+
## Set up the Azure Function
33+
34+
To get started, you need to create a new Azure Function. You can create the Azure Function by following the steps in the [Azure Functions documentation](https://learn.microsoft.com/azure/azure-functions/create-first-function-vs-code-csharp). If you aren't using an Azure Function and instead are using a different framework, skip this step and continue to the next section.
35+
36+
Once the Azure Function is set up, go to the `local.settings.json` file and add three more values that you need to store: the Azure Communication Services connection string, phone number (Ex. +15555555555) and URL Shortener endpoint (Ex. `https://<Azure_Function_URL>/api/UrlCreate`). These variables are all values you generated from the prerequisites at the beginning of the document.
37+
38+
```json
39+
40+
{
41+
"IsEncrypted": false,
42+
"Values": {
43+
"AzureWebJobsStorage": "",
44+
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
45+
"ACS_CONNECTIONSTRING": "<ACS CONNECTION STRING>",
46+
"ACS_PHONE_NUMBER": "<ACS PHONE NUMBER>",
47+
"URL_SHORTENER": "<URL SHORTENER ENDPOINT>"
48+
}
49+
}
50+
51+
```
52+
53+
## Configure query parameters
54+
55+
Now that you've created the Azure Function, you need to configure the query parameters needed to trigger it. The function expects a phone number and a URL. The phone number is used as the recipient of the SMS message. The URL is the link that is shortened and sent to the recipient.
56+
57+
```csharp
58+
59+
namespace Company.Function
60+
{
61+
public static class SendSMSUrlShortener
62+
{
63+
[FunctionName("SendSMSUrlShortener")]
64+
public static async Task<IActionResult> Run(
65+
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
66+
ILogger log)
67+
{
68+
log.LogInformation("C# HTTP trigger function processed a request.");
69+
70+
string phoneNumberTo = req.Query["phoneNumber"]; // get phone number query parameter
71+
string urlToShorten = req.Query["url"]; // get url to shorten query parameter
72+
73+
return new OkObjectResult(null);
74+
}
75+
}
76+
}
77+
78+
```
79+
80+
## Shorten the URL
81+
82+
Now that you have the phone number and URL, you can use the Azure URL Shortener service to shorten the URL. Ensure you have [deployed](https://github.com/microsoft/AzUrlShortener/wiki/How-to-deploy-your-AzUrlShortener) this service already. The service contains several endpoints, but for this tutorial the focus is on the `UrlCreate` endpoint. Use the `PostAsync` method to place a `POST` request to the Azure URL Shortener service with the URL you want to shorten. The service returns a JSON object with the shortened URL. Store the shortened URL in a variable called `shortUrl`. In the snippet, insert the endpoint of your deployed Azure URL Shortener service. For information on how to to get the endpoint, see [Validate the deployment](https://github.com/microsoft/AzUrlShortener/wiki/How-to-deploy-your-AzUrlShortener#validate-the-deployment).
83+
84+
```csharp
85+
...
86+
using System.Net.Http;
87+
using System.Text.Json;
88+
using System.Text;
89+
90+
namespace Company.Function
91+
{
92+
public class ShortenedUrl
93+
{
94+
public string ShortUrl { get; set; }
95+
}
96+
97+
public static class SendSMSUrlShortener
98+
{
99+
static string urlShortener = Environment.GetEnvironmentVariable("URL_SHORTENER", EnvironmentVariableTarget.Process);
100+
101+
[FunctionName("SendSMSUrlShortener")]
102+
public static async Task<IActionResult> Run(
103+
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
104+
ILogger log)
105+
{
106+
log.LogInformation("C# HTTP trigger function processed a request.");
107+
108+
//Parse Query Parameters
109+
string phoneNumberTo = req.Query["phoneNumber"]; // get phone number query parameter
110+
string urlToShorten = req.Query["url"]; // get url to shorten query parameter
111+
112+
//Get short URL from Azure URL Shortener
113+
using var client = new HttpClient();
114+
var requestData = new
115+
{
116+
Url = urlToShorten //Body request for the POST call
117+
};
118+
var requestBody = JsonSerializer.Serialize(requestData);
119+
var httpContent = new StringContent(requestBody, Encoding.UTF8, "application/json");
120+
var response = await client.PostAsync(urlShortener, httpContent); // POST call to the Azure URL Shortener
121+
var content = await response.Content.ReadAsStringAsync();
122+
var data = System.Text.Json.JsonSerializer.Deserialize<ShortenedUrl>(content); // Parse content to ShortenedUrl object
123+
var url = data.ShortUrl;
124+
log.LogInformation("Shortened URL " + url);
125+
126+
return new OkObjectResult(null);
127+
}
128+
}
129+
}
130+
131+
```
132+
133+
## Send SMS
134+
135+
Now that the URL is shortened, you can use Azure Communication Services to send the SMS. Use the `send` method from the `SmsClient` class from the `Azure.Communication.Sms` package.
136+
137+
```bash
138+
139+
dotnet add package Azure.Communication.Sms
140+
141+
```
142+
143+
This method sends the SMS to the phone number provided in the query parameters. The SMS contains the shortened URL. For more information on how to send SMS, see [Send SMS](https://learn.microsoft.com/azure/communication-services/quickstarts/sms/send?pivots=programming-language-csharp).
144+
145+
```csharp
146+
...
147+
using Azure;
148+
using Azure.Communication;
149+
using Azure.Communication.Sms;
150+
151+
namespace Company.Function
152+
{
153+
// Class to deserialize URL Shortener response
154+
public class ShortenedUrl
155+
{
156+
public string ShortUrl { get; set; }
157+
}
158+
159+
public static class SendSMSUrlShortener
160+
{
161+
[FunctionName("SendSMSUrlShortener")]
162+
public static async Task<IActionResult> Run(
163+
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
164+
ILogger log)
165+
{
166+
log.LogInformation("C# HTTP trigger function processed a request.");
167+
168+
//Parse Query Parameters
169+
string phoneNumberTo = req.Query["phoneNumber"]; // get phone number query parameter
170+
string urlToShorten = req.Query["url"]; // get url to shorten query parameter
171+
172+
//Get short URL from Azure URL Shortener
173+
using var client = new HttpClient();
174+
var requestData = new
175+
{
176+
Url = urlToShorten //Body request for the POST call
177+
};
178+
var requestBody = JsonSerializer.Serialize(requestData);
179+
var httpContent = new StringContent(requestBody, Encoding.UTF8, "application/json");
180+
string urlShortener = Environment.GetEnvironmentVariable("URL_SHORTENER", EnvironmentVariableTarget.Process); // Ex. https://<Azure Function URL>/api/UrlCreate
181+
var response = await client.PostAsync(urlShortener, httpContent); // POST call to the Azure URL Shortener
182+
var content = await response.Content.ReadAsStringAsync();
183+
var data = System.Text.Json.JsonSerializer.Deserialize<ShortenedUrl>(content); // Parse content to ShortenedUrl object
184+
var url = data.ShortUrl;
185+
log.LogInformation("Shortened URL " + url);
186+
187+
//Send SMS with Azure Communication Services
188+
string connectionString = Environment.GetEnvironmentVariable("ACS_CONNECTIONSTRING", EnvironmentVariableTarget.Process);
189+
string phoneNumberFrom = Environment.GetEnvironmentVariable("ACS_PHONE_NUMBER", EnvironmentVariableTarget.Process); // Ex. +15555555555
190+
SmsClient smsClient = new SmsClient(connectionString);
191+
SmsSendResult sendResult = smsClient.Send(
192+
from: phoneNumberFrom,
193+
to: phoneNumberTo,
194+
message: "Here is your shortened URL: " + url
195+
); // Send SMS message with shortened URL
196+
197+
return new OkObjectResult(sendResult);
198+
}
199+
}
200+
}
201+
202+
```
203+
204+
## Test locally
205+
206+
>[!NOTE]
207+
> You need to [verify your phone number](../../quickstarts/sms/apply-for-toll-free-verification.md) to send SMS messages with URLs. Once your verification applications is set to pending state (1-2 days), the phone number to be enabled to send URLs. The full verification will take 5-6 weeks. For more information on toll-free number verification, see [Toll Free Veritifcation FAQ](../../concepts/sms/sms-faq.md#toll-free-verification).
208+
209+
You can now run your Azure Function locally by pressing `F5` in Visual Studio Code or by running the following command in the terminal:
210+
211+
```bash
212+
213+
func host start
214+
215+
```
216+
217+
Then using a tool like [Postman](https://www.postman.com/), you can test your function by making a `POST` request to the endpoint of your Azure Function. You need to provide the phone number and URL as query parameters. For example, if your Azure Function is running locally, you can make a request to `http://localhost:7071/api/<FUNCTION NAME>?phoneNumber=%2B15555555555&url=https://www.microsoft.com`. You should receive a response with the shortened URL and a status of `Success`.
218+
219+
## Deploy to Azure
220+
221+
To deploy your Azure Function, you can follow [step by step instructions](https://learn.microsoft.com/azure/azure-functions/create-first-function-vs-code-csharp?pivots=programming-language-dotnet#sign-in-to-azure).
222+
223+
Once deployed, you can access the function through a similar method as you did when testing locally. You need to provide the phone number and URL as query parameters. For example, if your Azure Function is deployed to Azure, you can make a request to `https://<YOUR AZURE FUNCTION NAME>.azurewebsites.net/api/<FUNCTION NAME>?phoneNumber=%2B15555555555&url=https://www.microsoft.com`. You should receive a response with the shortened URL and a status of `Success`.

0 commit comments

Comments
 (0)