async ActivityTask DoFetchInternal(ActivityScope scope, bool forceRefresh)
        {
            fetching = true;
            bool hadError = false;

            do
            {
                statusText.Visibility = hadError ? ViewStates.Visible : ViewStates.Invisible;
                if (string.IsNullOrEmpty(StoredCredentials.Username) || string.IsNullOrEmpty(StoredCredentials.Password))
                {
                    SwitchLayoutPhase(LayoutPhase.Login);
                }
                if (currentLayoutPhase == LayoutPhase.Login)
                {
                    password.Text     = string.Empty;
                    StoredCredentials = await AcceptUserInputAsync();
                }
                rentals = new HubwayRentals(StoredCookies, StoredCredentials);
                SwitchLayoutPhase(LayoutPhase.Loading);
                hadError = !(await GetRentals(forceRefresh));
                if (hadError)
                {
                    StoredCredentials = new RentalCrendentials();
                }
            } while (hadError);
            fetching = false;
        }
示例#2
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IWorkContext context = (request.Properties.Get <IWorkContext>() ?? WorkContext.Empty)
                                   .WithTag(_tag);

            IEventLog eventLog = request.Properties.Get <IEventLog>() ?? NetEventSource.Log;

            var logDetails = new List <string>();

            logDetails.Add($"Method: {request.Method}");
            logDetails.Add($"Uri:{request.RequestUri}");

            if (request.Headers.Count() > 0)
            {
                logDetails.Add($"Headers: {request.Headers.Select(x => x.Key + "=" + x.Value).Aggregate(";")}");
            }

            try
            {
                using (var scope = new ActivityScope(context, string.Join(",", logDetails), eventLog))
                {
                    HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

                    logDetails.Add($"Response: StatusCode: {response.StatusCode}");
                    eventLog.Verbose(context, string.Join(",", logDetails));

                    return(response);
                }
            }
            catch (Exception ex)
            {
                eventLog.Error(context, string.Join(",", logDetails), ex);
                throw;
            }
        }
示例#3
0
        public void ScopeShouldChangeActivityId()
        {
            var initialActivityId = Trace.CorrelationManager.ActivityId;

            Console.WriteLine("Starting ID: {0}", initialActivityId);

            TraceSource source   = new TraceSource("testScope1Source");
            var         listener = source.Listeners.OfType <TestTraceListener>().First();

            listener.MethodCallInformation.Clear();

            source.TraceEvent(TraceEventType.Warning, 1, "A");
            using (var scope = new ActivityScope())
            {
                source.TraceEvent(TraceEventType.Warning, 2, "B");
            }
            source.TraceEvent(TraceEventType.Warning, 3, "C");

            var events = listener.MethodCallInformation;

            Assert.AreEqual(1, events[0].Id);
            Assert.AreEqual(initialActivityId, events[0].ActivityId);

            Assert.AreEqual(2, events[1].Id);
            Assert.AreNotEqual(initialActivityId, events[1].ActivityId, "Should be different activity ID");

            Assert.AreEqual(3, events[2].Id);
            Assert.AreEqual(initialActivityId, events[2].ActivityId, "Should be back to original activity ID");
        }
        public void ActivityNameForXmlListenersStrangeCharacters()
        {
            TraceSource source = new TraceSource("testScopeSource");
            var listener = source.Listeners.OfType<TestTraceListener>().First();
            listener.MethodCallInformation.Clear();
            string transferIn = "TransferIn";
            string start = "<";
            string transferOut = "TransferOut";
            string stop = "Stopping...";
            var activityName = "<";

            using (var scope = new ActivityScope(source, 11, 12, 13, 14, transferIn, start, transferOut, stop, activityName))
            {
                source.TraceEvent(TraceEventType.Warning, 2, "B");
            }

            var events = listener.MethodCallInformation;
            StringAssert.StartsWith(events[0].Message, transferIn);

            Console.WriteLine(string.Join(",", events[1].Data));
            Assert.AreEqual(1, events[1].Data.Length);
            Assert.IsInstanceOfType(events[1].Data[0], typeof(XPathNavigator));
            var navigator = (XPathNavigator)events[1].Data[0];
            var resolver = new XmlNamespaceManager(navigator.NameTable);
            resolver.AddNamespace("ns1", "http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord");
            resolver.AddNamespace("ns2", "http://schemas.microsoft.com/2006/08/ServiceModel/DictionaryTraceRecord");
            Assert.AreEqual(start, navigator.SelectSingleNode("/ns1:TraceRecord/ns1:Description", resolver).Value);
            Assert.AreEqual(activityName, navigator.SelectSingleNode("/ns1:TraceRecord/ns2:ExtendedData/ns2:ActivityName", resolver).Value);
            //StringAssert.Contains(events[1].Data[0].ToString(), activityName);
            //StringAssert.Contains(events[1].Data[0].ToString(), start);

            StringAssert.StartsWith(events[3].Message, transferOut);
            Assert.AreEqual(stop, events[4].Message);
        }
示例#5
0
        public async void FillUpMap(bool forceRefresh)
        {
            if (loading)
            {
                return;
            }
            loading = true;
            if (pane != null && pane.Opened)
            {
                pane.SetState(InfoPane.State.Closed, animated: false);
            }
            flashBar.ShowLoading();

            using (var scope = ActivityScope.Of(Activity))
                await DoFillUpMap(scope, forceRefresh);

            flashBar.ShowLoaded();
            showedStale = false;
            if (pendingSearchTerm != null)
            {
                OpenStationWithTerm(pendingSearchTerm);
                pendingSearchTerm = null;
            }
            loading = false;
        }
 public void ActivityScopeStopped(ActivitySource source, ref ActivityScope scope)
 {
     if (scope.Activity != null)
     {
         ActivitySourceListenerCompat.s_azureClientListener.Write(_stopEventName, scope.Activity);
     }
 }
示例#7
0
 public static void OnGlobalActivityEnded(ActivityScope globalActivityScope)
 {
     if (!ActivityCoverageReport.IsReportEnabled || globalActivityScope.ActivityType != ActivityType.Global)
     {
         return;
     }
     foreach (KeyValuePair <OperationKey, OperationStatistics> keyValuePair in globalActivityScope.Statistics)
     {
         OperationStatistics operationStatistics = null;
         if (ActivityCoverageReport.statistics.TryGetValue(keyValuePair.Key, out operationStatistics))
         {
             operationStatistics.Merge(keyValuePair.Value);
         }
         else
         {
             ActivityCoverageReport.statistics[keyValuePair.Key] = keyValuePair.Value;
         }
     }
     ActivityCoverageReport.currentActivityCycleCount++;
     if (ActivityCoverageReport.currentActivityCycleCount == ActivityCoverageReport.rollupActivityCycleCount)
     {
         ActivityCoverageReport.LogReport();
         ActivityCoverageReport.Clear();
     }
 }
        public virtual Response <ConfigurationSetting> Add(ConfigurationSetting setting, CancellationToken cancellationToken = default)
        {
            using ActivityScope scope = new ActivityScope(s_configClientAdd);
            scope.AddTag("key", setting?.Key);

            try
            {
                using Request request = CreateAddRequest(setting);
                Response response = _pipeline.SendRequest(request, cancellationToken);

                switch (response.Status)

                {
                case 200:
                case 201:
                    return(CreateResponse(response));

                default:
                    throw response.CreateRequestFailedException();
                }
            }
            catch (Exception e)
            {
                scope.SetStatus(e);
                throw;
            }
        }
示例#9
0
            public void CanDisposeRepeatedly()
            {
                var traceSource = new TraceSource(MethodBase.GetCurrentMethod().Name, SourceLevels.All);

                using (var context = new ActivityScope(traceSource, Guid.Empty))
                    context.Dispose();
            }
 private static void ChildTaskB(Barrier barrier, string expectedParentId)
 {
     using (var scopeB = new ActivityScope("Child task B", "CHILD-B-GUID")) {
         barrier.SignalAndWait();
         scopeB.ParentId.ShouldEqual(expectedParentId);
     }
 }
 public void ActivityScopeStarted(ActivitySource source, ref ActivityScope scope)
 {
     if (_sampleFunc(ref scope))
     {
         scope.EnsureActivityCreated().ActivityTraceFlags = System.Diagnostics.ActivityTraceFlags.Recorded;
     }
 }
示例#12
0
        internal static ActivityScope AddActivityScope(ActivityContextState activityContextState)
        {
            Guid          guid = Guid.NewGuid();
            ActivityScope result;

            using (DisposeGuard disposeGuard = default(DisposeGuard))
            {
                try
                {
                    ActivityScopeImpl.scopeCacheLock.EnterWriteLock();
                    ActivityScopeImpl activityScopeImpl = new ActivityScopeImpl(guid);
                    disposeGuard.Add <ActivityScopeImpl>(activityScopeImpl);
                    ActivityScopeImpl.scopeCache.Add(guid, activityScopeImpl);
                    ActivityScope activityScope = new ActivityScope(activityScopeImpl);
                    disposeGuard.Add <ActivityScope>(activityScope);
                    activityScopeImpl.UpdateFromState(activityContextState);
                    SingleContext.Singleton.LocalId = new Guid?(guid);
                    SingleContext.Singleton.SetId();
                    disposeGuard.Success();
                    result = activityScope;
                }
                finally
                {
                    try
                    {
                        ActivityScopeImpl.scopeCacheLock.ExitWriteLock();
                    }
                    catch (SynchronizationLockException)
                    {
                    }
                }
            }
            return(result);
        }
示例#13
0
        public void LogicalThenActivity()
        {
            var source = new TraceSource("Tests");

            using (var lScope = new LogicalOperationScope(source, "Process C"))
            {
                var sample2 = new SampleClass(source);

                using (var scope = new ActivityScope(source, "Login"))
                {
                    sample2.TraceEvent(TraceEventType.Verbose, 1, "Logged in!");
                }

                using (var scope = new ActivityScope(source, "Validate"))
                {
                    //var service = new TracingTests.ServiceReference1.Service1Client("BasicHttpBinding_IService1");

                    //service.DoWork();

                    sample2.TraceEvent(TraceEventType.Verbose, 2, "Request is Valid");
                }

                using (var scope = new ActivityScope(source, "Update"))
                {
                    sample2.TraceEvent(TraceEventType.Verbose, 3, "Record updating");

                    using (var scope1 = new ActivityScope(source, "COmmit"))
                    {
                        sample2.TraceEvent(TraceEventType.Verbose, 4, "Commit worked");
                    }
                }
            }
        }
示例#14
0
        public void ActivityThenLogical()
        {
            var source = GetTrace();

            using (var scope = new ActivityScope(source, "MultipleTracedClassTestScope"))
            {
                source.TraceEvent(TraceEventType.Information, 3, "Log entry 1");
                var sample1 = new SampleClass();

                sample1 = Extensions.Wrap <SampleClass>(sample1);

                var sample2 = new SampleClass();

                var oppId = "MyLogicalOpp";

                using (var lScope = new LogicalOperationScope(source, "MyLogicalScope"))
                {
                    sample1.Method1();
                    source.TraceEvent(TraceEventType.Information, 3, "Log entry 3");


                    using (var scope2 = new ActivityScope(source, "Sub Activity"))
                    {
                        using (var lScope1 = new LogicalOperationScope(source, "Scope 2"))
                            sample1.TraceInformation("test1");
                        sample2.TraceInformation("test2");
                    }
                }

                var listeners = sample2.Trace.Listeners;
                //var listener = listeners.OfType<TransactionTraceListener>().First();

                //var log = listener.GetTransaction();
            }
        }
 public void ActivityScopeStarted(ActivitySource source, ref ActivityScope scope)
 {
     if (ActivitySourceListenerCompat.s_azureClientListener.IsEnabled(_originalActivityName))
     {
         Activity a = scope.EnsureActivityCreated();
         ActivitySourceListenerCompat.s_azureClientListener.Write(_startEventName, a);
     }
 }
示例#16
0
 public void OneActivityWorkItemWithTags()
 {
     using (var scope = new ActivityScope(s_httpIn))
     {
         scope.AddTag("route", "/foo/bar");
         scope.AddTag("usedid", "1239");
     }
 }
示例#17
0
            public void ReturnActivityId()
            {
                var traceSource = new TraceSource(MethodBase.GetCurrentMethod().Name, SourceLevels.All);
                var activityId  = Guid.NewGuid();

                using (var context = new ActivityScope(traceSource, activityId))
                    Assert.Equal(activityId.ToString(), context.ToString());
            }
        public static void Start(ActivityScope scope)
        {
            var parent = ActivityStack.Any() ? ActivityStack.Peek() : null;

            if (parent != null)
                scope.ParentId = parent.Id;

            ActivityStack = ActivityStack.Push(scope);
        }
示例#19
0
        public void OneActivityWorkItemWithExternalParent()
        {
            ActivityContext parentContext = new ActivityContext();

            ParseActivityTraceId(incomingActivityId, ref parentContext);
            using (var scope = new ActivityScope(s_httpIn, parentContext))
            {
            }
        }
        public void ActivityScopeStopped(ActivitySource source, ref ActivityScope scope)
        {
            Activity a = scope.Activity;

            if (a != null)
            {
                LogCompletedActivity(a);
            }
        }
        public static void Start(ActivityScope scope)
        {
            ActivityScope parent = ActivityStack.Count > 0 ? ActivityStack.Peek() : null;

            if (parent != null)
                scope.ParentId = parent.Id;

            ActivityStack.Push(scope);
        }
示例#22
0
        async ActivityTask DoAsyncStuff(ActivityScope scope)
        {
            await Task.Delay(3000);             // Medium network call

            MyLabel(scope).Text = "Step 1";
            await Task.Delay(5000);             // Big network call

            MyLabel(scope).Text = "Step 2";
        }
示例#23
0
 async void LoadStationHistory(int stationID)
 {
     try {
         using (var scope = ActivityScope.Of(Activity))
             await DoLoadStationHistory(scope, stationID);
     } catch (Exception e) {
         AnalyticsHelper.LogException("HistoryFetcher", e);
         Android.Util.Log.Debug("HistoryFetcher", e.ToString());
     }
 }
示例#24
0
        async ActivityTask DoFillUpMap(ActivityScope scope, bool forceRefresh)
        {
            try {
                var stations = await hubway.GetStations(forceRefresh);
                await SetMapStationPins(stations);

                lastUpdateText.Text = "Last refreshed: " + DateTime.Now.ToShortTimeString();
            } catch (Exception e) {
                AnalyticsHelper.LogException("DataFetcher", e);
                Android.Util.Log.Debug("DataFetcher", e.ToString());
            }
        }
        static void Main(string[] args)
        {
            LoggingConfiguration.Current.UseNLog();

            _logger = LogManager.GetLogger("NLogSample");

            using (ActivityScope.New("Main Operation"))
            {
                _logger.LogTrace("preparing to do work");
                DoWork().Wait();
            }
        }
示例#26
0
        static void Main(string[] args)
        {
            var stopwatch = Stopwatch.StartNew();

            // Basic source
            var source = new TraceSource("SeqFrameworkDiagnostics.Example.Basic");

            source.TraceEvent(TraceEventType.Information, (int)ExampleEventId.StartExample, "Hello, {0}, from .NET Framework", Environment.UserName);
            source.TraceData(TraceEventType.Information, (int)ExampleEventId.DataTrace, "Data Item", 42.80D, Guid.NewGuid());

            source.TraceEvent(TraceEventType.Verbose, 0, "a={1} b={0}", "B", "A");

            // Detailed source
            var detailedSource = new TraceSource("SeqFrameworkDiagnostics.Example.Detailed");

            detailedSource.TraceEvent(TraceEventType.Warning, (int)ExampleEventId.DetailedWarning, "Sample detailed warning");

            // Logical operation stack context (using scope extension)
            using (var requestScope = new LogicalOperationScope(source, "Request 1234", (int)ExampleEventId.BeginRequest, (int)ExampleEventId.EndRequest, "Begin request", "End request"))
            {
                using (var transactionScope = new LogicalOperationScope("Transaction 5678"))
                {
                    source.TraceEvent(TraceEventType.Information, (int)ExampleEventId.LogicalOperationStackExample, "Sample with operation stack context {0}, {1}, {2}", 42, new DateTimeOffset(1973, 5, 14, 0, 0, 0, TimeSpan.FromHours(10)), "Fnord");
                }
            }

            // Activity ID & transfers (using scope extension)
            using (var activityScope = new ActivityScope(source))
            {
                source.TraceEvent(TraceEventType.Information, (int)ExampleEventId.ActivityTransferExample, "Correlation example with activity ID transfer");
            }

            // Fluent interface extensions
            ITraceLog <ExampleEventId> log = new AssemblyTraceLog <ExampleEventId, Program>();

            try
            {
                log.Information(ExampleEventId.FluentExample, "Fluent logging API, {0}", Environment.OSVersion);
                log.Verbose("About to throw exception");
                throw new DivideByZeroException();
            }
            catch (Exception ex)
            {
                log.Error(ExampleEventId.DivideException, ex, "Ooops!");
            }
            stopwatch.Stop();
            log.Verbose("Time {0:'P''T'hh'H'mm'M'ss'.'fff'S'}", stopwatch.Elapsed);
            log.Information(ExampleEventId.EndExample, "Done");

            Console.WriteLine("Done");
            Console.ReadKey();
        }
示例#27
0
        public void ScopeShouldWriteActivities()
        {
            var initialActivityId = Trace.CorrelationManager.ActivityId;

            Console.WriteLine("Starting ID: {0}", initialActivityId);

            TraceSource source   = new TraceSource("testScope1Source");
            var         listener = source.Listeners.OfType <TestTraceListener>().First();

            listener.MethodCallInformation.Clear();

            source.TraceEvent(TraceEventType.Warning, 1, "A");
            using (var scope = new ActivityScope(source, 11, 12, 13, 14))
            {
                source.TraceEvent(TraceEventType.Warning, 2, "B");
            }
            source.TraceEvent(TraceEventType.Warning, 3, "C");

            var events          = listener.MethodCallInformation;
            var innerActivityId = events[3].ActivityId;

            Assert.AreNotEqual(initialActivityId, innerActivityId, "Should be different activity ID");

            Assert.AreEqual(1, events[0].Id);
            Assert.AreEqual(initialActivityId, events[0].ActivityId);

            Assert.AreEqual(11, events[1].Id);
            Assert.AreEqual(TraceEventType.Transfer, events[1].EventType);
            Assert.AreEqual(initialActivityId, events[1].ActivityId);
            Assert.AreEqual(innerActivityId, events[1].RelatedActivityId);

            Assert.AreEqual(12, events[2].Id);
            Assert.AreEqual(TraceEventType.Start, events[2].EventType);
            Assert.AreEqual(innerActivityId, events[2].ActivityId);

            Assert.AreEqual(2, events[3].Id);
            Assert.AreEqual(TraceEventType.Warning, events[3].EventType);
            // Checked above
            //Assert.AreNotEqual(initialActivityId, events[3].ActivityId, "Should be different activity ID");

            Assert.AreEqual(13, events[4].Id);
            Assert.AreEqual(TraceEventType.Transfer, events[4].EventType);
            Assert.AreEqual(innerActivityId, events[4].ActivityId);
            Assert.AreEqual(initialActivityId, events[4].RelatedActivityId, "Should be transfer back to original ID");

            Assert.AreEqual(14, events[5].Id);
            Assert.AreEqual(TraceEventType.Stop, events[5].EventType);
            Assert.AreEqual(innerActivityId, events[5].ActivityId);

            Assert.AreEqual(3, events[6].Id);
            Assert.AreEqual(initialActivityId, events[6].ActivityId, "Should be back to original activity ID");
        }
示例#28
0
        /// <summary>
        /// Execute SQL and batch object
        /// </summary>
        /// <typeparam name="T">type to return</typeparam>
        /// <param name="context">execution context</param>
        /// <param name="factory">batch type factor</param>
        /// <returns>list of types</returns>
        public async Task <T> ExecuteBatch <T>(IWorkContext context, Func <IWorkContext, SqlDataReader, T> factory)
        {
            Verify.IsNotNull(nameof(context), context);
            Verify.IsNotNull(nameof(factory), factory);
            context = context.WithTag(_tag);

            SqlException saveEx = null;

            using (var conn = new SqlConnection(Configuration.ConnectionString))
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = Command;
                    cmd.CommandType = CommandType;
                    cmd.Parameters.AddRange(Parameters.Select(x => x.ToSqlParameter()).ToArray());

                    conn.Open();

                    for (int retry = 0; retry < _retryCount; retry++)
                    {
                        try
                        {
                            using (var scope = new ActivityScope(context, Command, ToolboxEventSource.Log))
                            {
                                using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
                                {
                                    return(factory(context, reader));
                                }
                            }
                        }
                        catch (SqlException sqlEx)
                        {
                            if (sqlEx.Number == _deadLockNumber)
                            {
                                saveEx = sqlEx;
                                await Task.Delay(TimeSpan.FromMilliseconds(_random.Next(10, 1000)));

                                continue;
                            }

                            ToolboxEventSource.Log.Error(context, sqlEx.Message, sqlEx);
                            throw;
                        }
                        catch (Exception ex)
                        {
                            ToolboxEventSource.Log.Error(context, ex.Message, ex);
                            throw;
                        }
                    }
                }

            throw new WorkException(_deadLockMessage, context, saveEx);
        }
示例#29
0
            public void FinalizerIgnoresContextInterleave()
            {
                var traceSource = new TraceSource(MethodBase.GetCurrentMethod().Name, SourceLevels.All);
                var finalizer   = typeof(ActivityScope).GetMethod("Finalize", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod);

                Trace.CorrelationManager.ActivityId = Guid.Empty;
                using (var context = new ActivityScope(traceSource, Guid.Empty))
                {
                    Trace.CorrelationManager.ActivityId = Guid.NewGuid();
                    finalizer.Invoke(context, null);
                    Trace.CorrelationManager.ActivityId = Guid.Empty;
                }
            }
        public static void End(ActivityScope scope)
        {
            if (Current == null)
                return;

            if (!ActivityStack.Any(scopeOnTheStack => scope.Id == scopeOnTheStack.Id))
                return;

            ActivityScope currentScope = ActivityStack.Pop();
            while(ActivityStack.Count > 0 && currentScope.Id != scope.Id) {
                currentScope = ActivityStack.Pop();
            }
        }
        private static async Task <HttpResponseMessage> InvokeWithNewScope(
            Func <Task <HttpResponseMessage> > continuation,
            string correlationScopeName, string correlationId)
        {
            using (var scope = ActivityScope.Create(correlationScopeName, correlationId))
            {
                var actionResult = await continuation();

                actionResult.Headers.Add(CorrelationIdHttpHeader, scope.Id);

                return(actionResult);
            }
        }
示例#32
0
 public static void Main(string[] args)
 {
     trace.TraceEvent(TraceEventType.Information, 1001, "Scope example started.");
     using (var logicalOperationScope = new LogicalOperationScope(string.Format("Transaction={0}", 1)))
     {
         using (var activityScope = new ActivityScope(trace, 0, 2001, 0, 3001))
         {
             trace.TraceEvent(TraceEventType.Warning, 4001, "Example warning.");
         }
     }
     trace.TraceEvent(TraceEventType.Information, 8001, "Scope example finished.");
     Console.ReadLine();
 }
示例#33
0
 public static void DoMagic(Request r)
 {
     using (var scope = new ActivityScope(s_requestActivity, ParseRequestFunc, r))
     {
         try
         {
             // do some work
         }
         catch (Exception e) // hopefully this is a more specific exception type related to the work being done
         {
             scope.SetStatus(e);
         }
     }
 }
示例#34
0
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            if (!launched)
            {
                launched = true;
                using (var scope = ActivityScope.Of(this))
                    await DoAsyncStuff(scope);
            }
        }
        public static void End(ActivityScope scope)
        {
            if (Current == null)
                return;

            if (ActivityStack.All(scopeOnTheStack => scope.Id != scopeOnTheStack.Id))
                return;

            ActivityScope currentScope;
            ActivityStack = ActivityStack.Pop(out currentScope);

            while(ActivityStack.Any() && currentScope.Id != scope.Id) {
                ActivityStack = ActivityStack.Pop(out currentScope);
            }
        }
        public void ScopeShouldWriteActivities()
        {
            var initialActivityId = Trace.CorrelationManager.ActivityId;
            Console.WriteLine("Starting ID: {0}", initialActivityId);

            TraceSource source = new TraceSource("inmemory1Source");
            var listener = source.Listeners.OfType<InMemoryTraceListener>().First();
            listener.Clear();

            source.TraceEvent(TraceEventType.Warning, 1, "A");
            using (var scope = new ActivityScope(source, 11, 12, 13, 14))
            {
                source.TraceEvent(TraceEventType.Warning, 2, "B");
            }
            source.TraceEvent(TraceEventType.Warning, 3, "C");

            var events = listener.GetEvents();
            var innerActivityId = events[3].ActivityId;
            Assert.AreNotEqual(initialActivityId, innerActivityId, "Should be different activity ID");

            Assert.AreEqual(1, events[0].Id);
            Assert.AreEqual(initialActivityId, events[0].ActivityId);

            Assert.AreEqual(11, events[1].Id);
            Assert.AreEqual(TraceEventType.Transfer, events[1].EventType);
            Assert.AreEqual(initialActivityId, events[1].ActivityId);
            Assert.AreEqual(innerActivityId, events[1].RelatedActivityId);

            Assert.AreEqual(12, events[2].Id);
            Assert.AreEqual(TraceEventType.Start, events[2].EventType);
            Assert.AreEqual(innerActivityId, events[2].ActivityId);

            Assert.AreEqual(2, events[3].Id);
            Assert.AreEqual(TraceEventType.Warning, events[3].EventType);
            // Checked above
            //Assert.AreNotEqual(initialActivityId, events[3].ActivityId, "Should be different activity ID");

            Assert.AreEqual(13, events[4].Id);
            Assert.AreEqual(TraceEventType.Transfer, events[4].EventType);
            Assert.AreEqual(innerActivityId, events[4].ActivityId);
            Assert.AreEqual(initialActivityId, events[4].RelatedActivityId, "Should be transfer back to original ID");

            Assert.AreEqual(14, events[5].Id);
            Assert.AreEqual(TraceEventType.Stop, events[5].EventType);
            Assert.AreEqual(innerActivityId, events[5].ActivityId);

            Assert.AreEqual(3, events[6].Id);
            Assert.AreEqual(initialActivityId, events[6].ActivityId, "Should be back to original activity ID");
        }
        public void AdditionalMessages()
        {
            TraceSource source = new TraceSource("testScopeSource");
            var listener = source.Listeners.OfType<TestTraceListener>().First();
            listener.MethodCallInformation.Clear();
            string transferIn = "TransferIn";
            string start = "Starting...";
            string transferOut = "TransferOut";
            string stop = "Stopping...";

            using (var scope = new ActivityScope(source, 11, 12, 13, 14, transferIn, start, transferOut, stop))
            {
                source.TraceEvent(TraceEventType.Warning, 2, "B");
            }

            var events = listener.MethodCallInformation;
            StringAssert.StartsWith(events[0].Message, transferIn);
            Assert.AreEqual(start, events[1].Message);
            StringAssert.StartsWith(events[3].Message, transferOut);
            Assert.AreEqual(stop, events[4].Message);
        }
            public void ReturnActivityId()
            {
                var traceSource = new TraceSource(MethodBase.GetCurrentMethod().Name, SourceLevels.All);
                var activityId = Guid.NewGuid();

                using (var context = new ActivityScope(traceSource, activityId))
                    Assert.Equal(activityId.ToString(), context.ToString());
            }
            public void CanDisposeRepeatedly()
            {
                var traceSource = new TraceSource(MethodBase.GetCurrentMethod().Name, SourceLevels.All);

                using (var context = new ActivityScope(traceSource, Guid.Empty))
                    context.Dispose();
            }
            public void CannotInterleaveActivityIds()
            {
                var activityId = Guid.NewGuid();
                var traceSource = new TraceSource(MethodBase.GetCurrentMethod().Name, SourceLevels.All);
                var context = new ActivityScope(traceSource, activityId);

                Trace.CorrelationManager.ActivityId = Guid.NewGuid();

                var ex = Assert.Throws<InvalidOperationException>(() => context.Dispose());
                Assert.Equal(Exceptions.ActivityIdModifiedInsideScope, ex.Message);

                Trace.CorrelationManager.ActivityId = activityId;

                context.Dispose();
            }
            public void FinalizerIgnoresContextInterleave()
            {
                var traceSource = new TraceSource(MethodBase.GetCurrentMethod().Name, SourceLevels.All);
                var finalizer = typeof(ActivityScope).GetMethod("Finalize", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod);

                Trace.CorrelationManager.ActivityId = Guid.Empty;
                using (var context = new ActivityScope(traceSource, Guid.Empty))
                {
                    Trace.CorrelationManager.ActivityId = Guid.NewGuid();
                    finalizer.Invoke(context, null);
                    Trace.CorrelationManager.ActivityId = Guid.Empty;
                }
            }
        public void ScopeShouldChangeActivityId()
        {
            var initialActivityId = Trace.CorrelationManager.ActivityId;
            Console.WriteLine("Starting ID: {0}", initialActivityId);

            TraceSource source = new TraceSource("inmemory1Source");
            var listener = source.Listeners.OfType<InMemoryTraceListener>().First();
            listener.Clear();

            source.TraceEvent(TraceEventType.Warning, 1, "A");
            using (var scope = new ActivityScope())
            {
                source.TraceEvent(TraceEventType.Warning, 2, "B");
            }
            source.TraceEvent(TraceEventType.Warning, 3, "C");

            var events = listener.GetEvents();

            Assert.AreEqual(1, events[0].Id);
            Assert.AreEqual(initialActivityId, events[0].ActivityId);

            Assert.AreEqual(2, events[1].Id);
            Assert.AreNotEqual(initialActivityId, events[1].ActivityId, "Should be different activity ID");

            Assert.AreEqual(3, events[2].Id);
            Assert.AreEqual(initialActivityId, events[2].ActivityId, "Should be back to original activity ID");
        }
 private static void ChildTaskB(Barrier barrier, string expectedParentId)
 {
     using (var scopeB = new ActivityScope("Child task B", "CHILD-B-GUID")) {
         barrier.SignalAndWait();
         scopeB.ParentId.ShouldEqual(expectedParentId);
     }
 }