Monitor Integration in .NET

This article will describe how to integrate the Analytics .NET monitor in any full .NET application. For instructions for other .NET platform (WinRT, Silverlight, Compact Framework etc), please see the article on integration on All Platforms.

The integration consists of three steps:

  1. Add the monitor assembly to your application
  2. Create and start the monitor

Before getting started you must also have created an application so you have a product id. You will need that in the integration. Read more about how to Add Analytics to Your Application.

Requirements

These are the requirements for adding Analytics into your .NET app:

  • .NET platform: minimum .NET 2.0

Step 1: Add the monitor assembly to your application

Download the monitor for your application and unzip the downloaded monitor file to your machine.

In your Visual Studio solution, go to the project and reference the assembly from your project. For C# projects you should right-click on the References item, select Add Reference and for VB.NET projects you should go to the Properties of your project, go to References and click the Add button. In the Reference Manager dialog, click Browse i and navigate to the unzipped EQATEC.Analytics.Monitor.dll.

Once referenced, try to Build your project again. If it builds without problems then proceed to Step 2. If the build fails, make sure that you have downloaded the monitor for the correct platform.

Referencing the assembly may fail with "A reference to a higher version or incompatible assembly cannot be added to the project" because downloaded assemblies can been deemed unsafe by Window and be blocked. The solution is to right-click on the unpacked monitor file, select Properties, and click Unblock. See also http://pcmusings.wordpress.com/2012/10/31/vs2012-windows-phone-and-the-reference-to-a-higher-version-error/

Step 2: Create and start the monitor

By now you have just added a reference to the assembly but have not referenced anything from this assembly. Your next step is creating and the starting the monitor, as described in the Monitor Integration article. After that, when running your application, you will see data from it appear in the Analytics client dashboard.

Precisely how you wish to use the monitor into your source is up to you and your coding-preferences. Your app needs to create a monitor instance and it needs to call Start and Stop on that object and later on you will most likely want to call other API methods on it, too.

Use a Singleton pattern for the monitor

The simplest approach to get started is to add the monitor as a singleton object within your application. It will handle the creation of the monitor and make it accessible from all over you application. The singleton object will ensure that only a single instance of the monitor will exist within your application and this instance is accessible.

You might prefer not to expose the monitor using a singleton pattern in your application in which case you can easily construct and expose the IAnalyticsMonitor interface as part of e.g. your IoC containers setup or other mechanisms.

Here is an example of a singleton class that can be dropped into your project and which exposes the monitor instance via the Analytics.Instance static property.

    public sealed class Analytics
    {
      public IAnalyticsMonitor Monitor { get; private set; }
      private const string s_productId = "YOUR-PRODUCT-KEY";
      private static readonly Analytics instance = new Analytics();
      static Analytics() {}
      private Analytics() 
      {
        var settings = AnalyticsMonitorFactory.CreateSettings(s_productId);
        settings.LoggingInterface = AnalyticsMonitorFactory.CreateTraceMonitor();
        // Modify settings here, if needed. For instance
        // settings.TestMode = true;
        // settings.UseSSL = true;
        Monitor = AnalyticsMonitorFactory.Create(settings);
      }
      public static IAnalyticsMonitor Instance
      {
        get { return instance.Monitor; }
      }
    }
    Public NotInheritable Class Analytics
    Public Property Monitor() As IAnalyticsMonitor
        Get
            Return m_Monitor
        End Get
        Private Set
            m_Monitor = Value
        End Set
    End Property
    Private m_Monitor As IAnalyticsMonitor
    Private Const s_productId As String = "YOUR-PRODUCT-KEY"
    Private Shared ReadOnly m_instance As New Analytics()
    Shared Sub New()
    End Sub
    Private Sub New()
        Dim settings = AnalyticsMonitorFactory.CreateSettings(s_productId)
        settings.LoggingInterface = AnalyticsMonitorFactory.CreateTraceMonitor()
        ' Modify settings here, if needed. For instance
        ' settings.TestMode = true;
        ' settings.UseSSL = true;
        Monitor = AnalyticsMonitorFactory.Create(settings)
    End Sub
    Public Shared ReadOnly Property Instance() As IAnalyticsMonitor
        Get
            Return m_instance.Monitor
        End Get
    End Property
    End Class

Starting and using the monitor

You can now use the Analytics singleton object and to start using the monitor you simply need to call the Start method to begin the tracking and the Stop method to stop the tracking. These calls control the monitor life cycle and should typically be closely aligned to the starting and stopping of your own application.

You must perform these calls from within your own application code and the location where you would typically place these calls are dependent upon the type of application you are creating. The following examples illustrate typical locations where you could integrate and call the Start and Stop methods from your software dependent on your project type:

Note that the examples shown below all make use of the singleton pattern suggested above to access the created monitor instance. Also note that the examples include recommended tracking of unhandled exception within your application.

Console application

Console applications are encapsulated by the Main method, so the immediate way to control the lifetime of your monitor would be to surround your existing application with calls to Start and Stop.

    class Program
      {
        static void Main(string[] args)
        {
          try
          {
            //Starting the monitor when the application starts
            Analytics.Instance.Start();

            // Recommended to always track unhandled exceptions
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
              Analytics.Instance.TrackException(e.ExceptionObject as Exception,
                                                "AppDomain.UnhandledException");
            };


            //Your regular application startup logic

          }
          finally
          {
            //Stopping the monitor as your application stops
            Analytics.Instance.Stop();       
          }
        }
      }
    Imports EQATEC.Analytics.Monitor

    Module Module1
        Sub Main()
            Try
                'Starting the monitor when the application starts
                Analytics.Instance.Start()

                'Recommended to always track unhandled exceptions
                AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf TrackUnhandledException

                'Your regular application startup logic

            Finally
                'Stopping the monitor as your application stops
                Analytics.Instance.Stop()
            End Try
        End Sub

        Private Sub TrackUnhandledException(ByVal sender As Object,
                                            ByVal args As UnhandledExceptionEventArgs)
            Analytics.Instance.TrackException(TryCast(args.ExceptionObject, Exception),
                                              "AppDomain.UnhandledException")
        End Sub
    End Module

Winforms application

Winform applications are typically started by running the event loop on the main form using the Application.Run method from within the Main method which runs until this main form is closed. The immediate way to control the lifetime of your monitor would be to surround your existing start of the event loop with calls to Start and Stop for C# and by hooking into the My.Application events for VB.NET.

    class Program
      {
        [STAThread]
        static void Main()
        {
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);

          try
          {
            //Starting the monitor when the application starts
            Analytics.Instance.Start();

            // Recommended to always track unhandled exceptions
            AppDomain.CurrentDomain.UnhandledException +=
               (s, e) => Analytics.Instance.TrackException(e.ExceptionObject as Exception,
                                                           "AppDomain.UnhandledException");
            Application.ThreadException +=
               (s, e) => Analytics.Instance.TrackException(e.Exception,
                                                           "Application.ThreadException");

            Application.Run(new Form1());
          }
          finally
          {
            //Stopping the monitor as your application stops
            Analytics.Instance.Stop();
          }
        }
      }
    Namespace My
        Partial Friend Class MyApplication

            Private Sub MyApplication_Startup(ByVal sender As Object,
                                   ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs)
                                   Handles Me.Startup
                Analytics.Instance.Start()
            End Sub

            Private Sub MyApplication_Shutdown(ByVal sender As Object,
                                               ByVal e As System.EventArgs) Handles Me.Shutdown
                Analytics.Instance.Stop()
            End Sub

            Private Sub MyApplication_UnhandledException(ByVal sender As Object,
                        ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs)
                        Handles Me.UnhandledException
                Analytics.Instance.TrackException(e.Exception, "UnhandledException")
            End Sub


        End Class

    End Namespace

WPF applications

WPF applications are started from the App or Application class in your project which allows you to override the OnStartup and OnExit virtual methods. These server as appropriate places to control the monitor life cycle.

    public partial class App : Application
      {
        protected override void OnExit(ExitEventArgs e)
        {
          base.OnExit(e);

          Analytics.Instance.Stop();
        }

        protected override void OnStartup(StartupEventArgs sea)
        {
          base.OnStartup(sea);

          Analytics.Instance.Start();
          AppDomain.CurrentDomain.UnhandledException +=
                 (s, e) => Analytics.Instance.TrackException(e.ExceptionObject as Exception,
                                                             "AppDomain.UnhandledException");
          DispatcherUnhandledException +=
                 (s, e) => Analytics.Instance.TrackException(e.Exception,
                                                             "DispatcherUnhandledException");
        }
      }
    Class Application

        Protected Overrides Sub OnExit(e As ExitEventArgs)
            MyBase.OnExit(e)

            Analytics.Instance.Start()
        End Sub

        Protected Overrides Sub OnStartup(e As StartupEventArgs)
            MyBase.OnStartup(e)

            Analytics.Instance.Start()
            AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf TrackUnhandledException
            AddHandler DispatcherUnhandledException, AddressOf TrackDispatcherUnhandledException

        End Sub

        Private Sub TrackUnhandledException(ByVal sender As Object,
                                            ByVal args As UnhandledExceptionEventArgs)
            Analytics.Instance.TrackException(TryCast(args.ExceptionObject, Exception),
                                              "AppDomain.UnhandledException")
        End Sub

        Private Sub TrackDispatcherUnhandledException(sender As Object,
                                e As System.Windows.Threading.DispatcherUnhandledExceptionEventArgs)
            Analytics.Instance.TrackException(e.Exception, "DispatcherUnhandledException")
        End Sub

    End Class

Windows Service applications

Windows Services are executed by the Service Control Manager and are at their root implemented as classes deriving from the ServiceBase class. These classes allow you override the OnStart and OnStop methods that signal the service starting and stopping respectively. These methods fit the mold of controlling the monitor life cycle.

    public partial class Service1 : ServiceBase
      {
        public Service1()
        {
          InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
          //Starting the monitor when the application starts
          Analytics.Instance.Start();

          // Recommended to always track unhandled exceptions
          AppDomain.CurrentDomain.UnhandledException +=
                (s, e) => Analytics.Instance.TrackException(e.ExceptionObject as Exception,
                                                            "AppDomain.UnhandledException");
        }

        protected override void OnStop()
        {
          Analytics.Instance.Stop();
        }
      }
    Public Class Service1

        Protected Overrides Sub OnStart(ByVal args() As String)
            Analytics.Instance.Start()
            AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf TrackUnhandledException
        End Sub

        Protected Overrides Sub OnStop()
            Analytics.Instance.Stop()
        End Sub

        Private Sub TrackUnhandledException(ByVal sender As Object,
                                            ByVal args As UnhandledExceptionEventArgs)
            Analytics.Instance.TrackException(TryCast(args.ExceptionObject, Exception),
                                              "AppDomain.UnhandledException")
        End Sub
    End Class

Conclusion

After completing the integration steps in this guide, Analytics should be integrated into your application. When you run it, you should see data within 5 minutes on the Analytics client dashboard. If not then please check the article on Your First Data.

See Also

Start a free trial Request a demo
Contact us: +1-888-365-2779
sales@telerik.com
Copyright © 2016-2017, Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.