• Home
  • How to use Dynatrace
  • RUM
  • Setup and configuration
  • Mobile apps
  • Development frameworks
  • Xamarin

Instrument mobile apps with Dynatrace Xamarin NuGet package

Dynatrace 1.214+

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
  • User tagging
  • Web requests
  • Crashes
  • Error reporting
  • Event reporting
  • Value reporting

Requirements

  • For Android:
    • Android 4.0.3+ (API level 15+)
    • Xamarin.Android SDK 10.1.x+
  • For iOS: iOS 9+
  • For Xamarin.Forms: .NET Standard 1.1+

Set up the package

The steps below describe how to set up the Dynatrace Xamarin NuGet package for your Xamarin app.

Step 1. 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. Search for Dynatrace.OneAgent.Xamarin from nuget.org, and select Add Package.
  3. Select the checkboxes of all the projects that you want to add the NuGet package to, and then select OK.

Step 2. 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.
  1. From the app settings, go to Instrumentation wizard, and then select Xamarin.
  2. Select Download dynatrace.config.json to get the configuration file.

If you don't see the Xamarin tab in the instrumentation wizard, you're using Dynatrace version 1.213 or earlier. As a workaround, create the dynatrace.config.json file manually using the information from Android or iOS instrumentation wizards.

Configuration file structure

Use the following code snippet as a template.

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

Never use the dot notation for the configuration file. Always write in full bracket style.

Step 3. Add the configuration file to your project

Add the dynatrace.config.json file that you've downloaded or created 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.

If you do not 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 are using the Debug build configuration, our package looks for a file named dynatraceDebug.config.json. If the package cannot find the configuration specific file, it used the default dynatrace.config.json file.

Step 4. Add the 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();

To enable the auto-instrumentation of web requests, see Set up HttpClient.

Xamarin.Forms

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 from 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 piece of 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.

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 } }

    Do not 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>") .WithDebugLogging(true) .WithCertificateValidation(true) .WithCrashReporting(true) .WithUserOptIn(true) .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

To create a custom action named Tap on Confirm, use the following code. LeaveAction closes the action.

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.

For information on user action naming for Android, see User action naming.

For iOS, auto-instrumentation captures the title from UIButton by calling the following objects and stopping when valid text is received: titleLabel.attributedText, attributedTitleForState:UIControlStateNormal, and accessibilityLabel. If none of these produce usable text, the default value is set to Button.

To report values for a custom action before closing it, see Report a value.

Create child actions

You can create a standalone custom action as well as child actions. The Tap on Confirm again action is automatically put under the Tap on Confirm action. As long as the Tap on Confirm action is open, it gathers all the web requests.

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.

Set up HttpClient

To enable the auto-instrumentation of web requests, use the following method:

c
using Dynatrace.Xamarin; HttpClient httpClient = new HttpClient(); Agent.Instance.SetupHttpClient(httpClient);

Every HttpClient passed to this function gets an additional handler that takes care of the manual web request instrumentation. All other available functions behave the same as their native counterparts.

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(); 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);

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

Android only When you use automated crash reporting, Visual Studio might catch the exception before OneAgent does. If you notice that Dynatrace does not report crashes to your environment, make sure that you are not using the debug option in Visual Studio. Otherwise, the debugger catches the crash, and nothing is reported to your Dynatrace environment.

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);

When you use the ReportCrash and ReportCrashWithException API calls to report a crash, it forces the session to be completed. Any subsequent actions are included in a new user session.

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");

End a session

You can force a session to end via the API call. This also closes all open actions.

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);

Native 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" } }

Build debug logs

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

Troubleshooting

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

If you use the manual startup, do not include the beacon URL and the application ID properties to the configuration file. If you do that, you encounter an exception.

Dynatrace.Xamarin.Build.iOS

The following error can occur in older Xamarin iOS projects:

plaintext
dotnet "/tools/netcoreapp2.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 iOS .csproj file, and remove all Dynatrace Xamarin package .dll references.
    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>.
    plaintext
    <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 projects

If you notice that crashes on Android devices are not reported to your environment, make sure that you are 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.

Contact Dynatrace ONE

If you're unable to resolve a problem, contact Dynatrace ONE via an in-product chat. Have the following details available:

  • Logs from OneAgent
  • Your dynatrace.config.json file
Related topics
  • Instrument Android apps

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

  • Instrument iOS apps

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