private void Application_EndRequest(object sender, EventArgs e)
        {
            AspNetTelemetryCorrelationEventSource.Log.TraceCallback("Application_EndRequest");

            var context = ((HttpApplication)sender).Context;

            // EndRequest does it's best effort to notify that request has ended
            // BeginRequest has never been called
            if (!context.Items.Contains(BeginCalledFlag))
            {
                // Activity has never been started
                var activity = ActivityHelper.CreateRootActivity(context);
                ActivityHelper.StopAspNetActivity(activity, context);
            }
            else
            {
                var activity = (Activity)context.Items[ActivityHelper.ActivityKey];

                // try to stop activity if it's in the Current stack
                if (!ActivityHelper.StopAspNetActivity(activity, context))
                {
                    // Activity we created was lost, let's report it
                    if (activity != null)
                    {
                        ActivityHelper.StopLostActivity(activity, context);
                    }
                }
            }
        }
        private void Application_EndRequest(object sender, EventArgs e)
        {
            AspNetTelemetryCorrelationEventSource.Log.TraceCallback("Application_EndRequest");

            var context = ((HttpApplication)sender).Context;

            // EndRequest does it's best effort to notify that request has ended
            // BeginRequest has never been called
            if (!context.Items.Contains(BeginCalledFlag))
            {
                // Activity has never been started
                var activity = ActivityHelper.CreateRootActivity(context, ParseHeaders);
                ActivityHelper.StopAspNetActivity(activity, context.Items);
            }
            else
            {
                var activity = (Activity)context.Items[ActivityHelper.ActivityKey];

                // try to stop activity if it's in the Current stack
                // stop all running Activities on the way
                if (!ActivityHelper.StopAspNetActivity(activity, context.Items))
                {
                    // perhaps we attempted to restore the Activity before
                    var restoredActivity = (Activity)context.Items[ActivityHelper.RestoredActivityKey];
                    if (restoredActivity != null)
                    {
                        // if so, report it
                        ActivityHelper.StopRestoredActivity(restoredActivity, context);
                    }

                    // Activity we created was lost let's report it
                    if (activity != null)
                    {
                        ActivityHelper.StopLostActivity(activity, context);
                    }
                }
            }
        }