Instrument mobile apps with Dynatrace .NET MAUI NuGet package
Dynatrace version 1.265+
The Dynatrace .NET MAUI NuGet package helps auto-instrument your .NET MAUI mobile application with OneAgent for Android and iOS as well as provides an API for manual instrumentation.
The Dynatrace .NET MAUI NuGet package is available for Android and iOS. You cannot use our package for macOS and Windows.
Supported features
Auto-instrumentation
User actions
Lifecycle events
Web requests
Crashes
Manual instrumentation
Custom actions
Web requests
Values
Events
Errors
Crashes
User tagging
Requirements
- For Android: Android version 5.0+ (API 21+)
- For iOS: iOS version 11+
Set up the package
Perform the following steps to set up the Dynatrace .NET MAUI NuGet package for your mobile application.
Install the Dynatrace .NET MAUI NuGet package
Create an application and get the config file
Add the config file to your project
Add the OneAgent start method
Enable automatic web request instrumentation
Install the NuGet package
Add the Dynatrace .NET MAUI NuGet package to your application.
- In Visual Studio, right-click the solution of your mobile application and select Manage NuGet packages.
- Find Dynatrace.OneAgent.MAUI from nuget.org and select Add Package.
Select the checkboxes of all the projects to which you want to add the NuGet package.
- Select OK.
Create an application and get the config file
Create a new mobile application in the Dynatrace web UI, and download the configuration file.
- In the Dynatrace menu, go to Deploy Dynatrace.
- Scroll down to the Mobile app monitoring section and select Set up mobile monitoring.
- Enter a name for your application and select Create mobile app. The application settings page opens.
- From the application settings, select Instrumentation wizard > .NET MAUI.
- Under step 2, select Download dynatrace.config.json to get the configuration file.
Add the config file to your project
Add the dynatrace.config.json
file, which you downloaded in the previous step, to your project.
Add the dynatrace.config.json
file to the Platforms/Android/Assets
directory of your project.
If you cannot find the Assets
directory, create it inside the Platforms/Android
directory.
Add the OneAgent start method
The start method is required for OneAgent to start.
1using Dynatrace.MAUI;23Agent.Instance.Start();
Enable automatic web request instrumentation optional
You can optionally use the following method to enable the auto-instrumentation of web requests. The HttpMessageHandler
used by HttpClient
takes care of the manual web request instrumentation.
1using Dynatrace.MAUI;23var httpHandler = Agent.Instance.GetHttpMessageHandler();4var httpClient = new HttpClient(httpHandler);
Moreover, you can also have your own HTTP handler:
1using Dynatrace.MAUI;23var defaultHttpHandler = new HttpClientHandler();4var httpHandler = Agent.Instance.GetHttpMessageHandler(defaultHttpHandler);5var httpClient = new HttpClient(httpHandler);
Manual instrumentation
The sections below describe how to start OneAgent manually, create custom actions, instrument web requests, and report values, events, and crashes.
Start OneAgent
You can use the manual startup with a configuration builder (Android) or a configuration dictionary (iOS).
-
Modify the
dynatrace.config.json
file to disable OneAgent autostart.1{2 "android": {3 "autoStart": {4 "enabled": false5 }6 }7}Don't add additional properties to the configuration file. If you do that, the build fails with an exception.
-
Start OneAgent manually and pass the required properties.
1using Dynatrace.MAUI;23Agent.Instance.Start(new ConfigurationBuilder("<insertBeaconURL>","<insertApplicationID>") .BuildConfiguration());
Create custom actions
You can create custom actions and enhance them with additional information such as values, events, and errors.
Call EnterAction
to start a custom action and LeaveAction
to close a custom action. Timing is measured automatically.
1using Dynatrace.MAUI;23IRootAction myAction = Agent.Instance.EnterAction("Tap on Confirm");4//Perform the action and whatever else is needed.5myAction.LeaveAction();
For a mobile custom action or a mobile autogenerated user action, the maximum name length is 250 characters.
Create child actions
Besides generating standalone custom actions, you can also create child actions.
Child actions are similar to parent custom actions. When a parent action is closed, all child actions of the parent action are automatically closed.
1using Dynatrace.MAUI;23IRootAction myAction = Agent.Instance.EnterAction("Tap on Confirm");4IAction mySubAction = myAction.EnterAction("Tap on Confirm again");5//Perform the action and whatever else is needed.6mySubAction.LeaveAction();7myAction.LeaveAction();
For a mobile custom action or a mobile autogenerated user action, the maximum name length is 250 characters.
There's no limit on the number of child actions attached to a custom action. However, note that you can have only one level of child actions—you can't create a child action for another child action (child actions can't have their own child actions). For an overview of a user action structure, see the illustration on the Real User Monitoring page.
Child actions are not displayed on the user session details page, but you can view them on the waterfall analysis page for a custom action to which these child actions are attached.
Cancel custom actions
If you need to cancel an already created but not yet closed custom action, call Cancel
. Canceling an action discards all data associated with it: all reported values, events, and errors are discarded; all child actions are canceled.
1using Dynatrace.MAUI;23IRootAction myAction = Agent.Instance.EnterAction("Tap on Confirm");4// Action is canceled5myAction.Cancel();
You can't cancel a closed action, so calling Cancel
after LeaveAction
is impossible for the same action. The same goes for closing a canceled action: you can't call LeaveAction
after using Cancel
for the same action.
Instrument web requests
Use the following code snippet to instrument web requests:
1using Dynatrace.MAUI;23// Create an action4IRootAction webAction = Agent.Instance.EnterAction(actionName: "WebRequest Action");5// Generate a new unique tag associated with the web request action6string requestTag = webAction.GetRequestTag(url);7string requestTagHeader = webAction.GetRequestTagHeader();8// Place the Dynatrace HTTP header on your web request9httpClient.DefaultRequestHeaders.Add(requestTagHeader, requestTag);10// Generate a WebRequestTiming object based on the unique tag11IWebRequestTiming timing = Agent.Instance.GetWebRequestTiming(requestTag, url);12// Start web request timing before the HTTP request is sent13timing.StartWebRequestTiming();14try15{16 var response = await httpClient.GetAsync(url);17 // Stop web request timing when the HTTP response is received and the response body is obtained18 timing.StopWebRequestTiming(url, (int)response.StatusCode, response.ReasonPhrase);19}20catch (HttpRequestException exception)21{22 // Stop web request timing when a connection exception occurs23 timing.StopWebRequestTiming(url, -1, exception.ToString());24}25finally26{27 // Leave an action28 webAction.LeaveAction();29}
Report a value
The reportValue
method allows you to report key-value pairs of metadata that you can later view in the Dynatrace web UI and convert into user action and user session properties. The reported values must be part of a user action.
You can report values of the following data types:
int
double
string
1ReportValue(valueName: string, value: int);2ReportValue(valueName: string, value: double);3ReportValue(valueName: string, value: string);
For instance, to report a string
value within the Tap on Confirm
action, use the following code:
1using Dynatrace.MAUI;23IRootAction myAction = Agent.Instance.EnterAction("Tap on Confirm");4myAction.ReportValue("Customer type", "Gold");5myAction.LeaveAction();
To view the reported values in the Dynatrace web UI, go to the details of the user action that should contain that metadata and scroll down to the Reported values section.
To add action and session properties based on the reported values and then use these properties to create powerful queries, segmentations, and aggregations, see Define user action and user session properties for mobile applications.
Report an event
For any open action, you can report an event. Use the following API call:
1ReportEvent(eventName: string);
If you want to report standalone events with lots of additional information, see Report a business event.
Report an error
To report an error, use the ReportError
method.
1ReportError(errorName: string, errorCode: number);
Report an error stack trace
To report an error stack trace, use the following API call:
1using Dynatrace.MAUI;23Agent.Instance.ReportErrorStacktrace("Error_Class", "Error_Value", "Error_Reason", "Error_Stacktrace");
Report a crash
To report a crash, use the following API call.
1using Dynatrace.MAUI;23Agent.Instance.ReportCrash("CrashWithoutException", "Crash_Reason", "Crash_Stacktrace");
You can also use an exception object:
1using Dynatrace.MAUI;23Agent.Instance.ReportCrashWithException("CrashWithExceptionObj", exception);
The time when the crash details are sent to Dynatrace depends on your mobile application operating system.
-
Android
In general, the crash details are sent immediately after the crash, so the user doesn’t have to relaunch the application. However, in some cases, the application should be reopened within 10 minutes so that the crash report is sent. Note that Dynatrace doesn't send crash reports that are older than 10 minutes (as such reports can no longer be correlated on the Dynatrace Cluster).
-
iOS
The crash details are sent only when the user reopens the mobile application (so on the next application launch). However, if the user doesn't open the application within 10 minutes, the crash report is deleted. This is because Dynatrace doesn't send crash reports that are older than 10 minutes (as such reports can no longer be correlated on the Dynatrace Cluster).
Reporting a crash forces a user session to be completed. Any subsequent actions are included in a new user session.
Android only When you use automated crash reporting, Visual Studio might catch the exception before OneAgent. If you notice that Dynatrace doesn't report crashes to your environment, make sure that you're not using the debug option in Visual Studio. Otherwise, the debugger catches the crash and nothing is reported to your Dynatrace environment.
Report a business event
With sendBizEvent
, you can report business events. These are standalone events, as Dynatrace sends them separately from user actions or user sessions.
For more information on business events, see Business Analytics.
1using Dynatrace.MAUI;23var attributes = new Dictionary<string, JsonValue>();4attributes.Add("event.name", "Confirmed Booking");5attributes.Add("screen", "booking-confirmation");6attributes.Add("product", "Danube Anna Hotel");7attributes.Add("amount", 358.35);8attributes.Add("currency", "USD");9attributes.Add("reviewScore", 4.8);10attributes.Add("arrivalDate", "2022-11-05");11attributes.Add("departureDate", "2022-11-15");12attributes.Add("journeyDuration", 10);13attributes.Add("adultTravelers", 2);14attributes.Add("childrenTravelers", 0);1516Agent.Instance.SendBizEvent("com.easytravel.funnel.booking-finished", attributes);
Tag specific users
You can tag each user of your mobile application with a unique user name. This enables you to search and filter specific user sessions and analyze individual user behavior over time. For more details, see User tagging.
Make the following API call to tag the current session with a particular name:
1using Dynatrace.MAUI;23Agent.Instance.IdentifyUser("John Smith");
OneAgent for Android version 237+ OneAgent for iOS version 235+ Sessions split due to idle or duration timeout are re-tagged automatically.
When OneAgent ends a tagged session because the session duration has reached its set limit or due to the user's inactivity, the subsequent session is re-tagged automatically. You don't need to provide the user identification information again.
However, note that OneAgent does not re-tag the subsequent session in the following cases:
- When you explicitly end a tagged user session via
endVisit
When the user or the mobile operating system closes or force stops the app
When OneAgent ends the current user session and generates a new session after the privacy settings have been changed
See User sessions > Session end to learn when OneAgent ends a mobile user session.
End a session
You can force a session to end via the API call. This also closes all open actions and starts a new session.
1using Dynatrace.MAUI;23Agent.Instance.EndVisit();
Configure data privacy
With the user opt-in mode for mobile applications, you can dynamically adjust data privacy settings and build your applications in compliance with data protection laws and regulations.
Enable user opt-in mode
To activate the user opt-in mode, set the userOptIn
property (Android) or DTXUserOptIn
configuration key (iOS) to true
in the dynatrace.config.json
file. After enabling the user opt-in mode, you should also specify the privacy setting.
Retrieve data privacy settings
To get the current UserPrivacyOptions
configuration, use the following API call:
1using Dynatrace.MAUI;23// Get the UserPrivacyOptions object4UserPrivacyOptions currentOptions = Agent.Instance.GetUserPrivacyOptions();56// Get the individual settings for DataCollectionLevel and crash reporting7bool crashOptedIn = Agent.Instance.GetUserPrivacyOptions().CrashReportingOptedIn;8DataCollectionLevel dataCollectionLevel = Agent.Instance.GetUserPrivacyOptions().DataCollectionLevel;
Change data privacy settings
To set new options on a UserPrivacyOptions
object, use the following code:
1using Dynatrace.MAUI;23// Creating a new UserPrivacyOptions object requires setting the two parameters of DataCollectionLevel and crash reporting4UserPrivacyOptions options = new UserPrivacyOptions(DataCollectionLevel.Performance, false);56// Update the options with the setter7// Set a data collection level (user allowed you to capture performance and personal data)8options.DataCollectionLevel = DataCollectionLevel.UserBehavior;9// Allow crash reporting (user allowed you to collect information on crashes)10options.CrashReportingOptedIn = true;1112// Get the values of the configuration with the getter13options.DataCollectionLevel;14options.CrashReportingOptedIn;1516// Get the UserPrivacyOptions object17UserPrivacyOptions currentOptions = Agent.Instance.GetUserPrivacyOptions();
To apply the new UserPrivacyOptions
configuration, use this code:
1using Dynatrace.MAUI;23UserPrivacyOptions options = new UserPrivacyOptions(DataCollectionLevel.UserBehavior, true);4Agent.Instance.ApplyUserPrivacyOptions(options);
Data collection levels
The table below describes the available data collection levels and shows whether user tags and custom user actions, events, values, and errors are reported for a particular level.
Level | Description | User tags, custom events, and custom values | Custom user actions and errors |
---|---|---|---|
Off Monitoring data is not sent | No personal data is sent; all identifiers are randomized on every launch.1 | ||
Performance Only performance, automatically captured data is sent | No personal data is sent; all identifiers are randomized on every launch. | ||
User behavior Performance data and user data is sent | Personal data is sent; OneAgent recognizes and reports users who revisit in the future.2 |
A single Loading <App>
event is sent to track the number of users that opted out.
If you haven't configured user tagging and custom event or value reporting, the User behavior level works similarly to the Performance level.
The possible values for the data collection levels are as follows:
Off
Performance
UserBehavior
Report GPS location
You can report the latitude and longitude.
1SetGPSLocation(latitude: double, longitude: double);
Configuration file
The dynatrace.config.json
configuration file contains your application ID, beacon URL, and some other settings.
- You can download this file from the Dynatrace web UI or create it manually.
- If you don't add a configuration file with at least the beacon URL and the application ID properties, the build fails. Alternatively, use the manual startup with a configuration builder (Android) or a configuration dictionary (iOS).
- When you use a specific build configuration—for example,
Debug
,Release
, or a custom-defined configuration—our package searches theAssets
(Android) orResources
(iOS) directory for a configuration file nameddynatrace<Configuration>.config.json
. For example, if you're using theDebug
build configuration, our package looks for a file nameddynatraceDebug.config.json
. If the package can't find the configuration-specific file, it uses the defaultdynatrace.config.json
file.
The following is the dynatrace.config.json
file structure for Android and iOS.
1{2 "android": {3 "autoStart": {4 "applicationId": "<insertApplicationID>",5 "beaconUrl": "<insertBeaconURL>"6 },7 "userOptIn": true,8 "agentBehavior": {9 "startupLoadBalancing": true10 }11 }12}
Never use dot notation for the configuration file. Always write in full bracket style.
Enable OneAgent debug logs
If the instrumentation runs through and your application starts, but you see no data in your Dynatrace environment, you probably need to dig deeper to find out why OneAgents aren't sending any data. Opening up a support ticket is a great idea but gathering logs first is even better.
Update your dynatrace.config.json
file to enable OneAgent debug logs.
1{2 "android": {3 "autoStart": {4 "applicationId": "<insertApplicationID>",5 "beaconUrl": "<insertBeaconURL>"6 },7 "userOptIn": true,8 "debug": {9 "agentLogging": true10 }11 }12}
Enable build debug logs for Android
Android only
If the Android instrumentation fails, you most likely need to open a support ticket and provide build debug logs. To provide those logs, you need to set the DynatraceInstrumentationLogging
property and change the build log level to Diagnostic
.
-
Set the
DynatraceInstrumentationLogging
property. Choose one of the following options to do that:- Create
Directory.Build.props
in the Android project directory:
1<Project>2 <PropertyGroup>3 <DynatraceInstrumentationLogging>true</DynatraceInstrumentationLogging>4 </PropertyGroup>5</Project>- Add the
DynatraceInstrumentationLogging
property to the.csproj
file of your project. Insert it into some existingPropertyGroup
, depending on the configuration that you're executing.
- Create
-
Change the build output verbosity to
Diagnostic
. For details, see the Microsoft documentation on how to change the amount of information included in the build log. -
Rebuild your project.
-
Attach the build logs to the support ticket so that we can further analyze your issue.
Troubleshooting
If you can't resolve a problem, please contact a Dynatrace product expert via live chat within your Dynatrace environment. Have the following details available:
- OneAgent debug logs
- Your
dynatrace.config.json
file
Failed build
If your build fails, make sure you've added the dynatrace.config.json
file to the Assets
(Android) or Resources
(iOS) directory and that the file includes at least the beacon URL and the application ID properties. For details, see Configuration file.
If you use the manual startup, don't include the beacon URL and the application ID properties in the configuration file. If you do that, you encounter an exception.
Turn off Visual Studio Debugger for Android
Android only
If you notice that Dynatrace doesn't report crashes for Android applications to your environment, make sure that you're not using the debug option in Visual Studio.
-
Right-click your Android project, and select Properties.
-
Go to Android Options, and clear Enable developer instrumentation (debugging and profiling).
Keep in mind that clearing Enable developer instrumentation disables debugging. Use this option only to verify that crashes are sent. Optionally, you can create a release build that is detached from Visual Studio.