Skip to content

Commit

Permalink
Merge pull request #1 from johnbilliris/SDKv3
Browse files Browse the repository at this point in the history
Changes for SDK v3
  • Loading branch information
johnbilliris authored Apr 4, 2022
2 parents 75ddae7 + f989eec commit d166de4
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 19 deletions.
70 changes: 70 additions & 0 deletions DependencyTelemetryRequestHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure.Cosmos;

namespace Company.Function
{

/*
* Custom RequestHandler that enriches the telemetry with the CosmosDB RU
* Charge and the Db query executed.
* https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.requesthandler?view=azure-dotnet
*/
public class DependencyTelemetryRequestHandler : RequestHandler
{
private readonly TelemetryClient telemetryClient;

private const string RequestCharge = "CosmosDBRequestCharge";

public DependencyTelemetryRequestHandler()
{
this.telemetryClient = new TelemetryClient();
}
public DependencyTelemetryRequestHandler(TelemetryClient telemetryClient)
{
this.telemetryClient = telemetryClient;
}


public override async Task<ResponseMessage> SendAsync(RequestMessage request, CancellationToken cancellationToken)
{
using (Microsoft.ApplicationInsights.Extensibility.IOperationHolder<DependencyTelemetry> operation = this.telemetryClient.StartOperation<DependencyTelemetry>("CosmosDBRequest"))
{
this.telemetryClient.TrackTrace($"{request.Method.Method} - {request.RequestUri.ToString()}");
ResponseMessage response = await base.SendAsync(request, cancellationToken);

var telemetry = operation.Telemetry;
telemetry.Type = "Azure DocumentDB";
telemetry.Data = request.RequestUri.OriginalString;
telemetry.ResultCode = ((int)response.StatusCode).ToString();
telemetry.Success = response.IsSuccessStatusCode;

telemetry.Metrics[RequestCharge] = response.Headers.RequestCharge;

if ( !telemetry.Properties.ContainsKey("CosmosDBQuery") ) {
if ( response.RequestMessage is not null ) {
if ( response.RequestMessage.Content is not null ) {
using (StreamReader reader = new StreamReader( response.RequestMessage.Content ))
{
var cosmosQuery = reader.ReadToEnd();
telemetry.Properties.Add("CosmosDBQuery",cosmosQuery );
}
}
}
}

this.telemetryClient.StopOperation(operation);
return response;
}
}
}
}
18 changes: 12 additions & 6 deletions GetDataFromCosmosDb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@

namespace Company.Function
{
public static class GetDataFromCosmosDb
public class GetDataFromCosmosDb
{

///
/// .NET SDK v2 Approach
/// https://docs.microsoft.com/en-us/azure/cosmos-db/sql/find-request-unit-charge?tabs=dotnetv2
///
[FunctionName("SDKv2")]
public static async Task<IActionResult> SDKv2(
public async Task<IActionResult> SDKv2(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
[CosmosDB(databaseName: "cosmosdb", collectionName: "posts", ConnectionStringSetting="CosmosDBConnection")] DocumentClient client,
ILogger log)
Expand Down Expand Up @@ -62,11 +63,16 @@ public static async Task<IActionResult> SDKv2(
/// https://docs.microsoft.com/en-us/azure/cosmos-db/sql/find-request-unit-charge?tabs=dotnetv3
///

private static CosmosClient cosmosClient = new CosmosClient(Environment.GetEnvironmentVariable("CosmosDBConnectionEndpoint"), Environment.GetEnvironmentVariable("CosmosDBConnectionAccountKey"));
private static Container _container = cosmosClient.GetContainer("cosmosdb", "posts");
private readonly CosmosClient cosmosClient;
private readonly Container container;
public GetDataFromCosmosDb(CosmosClient cosmosClient)
{
this.cosmosClient = cosmosClient;
this.container = cosmosClient.GetContainer("cosmosdb", "posts");
}

[FunctionName("SDKv3")]
public static async Task<IActionResult> SDKv3(
public async Task<IActionResult> SDKv3(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
ILogger log)
{
Expand All @@ -77,7 +83,7 @@ public static async Task<IActionResult> SDKv3(
log.LogInformation($"Searching for: {creatorId}");

QueryDefinition queryDefinition = new QueryDefinition("select * From c where c.CreatorId = @CreatorId").WithParameter("@CreatorId", creatorId);
using (Microsoft.Azure.Cosmos.FeedIterator<PostsModel> feedIterator = _container.GetItemQueryIterator<PostsModel>(queryDefinition))
using (Microsoft.Azure.Cosmos.FeedIterator<PostsModel> feedIterator = this.container.GetItemQueryIterator<PostsModel>(queryDefinition))
{
while (feedIterator.HasMoreResults)
{
Expand Down
21 changes: 19 additions & 2 deletions StartUp.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
using System;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.Fluent;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.ApplicationInsights.Extensibility;
Expand All @@ -7,11 +10,25 @@
namespace Company.Function
{
internal class StartUp : FunctionsStartup
{
{
public override void Configure(IFunctionsHostBuilder builder)
{
// For the Telemetry Initializer to grab the RU charge per call to CosmosDB
builder.Services.AddSingleton<ITelemetryInitializer, DependencyTelemetryInitializer>();
/// .NET SDK v2 Approach
builder.Services.AddSingleton<ITelemetryInitializer, DependencyTelemetryInitializer>();

/// .NET SDK v3 Approach
builder.Services.AddSingleton((s) => {
string connectionString = Environment.GetEnvironmentVariable("CosmosDBConnection");
if (string.IsNullOrEmpty(connectionString))
{
throw new ArgumentNullException("Please specify a valid CosmosDBConnection in the appSettings.json file or your Azure Functions Settings.");
}

CosmosClientBuilder configurationBuilder = new CosmosClientBuilder(connectionString);
configurationBuilder.AddCustomHandlers( new DependencyTelemetryRequestHandler() );
return configurationBuilder.Build();
});
}
}
}
12 changes: 1 addition & 11 deletions local.settings.json.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"APPINSIGHTS_INSTRUMENTATIONKEY": "",
"CosmosDBConnection": "AccountEndpoint=https://<your cosmos db>.documents.azure.com:443/;AccountKey=;",
"CosmosDBConnectionEndpoint": "https://<your cosmos db>.documents.azure.com:443/",
"CosmosDBConnectionAccountKey": ""
"CosmosDBConnection": "AccountEndpoint=https://<your cosmos db>.documents.azure.com:443/;AccountKey=;"
},
"bindings": [
{
Expand All @@ -22,14 +20,6 @@
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "cosmosDB",
"name": "client",
"databaseName": "cosmosdb",
"collectionName": "posts",
"connectionStringSetting": "CosmosDBConnection",
"direction": "in"
}
]
}

0 comments on commit d166de4

Please sign in to comment.