|
Add this skill
npx mdskills install sickn33/azure-mgmt-applicationinsights-dotnetComprehensive Azure SDK reference with rich examples but lacks agent-specific triggers and decision logic
1---2name: azure-mgmt-applicationinsights-dotnet3description: |4 Azure Application Insights SDK for .NET. Application performance monitoring and observability resource management. Use for creating Application Insights components, web tests, workbooks, analytics items, and API keys. Triggers: "Application Insights", "ApplicationInsights", "App Insights", "APM", "application monitoring", "web tests", "availability tests", "workbooks".5package: Azure.ResourceManager.ApplicationInsights6---78# Azure.ResourceManager.ApplicationInsights (.NET)910Azure Resource Manager SDK for managing Application Insights resources for application performance monitoring.1112## Installation1314```bash15dotnet add package Azure.ResourceManager.ApplicationInsights16dotnet add package Azure.Identity17```1819**Current Version**: v1.0.0 (GA)20**API Version**: 2022-06-152122## Environment Variables2324```bash25AZURE_SUBSCRIPTION_ID=<your-subscription-id>26AZURE_RESOURCE_GROUP=<your-resource-group>27AZURE_APPINSIGHTS_NAME=<your-appinsights-component>28```2930## Authentication3132```csharp33using Azure.Identity;34using Azure.ResourceManager;35using Azure.ResourceManager.ApplicationInsights;3637ArmClient client = new ArmClient(new DefaultAzureCredential());38```3940## Resource Hierarchy4142```43Subscription44└── ResourceGroup45 └── ApplicationInsightsComponent # App Insights resource46 ├── ApplicationInsightsComponentApiKey # API keys for programmatic access47 ├── ComponentLinkedStorageAccount # Linked storage for data export48 └── (via component ID)49 ├── WebTest # Availability tests50 ├── Workbook # Workbooks for analysis51 ├── WorkbookTemplate # Workbook templates52 └── MyWorkbook # Private workbooks53```5455## Core Workflows5657### 1. Create Application Insights Component (Workspace-based)5859```csharp60using Azure.ResourceManager.ApplicationInsights;61using Azure.ResourceManager.ApplicationInsights.Models;6263ResourceGroupResource resourceGroup = await client64 .GetDefaultSubscriptionAsync()65 .Result66 .GetResourceGroupAsync("my-resource-group");6768ApplicationInsightsComponentCollection components = resourceGroup.GetApplicationInsightsComponents();6970// Workspace-based Application Insights (recommended)71ApplicationInsightsComponentData data = new ApplicationInsightsComponentData(72 AzureLocation.EastUS,73 ApplicationInsightsApplicationType.Web)74{75 Kind = "web",76 WorkspaceResourceId = new ResourceIdentifier(77 "/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.OperationalInsights/workspaces/<workspace-name>"),78 IngestionMode = IngestionMode.LogAnalytics,79 PublicNetworkAccessForIngestion = PublicNetworkAccessType.Enabled,80 PublicNetworkAccessForQuery = PublicNetworkAccessType.Enabled,81 RetentionInDays = 90,82 SamplingPercentage = 100,83 DisableIPMasking = false,84 ImmediatePurgeDataOn30Days = false,85 Tags =86 {87 { "environment", "production" },88 { "application", "mywebapp" }89 }90};9192ArmOperation<ApplicationInsightsComponentResource> operation = await components93 .CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", data);9495ApplicationInsightsComponentResource component = operation.Value;9697Console.WriteLine($"Component created: {component.Data.Name}");98Console.WriteLine($"Instrumentation Key: {component.Data.InstrumentationKey}");99Console.WriteLine($"Connection String: {component.Data.ConnectionString}");100```101102### 2. Get Connection String and Keys103104```csharp105ApplicationInsightsComponentResource component = await resourceGroup106 .GetApplicationInsightsComponentAsync("my-appinsights");107108// Get connection string for SDK configuration109string connectionString = component.Data.ConnectionString;110string instrumentationKey = component.Data.InstrumentationKey;111string appId = component.Data.AppId;112113Console.WriteLine($"Connection String: {connectionString}");114Console.WriteLine($"Instrumentation Key: {instrumentationKey}");115Console.WriteLine($"App ID: {appId}");116```117118### 3. Create API Key119120```csharp121ApplicationInsightsComponentResource component = await resourceGroup122 .GetApplicationInsightsComponentAsync("my-appinsights");123124ApplicationInsightsComponentApiKeyCollection apiKeys = component.GetApplicationInsightsComponentApiKeys();125126// API key for reading telemetry127ApplicationInsightsApiKeyContent keyContent = new ApplicationInsightsApiKeyContent128{129 Name = "ReadTelemetryKey",130 LinkedReadProperties =131 {132 $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{component.Data.Name}/api",133 $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{component.Data.Name}/agentconfig"134 }135};136137ApplicationInsightsComponentApiKeyResource apiKey = await apiKeys138 .CreateOrUpdateAsync(WaitUntil.Completed, keyContent);139140Console.WriteLine($"API Key Name: {apiKey.Data.Name}");141Console.WriteLine($"API Key: {apiKey.Data.ApiKey}"); // Only shown once!142```143144### 4. Create Web Test (Availability Test)145146```csharp147WebTestCollection webTests = resourceGroup.GetWebTests();148149// URL Ping Test150WebTestData urlPingTest = new WebTestData(AzureLocation.EastUS)151{152 Kind = WebTestKind.Ping,153 SyntheticMonitorId = "webtest-ping-myapp",154 WebTestName = "Homepage Availability",155 Description = "Checks if homepage is available",156 IsEnabled = true,157 Frequency = 300, // 5 minutes158 Timeout = 120, // 2 minutes159 WebTestKind = WebTestKind.Ping,160 IsRetryEnabled = true,161 Locations =162 {163 new WebTestGeolocation { WebTestLocationId = "us-ca-sjc-azr" }, // West US164 new WebTestGeolocation { WebTestLocationId = "us-tx-sn1-azr" }, // South Central US165 new WebTestGeolocation { WebTestLocationId = "us-il-ch1-azr" }, // North Central US166 new WebTestGeolocation { WebTestLocationId = "emea-gb-db3-azr" }, // UK South167 new WebTestGeolocation { WebTestLocationId = "apac-sg-sin-azr" } // Southeast Asia168 },169 Configuration = new WebTestConfiguration170 {171 WebTest = """172 <WebTest Name="Homepage" Enabled="True" Timeout="120"173 xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">174 <Items>175 <Request Method="GET" Version="1.1" Url="https://myapp.example.com"176 ThinkTime="0" Timeout="120" ParseDependentRequests="False"177 FollowRedirects="True" RecordResult="True" Cache="False"178 ResponseTimeGoal="0" Encoding="utf-8" ExpectedHttpStatusCode="200" />179 </Items>180 </WebTest>181 """182 },183 Tags =184 {185 { $"hidden-link:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/my-appinsights", "Resource" }186 }187};188189ArmOperation<WebTestResource> operation = await webTests190 .CreateOrUpdateAsync(WaitUntil.Completed, "webtest-homepage", urlPingTest);191192WebTestResource webTest = operation.Value;193Console.WriteLine($"Web test created: {webTest.Data.Name}");194```195196### 5. Create Multi-Step Web Test197198```csharp199WebTestData multiStepTest = new WebTestData(AzureLocation.EastUS)200{201 Kind = WebTestKind.MultiStep,202 SyntheticMonitorId = "webtest-multistep-login",203 WebTestName = "Login Flow Test",204 Description = "Tests login functionality",205 IsEnabled = true,206 Frequency = 900, // 15 minutes207 Timeout = 300, // 5 minutes208 WebTestKind = WebTestKind.MultiStep,209 IsRetryEnabled = true,210 Locations =211 {212 new WebTestGeolocation { WebTestLocationId = "us-ca-sjc-azr" }213 },214 Configuration = new WebTestConfiguration215 {216 WebTest = """217 <WebTest Name="LoginFlow" Enabled="True" Timeout="300"218 xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">219 <Items>220 <Request Method="GET" Version="1.1" Url="https://myapp.example.com/login"221 ThinkTime="0" Timeout="60" />222 <Request Method="POST" Version="1.1" Url="https://myapp.example.com/api/auth"223 ThinkTime="0" Timeout="60">224 <Headers>225 <Header Name="Content-Type" Value="application/json" />226 </Headers>227 <Body>{"username":"testuser","password":"{{TestPassword}}"}</Body>228 </Request>229 </Items>230 </WebTest>231 """232 },233 Tags =234 {235 { $"hidden-link:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/my-appinsights", "Resource" }236 }237};238239await webTests.CreateOrUpdateAsync(WaitUntil.Completed, "webtest-login-flow", multiStepTest);240```241242### 6. Create Workbook243244```csharp245WorkbookCollection workbooks = resourceGroup.GetWorkbooks();246247WorkbookData workbookData = new WorkbookData(AzureLocation.EastUS)248{249 DisplayName = "Application Performance Dashboard",250 Category = "workbook",251 Kind = WorkbookSharedTypeKind.Shared,252 SerializedData = """253 {254 "version": "Notebook/1.0",255 "items": [256 {257 "type": 1,258 "content": {259 "json": "# Application Performance\n\nThis workbook shows application performance metrics."260 },261 "name": "header"262 },263 {264 "type": 3,265 "content": {266 "version": "KqlItem/1.0",267 "query": "requests\n| summarize count() by bin(timestamp, 1h)\n| render timechart",268 "size": 0,269 "title": "Requests per Hour",270 "timeContext": {271 "durationMs": 86400000272 },273 "queryType": 0,274 "resourceType": "microsoft.insights/components"275 },276 "name": "requestsChart"277 }278 ],279 "isLocked": false280 }281 """,282 SourceId = component.Id,283 Tags =284 {285 { "environment", "production" }286 }287};288289// Note: Workbook ID should be a new GUID290string workbookId = Guid.NewGuid().ToString();291292ArmOperation<WorkbookResource> operation = await workbooks293 .CreateOrUpdateAsync(WaitUntil.Completed, workbookId, workbookData);294295WorkbookResource workbook = operation.Value;296Console.WriteLine($"Workbook created: {workbook.Data.DisplayName}");297```298299### 7. Link Storage Account300301```csharp302ApplicationInsightsComponentResource component = await resourceGroup303 .GetApplicationInsightsComponentAsync("my-appinsights");304305ComponentLinkedStorageAccountCollection linkedStorage = component.GetComponentLinkedStorageAccounts();306307ComponentLinkedStorageAccountData storageData = new ComponentLinkedStorageAccountData308{309 LinkedStorageAccount = new ResourceIdentifier(310 "/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<storage-account>")311};312313ArmOperation<ComponentLinkedStorageAccountResource> operation = await linkedStorage314 .CreateOrUpdateAsync(WaitUntil.Completed, StorageType.ServiceProfiler, storageData);315```316317### 8. List and Manage Components318319```csharp320// List all Application Insights components in resource group321await foreach (ApplicationInsightsComponentResource component in322 resourceGroup.GetApplicationInsightsComponents())323{324 Console.WriteLine($"Component: {component.Data.Name}");325 Console.WriteLine($" App ID: {component.Data.AppId}");326 Console.WriteLine($" Type: {component.Data.ApplicationType}");327 Console.WriteLine($" Ingestion Mode: {component.Data.IngestionMode}");328 Console.WriteLine($" Retention: {component.Data.RetentionInDays} days");329}330331// List web tests332await foreach (WebTestResource webTest in resourceGroup.GetWebTests())333{334 Console.WriteLine($"Web Test: {webTest.Data.WebTestName}");335 Console.WriteLine($" Enabled: {webTest.Data.IsEnabled}");336 Console.WriteLine($" Frequency: {webTest.Data.Frequency}s");337}338339// List workbooks340await foreach (WorkbookResource workbook in resourceGroup.GetWorkbooks())341{342 Console.WriteLine($"Workbook: {workbook.Data.DisplayName}");343}344```345346### 9. Update Component347348```csharp349ApplicationInsightsComponentResource component = await resourceGroup350 .GetApplicationInsightsComponentAsync("my-appinsights");351352// Update using full data (PUT operation)353ApplicationInsightsComponentData updateData = component.Data;354updateData.RetentionInDays = 180;355updateData.SamplingPercentage = 50;356updateData.Tags["updated"] = "true";357358ArmOperation<ApplicationInsightsComponentResource> operation = await resourceGroup359 .GetApplicationInsightsComponents()360 .CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", updateData);361```362363### 10. Delete Resources364365```csharp366// Delete Application Insights component367ApplicationInsightsComponentResource component = await resourceGroup368 .GetApplicationInsightsComponentAsync("my-appinsights");369await component.DeleteAsync(WaitUntil.Completed);370371// Delete web test372WebTestResource webTest = await resourceGroup.GetWebTestAsync("webtest-homepage");373await webTest.DeleteAsync(WaitUntil.Completed);374```375376## Key Types Reference377378| Type | Purpose |379|------|---------|380| `ApplicationInsightsComponentResource` | App Insights component |381| `ApplicationInsightsComponentData` | Component configuration |382| `ApplicationInsightsComponentCollection` | Collection of components |383| `ApplicationInsightsComponentApiKeyResource` | API key for programmatic access |384| `WebTestResource` | Availability/web test |385| `WebTestData` | Web test configuration |386| `WorkbookResource` | Analysis workbook |387| `WorkbookData` | Workbook configuration |388| `ComponentLinkedStorageAccountResource` | Linked storage for exports |389390## Application Types391392| Type | Enum Value |393|------|------------|394| Web Application | `Web` |395| iOS Application | `iOS` |396| Java Application | `Java` |397| Node.js Application | `NodeJS` |398| .NET Application | `MRT` |399| Other | `Other` |400401## Web Test Locations402403| Location ID | Region |404|-------------|--------|405| `us-ca-sjc-azr` | West US |406| `us-tx-sn1-azr` | South Central US |407| `us-il-ch1-azr` | North Central US |408| `us-va-ash-azr` | East US |409| `emea-gb-db3-azr` | UK South |410| `emea-nl-ams-azr` | West Europe |411| `emea-fr-pra-edge` | France Central |412| `apac-sg-sin-azr` | Southeast Asia |413| `apac-hk-hkn-azr` | East Asia |414| `apac-jp-kaw-edge` | Japan East |415| `latam-br-gru-edge` | Brazil South |416| `emea-au-syd-edge` | Australia East |417418## Best Practices4194201. **Use workspace-based** — Workspace-based App Insights is the current standard4212. **Link to Log Analytics** — Store data in Log Analytics for better querying4223. **Set appropriate retention** — Balance cost vs. data availability4234. **Use sampling** — Reduce costs for high-volume applications4245. **Store connection string securely** — Use Key Vault or managed identity4256. **Enable multiple test locations** — For accurate availability monitoring4267. **Use workbooks** — For custom dashboards and analysis4278. **Set up alerts** — Based on availability tests and metrics4289. **Tag resources** — For cost allocation and organization42910. **Use private endpoints** — For secure data ingestion430431## Error Handling432433```csharp434using Azure;435436try437{438 ArmOperation<ApplicationInsightsComponentResource> operation = await components439 .CreateOrUpdateAsync(WaitUntil.Completed, "my-appinsights", data);440}441catch (RequestFailedException ex) when (ex.Status == 409)442{443 Console.WriteLine("Component already exists");444}445catch (RequestFailedException ex) when (ex.Status == 400)446{447 Console.WriteLine($"Invalid configuration: {ex.Message}");448}449catch (RequestFailedException ex)450{451 Console.WriteLine($"Azure error: {ex.Status} - {ex.Message}");452}453```454455## SDK Integration456457Use the connection string with Application Insights SDK:458459```csharp460// Program.cs in ASP.NET Core461builder.Services.AddApplicationInsightsTelemetry(options =>462{463 options.ConnectionString = configuration["ApplicationInsights:ConnectionString"];464});465466// Or set via environment variable467// APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...;IngestionEndpoint=...468```469470## Related SDKs471472| SDK | Purpose | Install |473|-----|---------|---------|474| `Azure.ResourceManager.ApplicationInsights` | Resource management (this SDK) | `dotnet add package Azure.ResourceManager.ApplicationInsights` |475| `Microsoft.ApplicationInsights` | Telemetry SDK | `dotnet add package Microsoft.ApplicationInsights` |476| `Microsoft.ApplicationInsights.AspNetCore` | ASP.NET Core integration | `dotnet add package Microsoft.ApplicationInsights.AspNetCore` |477| `Azure.Monitor.OpenTelemetry.Exporter` | OpenTelemetry export | `dotnet add package Azure.Monitor.OpenTelemetry.Exporter` |478479## Reference Links480481| Resource | URL |482|----------|-----|483| NuGet Package | https://www.nuget.org/packages/Azure.ResourceManager.ApplicationInsights |484| API Reference | https://learn.microsoft.com/dotnet/api/azure.resourcemanager.applicationinsights |485| Product Documentation | https://learn.microsoft.com/azure/azure-monitor/app/app-insights-overview |486| GitHub Source | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/applicationinsights/Azure.ResourceManager.ApplicationInsights |487
Full transparency — inspect the skill content before installing.