azure-mgmt-applicationinsights-dotnet
microsoft/skills
Управляйте ресурсами Azure Application Insights, включая компоненты, веб-тесты, рабочие книги и ключи API, с помощью SDK для .NET.
...Расширить всеAzure.ResourceManager.ApplicationInsights (.NET)
SDK Azure Resource Manager для управления ресурсами Application Insights, предназначенными для мониторинга производительности приложений.
Установка
dotnet add package Azure.ResourceManager.ApplicationInsights
dotnet add package Azure.Identity
Текущая версия: v1.0.0 (GA)
Версия API: 2022-06-15
Переменные среды
AZURE_SUBSCRIPTION_ID= # Обязательно: идентификатор подписки Azure
AZURE_RESOURCE_GROUP= # Обязательно: имя группы ресурсов Azure
AZURE_APPINSIGHTS_NAME= # Обязательно: имя компонента Application Insights
AZURE_TOKEN_CREDENTIALS=prod # Требуется только в том случае, если в производственной среде используется DefaultAzureCredential
Аутентификация
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApplicationInsights;
// Локальная разработка: DefaultAzureCredential. Производственная среда: установите AZURE_TOKEN_CREDENTIALS=prod или AZURE_TOKEN_CREDENTIALS=
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Или используйте конкретные учетные данные напрямую в производственной среде:
// См. https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
ArmClient client = new ArmClient(credential);
Иерархия ресурсов
Подписка
└── Группа ресурсов
└── ApplicationInsightsComponent # Ресурс App Insights
├── ApplicationInsightsComponentApiKey # Ключи API для программного доступа
├── ComponentLinkedStorageAccount # Связанное хранилище для экспорта данных
└── (через ID компонента)
├── WebTest # Тесты доступности
├── Workbook # Рабочие книги для анализа
├── WorkbookTemplate # Шаблоны рабочих книг
└── MyWorkbook # Частные рабочие книги
Основные рабочие процессы
1. Создание компонента Application Insights (на основе рабочей области)
using Azure.ResourceManager.ApplicationInsights;
using Azure.ResourceManager.ApplicationInsights.Models;
ResourceGroupResource resourceGroup = await client
.GetDefaultSubscriptionAsync()
.Result
.GetResourceGroupAsync("my-resource-group");
ApplicationInsightsComponentCollection components = resourceGroup.GetApplicationInsightsComponents();
// Application Insights на основе рабочей области (рекомендуется)
ApplicationInsightsComponentData data = new ApplicationInsightsComponentData(
AzureLocation.EastUS,
ApplicationInsightsApplicationType.Web)
{
Kind = "web",
WorkspaceResourceId = new ResourceIdentifier(
"/subscriptions//resourceGroups//providers/Microsoft.OperationalInsights/workspaces/"),
IngestionMode = IngestionMode.LogAnalytics,
PublicNetworkAccessForIngestion = PublicNetworkAccessType.Enabled,
PublicNetworkAccessForQuery = PublicNetworkAccessType.Enabled,
RetentionInDays = 90,
SamplingPercentage = 100,
DisableIPMasking = false,
ImmediatePurgeDataOn30Days = false,
Tags =
{
{ "environment", "production" },
{ "application", "mywebapp" }
}
};
ArmOperation operation = await components
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", data);
ApplicationInsightsComponentResource component = operation.Value;
Console.WriteLine($"Компонент создан: {component.Data.Name}");
Console.WriteLine($"Ключ инструментации: {component.Data.InstrumentationKey}");
Console.WriteLine($"Строка подключения: {component.Data.ConnectionString}");
2. Получение строки подключения и ключей
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
// Получение строки подключения для настройки SDK
string connectionString = component.Data.ConnectionString;
string instrumentationKey = component.Data.InstrumentationKey;
string appId = component.Data.AppId;
Console.WriteLine($"Строка подключения: {connectionString}");
Console.WriteLine($"Ключ инструментации: {instrumentationKey}");
Console.WriteLine($"Идентификатор приложения: {appId}");
3. Создание ключа API
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
ApplicationInsightsComponentApiKeyCollection apiKeys = component.GetApplicationInsightsComponentApiKeys();
// Ключ API для чтения телеметрии
ApplicationInsightsApiKeyContent keyContent = new ApplicationInsightsApiKeyContent
{
Name = "ReadTelemetryKey",
LinkedReadProperties =
{
$"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{component.Data.Name}/api",
$"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{component.Data.Name}/agentconfig"
}
};
ApplicationInsightsComponentApiKeyResource apiKey = await apiKeys
.CreateOrUpdateAsync(WaitUntil.Completed, keyContent);
Console.WriteLine($"Имя ключа API: {apiKey.Data.Name}");
Console.WriteLine($"Ключ API: {apiKey.Data.ApiKey}"); // Отображается только один раз!
4. Создание веб-теста (тест доступности)
WebTestCollection webTests = resourceGroup.GetWebTests();
// Тест пинга URL-адреса
WebTestData urlPingTest = new WebTestData(AzureLocation.EastUS)
{
Kind = WebTestKind.Ping,
SyntheticMonitorId = "webtest-ping-myapp",
WebTestName = "Доступность главной страницы",
Description = "Проверяет, доступна ли главная страница",
IsEnabled = true,
Frequency = 300, // 5 минут
Timeout = 120, // 2 минуты
WebTestKind = WebTestKind.Ping,
IsRetryEnabled = true,
Locations =
{
new WebTestGeolocation { WebTestLocationId = "us-ca-sjc-azr" }, // Запад США
new WebTestGeolocation { WebTestLocationId = "us-tx-sn1-azr" }, // Юго-центральная часть США
new WebTestGeolocation { WebTestLocationId = "us-il-ch1-azr" }, // Северный центр США
new WebTestGeolocation { WebTestLocationId = "emea-gb-db3-azr" }, // Юг Великобритании
new WebTestGeolocation { WebTestLocationId = "apac-sg-sin-azr" } // Юго-Восточная Азия
},
Configuration = new WebTestConfiguration
{
WebTest = """
"""
},
Tags =
{
{ $"hidden-link:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/my-appinsights", "Resource" }
}
};
ArmOperation operation = await webTests
.CreateOrUpdateAsync(WaitUntil.Completed, "webtest-homepage", urlPingTest);
WebTestResource webTest = operation.Value;
Console.WriteLine($"Веб-тест создан: {webTest.Data.Name}");
5. Создание многоэтапного веб-теста
WebTestData multiStepTest = new WebTestData(AzureLocation.EastUS)
{
Kind = WebTestKind.MultiStep,
SyntheticMonitorId = "webtest-multistep-login",
WebTestName = "Тест процесса входа",
Description = "Тестирование функциональности входа",
IsEnabled = true,
Frequency = 900, // 15 минут
Timeout = 300, // 5 минут
WebTestKind = WebTestKind.MultiStep,
IsRetryEnabled = true,
Locations =
{
new WebTestGeolocation { WebTestLocationId = "us-ca-sjc-azr" }
},
Configuration = new WebTestConfiguration
{
WebTest = """
{"username":"testuser","password":"{{TestPassword}}"}
"""
},
Tags =
{
{ $"hidden-link:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/my-appinsights", "Resource" }
}
};
await webTests.CreateOrUpdateAsync(WaitUntil.Completed, "webtest-login-flow", multiStepTest);
6. Создание рабочей книги
WorkbookCollection workbooks = resourceGroup.GetWorkbooks();
WorkbookData workbookData = new WorkbookData(AzureLocation.EastUS)
{
DisplayName = "Панель мониторинга производительности приложения",
Category = "workbook",
Kind = WorkbookSharedTypeKind.Shared,
SerializedData = """
{
"version": "Notebook/1.0",
"items": [
{
"type": 1,
"content": {
"json": "# Производительность приложений\n\nЭта рабочая книга отображает показатели производительности приложений."
},
"name": "header"
},
{
"type": 3,
"content": {
"version": "KqlItem/1.0",
"query": "requests\n| summarize count() by bin(timestamp, 1h)\n| render timechart",
"size": 0,
"title": "Запросы в час",
"timeContext": {
"durationMs": 86400000
},
"queryType": 0,
"resourceType": "microsoft.insights/components"
},
"name": "requestsChart"
}
],
"isLocked": false
}
""",
SourceId = component.Id,
Tags =
{
{ "environment", "production" }
}
};
// Примечание: идентификатор рабочей книги должен быть новым GUID
string workbookId = Guid.NewGuid().ToString();
ArmOperation operation = await workbooks
.CreateOrUpdateAsync(WaitUntil.Completed, workbookId, workbookData);
WorkbookResource workbook = operation.Value;
Console.WriteLine($"Рабочая книга создана: {workbook.Data.DisplayName}");
7. Связь с учётной записью хранения
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
ComponentLinkedStorageAccountCollection linkedStorage = component.GetComponentLinkedStorageAccounts();
ComponentLinkedStorageAccountData storageData = new ComponentLinkedStorageAccountData
{
LinkedStorageAccount = new ResourceIdentifier(
"/subscriptions//resourceGroups//providers/Microsoft.Storage/storageAccounts/")
};
ArmOperation operation = await linkedStorage
.CreateOrUpdateAsync(WaitUntil.Completed, StorageType.ServiceProfiler, storageData);
8. Просмотр списка компонентов и управление ими
// Перечислить все компоненты Application Insights в группе ресурсов
await foreach (ApplicationInsightsComponentResource component in
resourceGroup.GetApplicationInsightsComponents())
{
Console.WriteLine($"Компонент: {component.Data.Name}");
Console.WriteLine($" ID приложения: {component.Data.AppId}");
Console.WriteLine($" Тип: {component.Data.ApplicationType}");
Console.WriteLine($" Режим сбора данных: {component.Data.IngestionMode}");
Console.WriteLine($" Срок хранения: {component.Data.RetentionInDays} дней");
}
// Список веб-тестов
await foreach (WebTestResource webTest in resourceGroup.GetWebTests())
{
Console.WriteLine($"Веб-тест: {webTest.Data.WebTestName}");
Console.WriteLine($" Включено: {webTest.Data.IsEnabled}");
Console.WriteLine($" Частота: {webTest.Data.Frequency}s");
}
// Список рабочих книг
await foreach (WorkbookResource workbook in resourceGroup.GetWorkbooks())
{
Console.WriteLine($"Рабочая книга: {workbook.Data.DisplayName}");
}
9. Обновление компонента
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
// Обновление с использованием полных данных (операция PUT)
ApplicationInsightsComponentData updateData = component.Data;
updateData.RetentionInDays = 180;
updateData.SamplingPercentage = 50;
updateData.Tags["updated"] = "true";
ArmOperation operation = await resourceGroup
.GetApplicationInsightsComponents()
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", updateData);
10. Удаление ресурсов
// Удаление компонента Application Insights
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
await component.DeleteAsync(WaitUntil.Completed);
// Удаление веб-теста
WebTestResource webTest = await resourceGroup.GetWebTestAsync("webtest-homepage");
await webTest.DeleteAsync(WaitUntil.Completed);
Справочник типов ключей
| Тип | Назначение |
|---|---|
ApplicationInsightsComponentResource |
Компонент App Insights |
ApplicationInsightsComponentData |
Настройки компонента |
Коллекция компонентов ApplicationInsights |
Коллекция компонентов |
ApplicationInsightsComponentApiKeyResource |
Ключ API для программного доступа |
WebTestResource |
Тест доступности/веб-тест |
WebTestData |
Конфигурация веб-теста |
WorkbookResource |
Рабочая книга анализа |
WorkbookData |
Настройка рабочей книги |
ComponentLinkedStorageAccountResource |
Связанное хранилище для экспорта |
Типы приложений
| Тип | Значение перечисления |
|---|---|
| Веб-приложение | Веб |
| Приложение для iOS | iOS |
| Java-приложение | Java |
| Приложение Node.js | Node.js |
| .NET-приложение | MRT |
| Другое | Другое |
Места проведения веб-тестирования
| Идентификатор местоположения | Регион |
|---|---|
us-ca-sjc-azr |
Запад США |
us-tx-sn1-azr |
Юго-центральная часть США |
us-il-ch1-azr |
Северный центр США |
us-va-ash-azr |
Восточная часть США |
emea-gb-db3-azr |
Юг Великобритании |
emea-nl-ams-azr |
Западная Европа |
emea-fr-pra-edge |
Центральная Франция |
apac-sg-sin-azr |
Юго-Восточная Азия |
apac-hk-hkn-azr |
Восточная Азия |
apac-jp-kaw-edge |
Восточная Япония |
latam-br-gru-edge |
Юг Бразилии |
emea-au-syd-edge |
Восточная Австралия |
Рекомендации
- Используйте подход на основе рабочей среды — App Insights на основе рабочей среды является текущим стандартом
- Связь с Log Analytics — храните данные в Log Analytics для более эффективного выполнения запросов
- Установите подходящий срок хранения — найдите баланс между затратами и доступностью данных
- Используйте выборку — сократите затраты для приложений с большим объемом данных
- Безопасное хранение строки подключения — используйте Key Vault или управляемую идентичность
- Включите несколько тестовых локаций — для точного мониторинга доступности
- Используйте рабочие книги — для создания настраиваемых панелей мониторинга и анализа
- Настройте оповещения — на основе тестов доступности и метрик
- Помечайте ресурсы тегами — для распределения затрат и организации
- Используйте частные конечные точки — для безопасного поступления данных
Обработка ошибок
с использованием Azure;
try
{
ArmOperation operation = await components
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", data);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
Console.WriteLine("Компонент уже существует");
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
Console.WriteLine($"Неверная конфигурация: {ex.Message}");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Ошибка Azure: {ex.Status} - {ex.Message}");
}
Интеграция SDK
Используйте строку подключения с SDK Application Insights:
// Program.cs в ASP.NET Core
builder.Services.AddApplicationInsightsTelemetry(options =>
{
options.ConnectionString = configuration["ApplicationInsights:ConnectionString"];
});
// Или задайте через переменную среды
// APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...;IngestionEndpoint=...
Связанные SDK
| SDK | Назначение | Установка |
|---|---|---|
Azure.ResourceManager.ApplicationInsights |
Управление ресурсами (этот SDK) | dotnet add package Azure.ResourceManager.ApplicationInsights |
Microsoft.ApplicationInsights |
SDK для телеметрии | dotnet add package Microsoft.ApplicationInsights |
Microsoft.ApplicationInsights.AspNetCore |
Интеграция с ASP.NET Core | dotnet add package Microsoft.ApplicationInsights.AspNetCore |
Azure.Monitor.OpenTelemetry.Exporter |
Экспорт OpenTelemetry | dotnet add package Azure.Monitor.OpenTelemetry.Exporter |
Ссылки
| Ресурс | URL |
|---|---|
| Пакет NuGet | https://www.nuget.org/packages/Azure.ResourceManager.ApplicationInsights |
| Справочник по API | https://learn.microsoft.com/dotnet/api/azure.resourcemanager.applicationinsights |
| Документация по продукту | https://learn.microsoft.com/azure/azure-monitor/app/app-insights-overview |
| Исходный код на GitHub | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/applicationinsights/Azure.ResourceManager.ApplicationInsights |
---
name: azure-mgmt-applicationinsights-dotnet
description: Manage Azure Application Insights resources including components, web tests, workbooks, and API keys using the .NET SDK.
license: MIT
---
# Azure.ResourceManager.ApplicationInsights (.NET)
Azure Resource Manager SDK for managing Application Insights resources for application performance monitoring.
## Installation
```bash
dotnet add package Azure.ResourceManager.ApplicationInsights
dotnet add package Azure.Identity
```
**Current Version**: v1.0.0 (GA)
**API Version**: 2022-06-15
## Environment Variables
```bash
AZURE_SUBSCRIPTION_ID=<your-subscription-id> # Required: Azure subscription ID
AZURE_RESOURCE_GROUP=<your-resource-group> # Required: Azure resource group name
AZURE_APPINSIGHTS_NAME=<your-appinsights-component> # Required: Application Insights component name
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication
```csharp
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApplicationInsights;
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
ArmClient client = new ArmClient(credential);
```
## Resource Hierarchy
```
Subscription
└── ResourceGroup
└── ApplicationInsightsComponent # App Insights resource
├── ApplicationInsightsComponentApiKey # API keys for programmatic access
├── ComponentLinkedStorageAccount # Linked storage for data export
└── (via component ID)
├── WebTest # Availability tests
├── Workbook # Workbooks for analysis
├── WorkbookTemplate # Workbook templates
└── MyWorkbook # Private workbooks
```
## Core Workflows
### 1. Create Application Insights Component (Workspace-based)
```csharp
using Azure.ResourceManager.ApplicationInsights;
using Azure.ResourceManager.ApplicationInsights.Models;
ResourceGroupResource resourceGroup = await client
.GetDefaultSubscriptionAsync()
.Result
.GetResourceGroupAsync("my-resource-group");
ApplicationInsightsComponentCollection components = resourceGroup.GetApplicationInsightsComponents();
// Workspace-based Application Insights (recommended)
ApplicationInsightsComponentData data = new ApplicationInsightsComponentData(
AzureLocation.EastUS,
ApplicationInsightsApplicationType.Web)
{
Kind = "web",
WorkspaceResourceId = new ResourceIdentifier(
"/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.OperationalInsights/workspaces/<workspace-name>"),
IngestionMode = IngestionMode.LogAnalytics,
PublicNetworkAccessForIngestion = PublicNetworkAccessType.Enabled,
PublicNetworkAccessForQuery = PublicNetworkAccessType.Enabled,
RetentionInDays = 90,
SamplingPercentage = 100,
DisableIPMasking = false,
ImmediatePurgeDataOn30Days = false,
Tags =
{
{ "environment", "production" },
{ "application", "mywebapp" }
}
};
ArmOperation<ApplicationInsightsComponentResource> operation = await components
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", data);
ApplicationInsightsComponentResource component = operation.Value;
Console.WriteLine($"Component created: {component.Data.Name}");
Console.WriteLine($"Instrumentation Key: {component.Data.InstrumentationKey}");
Console.WriteLine($"Connection String: {component.Data.ConnectionString}");
```
### 2. Get Connection String and Keys
```csharp
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
// Get connection string for SDK configuration
string connectionString = component.Data.ConnectionString;
string instrumentationKey = component.Data.InstrumentationKey;
string appId = component.Data.AppId;
Console.WriteLine($"Connection String: {connectionString}");
Console.WriteLine($"Instrumentation Key: {instrumentationKey}");
Console.WriteLine($"App ID: {appId}");
```
### 3. Create API Key
```csharp
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
ApplicationInsightsComponentApiKeyCollection apiKeys = component.GetApplicationInsightsComponentApiKeys();
// API key for reading telemetry
ApplicationInsightsApiKeyContent keyContent = new ApplicationInsightsApiKeyContent
{
Name = "ReadTelemetryKey",
LinkedReadProperties =
{
$"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{component.Data.Name}/api",
$"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{component.Data.Name}/agentconfig"
}
};
ApplicationInsightsComponentApiKeyResource apiKey = await apiKeys
.CreateOrUpdateAsync(WaitUntil.Completed, keyContent);
Console.WriteLine($"API Key Name: {apiKey.Data.Name}");
Console.WriteLine($"API Key: {apiKey.Data.ApiKey}"); // Only shown once!
```
### 4. Create Web Test (Availability Test)
```csharp
WebTestCollection webTests = resourceGroup.GetWebTests();
// URL Ping Test
WebTestData urlPingTest = new WebTestData(AzureLocation.EastUS)
{
Kind = WebTestKind.Ping,
SyntheticMonitorId = "webtest-ping-myapp",
WebTestName = "Homepage Availability",
Description = "Checks if homepage is available",
IsEnabled = true,
Frequency = 300, // 5 minutes
Timeout = 120, // 2 minutes
WebTestKind = WebTestKind.Ping,
IsRetryEnabled = true,
Locations =
{
new WebTestGeolocation { WebTestLocationId = "us-ca-sjc-azr" }, // West US
new WebTestGeolocation { WebTestLocationId = "us-tx-sn1-azr" }, // South Central US
new WebTestGeolocation { WebTestLocationId = "us-il-ch1-azr" }, // North Central US
new WebTestGeolocation { WebTestLocationId = "emea-gb-db3-azr" }, // UK South
new WebTestGeolocation { WebTestLocationId = "apac-sg-sin-azr" } // Southeast Asia
},
Configuration = new WebTestConfiguration
{
WebTest = """
<WebTest Name="Homepage" Enabled="True" Timeout="120"
xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Items>
<Request Method="GET" Version="1.1" Url="https://myapp.example.com"
ThinkTime="0" Timeout="120" ParseDependentRequests="False"
FollowRedirects="True" RecordResult="True" Cache="False"
ResponseTimeGoal="0" Encoding="utf-8" ExpectedHttpStatusCode="200" />
</Items>
</WebTest>
"""
},
Tags =
{
{ $"hidden-link:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/my-appinsights", "Resource" }
}
};
ArmOperation<WebTestResource> operation = await webTests
.CreateOrUpdateAsync(WaitUntil.Completed, "webtest-homepage", urlPingTest);
WebTestResource webTest = operation.Value;
Console.WriteLine($"Web test created: {webTest.Data.Name}");
```
### 5. Create Multi-Step Web Test
```csharp
WebTestData multiStepTest = new WebTestData(AzureLocation.EastUS)
{
Kind = WebTestKind.MultiStep,
SyntheticMonitorId = "webtest-multistep-login",
WebTestName = "Login Flow Test",
Description = "Tests login functionality",
IsEnabled = true,
Frequency = 900, // 15 minutes
Timeout = 300, // 5 minutes
WebTestKind = WebTestKind.MultiStep,
IsRetryEnabled = true,
Locations =
{
new WebTestGeolocation { WebTestLocationId = "us-ca-sjc-azr" }
},
Configuration = new WebTestConfiguration
{
WebTest = """
<WebTest Name="LoginFlow" Enabled="True" Timeout="300"
xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Items>
<Request Method="GET" Version="1.1" Url="https://myapp.example.com/login"
ThinkTime="0" Timeout="60" />
<Request Method="POST" Version="1.1" Url="https://myapp.example.com/api/auth"
ThinkTime="0" Timeout="60">
<Headers>
<Header Name="Content-Type" Value="application/json" />
</Headers>
<Body>{"username":"testuser","password":"{{TestPassword}}"}</Body>
</Request>
</Items>
</WebTest>
"""
},
Tags =
{
{ $"hidden-link:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/my-appinsights", "Resource" }
}
};
await webTests.CreateOrUpdateAsync(WaitUntil.Completed, "webtest-login-flow", multiStepTest);
```
### 6. Create Workbook
```csharp
WorkbookCollection workbooks = resourceGroup.GetWorkbooks();
WorkbookData workbookData = new WorkbookData(AzureLocation.EastUS)
{
DisplayName = "Application Performance Dashboard",
Category = "workbook",
Kind = WorkbookSharedTypeKind.Shared,
SerializedData = """
{
"version": "Notebook/1.0",
"items": [
{
"type": 1,
"content": {
"json": "# Application Performance\n\nThis workbook shows application performance metrics."
},
"name": "header"
},
{
"type": 3,
"content": {
"version": "KqlItem/1.0",
"query": "requests\n| summarize count() by bin(timestamp, 1h)\n| render timechart",
"size": 0,
"title": "Requests per Hour",
"timeContext": {
"durationMs": 86400000
},
"queryType": 0,
"resourceType": "microsoft.insights/components"
},
"name": "requestsChart"
}
],
"isLocked": false
}
""",
SourceId = component.Id,
Tags =
{
{ "environment", "production" }
}
};
// Note: Workbook ID should be a new GUID
string workbookId = Guid.NewGuid().ToString();
ArmOperation<WorkbookResource> operation = await workbooks
.CreateOrUpdateAsync(WaitUntil.Completed, workbookId, workbookData);
WorkbookResource workbook = operation.Value;
Console.WriteLine($"Workbook created: {workbook.Data.DisplayName}");
```
### 7. Link Storage Account
```csharp
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
ComponentLinkedStorageAccountCollection linkedStorage = component.GetComponentLinkedStorageAccounts();
ComponentLinkedStorageAccountData storageData = new ComponentLinkedStorageAccountData
{
LinkedStorageAccount = new ResourceIdentifier(
"/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<storage-account>")
};
ArmOperation<ComponentLinkedStorageAccountResource> operation = await linkedStorage
.CreateOrUpdateAsync(WaitUntil.Completed, StorageType.ServiceProfiler, storageData);
```
### 8. List and Manage Components
```csharp
// List all Application Insights components in resource group
await foreach (ApplicationInsightsComponentResource component in
resourceGroup.GetApplicationInsightsComponents())
{
Console.WriteLine($"Component: {component.Data.Name}");
Console.WriteLine($" App ID: {component.Data.AppId}");
Console.WriteLine($" Type: {component.Data.ApplicationType}");
Console.WriteLine($" Ingestion Mode: {component.Data.IngestionMode}");
Console.WriteLine($" Retention: {component.Data.RetentionInDays} days");
}
// List web tests
await foreach (WebTestResource webTest in resourceGroup.GetWebTests())
{
Console.WriteLine($"Web Test: {webTest.Data.WebTestName}");
Console.WriteLine($" Enabled: {webTest.Data.IsEnabled}");
Console.WriteLine($" Frequency: {webTest.Data.Frequency}s");
}
// List workbooks
await foreach (WorkbookResource workbook in resourceGroup.GetWorkbooks())
{
Console.WriteLine($"Workbook: {workbook.Data.DisplayName}");
}
```
### 9. Update Component
```csharp
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
// Update using full data (PUT operation)
ApplicationInsightsComponentData updateData = component.Data;
updateData.RetentionInDays = 180;
updateData.SamplingPercentage = 50;
updateData.Tags["updated"] = "true";
ArmOperation<ApplicationInsightsComponentResource> operation = await resourceGroup
.GetApplicationInsightsComponents()
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", updateData);
```
### 10. Delete Resources
```csharp
// Delete Application Insights component
ApplicationInsightsComponentResource component = await resourceGroup
.GetApplicationInsightsComponentAsync("my-appinsights");
await component.DeleteAsync(WaitUntil.Completed);
// Delete web test
WebTestResource webTest = await resourceGroup.GetWebTestAsync("webtest-homepage");
await webTest.DeleteAsync(WaitUntil.Completed);
```
## Key Types Reference
| Type | Purpose |
|------|---------|
| `ApplicationInsightsComponentResource` | App Insights component |
| `ApplicationInsightsComponentData` | Component configuration |
| `ApplicationInsightsComponentCollection` | Collection of components |
| `ApplicationInsightsComponentApiKeyResource` | API key for programmatic access |
| `WebTestResource` | Availability/web test |
| `WebTestData` | Web test configuration |
| `WorkbookResource` | Analysis workbook |
| `WorkbookData` | Workbook configuration |
| `ComponentLinkedStorageAccountResource` | Linked storage for exports |
## Application Types
| Type | Enum Value |
|------|------------|
| Web Application | `Web` |
| iOS Application | `iOS` |
| Java Application | `Java` |
| Node.js Application | `NodeJS` |
| .NET Application | `MRT` |
| Other | `Other` |
## Web Test Locations
| Location ID | Region |
|-------------|--------|
| `us-ca-sjc-azr` | West US |
| `us-tx-sn1-azr` | South Central US |
| `us-il-ch1-azr` | North Central US |
| `us-va-ash-azr` | East US |
| `emea-gb-db3-azr` | UK South |
| `emea-nl-ams-azr` | West Europe |
| `emea-fr-pra-edge` | France Central |
| `apac-sg-sin-azr` | Southeast Asia |
| `apac-hk-hkn-azr` | East Asia |
| `apac-jp-kaw-edge` | Japan East |
| `latam-br-gru-edge` | Brazil South |
| `emea-au-syd-edge` | Australia East |
## Best Practices
1. **Use workspace-based** — Workspace-based App Insights is the current standard
2. **Link to Log Analytics** — Store data in Log Analytics for better querying
3. **Set appropriate retention** — Balance cost vs. data availability
4. **Use sampling** — Reduce costs for high-volume applications
5. **Store connection string securely** — Use Key Vault or managed identity
6. **Enable multiple test locations** — For accurate availability monitoring
7. **Use workbooks** — For custom dashboards and analysis
8. **Set up alerts** — Based on availability tests and metrics
9. **Tag resources** — For cost allocation and organization
10. **Use private endpoints** — For secure data ingestion
## Error Handling
```csharp
using Azure;
try
{
ArmOperation<ApplicationInsightsComponentResource> operation = await components
.CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", data);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
Console.WriteLine("Component already exists");
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
Console.WriteLine($"Invalid configuration: {ex.Message}");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Azure error: {ex.Status} - {ex.Message}");
}
```
## SDK Integration
Use the connection string with Application Insights SDK:
```csharp
// Program.cs in ASP.NET Core
builder.Services.AddApplicationInsightsTelemetry(options =>
{
options.ConnectionString = configuration["ApplicationInsights:ConnectionString"];
});
// Or set via environment variable
// APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...;IngestionEndpoint=...
```
## Related SDKs
| SDK | Purpose | Install |
|-----|---------|---------|
| `Azure.ResourceManager.ApplicationInsights` | Resource management (this SDK) | `dotnet add package Azure.ResourceManager.ApplicationInsights` |
| `Microsoft.ApplicationInsights` | Telemetry SDK | `dotnet add package Microsoft.ApplicationInsights` |
| `Microsoft.ApplicationInsights.AspNetCore` | ASP.NET Core integration | `dotnet add package Microsoft.ApplicationInsights.AspNetCore` |
| `Azure.Monitor.OpenTelemetry.Exporter` | OpenTelemetry export | `dotnet add package Azure.Monitor.OpenTelemetry.Exporter` |
## Reference Links
| Resource | URL |
|----------|-----|
| NuGet Package | https://www.nuget.org/packages/Azure.ResourceManager.ApplicationInsights |
| API Reference | https://learn.microsoft.com/dotnet/api/azure.resourcemanager.applicationinsights |
| Product Documentation | https://learn.microsoft.com/azure/azure-monitor/app/app-insights-overview |
| GitHub Source | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/applicationinsights/Azure.ResourceManager.ApplicationInsights |
Все файлы
0 файловУстановить azure-mgmt-applicationinsights-dotnet
Скачайте файлы навыков и распакуйте их в каталог .claude/skills/.
Скачать ZIPКлонируйте репозиторий и скопируйте файлы навыка в свой проект.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-mgmt-applicationinsights-dotnet # Copy SKILL.md to your .claude/skills/ directory
Копировать





Дом
