• Home
  • Platform modules
  • Digital Experience
  • Mobile applications
  • Development frameworks
  • Xamarin

Instrument mobile apps with Dynatrace Xamarin NuGet package

The Dynatrace Xamarin NuGet package helps auto-instrument your Xamarin app with OneAgent for Android and iOS as well as provides an API for manual instrumentation. The package is compatible with Xamarin.iOS, Xamarin.Android, and Xamarin.Forms projects.

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+)
    • Xamarin.Android SDK version 10.1.x+
  • For iOS: iOS version 11+
  • For Xamarin.Forms: .NET Standard version 2.0+

Set up the package

Perform the following steps to set up the Dynatrace Xamarin NuGet package for your Xamarin app.

Install the Dynatrace Xamarin NuGet package

Create an app and get the config file

Add the config file to your project

Add the OneAgent start method

Xamarin.Forms only

Set up Xamarin.Forms DependencyService

Enable automatic web request instrumentation

Install the NuGet package

Add the Dynatrace Xamarin NuGet package to all the required projects.

  1. In Visual Studio, right-click the main project of your app and select Manage NuGet packages.
  2. Find Dynatrace.OneAgent.Xamarin from nuget.org, and select Add Package.
  3. Select the checkboxes of all the projects to which you want to add the NuGet package.
  4. Select OK.

Create an app and get the config file

Create a new mobile app in the Dynatrace web UI, and download the configuration file.

  1. In the Dynatrace menu, go to Deploy Dynatrace.
  2. Scroll down, and select Set up mobile monitoring.
  3. Enter a name for your app, and select Create mobile app.
    The app settings page opens.
  1. From the mobile app settings, go to Instrumentation wizard, and select Xamarin.
  2. 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 Assets directory of your Android project.

Add the dynatrace.config.json file to the Resources directory of your iOS project.

Before each build, our package automatically creates a new Dynatrace.plist file based on the options set in your configuration file.

Add the OneAgent start method

The start method is required for OneAgent to start.

c
using Dynatrace.Xamarin; Agent.Instance.Start();
c
using Dynatrace.Xamarin; Agent.Instance.Start();

Set up Xamarin.Forms DependencyService

Xamarin.Forms only

This instruction is for Xamarin.Forms versions 4.7.0+, which use RegisterSingleton. For earlier Xamarin.Forms versions, see the instruction below.

Register the interface at startup in the native part of your Xamarin.Forms application, and paste the following code right after Forms.Init().

The following example is for an Android Forms application:

c
using Dynatrace.Xamarin; Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); Xamarin.Forms.DependencyService.RegisterSingleton<IDynatrace>(Agent.Instance); LoadApplication(new App());

The following code in your Xamarin.Forms application allows you to access OneAgent:

c
using Dynatrace.Xamarin; IDynatrace dynatrace = DependencyService.Get<IDynatrace>();

In case of auto-instrumentation, you also need to apply the Dynatrace Xamarin NuGet package to the native parts of your application.

Xamarin.Forms 4.6.0 and earlier

If you can't use DependencyService.RegisterSingleton as your Xamarin.Forms version is 4.6.0 or earlier, there is a workaround. The following code snippet shows how this works for Xamarin.Forms and Android, but you can easily apply it to iOS as well.

The App.xaml.cs file in the Xamarin.Forms part:

c
public partial class App : Application { static readonly Dictionary<Type, Func<object, object>> factories = new Dictionary<Type, Func<object, object>>(); public App() { InitializeComponent(); DependencyResolver.ResolveUsing((type, args) => factories.ContainsKey(type) ? factories[type].Invoke(args) : null); IDynatrace Dynatrace = DependencyService.Resolve<IDynatrace>(); Dynatrace.Start(null); } public static void Register(Type type, Func<object, object> factory) { factories[type] = factory; } ... }

The Android part, where you have to call RegisterSingleton, should look like this:

c
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { ... Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); App.Register(typeof(IDynatrace), (o) => Agent.Instance); LoadApplication(new App()); } ... }

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.

c
using Dynatrace.Xamarin; var httpHandler = Agent.Instance.GetHttpMessageHandler(); var httpClient = new HttpClient(httpHandler);

Moreover, you can also have your own HTTP handler:

c
using Dynatrace.Xamarin; var defaultHttpHandler = new HttpClientHandler(); var httpHandler = Agent.Instance.GetHttpMessageHandler(defaultHttpHandler); var 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).

  1. Modify the dynatrace.config.json file to disable OneAgent autostart.

    js
    { "android": { "autoStart": { "enabled": false } } }
    js
    { "ios": { "DTXAutoStart": false } }

    Don't add additional properties to the configuration file. If you do that, the build fails with an exception.

  2. Start OneAgent manually and pass the required properties.

    c
    using Dynatrace.Xamarin; Agent.Instance.Start(new ConfigurationBuilder("<insertBeaconURL>","<insertApplicationID>") .BuildConfiguration());
    c
    using Dynatrace.Xamarin; var configDict = new Dictionary<string, object>(); configDict.Add("DTXApplicationID", "<insertApplicationID>"); configDict.Add("DTXBeaconURL", "<insertBeaconURL"); Agent.Instance.Start(configDict);

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.

c
using Dynatrace.Xamarin; var myAction = Agent.Instance.EnterAction("Tap on Confirm"); //Perform the action and whatever else is needed. myAction.LeaveAction();

For a mobile custom action or a mobile autogenerated user action, the maximum name length is 250 characters.

Check the following links for information on user action naming: Android and iOS.

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.

c
using Dynatrace.Xamarin; var myAction = Agent.Instance.EnterAction("Tap on Confirm"); var mySubAction = myAction.EnterAction("Tap on Confirm again"); //Perform the action and whatever else is needed. mySubAction.LeaveAction(); myAction.LeaveAction();

For a mobile custom action or a mobile autogenerated user action, the maximum name length is 250 characters.

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.

c
using Dynatrace.Xamarin; var myAction = Agent.Instance.EnterAction("Tap on Confirm"); // Action is canceled myAction.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:

c
using Dynatrace.Xamarin; // Create an action var webAction = Agent.Instance.EnterAction(actionName: "WebRequest Action"); // Generate a new unique tag associated with the web request action string requestTag = webAction.GetRequestTag(url); string requestTagHeader = webAction.GetRequestTagHeader(); // Place the Dynatrace HTTP header on your web request httpClient.DefaultRequestHeaders.Add(requestTagHeader, requestTag); // Generate a WebRequestTiming object based on the unique tag WebRequestTiming timing = (WebRequestTiming)Agent.Instance.GetWebRequestTiming(requestTag, url); // Start web request timing before the HTTP request is sent timing.StartWebRequestTiming(); try { var response = await httpClient.GetAsync(url); // Stop web request timing when the HTTP response is received and the response body is obtained timing.StopWebRequestTiming(url, (int)response.StatusCode, response.ReasonPhrase); } catch (HttpRequestException exception) { // Stop web request timing when a connection exception occurs timing.StopWebRequestTiming(url, -1, exception.ToString()); } finally { // Leave an action webAction.LeaveAction(); }

Report a value

The ReportValue method allows you to report your own metrics. These metrics must be part of a user action. You can report int, double, and string values.

c
ReportValue(valueName: string, value: int); ReportValue(valueName: string, value: double); ReportValue(valueName: string, value: string);

For instance, to report a string value within the Tap on Confirm action, use the following code:

c
using Dynatrace.Xamarin; var myAction = Agent.Instance.EnterAction("Tap on Confirm"); myAction.ReportValue("Customer type", "Gold"); myAction.LeaveAction();

Report an event

For any open action, you can report an event. Use the following API call:

c
ReportEvent(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:

c
ReportError(errorName: string, errorCode: number);

Report an error stack trace

To report an error stack trace, use the following API call:

c
using Dynatrace.Xamarin; Agent.Instance.ReportErrorStacktrace("Error_Class", "Error_Value", "Error_Reason", "Error_Stacktrace");

Report a crash

To report a crash, use the following API call:

c
using Dynatrace.Xamarin; Agent.Instance.ReportCrash("CrashWithoutException", "Crash_Reason", "Crash_Stacktrace");

You can also use an exception object:

c
using Dynatrace.Xamarin; Agent.Instance.ReportCrashWithException("CrashWithExceptionObj", exception);

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

Dynatrace SaaS version 1.253+

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 in Dynatrace.

c
using Dynatrace.Xamarin; var attributes = new Dictionary<string, JsonValue>(); attributes.Add("event.name", "Confirmed Booking"); attributes.Add("screen", "booking-confirmation"); attributes.Add("product", "Danube Anna Hotel"); attributes.Add("amount", 358.35); attributes.Add("currency", "USD"); attributes.Add("reviewScore", 4.8); attributes.Add("arrivalDate", "2022-11-05"); attributes.Add("departureDate", "2022-11-15"); attributes.Add("journeyDuration", 10); attributes.Add("adultTravelers", 2); attributes.Add("childrenTravelers", 0); Agent.Instance.SendBizEvent("com.easytravel.funnel.booking-finished", attributes);

Tag specific users

You can tag each user of your app with a unique user name. This enables you to search and filter specific user sessions and analyze individual user behavior over time.

Make the following API call to tag the current session with a particular name:

c
using Dynatrace.Xamarin; Agent.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.

c
using Dynatrace.Xamarin; Agent.Instance.EndVisit();

Configure data privacy

With the user opt-in mode for mobile apps, you can dynamically adjust data privacy settings and build your apps in compliance with data protection laws and regulations.

To activate the user opt-in mode, set the userOptIn (Android) or DTXUserOptIn (iOS) property to true in the dynatrace.config.json file. After enabling the user opt-in mode, you should also specify the privacy setting.

To get the current UserPrivacyOptions configuration, use the following API call:

c
using Dynatrace.Xamarin; // Get the UserPrivacyOptions object UserPrivacyOptions currentOptions = Agent.Instance.GetUserPrivacyOptions(); // Get the individual settings for DataCollectionLevel and crash reporting bool crashOptedIn = Agent.Instance.GetUserPrivacyOptions().CrashReportingOptedIn; DataCollectionLevel dataCollectionLevel = Agent.Instance.GetUserPrivacyOptions().DataCollectionLevel;

To set new options on a UserPrivacyOptions object, use the following code:

c
using Dynatrace.Xamarin; // Creating a new UserPrivacyOptions object requires setting the two parameters of DataCollectionLevel and crash reporting UserPrivacyOptions options = new UserPrivacyOptions(DataCollectionLevel.Performance, false); // Update the options with the setter options.DataCollectionLevel = DataCollectionLevel.UserBehavior; options.CrashReportingOptedIn = true; // Get the values of the configuration with the getter options.DataCollectionLevel; options.CrashReportingOptedIn; // Get the UserPrivacyOptions object UserPrivacyOptions currentOptions = Agent.Instance.GetUserPrivacyOptions();

To apply the new UserPrivacyOptions configuration, use this code:

c
using Dynatrace.Xamarin; UserPrivacyOptions options = new UserPrivacyOptions(DataCollectionLevel.UserBehavior, true); Agent.Instance.ApplyUserPrivacyOptions(options);

The following data collection levels are available:

  • Off
  • Performance
  • UserBehavior

Report GPS location

You can report the latitude and longitude.

c
SetGPSLocation(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 the Assets (Android) or Resources (iOS) directory for a configuration file named dynatrace<Configuration>.config.json. For example, if you're using the Debug build configuration, our package looks for a file named dynatraceDebug.config.json. If the package can't find the configuration-specific file, it uses the default dynatrace.config.json file.

The following is the dynatrace.config.json file structure for Android and iOS.

js
{ "android": { "autoStart": { "applicationId": "<insertApplicationID>", "beaconUrl": "<insertBeaconURL>" }, "userOptIn": true, "agentBehavior": { "startupLoadBalancing": true } } }
js
{ "ios": { "DTXApplicationId": "<insertApplicationID>", "DTXBeaconUrl": "<insertBeaconURL>", "DTXUserOptIn": true, "DTXStartupLoadBalancing": true } }

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 app 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.

json
{ "android": { "autoStart": { "applicationId": "<insertApplicationID>", "beaconUrl": "<insertBeaconURL>" }, "userOptIn": true, "debug": { "agentLogging": true } } }

Add the following configuration snippet to the dynatrace.config.json file:

json
{ "ios": { "DTXApplicationId": "<insertApplicationID>", "DTXBeaconUrl": "<insertBeaconURL>", "DTXUserOptIn": true, "DTXLogLevel": "ALL" } }

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.

  1. Set the DynatraceInstrumentationLogging property. Choose one of the following options to do that:

    • Create Directory.Build.props in the Android project directory:
    xml
    <Project> <PropertyGroup> <DynatraceInstrumentationLogging>true</DynatraceInstrumentationLogging> </PropertyGroup> </Project>
    • Add the DynatraceInstrumentationLogging property to the .csproj file of your project. Insert it into some existing PropertyGroup, depending on the configuration that you're executing.
  2. 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.

  3. Rebuild your project.

  4. Attach the build logs to the support ticket so that we can further analyze your issue.

Enable instant crash reporting for iOS

iOS only

By default, our Xamarin NuGet package captures the C# stack trace when a crash happens on the C# layer, or it captures the native iOS crash report when a crash happens on the native layer. The package sends out the C# stack trace or the native iOS crash report on the next app launch.

To change the default behavior and allow our Xamarin NuGet package to send native formatted crash reports instantly, enable instant crash reporting using one of the following:

  • dynatrace.config.json configuration file. See Configuration file for more details on this file.
  • Configuration builder
  • Configuration dictionary
js
{ "ios": { "DTXApplicationId": "<insertApplicationID>", "DTXBeaconUrl": "<insertBeaconURL>", "DTXCrashReportingEnabled": true, "DTXInstantCrashReportingEnabled": true } }
c
using Dynatrace.Xamarin; Agent.Instance.Start(new ConfigurationBuilder("<insertBeaconURL>","<insertApplicationID>") .WithCertificateValidation(true) .WithCrashReporting(true) .WithInstantCrashReporting(true) .WithUserOptIn(true) .BuildConfiguration());
c
using Dynatrace.Xamarin; var configDict = new Dictionary<string, object>(); configDict.Add("DTXApplicationID", "<insertApplicationID>"); configDict.Add("DTXBeaconURL", "<insertBeaconURL>"); configDict.Add("DTXCrashReportingEnabled", true); configDict.Add("DTXInstantCrashReportingEnabled", true); Agent.Instance.Start(configDict);

After you enable instant crash reporting, you get crash reports in the format of a native crash report, not a stack trace like you would for a standard unhandled exception triggered on the C# layer.

Troubleshooting

If you can't resolve a problem, please contact Dynatrace ONE via an in-product chat. 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.

Dynatrace.Xamarin.Build.Android and iOS

The following error might occur in older Xamarin Android or iOS projects:

plaintext
Target DynatraceAndroidBuildVerify: dotnet "/tools/netcoreapp3.1/Dynatrace.Xamarin.Build.Android.dll" verify config="obj/Debug/assets/dynatrace.config.json" java="/Users/<user>/Library/Developer/Xamarin/jdk/microsoft_dist_openjdk_1.8.0.25/bin" dynatraceJar="/tools/java/instrumentor-cli-8.223.1.1003.jar" Could not execute because the specified command or file was not found.
plaintext
dotnet "/tools/netcoreapp3.1/Dynatrace.Xamarin.Build.iOS.dll" "Debug" Could not execute because the specified command or file was not found.

The Dynatrace Xamarin package MSBuild command can't resolve the package directory because the .csproj file references Dynatrace Xamarin package dependencies individually and not as a package.

To resolve the problem

  1. Open your Android or iOS .csproj file, and remove all Dynatrace Xamarin package .dll references. For example, remove the following code for iOS:
    xml
    <Reference Include="Dynatrace.Xamarin.Abstraction"> <HintPath>..\packages\Dynatrace.OneAgent.Xamarin.8.x.x.x\lib\xamarinios10\Dynatrace.Xamarin.Abstraction.dll</HintPath> </Reference> <Reference Include="Dynatrace.Xamarin.Binding.iOS"> <HintPath>..\packages\Dynatrace.OneAgent.Xamarin.8.x.x.x\lib\xamarinios10\Dynatrace.Xamarin.Binding.iOS.dll</HintPath> </Reference> <Reference Include="Dynatrace.Xamarin.iOS"> <HintPath>..\packages\Dynatrace.OneAgent.Xamarin.8.x.x.x\lib\xamarinios10\Dynatrace.Xamarin.iOS.dll</HintPath> </Reference>
  2. Add the Dynatrace Xamarin package reference to the .csproj file. Add the actual package version as the value of <Version>.
    xml
    <ItemGroup> <PackageReference Include="Dynatrace.OneAgent.Xamarin"> <Version>8.x.x.x</Version> </PackageReference> </ItemGroup>
  3. Rebuild your project.

Turn off Visual Studio Debugger for Android

Android only

If you notice that Dynatrace doesn't report crashes for Android apps to your environment, make sure that you're not using the debug option in Visual Studio.

  1. Right-click your Android project, and select Properties.

  2. Go to Android Options, and clear Enable developer instrumentation (debugging and profiling).

    Disable developer instrumentation

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.

Disposed WebRequestTiming object for Android

Android only

When you use the third-party modernhttpclient or modernhttpclient-updated library together with SSL pinning via the NativeMessageHandler, the following exception might occur:

plaintext
Cannot access a disposed object. Object name: 'Dynatrace.Xamarin.Binding.Android.WebRequestTiming'.

To resolve this issue, change the default Mono Garbage Collector bridge implementation from tarjan to new. Check this Microsoft blog post to learn about different Garbage Collectors and understand how to change them via the environment.txt file.

Related topics
  • Instrument Android apps

    Learn how to instrument mobile application monitoring on Android, how to customize instrumentation and more.

  • Instrument iOS apps

    Instrument mobile application monitoring for iOS apps, customize the auto-instrumentation, and capture additional data via manual instrumentation.