Skip to content

Commit 9db63ae

Browse files
committed
Merge branch 'fxl---update-AMR-Entra-for-4-net-asp-quickstarts' of https://github.com/flang-msft/azure-docs-pr into fxl---update-AMR-Entra-for-4-net-asp-quickstarts
2 parents 01060be + 2e19037 commit 9db63ae

File tree

4 files changed

+109
-408
lines changed

4 files changed

+109
-408
lines changed

articles/azure-cache-for-redis/cache-dotnet-core-quickstart.md

Lines changed: 26 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -39,120 +39,56 @@ Clone the repo [https://github.com/Azure-Samples/azure-cache-redis-samples/tree/
3939

4040
::: zone-end
4141

42-
## [Microsoft Entra ID Authentication (recommended)](#tab/entraid)
42+
## Microsoft Entra ID Authentication (recommended)
4343

4444
[!INCLUDE [cache-entra-access](includes/cache-entra-access.md)]
4545

46-
## [Access Key Authentication](#tab/accesskey)
46+
<!-- ## [Access Key Authentication](#tab/accesskey) -->
4747

4848
[!INCLUDE [redis-access-key-alert](includes/redis-access-key-alert.md)]
4949

50-
[!INCLUDE [redis-cache-passwordless](includes/redis-cache-passwordless.md)]
50+
<!-- [!INCLUDE [redis-cache-passwordless](includes/redis-cache-passwordless.md)] -->
5151

52-
## Add a local secret for the connection string
52+
### Install the Library for using Entra ID Authentication
53+
The [Azure.StackExchange.Redis](https://www.nuget.org/packages/Microsoft.Azure.StackExchangeRedis) library contains the Microsoft Entra ID authentication method for connecting to Azure Redis services using Entra ID. It is applicable to all Azure Cache for Redis, Azure Cache for Redis Enterprise, and Azure Managed Redis (Preview).
5354

54-
In your _appsettings.json_ file, add the following:
55-
56-
```json
57-
{
58-
"RedisHostName": "your_Azure_Redis_hostname"
59-
}
55+
```cli
56+
dotnet add package Microsoft.Azure.StackExchangeRedis
6057
```
6158

62-
1. Replace `"your_Azure_Redis_hostname"` with your Azure Redis host name and port numbers. For example: `cache-name.region.redis.azure.net:10000` for Azure Managed Redis (preview), and `cache-name.redis.cache.windows.net:6380` for Azure Cache for Redis services.
63-
64-
1. Save the file.
65-
6659
---
6760

68-
## Connect to the cache with RedisConnection
69-
70-
In `RedisConnection.cs`, you see the `StackExchange.Redis` namespace has been added to the code. This is needed for the `RedisConnection` class.
71-
72-
```csharp
73-
using StackExchange.Redis;
61+
## Connect to the cache using Entra ID
7462

63+
1. Include the libraries in your code
64+
65+
```
66+
using Azure.Identity;
67+
using StackExchange.Redis
7568
```
7669

77-
The `RedisConnection` code ensures that there is always a healthy connection to the cache by managing the `ConnectionMultiplexer` instance from `StackExchange.Redis`. The `RedisConnection` class recreates the connection when a connection is lost and unable to reconnect automatically.
78-
79-
For more information, see [StackExchange.Redis](https://stackexchange.github.io/StackExchange.Redis/) and the code in a [GitHub repo](https://github.com/StackExchange/StackExchange.Redis).
80-
81-
<!-- :::code language="csharp" source="~/samples-cache/quickstart/dotnet-core/RedisConnection.cs"::: -->
82-
83-
## Executing cache commands
84-
85-
In `program.cs`, you can see the following code for the `RunRedisCommandsAsync` method in the `Program` class for the console application:
86-
70+
1. Using the default Azure credentials to authenticate the client connection. This enables your code to use the signed-in user credential when running locally, and an Azure managed identity when running in Azure without code change.
71+
8772
```csharp
88-
private static async Task RunRedisCommandsAsync(string prefix)
89-
{
90-
// Simple PING command
91-
Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: PING");
92-
RedisResult pingResult = await _redisConnection.BasicRetryAsync(async (db) => await db.ExecuteAsync("PING"));
93-
Console.WriteLine($"{prefix}: Cache response: {pingResult}");
94-
95-
// Simple get and put of integral data types into the cache
96-
string key = "Message";
97-
string value = "Hello! The cache is working from a .NET console app!";
98-
99-
Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: GET {key} via StringGetAsync()");
100-
RedisValue getMessageResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringGetAsync(key));
101-
Console.WriteLine($"{prefix}: Cache response: {getMessageResult}");
102-
103-
Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: SET {key} \"{value}\" via StringSetAsync()");
104-
bool stringSetResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringSetAsync(key, value));
105-
Console.WriteLine($"{prefix}: Cache response: {stringSetResult}");
106-
107-
Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: GET {key} via StringGetAsync()");
108-
getMessageResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringGetAsync(key));
109-
Console.WriteLine($"{prefix}: Cache response: {getMessageResult}");
110-
111-
// Store serialized object to cache
112-
Employee e007 = new Employee("007", "Davide Columbo", 100);
113-
stringSetResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringSetAsync("e007", JsonSerializer.Serialize(e007)));
114-
Console.WriteLine($"{Environment.NewLine}{prefix}: Cache response from storing serialized Employee object: {stringSetResult}");
115-
116-
// Retrieve serialized object from cache
117-
getMessageResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringGetAsync("e007"));
118-
Employee e007FromCache = JsonSerializer.Deserialize<Employee>(getMessageResult);
119-
Console.WriteLine($"{prefix}: Deserialized Employee .NET object:{Environment.NewLine}");
120-
Console.WriteLine($"{prefix}: Employee.Name : {e007FromCache.Name}");
121-
Console.WriteLine($"{prefix}: Employee.Id : {e007FromCache.Id}");
122-
Console.WriteLine($"{prefix}: Employee.Age : {e007FromCache.Age}{Environment.NewLine}");
123-
}
124-
73+
var configurationOptions = await ConfigurationOptions.Parse($"{_redisHostName}").ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
74+
ConnectionMultiplexer _newConnection = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
75+
IDatabase Database = _newConnection.GetDatabase();
12576
```
12677

127-
Cache items can be stored and retrieved by using the `StringSetAsync` and `StringGetAsync` methods.
78+
### To edit the *appsettings.json* file
12879

129-
In the example, you can see the `Message` key is set to value. The app updated that cached value. The app also executed the `PING` and command.
80+
1. Edit the *Web.config* file. Then add the following content:
13081

131-
### Work with .NET objects in the cache
82+
```json
83+
"_redisHostName":"<cache-hostname>"
84+
```
13285

133-
The Redis server stores most data as strings, but these strings can contain many types of data, including serialized binary data, which can be used when storing .NET objects in the cache.
86+
1. Replace `<cache-hostname>` with your cache host name as it appears in the Overview blade of Azure Portal. For example, *my-redis.eastus.azure.net:10000*
13487

135-
Azure Cache for Redis can cache both .NET objects and primitive data types, but before a .NET object can be cached it must be serialized.
136-
137-
This .NET object serialization is the responsibility of the application developer, and gives the developer flexibility in the choice of the serializer.
88+
1. Save the file.
13889

139-
The following `Employee` class was defined in _Program.cs_ so that the sample could also show how to get and set a serialized object:
90+
For more information, see [StackExchange.Redis](https://stackexchange.github.io/StackExchange.Redis/) and the code in a [GitHub repo](https://github.com/StackExchange/StackExchange.Redis).
14091

141-
```csharp
142-
class Employee
143-
{
144-
public string Id { get; set; }
145-
public string Name { get; set; }
146-
public int Age { get; set; }
147-
148-
public Employee(string id, string name, int age)
149-
{
150-
Id = id;
151-
Name = name;
152-
Age = age;
153-
}
154-
}
155-
```
15692

15793
## Run the sample
15894

articles/azure-cache-for-redis/cache-dotnet-how-to-use-azure-redis-cache.md

Lines changed: 29 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -40,153 +40,60 @@ Clone the repo from [Azure-Samples/azure-cache-redis-samples](https://github.com
4040

4141
::: zone-end
4242

43-
## [Microsoft Entra ID Authentication (recommended)](#tab/entraid)
43+
## Microsoft Entra ID Authentication (recommended)
4444

4545
[!INCLUDE [cache-entra-access](includes/cache-entra-access.md)]
4646

47-
## [Access Key Authentication](#tab/accesskey)
47+
<!-- ## [Access Key Authentication](#tab/accesskey) -->
4848

4949
[!INCLUDE [redis-access-key-alert](includes/redis-access-key-alert.md)]
5050

51-
[!INCLUDE [redis-cache-passwordless](includes/redis-cache-passwordless.md)]
51+
<!-- [!INCLUDE [redis-cache-passwordless](includes/redis-cache-passwordless.md)] -->
5252

53-
1. Edit the *App.config* file and add the following contents:
53+
### Install the Library for using Entra ID Authentication
54+
The [Azure.StackExchange.Redis](https://www.nuget.org/packages/Microsoft.Azure.StackExchangeRedis) library contains the Microsoft Entra ID authentication method for connecting to Azure Redis services using Entra ID. It is applicable to all Azure Cache for Redis, Azure Cache for Redis Enterprise, and Azure Managed Redis (Preview).
5455

55-
```xml
56-
<appSettings>
57-
<add key="RedisHostName" value="your_redis_cache_hostname"/>
58-
</appSettings>
59-
60-
```
61-
62-
1. Replace `"your_Azure_Redis_hostname"` with your Azure Redis host name and port numbers. For example: `cache-name.eastus.redis.azure.net:10000` for Azure Cache for Redis Enterprise, and `cache-name.redis.cache.windows.net:6380` for Azure Cache for Redis services.
63-
64-
1. Save the file.
56+
```cli
57+
dotnet add package Microsoft.Azure.StackExchangeRedis
58+
```
6559

6660
----
6761

68-
## Configure the cache client
69-
70-
In this section, you prepare the console application to use the [StackExchange.Redis](https://github.com/StackExchange/StackExchange.Redis) client for .NET.
71-
72-
1. In Visual Studio, select **Tools** > **NuGet Package Manager** > **Package Manager Console**, and run the following command from the Package Manager Console window.
62+
### Connect to the cache using Entra ID
7363

74-
```powershell
75-
Install-Package Microsoft.Azure.StackExchangeRedis
76-
```
77-
78-
1. Once the installation is completed, the *StackExchange.Redis* cache client is available to use with your project.
79-
80-
## Connect to the cache with RedisConnection
81-
82-
The connection to your cache is managed by the `RedisConnection` class. The connection is first made in this statement from `Program.cs`:
83-
84-
```csharp
85-
_redisConnection = await RedisConnection.InitializeAsync(redisHostName: ConfigurationManager.AppSettings["RedisHostName"].ToString());
64+
1. Include the libraries in your code
65+
8666
```
87-
88-
The value of the *CacheConnection* appSetting is used to reference the cache connection string from the Azure portal as the password parameter.
89-
90-
In `RedisConnection.cs`, you see the `StackExchange.Redis` namespace with the `using` keyword. This is needed for the `RedisConnection` class.
91-
92-
```csharp
93-
using StackExchange.Redis;
67+
using Azure.Identity;
68+
using StackExchange.Redis
9469
```
9570

96-
The `RedisConnection` code ensures that there is always a healthy connection to the cache by managing the `ConnectionMultiplexer` instance from `StackExchange.Redis`. The `RedisConnection` class recreates the connection when a connection is lost and unable to reconnect automatically.
97-
98-
For more information, see [StackExchange.Redis](https://stackexchange.github.io/StackExchange.Redis/) and the code in a [GitHub repo](https://github.com/StackExchange/StackExchange.Redis).
99-
100-
<!-- :::code language="csharp" source="~/samples-cache/quickstart/dotnet/Redistest/RedisConnection.cs"::: -->
101-
102-
## Executing cache commands
103-
104-
In `program.cs`, you can see the following code for the `RunRedisCommandsAsync` method in the `Program` class for the console application:
105-
71+
1. Using the default Azure credentials to authenticate the client connection. This enables your code to use the signed-in user credential when running locally, and an Azure managed identity when running in Azure without code change.
72+
10673
```csharp
107-
private static async Task RunRedisCommandsAsync(string prefix)
108-
{
109-
// Simple PING command
110-
Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: PING");
111-
RedisResult pingResult = await _redisConnection.BasicRetryAsync(async (db) => await db.ExecuteAsync("PING"));
112-
Console.WriteLine($"{prefix}: Cache response: {pingResult}");
113-
114-
// Simple get and put of integral data types into the cache
115-
string key = "Message";
116-
string value = "Hello! The cache is working from a .NET console app!";
117-
118-
Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: GET {key} via StringGetAsync()");
119-
RedisValue getMessageResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringGetAsync(key));
120-
Console.WriteLine($"{prefix}: Cache response: {getMessageResult}");
121-
122-
Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: SET {key} \"{value}\" via StringSetAsync()");
123-
bool stringSetResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringSetAsync(key, value));
124-
Console.WriteLine($"{prefix}: Cache response: {stringSetResult}");
125-
126-
Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: GET {key} via StringGetAsync()");
127-
getMessageResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringGetAsync(key));
128-
Console.WriteLine($"{prefix}: Cache response: {getMessageResult}");
129-
130-
// Store serialized object to cache
131-
Employee e007 = new Employee("007", "Davide Columbo", 100);
132-
stringSetResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringSetAsync("e007", JsonSerializer.Serialize(e007)));
133-
Console.WriteLine($"{Environment.NewLine}{prefix}: Cache response from storing serialized Employee object: {stringSetResult}");
134-
135-
// Retrieve serialized object from cache
136-
getMessageResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringGetAsync("e007"));
137-
Employee e007FromCache = JsonSerializer.Deserialize<Employee>(getMessageResult);
138-
Console.WriteLine($"{prefix}: Deserialized Employee .NET object:{Environment.NewLine}");
139-
Console.WriteLine($"{prefix}: Employee.Name : {e007FromCache.Name}");
140-
Console.WriteLine($"{prefix}: Employee.Id : {e007FromCache.Id}");
141-
Console.WriteLine($"{prefix}: Employee.Age : {e007FromCache.Age}{Environment.NewLine}");
142-
}
143-
144-
74+
var configurationOptions = await ConfigurationOptions.Parse($"{_redisHostName}").ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
75+
ConnectionMultiplexer _newConnection = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
76+
IDatabase Database = _newConnection.GetDatabase();
14577
```
14678

147-
Cache items can be stored and retrieved by using the `StringSetAsync` and `StringGetAsync` methods.
148-
149-
In the example, you can see the `Message` key is set to value. The app updated that cached value. The app also executed the `PING` and command.
150-
151-
### Work with .NET objects in the cache
152-
153-
The Redis server stores most data as strings, but these strings can contain many types of data, including serialized binary data, which can be used when storing .NET objects in the cache.
154-
155-
Azure Cache for Redis can cache both .NET objects and primitive data types, but before a .NET object can be cached it must be serialized.
79+
### To edit the *CacheSecrets.config* file
15680

157-
This .NET object serialization is the responsibility of the application developer, and gives the developer flexibility in the choice of the serializer.
81+
1. Create a file on your computer named *CacheSecrets.config*. Put it in a location where it won't be checked in with the source code of your sample application. For this quickstart, the *CacheSecrets.config* file is located at *C:\AppSecrets\CacheSecrets.config*.
15882

159-
One simple way to serialize objects is to use the `JsonConvert` serialization methods in `System.text.Json`.
83+
1. Edit the *app.config* file. Then add the following content:
16084

161-
Add the `System.text.Json` namespace to Visual Studio:
162-
163-
1. Select **Tools** > **NuGet Package Manager** > **Package Manager Console**.
164-
165-
1. Then, run the following command from the Package Manager Console window.
166-
167-
```powershell
168-
Install-Package system.text.json
85+
```xml
86+
<appSettings>
87+
<add key="RedisHostName" value="<cache-hostname-with-portnumber>"/>
88+
</appSettings>
16989
```
17090

171-
<!-- :::image type="content" source="media/cache-dotnet-how-to-use-azure-redis-cache/cache-console-app-partial.png" alt-text="Screenshot that shows console app."::: -->
91+
1. Replace `<cache-hostname>` with your cache host name as it appears in the Overview blade of Azure Portal. For example, *my-redis.eastus.azure.net:10000*
17292

173-
The following `Employee` class was defined in *Program.cs* so that the sample could also show how to get and set a serialized object:
93+
1. Save the file.
94+
95+
For more information, see [StackExchange.Redis](https://stackexchange.github.io/StackExchange.Redis/) and the code in a [GitHub repo](https://github.com/StackExchange/StackExchange.Redis).
17496

175-
```csharp
176-
class Employee
177-
{
178-
public string Id { get; set; }
179-
public string Name { get; set; }
180-
public int Age { get; set; }
181-
182-
public Employee(string employeeId, string name, int age)
183-
{
184-
Id = employeeId;
185-
Name = name;
186-
Age = age;
187-
}
188-
}
189-
```
19097

19198
## Run the sample
19299

0 commit comments

Comments
 (0)