Concrete implementation of IActivityMonitor.
        void Create()
        {
            {
                var m = new ActivityMonitor();
            }
            {
                var m = new ActivityMonitor( applyAutoConfigurations: false );
            }
            {
                IActivityMonitor m = new ActivityMonitor();
                var counter = new ActivityMonitorErrorCounter();
                m.Output.RegisterClient( counter );

                m.Fatal().Send( "An horrible error occurred." );

                Assert.That( counter.Current.FatalCount == 1 );
                m.Output.UnregisterClient( counter );
            }
            {
                IActivityMonitor m = new ActivityMonitor();

                int errorCount = 0;
                using( m.OnError( () => ++errorCount ) )
                {
                    m.Fatal().Send( "An horrible error occurred." );
                }
                Assert.That( errorCount == 1 );
            }
            {
                IActivityMonitor m = new ActivityMonitor();
                m.MinimalFilter = LogFilter.Off;
                // ...
                m.MinimalFilter = LogFilter.Debug;
            }
            {
                IActivityMonitor m = new ActivityMonitor();
                m.MinimalFilter = LogFilter.Terse;
                using( m.SetMinimalFilter( LogFilter.Debug ) )
                {
                    Assert.That( m.ActualFilter == LogFilter.Debug );
                }
                Assert.That( m.ActualFilter == LogFilter.Terse, "Filter has been restored to previous value." );
            }
            {
                IActivityMonitor m = new ActivityMonitor();
                m.MinimalFilter = LogFilter.Off;
                // ...
                using( m.OpenWarn().Send( "Ouch..." ) )
                {
                    Assert.That( m.ActualFilter == LogFilter.Off );
                    m.MinimalFilter = LogFilter.Debug;
                    // ... in debug filter ...
                }
                Assert.That( m.ActualFilter == LogFilter.Off, "Back to Off." );

                var strange = new LogFilter( LogLevelFilter.Fatal, LogLevelFilter.Trace );
            }
        }
Ejemplo n.º 2
0
 public static List<StupidStringClient> ReadAllLogs( DirectoryInfo folder, bool recurse )
 {
     List<StupidStringClient> logs = new List<StupidStringClient>();
     ReplayLogs( folder, recurse, mon =>
     {
         var m = new ActivityMonitor( false );
         logs.Add( m.Output.RegisterClient( new StupidStringClient() ) );
         return m;
     }, TestHelper.ConsoleMonitor );
     return logs;
 }
Ejemplo n.º 3
0
        private static void DuplicateTestWith6Entries( int nbEntries1, int nbEntries2, bool gzip = false )
        {
            var folder = String.Format( "{0}\\ReadDuplicates", TestHelper.TestFolder );
            TestHelper.CleanupFolder( folder );
            string config = String.Format( @"
<GrandOutputConfiguration>
    <Channel>
        <Add Type=""BinaryFile"" Name=""All-1"" MaxCountPerFile=""{1}"" Path=""{0}"" UseGzipCompression=""{3}"" /> 
        <Add Type=""BinaryFile"" Name=""All-2"" MaxCountPerFile=""{2}"" Path=""{0}"" UseGzipCompression=""{3}"" /> 
    </Channel>
</GrandOutputConfiguration>
", folder, nbEntries1, nbEntries2, gzip );

            using( var o = new GrandOutput() )
            {
                GrandOutputConfiguration c = new GrandOutputConfiguration();
                Assert.That( c.Load( XDocument.Parse( config ).Root, TestHelper.ConsoleMonitor ), Is.True );
                Assert.That( o.SetConfiguration( c, TestHelper.ConsoleMonitor ), Is.True );

                var m = new ActivityMonitor();
                o.Register( m );
                var direct = m.Output.RegisterClient( new CKMonWriterClient( folder, Math.Min( nbEntries1, nbEntries2 ), LogFilter.Debug, gzip ) );
                // 6 traces that go to the GrandOutput but also to the direct CKMonWriterClient.
                m.Trace().Send( "Trace 1" );
                m.OpenTrace().Send( "OpenTrace 1" );
                m.Trace().Send( "Trace 1.1" );
                m.Trace().Send( "Trace 1.2" );
                m.CloseGroup();
                m.Trace().Send( "Trace 2" );
                System.Threading.Thread.Sleep( 100 );
                m.Output.UnregisterClient( direct );
            }
            var files = TestHelper.WaitForCkmonFilesInDirectory( folder, 3 );
            for( int pageReadLength = 1; pageReadLength < 10; ++pageReadLength )
            {
                MultiLogReader reader = new MultiLogReader();
                reader.Add( files );
                var map = reader.GetActivityMap();
                Assert.That( map.ValidFiles.All( rawFile => rawFile.IsValidFile ), Is.True, "All files are correctly closed with the final 0 byte and no exception occurred while reading them." );

                var readMonitor = map.Monitors.Single();

                List<ParentedLogEntry> allEntries = new List<ParentedLogEntry>();
                using( var pageReader = readMonitor.ReadFirstPage( pageReadLength ) )
                {
                    do
                    {
                        allEntries.AddRange( pageReader.Entries );
                    }
                    while( pageReader.ForwardPage() > 0 );
                }
                CollectionAssert.AreEqual( new[] { "Trace 1", "OpenTrace 1", "Trace 1.1", "Trace 1.2", null, "Trace 2" }, allEntries.Select( e => e.Entry.Text ).ToArray(), StringComparer.Ordinal );
            }
        }
        public void FilteringBySource()
        {
            TestHelper.CleanupFolder( SystemActivityMonitor.RootLogPath + "FilteringBySource" );

            using( GrandOutput g = new GrandOutput() )
            {
                GrandOutputConfiguration config = new GrandOutputConfiguration();
                config.Load( XDocument.Parse( @"
<GrandOutputConfiguration>
    <Channel MinimalFilter=""Debug"">
        <Add Type=""BinaryFile"" Name=""All"" Path=""FilteringBySource"" />
        <Channel Name=""HiddenTopic"" MinimalFilter=""Off"" TopicRegex=""(hidden\s+topic|hide\s+this\s+topic)"" MatchOptions=""CultureInvariant, ExplicitCapture, Compiled, Multiline"" />
    </Channel>
    <SourceOverrideFilter>
        <Add File=""SourceFile-Debug.cs"" Filter=""Debug"" />
        <Add File=""SourceFile-Off.cs"" Filter=""Off"" />
        <Add File=""SourceFile-Strange.cs"" Filter=""{Trace,Fatal}"" />
    </SourceOverrideFilter>
</GrandOutputConfiguration>", LoadOptions.SetLineInfo ).Root, TestHelper.ConsoleMonitor );

                Assert.That( g.SetConfiguration( config, TestHelper.ConsoleMonitor ) );

                var m = new ActivityMonitor( false );
                g.Register( m );

                m.Fatal( fileName: "SourceFile-Off.cs" ).Send( "NOSHOW" );
                m.SetTopic( "This is a hidden topic..." );
                m.Trace( 0, "SourceFile-Debug.cs" ).Send( "Trace-1" );
                m.Trace().Send( "NOSHOW" );
                m.SetTopic( "Please, hide this topic!" );
                m.Trace( fileName: "SourceFile-Strange.cs" ).Send( "NOSHOW" );
                using( m.OpenTrace( fileName: "SourceFile-Strange.cs" ).Send( "Trace-2" ) )
                {
                    m.Trace( fileName: "SourceFile-Strange.cs" ).Send( "NOSHOW" );
                    m.Fatal( fileName: "SourceFile-Strange.cs" ).Send( "Fatal-1" );
                    m.Fatal( fileName: "SourceFile-Off.cs" ).Send( "NOSHOW" );
                }
                m.SetTopic( null );
                m.Trace( fileName: "SourceFile-Strange.cs" ).Send( "NOSHOW" );
                m.Fatal( fileName: "SourceFile-Off.cs" ).Send( "NOSHOW" );
                m.Trace().Send( "Trace-3" );
            }
            List<StupidStringClient> logs = TestHelper.ReadAllLogs( new DirectoryInfo( SystemActivityMonitor.RootLogPath + "FilteringBySource" ), false );
            Assert.That( logs.Count, Is.EqualTo( 1 ) );
            Assert.That( logs[0].ToString(), Does.Not.Contain( "NOSHOW" ) );
            var texts = logs[0].Entries.Select( e => e.Text ).ToArray();
            CollectionAssert.AreEqual( new string[] { 
                "Trace-1", 
                "Trace-2", 
                "Fatal-1", 
                ActivityMonitor.SetTopicPrefix, 
                "Trace-3", 
            }, texts, StringComparer.Ordinal );
        }
Ejemplo n.º 5
0
        public ActionResult AddKeyboard( KeyboardModel keyboard )
        {
            IActivityMonitor m = new ActivityMonitor();

            KeyboardPostError err = KeyboardPostError.None;

            string uploadedFolderPath = AppSettings.Default.GetRequired<string>( "UploadFolderPath" );

            using( m.OpenInfo().Send( "Try AddKeyboard" ) )
            {
                if( ModelState.IsValid )
                {
                    if( Request.Files.Count > 0 )
                    {
                        string filePath = Path.Combine( uploadedFolderPath, String.Format( "{0}-{1}", keyboard.Name, Guid.NewGuid() ) );
                        Request.Files[0].SaveAs( filePath );

                        using( m.OpenInfo().Send( "Sending Keyboard submitted mail to {0}", DestinationEmail ) )
                        {
                            var model = new KeyboardSubmittedMailModel()
                            {
                                Name = keyboard.Name,
                                Description = keyboard.Description,
                                Email = keyboard.Email,
                                Author = keyboard.Author
                            };
                            try
                            {
                                IMailerService mailer = new CK.Mailer.DefaultMailerService( activityLogger: m );
                                mailer.SendMail( model, new RazorMailTemplateKey( "KeyboardSubmitted" ), new Recipient( DestinationEmail ) );
                            }
                            catch( Exception ex )
                            {
                                m.Error().Send( ex, "Email : {0}, Subject : {1}, Name : {2}, Description : {3}, Author : {4}",
                                    model.Email, model.Subject, model.Name, model.Description, model.Author );
                            }
                        }

                    }
                    else
                    {
                        err = KeyboardPostError.MissingPicture;
                        m.Error().Send( "Missing file." );
                    }
                }
                else
                {
                    err = KeyboardPostError.InvalidForm;
                    m.Error().Send( "InvalidForm" );
                }
                return Json( new { valid = false, error = err, keyboard = keyboard } );
            }
        }
Ejemplo n.º 6
0
        public void ApplyEmptyAndDefaultConfig()
        {
            TestHelper.CleanupFolder( SystemActivityMonitor.RootLogPath + "ApplyEmptyAndDefaultConfig" );

            using( GrandOutput g = new GrandOutput() )
            {
                var m = new ActivityMonitor( false );
                g.Register( m );
                m.Trace().Send( "NoShow-1" );
                Assert.That( g.SetConfiguration( new GrandOutputConfiguration(), TestHelper.ConsoleMonitor ) );
                m.Trace().Send( "NoShow-2" );
                Assert.That( g.SetConfiguration( CreateDefaultConfig( "ApplyEmptyAndDefaultConfig" ), TestHelper.ConsoleMonitor ) );
                m.Trace().Send( "Show-1" );
                Assert.That( g.SetConfiguration( new GrandOutputConfiguration(), TestHelper.ConsoleMonitor ) );
                m.Trace().Send( "NoShow-3" );
            }
            var replayed = new ActivityMonitor( false );
            var c = replayed.Output.RegisterClient( new StupidStringClient() );
            TestHelper.ReplayLogs( new DirectoryInfo( SystemActivityMonitor.RootLogPath + "ApplyEmptyAndDefaultConfig" ), true, mon => replayed, TestHelper.ConsoleMonitor );
            CollectionAssert.AreEqual( new[] { "<Missing log data>", "Show-1" }, c.Entries.Select( e => e.Text ), StringComparer.OrdinalIgnoreCase );
        }
        public ActionResult Support( SupportEmailViewModel model )
        {
            IActivityMonitor m = new ActivityMonitor();
            if( ModelState.IsValid )
            {
                using (m.OpenInfo().Send( "Sending Support mail to {0}", ConfigurationManager.AppSettings.Get( "DestinationEmail" ) ))
                {
                    try
                    {
                        IMailerService mailer = new DefaultMailerService( m );
                        mailer.SendMail( model, new RazorMailTemplateKey( "SupportEmail" ), new Recipient( ConfigurationManager.AppSettings.Get( "DestinationEmail" ) ) );
                    }
                    catch (Exception ex)
                    {
                        m.Error().Send( ex, "Email : {0}, Subject : {1}, Body : {2}", model.Email, model.Subject, model.Body );
                        return PartialView( "_EmailNotSent." + RouteData.Values["culture"], model );
                    }
                }

                return PartialView( "_EmailSent." + RouteData.Values["culture"] );
            }
            return PartialView( "_Form." + RouteData.Values["culture"], model );
        }
 /// <summary>
 /// Starts a dependent activity. This sets the <see cref="ActivityMonitor.DependentToken.Topic"/> if it is not null and opens a group
 /// tagged with <see cref="ActivityMonitor.Tags.StartDependentActivity"/> with a message that can be parsed back thanks to <see cref="ActivityMonitor.DependentToken.TryParseStartMessage"/>.
 /// </summary>
 /// <param name="this">This <see cref="IActivityMonitor"/>.</param>
 /// <param name="token">Token that describes the origin of the activity.</param>
 /// <param name="fileName">Source file name of the emitter (automatically injected by C# compiler but can be explicitly set).</param>
 /// <param name="lineNumber">Line number in the source file (automatically injected by C# compiler but can be explicitly set).</param>
 /// <returns>A disposable object. It must be disposed at the end of the activity.</returns>
 static public IDisposable StartDependentActivity( this IActivityMonitor @this, ActivityMonitor.DependentToken token, [CallerFilePath]string fileName = null, [CallerLineNumber]int lineNumber = 0 )
 {
     if( token == null ) throw new ArgumentNullException( "token" );
     return ActivityMonitor.DependentToken.Start( token, @this, fileName, lineNumber );
 }
Ejemplo n.º 9
0
        public void CKMonWriterClientTest()
        {
            TestHelper.CleanupTestFolder();
            using( TextWriter w = new StringWriter() )
            {
                var m = new ActivityMonitor();
                m.Output.RegisterClient( new ActivityMonitorTextWriterClient( s => w.Write( s ) ) );
                m.Output.RegisterClient( new ActivityMonitorErrorCounter( true ) );

                using( m.OpenWarn().Send( "First" ) )
                {
                    m.Info().Send( "Inner first test" );
                }

                w.Flush();
                Assert.That( w.ToString(), Is.Not.Empty );
                Assert.That( w.ToString(), Is.StringContaining( "First" ) );
                Assert.That( w.ToString(), Is.StringContaining( "Inner first test" ) );
                Assert.That( w.ToString(), Is.Not.StringContaining( "Second" ) );
                Assert.That( w.ToString(), Is.Not.StringContaining( "Inner second test" ) );


                m.Output.RegisterClient( new CKMonWriterClient( Path.Combine( TestHelper.TestFolder, "CKMonWriterClientTest" ), 20000, LogFilter.Undefined ) );

                using( m.OpenWarn().Send( "Second" ) )
                {
                    m.Info().Send( "Inner second test" );
                }

                w.Flush();

                Assert.That( w.ToString(), Is.Not.Empty );
                Assert.That( w.ToString(), Is.StringContaining( "First" ) );
                Assert.That( w.ToString(), Is.StringContaining( "Inner first test" ) );
                Assert.That( w.ToString(), Is.StringContaining( "Second" ) );
                Assert.That( w.ToString(), Is.StringContaining( "Inner second test" ) );

            }
        }
Ejemplo n.º 10
0
        static void DumpSampleLogs2( Random r, GrandOutput g )
        {
            var m = new ActivityMonitor( false );
            g.Register( m );

            m.Fatal().Send( ThrowExceptionWithInner( false ), "An error occured" );
            m.SetTopic( "This is a topic..." );
            m.Trace().Send( "a trace" );
            m.Trace().Send( "another one" );
            m.SetTopic( "Please, show this topic!" );
            m.Trace().Send( "Anotther trace." );
            using( m.OpenTrace().Send( "A group trace." ) )
            {
                m.Trace().Send( "A trace in group." );
                m.Info().Send( "An info..." );
                using( m.OpenInfo().Send( @"A group information... with a 
multi
-line
message. 
This MUST be correctly indented!" ) )
                {
                    m.Info().Send( "Info in info group." );
                    m.Info().Send( "Another info in info group." );
                    m.Error().Send( ThrowExceptionWithInner( true ), "An error." );
                    m.Warn().Send( "A warning." );
                    m.Trace().Send( "Something must be said." );
                    m.CloseGroup( "Everything is in place." );
                }
            }
            m.SetTopic( null );
            using( m.OpenTrace().Send( "A group with multiple conclusions." ) )
            {
                using( m.OpenTrace().Send( "A group with no conclusion." ) )
                {
                    m.Trace().Send( "Something must be said." );
                }
                m.CloseGroup( new[] {
                        new ActivityLogGroupConclusion( "My very first conclusion." ),
                        new ActivityLogGroupConclusion( "My second conclusion." ),
                        new ActivityLogGroupConclusion( @"My very last conclusion
is a multi line one.
and this is fine!" )
                    } );
            }
            m.Trace().Send( "This is the final trace." );
        }
Ejemplo n.º 11
0
 static void DumpSampleLogs1( Random r, GrandOutput g )
 {
     var m = new ActivityMonitor( false );
     g.Register( m );
     m.SetTopic( "First Activity..." );
     if( r.Next( 3 ) == 0 ) System.Threading.Thread.Sleep( 100 + r.Next( 2500 ) );
     using( m.OpenTrace().Send( "Opening trace" ) )
     {
         if( r.Next( 3 ) == 0 ) System.Threading.Thread.Sleep( 100 + r.Next( 2500 ) );
         m.Trace().Send( "A trace in group." );
         if( r.Next( 3 ) == 0 ) System.Threading.Thread.Sleep( 100 + r.Next( 2500 ) );
         m.Info().Send( "An info in group." );
         if( r.Next( 3 ) == 0 ) System.Threading.Thread.Sleep( 100 + r.Next( 2500 ) );
         m.Warn().Send( "A warning in group." );
         if( r.Next( 3 ) == 0 ) System.Threading.Thread.Sleep( 100 + r.Next( 2500 ) );
         m.Error().Send( "An error in group." );
         if( r.Next( 3 ) == 0 ) System.Threading.Thread.Sleep( 100 + r.Next( 2500 ) );
         m.Fatal().Send( "A fatal in group." );
     }
     if( r.Next( 3 ) == 0 ) System.Threading.Thread.Sleep( 100 + r.Next( 2500 ) );
     m.Trace().Send( "End of first activity." );
 }
Ejemplo n.º 12
0
 public RAndCChecker(ActivityMonitor m)
 {
     _m = m;
     _m.ReentrantAndConcurrentCheck();
 }
Ejemplo n.º 13
0
 static IActivityMonitor CreateMonitorAndRegisterGrandOutput( string topic, GrandOutput go )
 {
     var m = new ActivityMonitor( topic );
     go.Register( m );
     return m;
 }
Ejemplo n.º 14
0
        public void ApplyConfigSimple()
        {
            GrandOutputConfiguration c = new GrandOutputConfiguration();

            Assert.That( c.Load( XDocument.Parse( @"
<GrandOutputConfiguration AppDomainDefaultFilter=""Release"" >
    <Channel MinimalFilter=""{Trace,Info}"">
        <Add Type=""BinaryFile"" Name=""GlobalCatch"" Path=""Configuration/ApplyConfig"" />
    </Channel>
</GrandOutputConfiguration>" ).Root, TestHelper.ConsoleMonitor ) );

            Assert.That( c.ChannelsConfiguration.Configurations.Count, Is.EqualTo( 1 ) );

            ActivityMonitor m = new ActivityMonitor( false );
            using( GrandOutput g = new GrandOutput() )
            {
                m.Info().Send( "Before Registering - NOSHOW" );
                g.Register( m );
                m.Info().Send( "Before configuration - NOSHOW" );
                Assert.That( g.SetConfiguration( c, TestHelper.ConsoleMonitor ) );
                m.Info().Send( "After configuration. INFO1" );

                Assert.That( m.ActualFilter, Is.EqualTo( new LogFilter( LogLevelFilter.Trace, LogLevelFilter.Info ) ) ); 
                m.Trace().Send( "TRACE1-NOSHOW (MinimalFilter of the Channel)." );
                
                Assert.That( g.SetConfiguration( new GrandOutputConfiguration(), TestHelper.ConsoleMonitor ) );
                g.Dispose( TestHelper.ConsoleMonitor );

                m.Info().Send( "After disposing - NOSHOW." );

                Assert.That( m.ActualFilter, Is.EqualTo( LogFilter.Undefined ) ); 
            }
            
        }
        public void FilteringByTopic()
        {
            TestHelper.CleanupFolder( SystemActivityMonitor.RootLogPath + "FilteringByTopic" );

            using( GrandOutput g = new GrandOutput() )
            {
                GrandOutputConfiguration config = new GrandOutputConfiguration();
                config.Load( XDocument.Parse( @"
<GrandOutputConfiguration>
    <Channel MinimalFilter=""Debug"">
        <Add Type=""BinaryFile"" Name=""All"" Path=""FilteringByTopic"" />
        <Channel Name=""HiddenTopic"" MinimalFilter=""Off"" TopicFilter=""*H*T?pic*"" >
            <Channel Name=""SavedHiddenTopic"" MinimalFilter=""Release"" TopicFilter=""*DOSHOW*"" >
            </Channel>
        </Channel>
        <Channel Name=""MonitoredTopic"" MinimalFilter=""Monitor"" TopicFilter=""*MONITOR*"" >
        </Channel>
    </Channel>
</GrandOutputConfiguration>", LoadOptions.SetLineInfo ).Root, TestHelper.ConsoleMonitor );

                Assert.That( g.SetConfiguration( config, TestHelper.ConsoleMonitor ) );

                var fullyHidden = new ActivityMonitor( false );
                g.Register( fullyHidden );
                fullyHidden.SetTopic( "A fully hidden topic: setting the topic before any send, totally hides the monitor if the Actual filter is Off. - NOSHOW" );
                fullyHidden.Fatal().Send( "NOSHOW" );
                using( fullyHidden.OpenFatal().Send( "NOSHOW" ) )
                {
                    fullyHidden.Fatal().Send( "NOSHOW" );
                }

                var m = new ActivityMonitor( false );
                g.Register( m );
                m.Trace().Send( "Trace-1" );
                m.SetTopic( "This is a Hidden Topic - NOSHOW" );
                m.Fatal().Send( "NOSHOW" );
                m.SetTopic( "Visible Topic" );
                m.Trace().Send( "Trace-2" );
                m.SetTopic( "This is a Hidden Topic but DOSHOW puts it in Release mode." );
                m.Trace().Send( "NOSHOW" );
                m.Info().Send( "NOSHOW" );
                m.Warn().Send( "NOSHOW" );
                m.Error().Send( "Error-1" );
                m.Fatal().Send( "Fatal-1" );
                m.SetTopic( "This is a HT?PIC (off). Match is case insensitive - NOSHOW" );
                m.Fatal().Send( "NOSHOW" );
                m.SetTopic( null );
                m.Trace().Send( "Trace-3" );
                m.SetTopic( "A MONITORed topic: If i wrote This is a t.o.p.i.c (without the dots), this would have matched the HiddenT.o.p.i.c channel..." );
                m.Trace().Send( "NOSHOW" );
                m.Warn().Send( "Warn-1" );
            }
            List<StupidStringClient> logs = TestHelper.ReadAllLogs( new DirectoryInfo( SystemActivityMonitor.RootLogPath + "FilteringByTopic" ), false );
            Assert.That( logs.Count, Is.EqualTo( 1 ), "Fully hidden monitor does not appear." );
            Assert.That( logs[0].ToString(), Does.Not.Contain( "NOSHOW" ) );
            var texts = logs[0].Entries.Select( e => e.Text ).ToArray();
            CollectionAssert.AreEqual( new string[] { 
                "Trace-1", 
                ActivityMonitor.SetTopicPrefix + "Visible Topic", 
                "Trace-2", 
                ActivityMonitor.SetTopicPrefix + "This is a Hidden Topic but DOSHOW puts it in Release mode.", 
                "Error-1", 
                "Fatal-1", 
                ActivityMonitor.SetTopicPrefix, 
                "Trace-3", 
                ActivityMonitor.SetTopicPrefix + "A MONITORed topic: If i wrote This is a t.o.p.i.c (without the dots), this would have matched the HiddenT.o.p.i.c channel...", 
                "Warn-1"
            }, texts, StringComparer.Ordinal );
        }
 static internal IDisposable Start( ActivityMonitor.DependentToken token, IActivityMonitor monitor, string fileName, int lineNumber )
 {
     string msg = token.FormatStartMessage();
     if( token.Topic != null )
     {
         string currentTopic = token.Topic;
         monitor.SetTopic( token.Topic, fileName, lineNumber );
         var g = monitor.UnfilteredOpenGroup( ActivityMonitor.Tags.StartDependentActivity, LogLevel.Info, null, msg, monitor.NextLogTime(), null, fileName, lineNumber );
         return Util.CreateDisposableAction( () => { g.Dispose(); monitor.SetTopic( currentTopic, fileName, lineNumber ); } );
     }
     return monitor.UnfilteredOpenGroup( ActivityMonitor.Tags.StartDependentActivity, LogLevel.Info, null, msg, monitor.NextLogTime(), null, fileName, lineNumber );
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Initialized a new Group at a given index.
 /// </summary>
 /// <param name="monitor">Monitor.</param>
 /// <param name="index">Index of the group.</param>
 internal Group(ActivityMonitor monitor, int index)
 {
     Monitor = monitor;
     Index   = index;
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Initialized a new Group at a given index.
 /// </summary>
 /// <param name="monitor">Monitor.</param>
 /// <param name="index">Index of the group.</param>
 internal Group( ActivityMonitor monitor, int index )
 {
     Monitor = monitor;
     Index = index;
 }
Ejemplo n.º 19
0
            static GrandOutput CreateGrandOutputWithFakeHandler( int handlerExtralLoad, bool useAdaptive, int dispatcherMaxCapacity )
            {
                IActivityMonitor mLoad = new ActivityMonitor( false );

                GrandOutputConfiguration c = new GrandOutputConfiguration();
                var textConfig = @"<GrandOutputConfiguration><Channel><Add Type=""FakeHandler, CK.Monitoring.Tests"" Name=""GlobalCatch"" ExtraLoad="""
                    + handlerExtralLoad.ToString()
                    + @""" /></Channel></GrandOutputConfiguration>";
                Assert.That( c.Load( XDocument.Parse( textConfig ).Root, mLoad ) );
                Assert.That( c.ChannelsConfiguration.Configurations.Count, Is.EqualTo( 1 ) );

                IGrandOutputDispatcherStrategy strat;
                if( useAdaptive )
                {
                    strat = new Impl.EventDispatcherLocalTestStrategy( dispatcherMaxCapacity );
                }
                else 
                {
                    strat = new Impl.EventDispatcherBasicStrategy( dispatcherMaxCapacity );
                }
                GrandOutput g = new GrandOutput( strat );
                g.SetConfiguration( c, mLoad );
                return g;
            }
Ejemplo n.º 20
0
 void Run( object state )
 {
     Random r = new Random();
     var a = (Action<RunContext, IActivityMonitor,Random>)state;
     IActivityMonitor m = new ActivityMonitor( false );
     GrandOutput.Register( m );
     Barrier.SignalAndWait();
     for( int i = 0; i < LoopCount; ++i )
     {
         a( this, m, r );
     }
     Barrier.SignalAndWait();
 }
 /// <summary>
 /// Signals the launch of one or more dependent activities by emitting a log line that describes the token.
 /// The token must have been created by <see cref="CreateToken"/> or <see cref="CreateTokenWithTopic"/> with a true delayedLaunch parameter
 /// otherwise an <see cref="InvalidOperationException"/> is thrown.
 /// </summary>
 /// <param name="token">Dependent token.</param>
 public void Launch( ActivityMonitor.DependentToken token )
 {
     if( token.DelayedLaunchMessage == null ) throw new InvalidOperationException( Impl.ActivityMonitorResources.ActivityMonitorDependentTokenMustBeDelayedLaunch );
     _monitor.UnfilteredLog( ActivityMonitor.Tags.CreateDependentActivity, LogLevel.Info, token.DelayedLaunchMessage, _monitor.NextLogTime(), null, _fileName, _lineNumber );
 }
Ejemplo n.º 22
0
 public ActionResult DownloadSubscription( DownloadFormViewModel model )
 {
     if( ModelState.IsValid )
     {
         IActivityMonitor m = new ActivityMonitor();
         CKTrait trait = ActivityMonitor.Tags.Register( "downloadSubscriber" );
         using( m.OpenInfo().Send( trait, "Download: Email: {0}", model.Email ) )
         {
             return PartialView( "_Thanks" );
         }
     }
     return PartialView( "_DownloadModal", model );
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Creates a new instance of this ViewModel.
        /// </summary>
        /// <param name="loadDefaultState">True if the default XML state should be loaded, false to start on an empty state.</param>
        public MainWindowViewModel( bool loadDefaultState = false )
        {
            _recentFiles = new CKObservableSortedArrayList<RecentFile>( ( a, b ) => DateTime.Compare( b.AccessTime, a.AccessTime ) );

            // Lab objects, live objects and static infos are managed in the LabStateManager.
            _labStateManager = new LabStateManager();
            _engine = _labStateManager.Engine;

            _labStateManager.Engine.PropertyChanged += Engine_PropertyChanged;
            _labStateManager.ServiceInfos.CollectionChanged += ServiceInfos_CollectionChanged;
            _labStateManager.PluginInfos.CollectionChanged += PluginInfos_CollectionChanged;
            _labStateManager.RunningPlugins.CollectionChanged += RunningPlugins_CollectionChanged;

            _engine.Configuration.Layers.CollectionChanged += Layers_CollectionChanged;

            _activityMonitor = new ActivityMonitor();

            _activityMonitor.OpenTrace().Send( "Hello world" );

            _graph = new YodiiGraph( _engine.Configuration, _labStateManager );

            _removeSelectedVertexCommand = new RelayCommand( RemoveSelectedVertexExecute, CanEditSelectedVertex );
            _toggleEngineCommand = new RelayCommand( ToggleEngineExecute );
            _openFileCommand = new RelayCommand( OpenFileExecute );
            _saveAsFileCommand = new RelayCommand( SaveAsFileExecute );
            _saveCommand = new RelayCommand( SaveExecute ); // Save is always available.e
            _reorderGraphLayoutCommand = new RelayCommand( ReorderGraphLayoutExecute );
            _createPluginCommand = new RelayCommand( CreatePluginExecute, CanEditItems );
            _createServiceCommand = new RelayCommand( CreateServiceExecute, CanEditItems );
            _openConfigurationEditorCommand = new RelayCommand( OpenConfigurationEditorExecute );
            _newFileCommand = new RelayCommand( NewFileExecute );
            _revokeAllCommandsCommand = new RelayCommand( RevokeAllCommandsExecute, CanRevokeAllCommands );
            _autoPositionCommand = new RelayCommand( AutoPositionExecute );

            LoadRecentFiles();

            // Appication is only available on WPF context.
            if( Application.Current != null )
            {
                _autosaveTimer = new DispatcherTimer( DispatcherPriority.Background, Application.Current.Dispatcher );
            }
            else
            {
                _autosaveTimer = new DispatcherTimer( DispatcherPriority.Background, Dispatcher.CurrentDispatcher );
            }

            _autosaveTimer.Interval = new TimeSpan( 0, 0, 5 );
            _autosaveTimer.Tick += AutosaveTick;

            // Autosave timer is started from outside, using StartAutosaveTimer().

            if( loadDefaultState ) LoadDefaultState();
        }
Ejemplo n.º 24
0
        public ActionResult Support( SupportEmailViewModel model )
        {
            IActivityMonitor m = new ActivityMonitor();
            if( ModelState.IsValid )
            {
                using( m.OpenInfo().Send( "Sending Support mail to {0}", DestinationEmail ) )
                {
                    try
                    {
                        IMailerService mailer = new CK.Mailer.DefaultMailerService( m );
                        mailer.SendMail( model, new RazorMailTemplateKey( "SupportEmail" ), new Recipient( DestinationEmail ) );
                    }
                    catch( Exception ex )
                    {
                        m.Error().Send( ex, "Email : {0}, Subject : {1}, Body : {2}", model.Email, model.Subject, model.Body );
                        return PartialView( "_EmailNotSent", model );
                    }
                }

                return PartialView( "_EmailSent" );
            }
            return PartialView( "_Form", model );
        }
Ejemplo n.º 25
0
 IActivityMonitor CreateMonitorWithBuggyListeners( int buggyClientCount )
 {
     IActivityMonitor monitor = new ActivityMonitor();
     for( int i = 0; i < buggyClientCount; ++i ) monitor.Output.RegisterClient( _context.NewBuggyClient( this ) );
     monitor.Output.RegisterClient( _context.SafeClient );
     return monitor;
 }
Ejemplo n.º 26
0
 public void CompressedReadWriteTests()
 {
     TestHelper.CleanupTestFolder();
     string directoryPath = Path.Combine( TestHelper.TestFolder, "GzipCKMonWriterClientTest" );
     ActivityMonitor m = new ActivityMonitor();
     var client = new CKMonWriterClient( directoryPath, 20000, LogFilter.Undefined, true );
     m.Output.RegisterClient( client );
     using( m.OpenWarn().Send( "Group test" ) )
     {
         m.Info().Send( "Line test" );
     }
     // This closes the client: the file is then compressed asynchronously
     // on a thread from the ThreadPool.
     Assert.That( client.IsOpened );
     m.Output.UnregisterClient( client );
     string ckmonPath = TestHelper.WaitForCkmonFilesInDirectory( directoryPath, 1 )[0];
     LogReader r = LogReader.Open( ckmonPath );
     r.MoveNext();
     Assert.That( r.Current.LogType, Is.EqualTo( LogEntryType.OpenGroup ) );
     Assert.That( r.Current.Text, Is.EqualTo( "Group test" ) );
     r.MoveNext();
     Assert.That( r.Current.LogType, Is.EqualTo( LogEntryType.Line ) );
     Assert.That( r.Current.Text, Is.EqualTo( "Line test" ) );
     r.MoveNext();
     Assert.That( r.Current.LogType, Is.EqualTo( LogEntryType.CloseGroup ) );
     bool hasRemainingEntries = r.MoveNext();
     Assert.That( hasRemainingEntries, Is.False );
 }