Info() public static method

public static Info ( string format ) : void
format string
return void
Exemplo n.º 1
0
 private void ConnectCallback(object sender, SocketAsyncEventArgs e)
 {
     session = new Session(e.ConnectSocket, socketBufferSize, logger);
     logger?.Info($"Client.ConnectCallback: session={session.GetHashCode()}, e={e.GetHashCode()}, e.SocketError={e?.SocketError}");
     session.ReceiveCallback += ReceiveCallback;
     session.Start();
 }
Exemplo n.º 2
0
 private void AcceptCallback(object sender, SocketAsyncEventArgs e)
 {
     session = new Session(e.AcceptSocket, socketBufferSize, logger);
     session.ReceiveCallback += ReceiveCallback;
     logger?.Info($"Server.AcceptCallback, sender={sender.GetHashCode()}, e.SocketError={e?.SocketError}");
     session.Start();
 }
Exemplo n.º 3
0
        // TODO - Define a margin to move time and review possible tamper scenarios
        private DateTime GetUtc()
        {
            DateTime? antiBack  = null;
            DateTime? reliable  = null;
            Exception exception = null;

            try
            {
                reliable = ReliableTimeProvider.UtcNow();
                Log?.Info("Reliable provider get time successfully");
                AntiBackTimeProvider.SetValue(reliable.Value);
            }
            catch (Exception ex)
            {
                exception = ex;
                Log?.Error($"Error '{ex.GetType().Name}' in ReliableTimeProvider: {ex.Message}", ex);
            }
            try
            {
                antiBack = AntiBackTimeProvider.UtcNow();
                Log?.Info("Anti-back provider get time successfully");
            }
            //catch (NoStoredTimeValueException nstvex) { exception = nstvex; }
            //catch (BackTimeException btex) { exception = btex; }
            catch (Exception ex)
            {
                exception = ex;
                Log?.Error($"Error '{ex.GetType().Name}' in AntiBackProvider: {ex.Message}", ex);
            }
            if (reliable != null || antiBack != null)
            {
                return((reliable ?? antiBack).Value);
            }
            throw new TamperedTimeException(exception);
        }
Exemplo n.º 4
0
        private bool StartWsRouter()
        {
            try
            {
                if (Router != null && Router.IsListening())
                {
                    return(true);
                }
                Router = new WsRouter();
                Router.NewConnection += RouterOnNewConnection;
                Router.DataReceived  += RouterOnDataReceived;
                Router.Listen(WsRouter.StartPort);
                var r = Router.IsListening();

                Log?.Info(string.Format("Router {0}",
                                        r ? "started -> localhost Port: " + Router.Port
                                                : "failed"));
                return(Router.IsListening());
            }
            catch (Exception ex)
            {
                ex.Show();

                return(false);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        ///     Unloads all data.
        /// </summary>
        protected override void UnloadData()
        {
            Log?.EnterMethod(nameof(UnloadData));
            if (PROFILE)
            {
                Log?.Info("Writing profiler data");
                WriteProfileResults();
                if (_profilerLog != null)
                {
                    Log?.Info("Profiler logging stopped");
                    _profilerLog.Flush();
                    _profilerLog.Close();
                    _profilerLog = null;
                }
            }

            if (Log != null)
            {
                Log.Info("Logging stopped");
                Log.Flush();
                Log.Close();
                Log = null;
            }

            if (Network != null)
            {
                Log?.Info("Cap network connections");
                Network.Close();
                Network = null;
            }

            Static = null;
        }
Exemplo n.º 6
0
        private void Run(BaconArgs Args)
        {
            Log?.PushStack("private void Run()");
            if (Args.hasOption("reactors"))
            {
                INCLUDE_REACTORS = true;
                Log?.Info("Include reactors in sorting.");
            }
            if (Args.hasOption("weapons"))
            {
                INCLUDE_WEAPONS = true;
                Log?.Info("Include weapons in sorting.");
            }
            if (Args.hasOption("docked"))
            {
                INCLUDE_DOCKED = true;
                Log?.Info("Include docked in sorting.");
            }
            if (Args.hasOption("ignore") && Args.getOption("ignore")[0] != null)
            {
                TAG_IGNORE = Args.getOption("ignore")[0];
                Log?.Info("Use Tag \"{0}\" instead of \"#!BaconSort\" to exclude containers.", TAG_IGNORE);
            }
            List <IMyTerminalBlock> SourceBlocks = findAllBlocks();
            Dictionary <string, List <IMyTerminalBlock> > DestinationBlockMap = getDestinationMap(SourceBlocks);

            foreach (IMyTerminalBlock SourceBlock in SourceBlocks)
            {
                DoSortContainer(SourceBlock, DestinationBlockMap);
            }
            Log?.PopStack();
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            var log = new Log();
            log.Info("Startup");

            var servers = new List<ServerInfo>();

            using (var dc = new Arma3BeClientContext())
            {
                servers = dc.ServerInfo.Where(x => x.Active).ToList();
            }

            var models = servers.Select(x=>OpenServerInfo(x, log)).ToList();

            while (true)
            {
                try
                {
                    var t = Task.Run(() => run(models));
                    t.Wait();
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
        }
Exemplo n.º 8
0
        public async void OnApplicationStart()
        {
            Log?.Debug("OnApplicationStart");

            // Harmony
            Harmony = new HarmonyLib.Harmony(HarmonyId);
            Harmony.PatchAll(Assembly.GetExecutingAssembly());
            Log?.Debug($"Harmony patching complete.");

            // Assets
            Sprites.Initialize();
            Log?.Debug($"Sprite conversion complete.");

            // HTTP client
            Log?.Info(UserAgent);

            HttpClient = new HttpClient();
            HttpClient.DefaultRequestHeaders.Add("User-Agent", Plugin.UserAgent);
            HttpClient.DefaultRequestHeaders.Add("X-BSSB", "✔");

            // BS Events
            BSEvents.lateMenuSceneLoadedFresh += OnLateMenuSceneLoadedFresh;

            // Start update timer
            UpdateTimer.Start();

            // Detect platform
            // Note - currently (will be fixed in BS utils soon!): if the health warning is skipped (like in fpfc mode),
            //  this await will hang until a song is played, so the platform will be stuck on "unknown" til then
            await DetectPlatform();
        }
Exemplo n.º 9
0
        /// <summary>
        /// Handles new connections.
        /// </summary>
        /// <param name="socket">The connection socket.</param>
        protected override void HandleConnection(Socket socket)
        {
            ClientAgentSession session = new ClientAgentSession(SessionManager, socket, 0);

            SessionManager.NewSession(session);
            Log?.Info("Began new session. (id: {0}, channel: {1})", session.SessionId, session.ClientChannel);
        }
Exemplo n.º 10
0
        /// <inheritdoc cref="CodeMonkeys.Navigation.INavigationService.ClearCache" />
        public void ClearCache()
        {
            Log?.Info(
                $"{ContentCache.Count} cached pages removed.");

            ContentCache.Clear();
        }
Exemplo n.º 11
0
 private DateTime GetUtc(out bool fromCache)
 {
     Log?.Notice($"Getting time from {nameof(CachedTimeProvider)} ...");
     if (!stopwatch.IsRunning || stopwatch.Elapsed > ExpirationInterval)
     {
         if (!stopwatch.IsRunning)
         {
             Log?.Info("There is no data stored in cache yet, time provider will be used");
         }
         else
         {
             Log?.Info("Cache expired, time provider will be used");
         }
         fromCache = false;
         var res = TimeProvider.UtcNow();
         stopwatch.Restart();
         cachedValue = res;
     }
     else
     {
         Log?.Info($"Result is cache + elapsed = {cachedValue} + {stopwatch.Elapsed}");
         fromCache = true;
     }
     return(cachedValue.Add(stopwatch.Elapsed));
 }
Exemplo n.º 12
0
        /// <summary>
        /// Loads a configuration file to use when creating bots.
        /// </summary>
        /// <param name="configFile"><c>false</c> if there was problems loading the config file.</param>
        public bool LoadConfiguration(string configFile)
        {
            if (!File.Exists(configFile))
                return false;

            try
            {
                ConfigObject = Configuration.LoadConfiguration(configFile);
            }
            catch (JsonReaderException)
            {
                // handle basic json formatting screwups
                ConfigObject = null;
            }

            if (ConfigObject == null)
                return false;

            useSeparateProcesses = ConfigObject.UseSeparateProcesses;

            mainLog = new Log(ConfigObject.MainLog, null, Log.LogLevel.Debug);

            for (int i = 0; i < ConfigObject.Bots.Length; i++)
            {
                Configuration.BotInfo info = ConfigObject.Bots[i];
                mainLog.Info("Launching Bot " + info.DisplayName + "...");

                var v = new RunningBot(useSeparateProcesses, i, ConfigObject);
                botProcs.Add(v);
            }

            return true;
        }
Exemplo n.º 13
0
        private Value GetOptimalValue(IDeterministicPolicy <TState> policy, double tolerance = 1e-4, bool ignoreZeroChange = false, TState[] outputStates = null)
        {
            if (outputStates == null)
            {
                outputStates = new[] { _initialState }
            }
            ;
            Initialize(policy, outputStates);
            var values = new Value[outputStates.Length];
            var diff   = new Value[outputStates.Length];
            var change = double.MaxValue;

            while ((change > tolerance || (change == 0 && !ignoreZeroChange) || values[0].Mean == 0) && _iteration < _maxIterations && StateSpace[_iteration].Count > 0)
            {
                var nextValues = Iterate(policy);

                for (var i = 0; i < outputStates.Length; ++i)
                {
                    diff[i] = nextValues[i] + ((-1) * values[i]);
                }
                change = Norm(diff);

                if (LogIterations)
                {
                    Log?.Info($"Iteration {_iteration} : {values[0].Mean} -> {nextValues[0].Mean} \t {change}");
                }

                values = nextValues;
            }

            return(values[0]);
        }
Exemplo n.º 14
0
 public static void Main(string[] args)
 {
     Configuration config = Configuration.LoadConfiguration("settings.json");
     Log mainLog = new Log (config.MainLog, null);
     //byte counter = 0;
     foreach (Configuration.BotInfo info in config.Bots)
     {
         //Console.WriteLine("--Launching bot " + info.DisplayName +"--");
         mainLog.Info ("Launching Bot " + info.DisplayName + "...");
         new Thread(() =>
         {
             int crashes = 0;
             while (crashes < 1000)
             {
                 try
                 {
                     new Bot(info, config.ApiKey);
                 }
                 catch (Exception e)
                 {
                     mainLog.Error ("Error With Bot: "+e);
                     crashes++;
                 }
             }
         }).Start();
         Thread.Sleep(5000);
     }
 }
Exemplo n.º 15
0
        /// <summary>
        ///     Unloads all data.
        /// </summary>
        protected override void UnloadData()
        {
            Log?.EnterMethod(nameof(UnloadData));
            MyAPIGateway.Gui.GuiControlRemoved  -= OnGuiControlRemoved;
            MyAPIGateway.Session.OnSessionReady -= OnSessionReady;

            if (Network != null)
            {
                Log?.Info("Cap network connections");
                Network.Close();
                Network = null;
            }

            if (Log != null)
            {
                Log.Info("Logging stopped");
                Log.Flush();
                Log.Close();
                Log = null;
            }

            if (Controls != null)
            {
                Controls = null;
            }

            if (Defs != null)
            {
                Defs = null;
            }

            Static = null;
        }
        /// <inheritdoc cref="CodeMonkeys.Navigation.INavigationService.ClearCache" />
        public void ClearCache()
        {
            Log?.Info(
                $"{PageCache.Count} cached pages removed.");

            PageCache.Clear();
        }
Exemplo n.º 17
0
        private IDeterministicPolicy <TState> PolicyIteration(IDeterministicPolicy <TState> policy)
        {
            if (!UseReachableStateSpace)
            {
                return(PartialPolicyIteration(policy));
            }

            if (ReachableStates == null)
            {
                ReachableStates = GetReachableStateSpace(policy, _initialState);
            }

            var nextPolicy = (IDeterministicPolicy <TState>)policy.Clone();

            var progress = 0.0;
            var step     = 1.0 / ReachableStates.Count;
            var logStep  = 0.01;

            Log?.Info("Calculating optimal actions...");
            foreach (var state in ReachableStates.Keys)
            {
                var optimalAction = GetOptimalActionEx(policy, state);
                if (optimalAction != null)
                {
                    nextPolicy[state] = optimalAction;
                }
                if ((progress / logStep) - Math.Truncate(progress / logStep) < step / logStep)
                {
                    Log?.Info($"{Math.Truncate(progress * 10000) / 100}%");
                }
                progress += step;
            }

            return(nextPolicy);
        }
Exemplo n.º 18
0
 public void TestContext()
 {
     var queue = new Loggers.Queue();
      var log = new Log(this);
      using (Log.RegisterInstance(
        new Instance()
        {
           Properties = new[]
           {
              "Thread.ID",
              "Thread.StackTrace"
           },
           Logger = queue,
           Buffer = 0,
           Synchronous = true
        }
     )
      )
      {
     log.Info("test");
     var evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Thread.ID"], System.Threading.Thread.CurrentThread.ManagedThreadId);
     Assert.IsTrue(((String)evt["Thread.StackTrace"]).Contains("TestContext"));
      }
 }
Exemplo n.º 19
0
 public void TestContext()
 {
     var queue = new Loggers.Queue();
      var log = new Log(this);
      using (Log.RegisterInstance(
        new Instance()
        {
           Properties = new[]
           {
              "Environment.MachineName",
              "Environment.UserName",
              "Environment.UserDomainName",
              "Environment.CurrentDirectory",
              "Environment.OSVersion",
              "Environment.ProcessorCount",
              "Environment.SystemRoot"
           },
           Logger = queue,
           Buffer = 0,
           Synchronous = true
        }
     )
      )
      {
     log.Info("test");
     var evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Environment.MachineName"], Environment.MachineName);
     Assert.AreEqual(evt["Environment.UserName"], Environment.UserName);
     Assert.AreEqual(evt["Environment.UserDomainName"], Environment.UserDomainName);
     Assert.AreEqual(evt["Environment.CurrentDirectory"], Environment.CurrentDirectory);
     Assert.AreEqual(evt["Environment.OSVersion"], Convert.ToString(Environment.OSVersion));
     Assert.AreEqual(evt["Environment.ProcessorCount"], Environment.ProcessorCount);
     Assert.AreEqual(evt["Environment.SystemRoot"], Environment.GetEnvironmentVariable("SystemRoot"));
      }
 }
Exemplo n.º 20
0
        private bool isAllowedToExecute(BaconArgs Args)
        {
            if (LastRun == null)
            {
                return(true);
            }
            int buff = 0;

            if (Args.hasOption("sleep") && int.TryParse(Args.getOption("sleep")[0], out buff))
            {
                sleepTimeS = buff;
            }
            Log?.Debug("execution limit once every {0} seconds", sleepTimeS);

            TimeSpan TimeSinceLastRun = DateTime.Now.Subtract(LastRun);

            if (sleepTimeS <= TimeSinceLastRun.TotalSeconds)
            {
                LastRun = DateTime.Now;
                return(true);
            }

            Log?.Info("Sorting in {0} seconds.", sleepTimeS - TimeSinceLastRun.TotalSeconds);
            return(false);
        }
Exemplo n.º 21
0
        public async Task CheckVersion()
        {
            try
            {
                GithubVersion latest = await VersionCheck.GetLatestVersionAsync("Goobwabber", "MultiplayerAvatars");

                Log?.Debug($"Latest version is {latest}, released on {latest.ReleaseDate.ToShortDateString()}");
                if (PluginMetadata != null)
                {
                    SemVer.Version currentVer      = PluginMetadata.Version;
                    SemVer.Version latestVersion   = new SemVer.Version(latest.ToString());
                    bool           updateAvailable = new SemVer.Range($">{currentVer}").IsSatisfied(latestVersion);
                    if (updateAvailable)
                    {
                        Log?.Info($"An update is available!\nNew mod version: {latestVersion}\nCurrent mod version: {currentVer}");
                    }
                }
            }
            catch (ReleaseNotFoundException ex)
            {
                Log?.Warn(ex.Message);
            }
            catch (Exception ex)
            {
                Log?.Warn($"Error checking latest version: {ex.Message}");
                Log?.Debug(ex);
            }
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            // with the default implementations
            ILogAdapter logAdapter = new TraceLogAdapter(null);
            ILog log = new Log(logAdapter);

            log.Info("Info message", 1);
            log.Warning("Warning message", 1);
            log.Critical("Critical message", 2);

            // Example with a custom implementation
            Console.WriteLine("");
            Console.WriteLine("Example with a custom implementation");

            MyLogSettings settings = new MyLogSettings();
            logAdapter = new MyLogAdapter(settings);
            log = new Log(logAdapter);

            log.Info("Info message", 1);
            log.Warning("Warning message", 1);
            log.Critical("Critical message", 2);

            Console.WriteLine("Terminé");
            Console.ReadLine();
        }
Exemplo n.º 23
0
 public void TestContext ()
 {
    var queue = new Loggers.Queue();
    var log = new Log(this);
    using (Log.RegisterInstance(
          new Instance()
          {
             Properties = new[]
             {
                "StackFrame.File",
                "StackFrame.Line",
                "StackFrame.Type",
                "StackFrame.Method"
             },
             Logger = queue,
             Buffer = 0,
             Synchronous = true
          }
       )
    )
    {
       var frame = new System.Diagnostics.StackFrame(0, true);
       log.Info("test");
       var evt = queue.Dequeue().Single();
       Assert.AreEqual(evt["StackFrame.File"], frame.GetFileName());
       Assert.AreEqual(evt["StackFrame.Line"], frame.GetFileLineNumber() + 1);
       Assert.AreEqual(evt["StackFrame.Type"], frame.GetMethod().DeclaringType.FullName);
       Assert.AreEqual(evt["StackFrame.Method"], frame.GetMethod().Name);
    }
 }
Exemplo n.º 24
0
        private static void Main()
        {
            logger = new LogBuilder().Build();

            logger?.Info($"Server starts: IP={IPAddress.Any}, port={port}");
            server = new Server(new IPEndPoint(IPAddress.Any, port), backlog, socketBufferSize, logger);
            server.Start();

            logger?.SetFileMinLevel(Serilog.Events.LogEventLevel.Warning);

            string input;

            while ((input = Console.ReadLine()) != null)
            {
                switch (input.ToLower())
                {
                case "quit":
                    return;

                case "close":
                    server.Stop();
                    break;
                }
            }
        }
Exemplo n.º 25
0
        /// <inheritdoc />
        protected override int ExecuteCommand(CommandLineApplication app, IConsole console)
        {
            var appName = app.GetRootCommandLineApplication().Name;

            string executableDir = Path.GetDirectoryName(RunningAssembly.Info.Location);

            if (string.IsNullOrEmpty(executableDir))
            {
                throw new CommandException($"Could not find the directory of the executing assembly: {RunningAssembly.Info.Location}.");
            }

            var starterFilePath = GetStartScriptFilePath(appName);

            Log.Debug($"Creating starter script: {starterFilePath.PrettyQuote()}.");

            if (StaticUtilities.IsRuntimeWindowsPlatform)
            {
                File.WriteAllText(starterFilePath, $"@echo off\r\ndotnet exec \"%~dp0{GetDllName()}\" %*");
            }
            else
            {
                File.WriteAllText(starterFilePath, (@"#!/bin/bash
SOURCE=""${BASH_SOURCE[0]}""
while [ -h ""$SOURCE"" ]; do
    DIR=""$( cd -P ""$( dirname ""$SOURCE"" )"" && pwd )""
    SOURCE=""$(readlink ""$SOURCE"")""
    [[ $SOURCE != /* ]] && SOURCE=""$DIR/$SOURCE""
done
DIR=""$( cd -P ""$( dirname ""$SOURCE"" )"" && pwd )""
dotnet exec ""$DIR/" + GetDllName() + @""" ""$@""").Replace("\r", ""));
            }

            Log?.Info($"Starter script created: {starterFilePath.PrettyQuote()}.");

            HelpWriter.WriteOnNewLine(null);
            HelpWriter.WriteSectionTitle("IMPORTANT README:");
            HelpWriter.WriteOnNewLine(@"
A starter script has been created in the same directory as this executable: " + starterFilePath.PrettyQuote() + $@".

It allows you to call this tool in a more natural way: `{appName} [command]`. This strips the need to run the .dll with dotnet (the script does that for you).

The directory containing the starter script created should be added to your system PATH in order to be able to call `{appName} [command]` from anywhere on your system.

The command to add this directory to your path is:");
            HelpWriter.WriteOnNewLine(null);

            if (StaticUtilities.IsRuntimeWindowsPlatform)
            {
                Out.WriteResultOnNewLine($"for /f \"usebackq tokens=2,*\" %A in (`reg query HKCU\\Environment /v PATH`) do SetX Path \"%B;{Path.GetDirectoryName(starterFilePath)}\"");
            }
            else
            {
                Out.WriteResultOnNewLine($"echo \"export PATH=$PATH:{Path.GetDirectoryName(starterFilePath)}\" >> ~/.bashrc && source ~/.bashrc && chmod +x \"{starterFilePath}\"");
            }

            HelpWriter.WriteOnNewLine(null);

            return(0);
        }
        private async Task PopToRootAsync()
        {
            await Navigation.PopToRootAsync(
                animated : Configuration.UseAnimations);

            Log?.Info(
                $"Navigation stack cleared.");
        }
        private async Task CloseCurrentPage()
        {
            await Navigation.PopAsync(
                animated : Configuration.UseAnimations);

            Log?.Info(
                "Page has been removed from Xamarin navigation stack.");
        }
Exemplo n.º 28
0
        private void MWebSocketServerOnSessionClosed(WebSocketSession session, CloseReason value)
        {
            var res = Clients.Remove(session);

            Log?.Info($"Client left: {session.Host}");
            Log?.Info($"Memory freed '{res}'");
            Log?.Info($"Current connected clients: {Clients.Count}");
        }
Exemplo n.º 29
0
 public void AddEntry_CreateEntryWithInvalidStrings_ArgumentNullException(string input)
 {
     Console.WriteLine(input.Length);
     var uut = new Log(new ConsoleOutput(), new FileFormatter());
     var ex = Assert.Throws<Log.LogEntry.StringLengthValidationException>(() => uut.Info(input));
     Assert.That(ex.Message, Is.EqualTo("LogEntry must be between " + 
                                           Log.MINCHARLENGTH + " and " + 
                                           Log.MAXCHARLENGTH + " characters in length."));
 }
Exemplo n.º 30
0
        //public DateTime LastVerifiedValue { get; set; }
        //TimeSpan VerificationExpirationInterval { get; set; }
        public DateTime GetUtc()
        {
            //await Task.Delay(500).ConfigureAwait(false);
            Log?.Notice($"Get UTC time using {RandomizedProvidersPerTry} randomized servers with a maximum of {MaxFailsPerTry} fails.");
            var res = TaskManager.StartNew(async() =>
            {
                if (Providers.Count(p => p.IsRandomized) < RandomizedProvidersPerTry)
                {
                    throw new Exception($"At least {RandomizedProvidersPerTry} providers must be added");
                }

                //var ents = Providers.ToList();
                var ents = Providers.TakeRandomly(RandomizedProvidersPerTry, ran).ToList();
                Log?.Debug($@"Selected servers: {ents.Aggregate("", (a, c) => a + "\r\n - " + c.Provider)}");

                foreach (var en in ents)
                {
                    en.Task = TaskManager.StartNew(p => p.Provider.UtcNow(), en);
                }
                DateTime[] results = null;
                try
                {
                    //Task.WaitAll(ents.Select(en => en.Task).ToArray());
                    results = await Task.WhenAll(ents.Select(en => en.Task).ToArray()).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("");
                }
                foreach (var en in ents)
                {
                    if (en.Task.Exception == null)
                    {
                        Log?.Info($"Provider '{en.Provider}' was a result: " + en.Task.Result);
                    }
                    else
                    {
                        Log?.Warn($"Provider '{en.Provider}' failed with error '{en.Task.Exception.GetType().Name}': " + en.Task.Exception.Message, en.Task.Exception);
                    }
                }
                var fails = ents.Where(p => p.Task.Exception != null).ToList();
                if (fails.Count > MaxFailsPerTry)
                {
                    throw new Exception($"Failed {fails.Count} providers when the maximun to fail is {MaxFailsPerTry}");
                }

                var r = ents
                        .Where(en => en.Task.Exception == null)
                        .Select(en => en.Task.Result)
                        .RemoveOutliers()
                        .AverageDateTime();
                Log?.Notice("Result: " + r);
                return(r);
            });

            return(res.Result);
        }
Exemplo n.º 31
0
        private void IOCompleted(object sender, SocketAsyncEventArgs e)
        {
            logger?.Info($"Session.IOCompleted: this={GetHashCode()}, e.SocketError={e?.SocketError}");

            switch (e.LastOperation)
            {
            case SocketAsyncOperation.Receive:
                ProcessReceive(sender, e);
                break;

            case SocketAsyncOperation.Send:
                ProcessSend(sender, e);
                break;

            default:
                throw new ArgumentException($"[{DateTime.Now:HH:mm:ss.ffff}] The last operation completed on the socket was not a receive or send.");
            }
        }
Exemplo n.º 32
0
        protected override int ExecuteCommand(CommandLineApplication app, IConsole console)
        {
            var gitIgnorePath = Path.Combine(SourceDirectory, ".gitignore");

            bool hasCarriageReturn = false;

            if (File.Exists(gitIgnorePath))
            {
                var gitIgnoreContent = File.ReadAllText(gitIgnorePath);
                if (gitIgnoreContent.Contains(".oe/local/"))
                {
                    Log?.Info("The .gitignore already exists and seems to already contain the appropriate exclusions.");
                    return(0);
                }

                hasCarriageReturn = gitIgnoreContent.IndexOf('\r') >= 0;
            }

            var ignoreContent = new StringBuilder(@"
############
#  Sakoe   #
############

# never push the local directory
.oe/local/

# do not push the bin directory
bin/

# do not version the project xsd
Project.xsd

# file extensions that should not be versioned
");

            ignoreContent.Append("*").AppendLine(UoeConstants.ExtListing);
            ignoreContent.Append("*").AppendLine(UoeConstants.ExtPreprocessed);
            ignoreContent.Append("*").AppendLine(UoeConstants.ExtXref);
            ignoreContent.Append("*").AppendLine(UoeConstants.ExtXrefXml);
            ignoreContent.Append("*").AppendLine(UoeConstants.ExtDebugList);
            ignoreContent.Append("*").AppendLine(UoeConstants.ExtR);
            ignoreContent.Append("*").AppendLine(UoeConstants.ExtProlibFile);

            ignoreContent.Replace("\r", "");

            if (hasCarriageReturn)
            {
                ignoreContent.Replace("\n", "\r\n");
            }

            File.AppendAllText(gitIgnorePath, ignoreContent.ToString());

            Log?.Info($"File written: {gitIgnorePath}.");

            return(0);
        }
Exemplo n.º 33
0
        static void Main(string[] args)
        {
            var log = new Log();
              var statistics = new Statistics(log);

              var programConfiguration = new ProgramConfiguration();

              if (!programConfiguration.Initialize(args))
            return;

              log.IsVerbose = programConfiguration.IsVerbose;

              INetworkNode networkNode;

              switch (programConfiguration.Direction)
              {
            case DirectionTypes.Sender:
              {
            networkNode = new Sender(log, statistics, programConfiguration);

            log.Info("Application initialized - press Escape to exit.");
              }
              break;
            case DirectionTypes.Receiver:
              {
            networkNode = new Receiver(log, statistics, programConfiguration);

            log.Info("Application initialized - press Escape to exit.");
              }
              break;
            default:
              throw new Exception("Invalid network node direction.");
              }

              networkNode.Start();
              statistics.StartPrintStatistics(programConfiguration.Direction);

              while (Console.ReadKey(true).Key != ConsoleKey.Escape)
              {
              }

              log.Info("Application shutting down...");
        }
Exemplo n.º 34
0
        /// <summary>
        /// Policy iteration for MDP
        /// </summary>
        /// <param name="basePolicy">Starting policy</param>
        /// <param name="optimalPolicy">Resulting optimal policy</param>
        /// <param name="tolerance">Convergence tolerance</param>
        /// <returns>Optimal value</returns>
        public double GetOptimalValueViaPolicyIteration(
            IDeterministicPolicy <TState> basePolicy,
            out IDeterministicPolicy <TState> optimalPolicy,
            double tolerance = 0.0001)
        {
            var policy = (IDeterministicPolicy <TState>)basePolicy.Clone();
            var node   = Policies.AddFirst(basePolicy);
            var value  = GetOptimalValue(policy, tolerance);

            optimalPolicy = policy = PolicyIteration(policy);
            var outputStates = new List <TState> {
                _initialState
            };

            outputStates.AddRange(policy.GetAllowedActions(_initialState).Where(a => a != null)
                                  .SelectMany(a => a[_initialState]));
            while (policy.IsModified)
            {
                node = Policies.AddAfter(node, policy);
                var nextValue = GetOptimalValue(policy, tolerance, false, outputStates.Distinct().ToArray());
                if (LogProgress)
                {
                    Log?.Info($"{value.Mean}->{nextValue.Mean} at variance {Math.Sqrt(value.Variance - (value.Mean * value.Mean))}->{Math.Sqrt(nextValue.Variance - (nextValue.Mean * nextValue.Mean))} with {policy.Modifications.Length} modifications");
                }
                var ratio = value.Mean > 0 ? nextValue.Mean / value.Mean : value.Mean / nextValue.Mean;
                if ((nextValue.Mean - (tolerance * 100) < value.Mean) || Math.Abs(ratio) < 1 + RelativeOptimalTolerance)
                {
                    value = nextValue;
                    break;
                }

                value  = nextValue;
                policy = PolicyIteration(policy);
                if (node.Previous == null)
                {
                    continue;
                }

                ValueFunctions[node.Previous.Value].Clear();
                ValueFunctions.Remove(node.Previous.Value);
                Policies.Remove(node.Previous);
            }

            value         = GetOptimalValue(policy, tolerance);
            optimalPolicy = (IDeterministicPolicy <TState>)basePolicy.Clone();
            foreach (var state in AllStateSpace)
            {
                optimalPolicy[state] = policy[state];
            }

            ValueFunctions.Clear();
            Policies.Clear();

            return(value.Mean);
        }
        /// <inheritdoc cref="CodeMonkeys.Navigation.INavigationService.Register(INavigationRegistration)" />
        public void Register(INavigationRegistration registration)
        {
            RegisterInternal(registration);

            if (registration.PreCreateInstance)
            {
                Task.Run(() => CreateCachedContent(registration));
            }

            Log?.Info($"Registered ViewModel of type {registration.ViewModelType.Name} to page {registration.ViewType.Name}.");
        }
Exemplo n.º 36
0
 public void AddEntry_CreateLogEntries_EntriesIncreased(int input)
 {
     var uut = new Log(new ConsoleOutput(), new FileFormatter());
     int i = input;
     while (i > 0)
     {
         uut.Info(testString);
         i--;
     }
     Assert.That(uut.NumberOfEntries, Is.EqualTo(input));
 }
Exemplo n.º 37
0
        private void S88COnStarted(object sender, EventArgs e)
        {
            Log?.Info("ECoS connection for S88 established");

            List <ICommand> initialCommands = new List <ICommand>()
            {
                CommandFactory.Create($"queryObjects({Globals.ID_EV_S88}, ports)"),
                CommandFactory.Create($"request({Globals.ID_EV_S88}, view)")
            };

            S88Connector.SendCommands(initialCommands);
        }
Exemplo n.º 38
0
 public void Write_OutputEntryToConsole_EntryOutputted()
 {
     string infoString = "Dette er bare en smule info!";
     var output = Substitute.For<ILogOutput>();
     string result = null;
     output.Write(Arg.Do<string>(arg => result = arg));
     using ( var uut = new Log(output, new FileFormatter()))
     {
         uut.Info(infoString);
     }
     Assert.That(result.Contains(infoString));
 }
        internal static async Task <TViewModelInterface> InitializeViewModelInternal <TViewModelInterface>()

            where TViewModelInterface : class, IViewModel
        {
            var viewModelInstance = dependencyResolver.Resolve <TViewModelInterface>();
            await viewModelInstance.InitializeAsync();

            Log?.Info(
                $"ViewModel viewModel of type {typeof(TViewModelInterface).Name} has been created and initialized!");

            return(viewModelInstance);
        }
        public TResolve Resolve <TResolve>()
            where TResolve : class
        {
            Log?.Info($"Trying to resolve type '{typeof(TResolve).Name}'...");

            if (!container.CanResolve <TResolve>())
            {
                throw new KeyNotFoundException(
                          $"There is no registration for the type '{typeof(TResolve).Name}'. Check your bootstrap!");
            }

            return(container.TryGetAndThrowOnInvalidBinding <TResolve>());
        }
Exemplo n.º 41
0
        public Session(Socket socket, int socketBufferSize, Log logger)
        {
            sendSaea.AcceptSocket = socket;
            sendSaea.Completed   += IOCompleted;
            sendSaea.SetBuffer(new byte[socketBufferSize], 0, socketBufferSize);

            receiveSaea.AcceptSocket = socket;
            receiveSaea.Completed   += IOCompleted;
            receiveSaea.SetBuffer(new byte[socketBufferSize], 0, socketBufferSize);

            this.logger = logger;

            logger?.Info($"Session.Session: receiveSaea={receiveSaea.GetHashCode()}, sendSaea={sendSaea.GetHashCode()}, socket={receiveSaea.AcceptSocket.GetHashCode()}");
        }
Exemplo n.º 42
0
        public void WatersLockmassPerfTest()
        {
            Log.AddMemoryAppender();
            TestFilesZip = "https://skyline.gs.washington.edu/perftests/PerfTestLockmass.zip";
            TestFilesPersistent = new[] { "ID19638_01_UCA195_2533_082715.raw" }; // List of files that we'd like to unzip alongside parent zipFile, and (re)use in place

            MsDataFileImpl.PerfUtilFactory.IssueDummyPerfUtils = false; // Turn on performance measurement

            RunFunctionalTest();
            
            var logs = Log.GetMemoryAppendedLogEvents();
            var stats = PerfUtilFactory.SummarizeLogs(logs, TestFilesPersistent); // Show summary
            var log = new Log("Summary");
            if (TestFilesDirs != null)
                log.Info(stats.Replace(TestFilesDir.PersistentFilesDir, "")); // Remove tempfile info from log
        }
        public void WatersIMSImportTest()
        {
            Log.AddMemoryAppender();
            TestFilesZip = "https://skyline.gs.washington.edu/perftests/PerfImportResultsWatersIMS.zip";
            TestFilesPersistent = new[] { "ID12692_01_UCA168_3727_040714.raw", "ID12692_01_UCA168_3727_040714_IA_final_fragment.csv" }; // List of files that we'd like to unzip alongside parent zipFile, and (re)use in place

            MsDataFileImpl.PerfUtilFactory.IssueDummyPerfUtils = false; // Turn on performance measurement

            RunFunctionalTest();
            
            var logs = Log.GetMemoryAppendedLogEvents();
            var stats = PerfUtilFactory.SummarizeLogs(logs, TestFilesPersistent); // Show summary
            var log = new Log("Summary");
            if (TestFilesDirs != null)
                log.Info(stats.Replace(TestFilesDir.PersistentFilesDir, "")); // Remove tempfile info from log
        }
        public void AgilentIMSImportTest()
        {
            Log.AddMemoryAppender();

            TestFilesZip = "https://skyline.gs.washington.edu/perftests/PerfImportResultsAgilentIMSv3.zip";
            TestFilesPersistent = new[] { "19pep_1700V_pos_3May14_Legolas.d", "19pep_1700V_CE22_pos_5May14_Legolas.d" }; // list of files that we'd like to unzip alongside parent zipFile, and (re)use in place

            MsDataFileImpl.PerfUtilFactory.IssueDummyPerfUtils = false; // turn on performance measurement

            RunFunctionalTest();
            
            var logs = Log.GetMemoryAppendedLogEvents();
            var stats = PerfUtilFactory.SummarizeLogs(logs, TestFilesPersistent); // show summary
            var log = new Log("Summary");
            if (TestFilesDirs != null)
                log.Info(stats.Replace(TestFilesDir.PersistentFilesDir, "")); // Remove tempfile info from log
        }
Exemplo n.º 45
0
 public void TestContext()
 {
     var queue = new Loggers.Queue();
      var log = new Log(this);
      using (Log.RegisterInstance(
        new Instance()
        {
           Properties = new[]
           {
              "Process.ID",
              "Process.Name",
              "Process.StartTime",
              "Process.PeakVirtualMemory",
              "Process.PeakPagedMemory",
              "Process.PeakWorkingSetMemory",
              "Process.ProcessorTime",
              "Process.PrivilegedProcessorTime",
              "Process.UserProcessorTime"
           },
           Logger = queue,
           Buffer = 0,
           Synchronous = true
        }
     )
      )
      {
     log.Info("test");
     var evt = queue.Dequeue().Single();
     using (var process = System.Diagnostics.Process.GetCurrentProcess())
     {
        Assert.AreEqual(evt["Process.ID"], process.Id);
        Assert.AreEqual(evt["Process.Name"], process.ProcessName);
        Assert.AreEqual(evt["Process.StartTime"], process.StartTime);
        Assert.IsTrue((Int64)evt["Process.PeakVirtualMemory"] > 0);
        Assert.IsTrue((Int64)evt["Process.PeakPagedMemory"] > 0);
        Assert.IsTrue((Int64)evt["Process.PeakWorkingSetMemory"] > 0);
        Assert.IsTrue((TimeSpan)evt["Process.ProcessorTime"] > TimeSpan.FromTicks(0));
        Assert.IsTrue((TimeSpan)evt["Process.PrivilegedProcessorTime"] > TimeSpan.FromTicks(0));
        Assert.IsTrue((TimeSpan)evt["Process.UserProcessorTime"] > TimeSpan.FromTicks(0));
     }
      }
 }
Exemplo n.º 46
0
        public LogManager()
        {
            if (!DesignerProperties.IsInDesignTool)
                m_logs = new ObservableCollection<ILog>();
            else
            {
                Log stringLog = new Log(typeof(string), null);
                stringLog.Debug("Debug");
                stringLog.Info("Info");
                stringLog.Warn("Warn");
                stringLog.Fatal("Fatal");

                m_logs = new ObservableCollection<ILog>();
                m_logs.Add(stringLog);
            }

            m_readonlyLogs = new ReadOnlyObservableCollection<ILog>(m_logs);
            m_globalLog = new Log(typeof(Global), null);
            m_logs.Add(m_globalLog);
        }
Exemplo n.º 47
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TestContext"/> class.
        /// </summary>
        /// <param name="path">The full path to the application executable.</param>
        /// <param name="log">The log for the test.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="path"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     Thrown if <paramref name="path"/> is an empty string.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="log"/> is <see langword="null" />.
        /// </exception>
        public TestContext(string path, Log log)
        {
            {
                Lokad.Enforce.Argument(() => path);
                Lokad.Enforce.Argument(() => path, Lokad.Rules.StringIs.NotEmpty);
                Lokad.Enforce.Argument(() => log);
            }

            m_Log = log;
            m_Application = ApplicationProxies.StartApplication(path, log);
            if ((m_Application == null) || (m_Application.Process == null) || Application.Process.HasExited)
            {
                throw new RegressionTestFailedException();
            }

            var text = string.Format(
                CultureInfo.InvariantCulture,
                "Started [{0}] - PID: [{1}]",
                m_Application.Name,
                m_Application.Process.Id);
            log.Info("TestContext - Create", text);
        }
Exemplo n.º 48
0
 public static void Main(string[] args)
 {
     if (System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/settings.json"))
     {
         Configuration config = Configuration.LoadConfiguration(AppDomain.CurrentDomain.BaseDirectory + "/settings.json");
         Log mainLog = new Log(config.MainLog, null);
         foreach (Configuration.BotInfo info in config.Bots)
         {
             mainLog.Info("Launching Bot " + info.DisplayName + "...");
             new Thread(() =>
             {
                 int crashes = 0;
                 while (crashes < 1000)
                 {
                     try
                     {
                         new Bot(info, config.ApiKey, (Bot bot, SteamID sid) =>
                         {
                             return (SteamBot.UserHandler)System.Activator.CreateInstance(Type.GetType(info.BotControlClass), new object[] { bot, sid });
                         });
                     }
                     catch (Exception e)
                     {
                         mainLog.Error("Error With Bot: " + e);
                         crashes++;
                     }
                 }
             }).Start();
             Thread.Sleep(5000);
         }
         MySQL.start();
     }
     else
     {
         Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory);
         Console.WriteLine("Configuration File Does not exist. Please rename 'settings-template.json' to 'settings.json' and modify the settings to match your environment");
     }
 }
Exemplo n.º 49
0
 public static void Main(string[] args)
 {
     if (System.IO.File.Exists("settings.json"))
     {
         Configuration config = Configuration.LoadConfiguration("settings.json");
         Log mainLog = new Log(config.MainLog, null);
         foreach (Configuration.BotInfo info in config.Bots)
         {
             mainLog.Info("Launching Bot " + info.DisplayName + "...");
             new Thread(() =>
             {
                 int crashes = 0;
                 while (crashes < 1000)
                 {
                     try
                     {
                         new Bot(info, config.ApiKey, (Bot bot, SteamID sid) =>
                         {
                             return new SimpleUserHandler(bot, sid);
                         }, true);
                     }
                     catch (Exception e)
                     {
                         mainLog.Error("Error With Bot: " + e);
                         crashes++;
                     }
                 }
             }).Start();
             Thread.Sleep(5000);
         }
     }
     else
     {
         Console.WriteLine("Configuration File Does not exist. Please rename 'settings-template.json' to 'settings.json' and modify the settings to match your environment");
     }
 }
Exemplo n.º 50
0
 public void Write_LogEntryContainingInfo_True()
 {
     string infoString = "Dette er bare en smule test!";
     var output = Substitute.For<ILogOutput>();
     string result = null;
     output.Write(Arg.Do<string>(arg => result = arg));
     using (var uut = new Log(output, new FileFormatter()))
     {
         uut.Info(infoString);
     }
     Assert.That(result.Contains(Log.Priority.Info.ToString()));
 }
Exemplo n.º 51
0
        private static TestResult ExecuteTestCase(TestStep testCase, Log testLog, string applicationPath)
        {
            const string prefix = "Execute test case";
            var count = 0;
            var hasPassed = false;
            var results = Enumerable.Range(0, TestConstants.MaximumRetryCount)
                .Select(i => new TestResult())
                .ToArray();
            while ((count < TestConstants.MaximumRetryCount) && (!hasPassed))
            {
                testLog.Info(
                    prefix,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Executing test case: {0}. Iteration: {1}",
                        testCase.Name,
                        count + 1));
                try
                {
                    using (var context = new TestContext(applicationPath, testLog))
                    {
                        TestResult local;
                        try
                        {
                            local = testCase.Test(context.Application, testLog);
                            foreach (var error in local.Errors)
                            {
                                results[count].AddError(error);
                            }
                        }
                        catch (Exception e)
                        {
                            testLog.Error(prefix, e.ToString());
                            results[count].AddError(
                                string.Format(
                                    CultureInfo.InvariantCulture,
                                    "Error in test case: {0}. Error was: {1}",
                                    testCase.Name,
                                    e));
                        }
                        finally
                        {
                            testLog.Info(
                                prefix,
                                string.Format(
                                    CultureInfo.InvariantCulture,
                                    "Completed test case: {0}. Result: {1}",
                                    testCase.Name,
                                    results[count].Status));
                        }
                    }
                }
                catch (Exception e)
                {
                    results[count].AddError(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "Test case failed for: {0}. Iteration: {1}. Error: {2}",
                            testCase.Name,
                            count + 1,
                            e));
                }

                // Take snapshot of application
                // Grab log and error log
                hasPassed = results[count].Status == TestStatus.Passed;
                count++;
            }

            return results[count - 1];
        }
Exemplo n.º 52
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            Username     = config.Username;
            Password     = config.Password;
            DisplayName  = config.DisplayName;
            ChatResponse = config.ChatResponse;
            MaximumTradeTime = config.MaximumTradeTime;
            MaximiumActionGap = config.MaximumActionGap;
            DisplayNamePrefix = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            Admins       = config.Admins;
            this.apiKey  = apiKey;
            AuthCode     = null;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            log          = new Log (config.LogFile, this.DisplayName, LogLevel);
            CreateHandler = handlerCreator;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug ("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();
            log.Info ("Connecting...");
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback (true);
                    HandleSteamMessage (msg);
                }
            });

            new Thread(() => // Trade Polling if needed
            {
                while (true)
                {
                    Thread.Sleep (TradePollingInterval);
                    if (CurrentTrade != null)
                    {
                        try
                        {
                            CurrentTrade.Poll ();

                            if (CurrentTrade.OtherUserCancelled)
                            {
                                log.Info("Other user cancelled the trade.");
                                CurrentTrade = null;
                            }
                        }
                        catch (Exception e)
                        {
                            log.Error ("Error Polling Trade: " + e);
                            // ok then we should stop polling...
                            CurrentTrade = null;
                        }
                    }
                }
            }).Start ();

            CallbackThread.Start();
            log.Success ("Done Loading Bot!");
            CallbackThread.Join();
        }
Exemplo n.º 53
0
 public void TestEventProperties()
 {
     // configure the log
      var log = new Log(this);
      var queue = new Loggers.Queue();
      var props = new List<String>()
      {
     "Event.Type",
     "Event.Source",
     "Event.Timestamp",
     "Event.Time",
     "Event.Message",
     "Event.Exception",
      };
      using (
     Log.RegisterInstance(
        new Instance()
        {
           Logger = queue,
           Synchronous = true,
           Buffer = 0,
           Properties = props
        }
     )
      )
      {
     Event evt;
     // invalid property
     log.Trace("");
     evt = queue.Dequeue().Single();
     Assert.IsNull(evt[null]);
     Assert.IsNull(evt[""]);
     Assert.IsNull(evt[" "]);
     Assert.IsNull(evt["Invalid"]);
     Assert.IsNull(evt["Event.Invalid"]);
     // property list
     log.Error(new Exception("test"));
     evt = queue.Dequeue().Single();
     Assert.IsTrue(evt.Names.SequenceEqual(props));
     Assert.IsTrue(evt.Properties.Select(p => p.Key).SequenceEqual(props));
     Assert.IsTrue(!evt.Values.Any(v => v == null));
     Assert.IsTrue(!evt.Properties.Any(p => p.Value == null));
     // event type
     log.Trace("");
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Event.Type"], EventType.Trace);
     log.Info("");
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["event.type"], EventType.Info);
     log.Warn("");
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Event.type"], EventType.Warning);
     log.Error("");
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["event.Type"], EventType.Error);
     // event source
     log.Info("");
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Event.Source"], GetType());
     new Log(typeof(String)).Info("");
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Event.Source"], typeof(String));
     // event timestamp
     Int64 oldStamp = 0;
     log.Info("");
     evt = queue.Dequeue().Single();
     oldStamp = (Int64)evt["Event.Timestamp"];
     Assert.IsTrue(oldStamp != 0);
     log.Info("");
     evt = queue.Dequeue().Single();
     Assert.IsTrue((Int64)evt["Event.Timestamp"] > oldStamp);
     // event time
     DateTime oldTime;
     log.Info("");
     evt = queue.Dequeue().Single();
     oldTime = (DateTime)evt["Event.Time"];
     Assert.IsTrue(oldTime > DateTime.UtcNow - TimeSpan.FromMinutes(1));
     Assert.IsTrue(oldTime <= DateTime.UtcNow);
     log.Info("");
     evt = queue.Dequeue().Single();
     Assert.IsTrue((DateTime)evt["Event.Time"] >= oldTime);
     // event message
     log.Info(null);
     evt = queue.Dequeue().Single();
     Assert.IsNull(evt["Event.Message"]);
     log.Info("");
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Event.Message"], "");
     log.Info(" ");
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Event.Message"], " ");
     log.Info("test");
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Event.Message"], "test");
     log.Info("test{0}test{1}test", 0, 1);
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Event.Message"], "test0test1test");
     // event exception
     log.Trace(null);
     evt = queue.Dequeue().Single();
     Assert.IsNull(evt["Event.Exception"]);
     log.Info(null);
     evt = queue.Dequeue().Single();
     Assert.IsNull(evt["Event.Exception"]);
     log.Warn((Exception)null);
     evt = queue.Dequeue().Single();
     Assert.IsNull(evt["Event.Exception"]);
     log.Error((Exception)null);
     evt = queue.Dequeue().Single();
     Assert.IsNull(evt["Event.Exception"]);
     log.Warn(new Exception("test"));
     evt = queue.Dequeue().Single();
     Assert.AreEqual(((Exception)evt["Event.Exception"]).Message, "test");
     Assert.AreEqual(evt["Event.Message"], "test");
     log.Error(new Exception("test"));
     evt = queue.Dequeue().Single();
     Assert.AreEqual(((Exception)evt["Event.Exception"]).Message, "test");
     Assert.AreEqual(evt["Event.Message"], "test");
      }
 }
Exemplo n.º 54
0
 public void TestFiltering()
 {
     var log = new Log(this);
      var queue = new Loggers.Queue();
      var instance = new Instance()
      {
     Logger = queue,
     Synchronous = true,
     Buffer = 0,
     Properties = new[]
     {
        "Event.Type",
        "TestLog.ClassValue",
        "Event.EventValue",
        "Global.Host"
     }
      };
      // property inclusion
      instance.Filter = new Filter()
      {
     IncludeProps = new[]
     {
        new Filter.Property("Event.Type", "Error"),
        new Filter.Property("Event.Type", "Warning")
     }
      };
      using (Log.RegisterInstance(instance))
      {
     log.Error("test");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
     log.Warn("test");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
     log.Info("test");
     Assert.IsFalse(queue.Dequeue().Any());
      }
      // property exclusion
      instance.Filter = new Filter()
      {
     ExcludeProps = new[]
     {
        new Filter.Property("Event.Type", "Error"),
        new Filter.Property("Event.Type", "Warning")
     }
      };
      using (Log.RegisterInstance(instance))
      {
     log.Error("test");
     Assert.IsFalse(queue.Dequeue().Any());
     log.Warn("test");
     Assert.IsFalse(queue.Dequeue().Any());
     log.Info("test");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
      }
      instance.Filter = new Filter()
      {
     ExcludeProps = new[]
     {
        new Filter.Property("Event.Type", "Error"),
        new Filter.Property("Event.Type", "Warning")
     }
      };
      using (Log.RegisterInstance(instance))
      {
     log.Error("test");
     Assert.IsFalse(queue.Dequeue().Any());
     log.Warn("test");
     Assert.IsFalse(queue.Dequeue().Any());
     log.Info("test");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
      }
      // property inclusion/exclusion
      instance.Filter = new Filter()
      {
     IncludeProps = new[]
     {
        new Filter.Property("Event.Type", "Error"),
        new Filter.Property("Event.Type", "Warning")
     },
     ExcludeProps = new[]
     {
        new Filter.Property("Event.Type", "Warning"),
     }
      };
      using (Log.RegisterInstance(instance))
      {
     log.Error("test");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
     log.Warn("test");
     Assert.IsFalse(queue.Dequeue().Any());
     log.Info("test");
     Assert.IsFalse(queue.Dequeue().Any());
      }
      // source inclusion
      instance.Filter = new Filter()
      {
     IncludeProps = new[]
     {
        new Filter.Property("Event.Source", GetType().AssemblyQualifiedName),
        new Filter.Property("Event.Source", typeof(Int32).AssemblyQualifiedName)
     }
      };
      using (Log.RegisterInstance(instance))
      {
     log.Info("test");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
     new Log(typeof(Int32)).Info("test");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
     new Log(typeof(String)).Info("test");
     Assert.IsFalse(queue.Dequeue().Any());
      }
      // source exclusion
      instance.Filter = new Filter()
      {
     ExcludeProps = new[]
     {
        new Filter.Property("Event.Source", GetType().AssemblyQualifiedName),
        new Filter.Property("Event.Source", typeof(Int32).AssemblyQualifiedName)
     }
      };
      using (Log.RegisterInstance(instance))
      {
     log.Info("test");
     Assert.IsFalse(queue.Dequeue().Any());
     new Log(typeof(Int32)).Info("test");
     Assert.IsFalse(queue.Dequeue().Any());
     new Log(typeof(String)).Info("test");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
      }
      // source inclusion/exclusion
      instance.Filter = new Filter()
      {
     IncludeProps = new[]
     {
        new Filter.Property("Event.Source", GetType().AssemblyQualifiedName),
        new Filter.Property("Event.Source", typeof(Int32).AssemblyQualifiedName)
     },
     ExcludeProps = new[]
     {
        new Filter.Property("Event.Source", typeof(Int32).AssemblyQualifiedName)
     }
      };
      using (Log.RegisterInstance(instance))
      {
     log.Info("test");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
     new Log(typeof(Int32)).Info("test");
     Assert.IsFalse(queue.Dequeue().Any());
     new Log(typeof(String)).Info("test");
     Assert.IsFalse(queue.Dequeue().Any());
      }
      // non-event property filter
      instance.Filter = new Filter()
      {
     IncludeProps = new[]
     {
        new Filter.Property("Event.Message", "test"),
     }
      };
      using (Log.RegisterInstance(instance))
      {
     log.Error("test");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
     log.Error("invalid");
     Assert.IsFalse(queue.Dequeue().Any());
      }
      instance.Filter = new Filter()
      {
     ExcludeProps = new[]
     {
        new Filter.Property("Event.Message", "test"),
     }
      };
      using (Log.RegisterInstance(instance))
      {
     log.Error("test");
     Assert.IsFalse(queue.Dequeue().Any());
     log.Error("invalid");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
      }
      // non-event global property filter
      instance.Filter = new Filter()
      {
     IncludeProps = new[]
     {
        new Filter.Property("Global.Host", Environment.MachineName),
     }
      };
      using (Log.RegisterInstance(instance))
      {
     log.Error("test");
     Assert.AreEqual(queue.Dequeue().Count(), 1);
      }
      instance.Filter = new Filter()
      {
     ExcludeProps = new[]
     {
        new Filter.Property("Global.Host", Environment.MachineName),
     }
      };
      using (Log.RegisterInstance(instance))
      {
     log.Error("test");
     Assert.IsFalse(queue.Dequeue().Any());
      }
 }
Exemplo n.º 55
0
 public void TestPerformance()
 {
     var log = new Log(this);
      Stopwatch clock = new Stopwatch();
      // zero loggers, event context, unfiltered, unbuffered, synchronous
      clock.Restart();
      for (Int32 i = 0; i < PerformanceIterations; i++)
     log.Info("test");
      clock.Stop();
      TraceClock("ZEUUS", clock);
      // single logger, event context, unfiltered, unbuffered, synchronous
      using (
     Log.RegisterInstance(
        new Instance()
        {
           Properties = new[] { "Event.Type" },
           Logger = new Loggers.Null(),
           Buffer = 0,
           Synchronous = true
        }
     )
      )
      {
     clock.Restart();
     for (Int32 i = 0; i < PerformanceIterations; i++)
        log.Info("test");
     clock.Stop();
     TraceClock("SEUUS", clock);
      }
      // two loggers, event context, unfiltered, unbuffered, synchronous
      using (
     Log.RegisterInstance(
        new Instance()
        {
           Properties = new[] { "Event.Type" },
           Logger = new Loggers.Null(),
           Buffer = 0,
           Synchronous = true
        }
     )
      )
      using (
     Log.RegisterInstance(
        new Instance()
        {
           Properties = new[] { "Event.Type" },
           Logger = new Loggers.Null(),
           Buffer = 0,
           Synchronous = true
        }
     )
      )
      {
     clock.Restart();
     for (Int32 i = 0; i < PerformanceIterations; i++)
        log.Info("test");
     clock.Stop();
     TraceClock("TEUUS", clock);
      }
      // single logger, global context, unfiltered, unbuffered, synchronous
      using (
     Log.RegisterInstance(
        new Instance()
        {
           Properties = new[] { "Global.Value" },
           Logger = new Loggers.Null(),
           Buffer = 0,
           Synchronous = true
        }
     )
      )
      {
     clock.Restart();
     for (Int32 i = 0; i < PerformanceIterations; i++)
        log.Info("test");
     clock.Stop();
     TraceClock("SGUUS", clock);
      }
      // single logger, event context, property filtered, unbuffered, synchronous
      using (
     Log.RegisterInstance(
        new Instance()
        {
           Properties = new[] { "Event.Type" },
           Logger = new Loggers.Null(),
           Filter = new Filter()
           {
              IncludeProps = new[]
              {
                 new Filter.Property("Event.Type", EventType.Info.ToString())
              }
           },
           Buffer = 0,
           Synchronous = true
        }
     )
      )
      {
     clock.Restart();
     for (Int32 i = 0; i < PerformanceIterations; i++)
        log.Info("test");
     clock.Stop();
     TraceClock("SEPUS", clock);
      }
      // single logger, event context, unfiltered, buffered, synchronous
      using (
     Log.RegisterInstance(
        new Instance()
        {
           Properties = new[] { "Event.Type" },
           Logger = new Loggers.Null(),
           Buffer = Math.Max(PerformanceIterations / 10, 10),
           Synchronous = true
        }
     )
      )
      {
     clock.Restart();
     for (Int32 i = 0; i < PerformanceIterations; i++)
        log.Info("test");
     clock.Stop();
     TraceClock("SEUBS", clock);
      }
      // single logger, event context, unfiltered, unbuffered, asynchronous
      using (
     Log.RegisterInstance(
        new Instance()
        {
           Properties = new[] { "Event.Type" },
           Logger = new Loggers.Null(),
           Buffer = Math.Max(PerformanceIterations / 10, 10),
           Synchronous = false
        }
     )
      )
      {
     clock.Restart();
     for (Int32 i = 0; i < PerformanceIterations; i++)
        log.Info("test");
     clock.Stop();
     TraceClock("SEUUA", clock);
      }
      Log.Flush();
 }
Exemplo n.º 56
0
        public Bot(Configuration.BotInfo config, Log log, string apiKey, UserHandlerCreator handlerCreator, Login _login, bool debug = false)
        {
            this.main = _login;
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = _login.Username,
                Password = _login.Password
            };
            ChatResponse = "";
            TradePollingInterval = 500;
            Admins = new ulong[1];
            Admins[0] = 0;
            this.apiKey = apiKey;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), "Debug", true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            this.log = log;
            CreateHandler = handlerCreator;
            BotControlClass = "SteamBot.SimpleUserHandler";

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug ("Initializing Steam account...");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Initializing Steam account...";
            }));
            SteamClient = new SteamClient();
            SteamClient.AddHandler(new ClientPlayerNicknameListHandler());
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>();
            SteamNicknames = SteamClient.GetHandler<ClientPlayerNicknameListHandler>();
            log.Info ("Connecting...");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Connecting to Steam...";
            }));
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback(true);

                    new Thread(() => HandleSteamMessage(msg)).Start();
                }
            });

            CallbackThread.Start();
            CallbackThread.Join();
            log.Success("Done loading account!");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Done loading account!";
            }));
        }
Exemplo n.º 57
0
        public void Dispose_CallingWithTryCatchBlockThreeEntries_TryCatchBlock()
        {
            var output = Substitute.For<ILogOutput>();
            string result = null;
            output.Write(Arg.Do<string>(arg => result = arg));

            var uut = new Log(output, new FileFormatter());
            try
            {
                uut.Info(testString);
                uut.Info(testString);
                uut.Info(testString);
            }
            finally
            {
                if (uut != null)
                    ((IDisposable) uut).Dispose();

            }
            Assert.That(result.Contains(testString));
        }
Exemplo n.º 58
0
 public void TestConfiguration()
 {
     var log = new Log(this);
      var queue = new Loggers.Queue();
      Event evt = null;
      // invalid global context
      AssertException(() => Log.RegisterContext("Global", new Dictionary<String, Func<Object>>()
     {
        { "Host", () => "test" }
     }
      ));
      // invalid instance registration
      AssertException(() => Log.RegisterInstance(null));
      AssertException(() => Log.RegisterInstance(new Instance()));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Buffer = -1,
        Logger = new Loggers.Null(),
        Properties = new[] { "Event.Type" },
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = null,
        Properties = new[] { "Event.Type" },
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = null,
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = new String[0],
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = new[] { (String)null },
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = new[] { "" },
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = new[] { " " },
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = new[] { "invalid" },
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = new[] { "Event.Type" },
        Filter = new Filter()
        {
           IncludeProps = new[] { new Filter.Property(null, "test") },
        }
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = new[] { "Event.Type" },
        Filter = new Filter()
        {
           IncludeProps = new[] { new Filter.Property("", "test") },
        }
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = new[] { "Event.Type" },
        Filter = new Filter()
        {
           IncludeProps = new[] { new Filter.Property(" ", "test") },
        }
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = new[] { "Event.Type" },
        Filter = new Filter()
        {
           ExcludeProps = new[] { new Filter.Property(null, "test") },
        }
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = new[] { "Event.Type" },
        Filter = new Filter()
        {
           ExcludeProps = new[] { new Filter.Property("", "test") },
        }
     }
      ));
      AssertException(() => Log.RegisterInstance(
     new Instance()
     {
        Logger = new Loggers.Null(),
        Properties = new[] { "Event.Type" },
        Filter = new Filter()
        {
           ExcludeProps = new[] { new Filter.Property(" ", "test") },
        }
     }
      ));
      // default instance registration
      var instance = new Instance()
      {
     Logger = queue,
     Synchronous = true,
     Buffer = 0,
     Properties = new[] { "Event.Type" }
      };
      Log.RegisterInstance(instance);
      log.Trace("trace");
      evt = queue.Dequeue().Single();
      Assert.AreEqual(evt["Event.Type"], EventType.Trace);
      Log.UnregisterInstance(instance);
      log.Trace("trace");
      Assert.IsFalse(queue.Dequeue().Any());
      // disposable instance registration
      using (
     Log.RegisterInstance(
        new Instance()
        {
           Logger = queue,
           Synchronous = true,
           Buffer = 0,
           Properties = new[] { "Event.Type" }
        }
     )
      )
      {
     log.Info("info");
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Event.Type"], EventType.Info);
      }
      log.Info("info");
      Assert.IsFalse(queue.Dequeue().Any());
      // log source type
      Assert.AreEqual(log.SourceType, GetType());
 }
Exemplo n.º 59
0
 public void TestGlobalProperties()
 {
     // configure the log
      var log = new Log(this);
      var queue = new Loggers.Queue();
      using (
     Log.RegisterInstance(
        new Instance()
        {
           Logger = queue,
           Synchronous = true,
           Buffer = 0,
           Properties = new[]
           {
              "Global.Value",
              "Global.Host"
           }
        }
     )
      )
      {
     Event evt;
     var globalCurrent = globalValue;
     // initial value
     log.Info(null);
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Global.Value"], globalValue);
     Assert.AreEqual(evt["Global.Value"], ++globalCurrent);
     Assert.AreEqual(evt["Global.Host"], Environment.MachineName);
     // subsequent
     log.Info(null);
     evt = queue.Dequeue().Single();
     Assert.AreEqual(evt["Global.Value"], globalValue);
     Assert.AreEqual(evt["Global.Value"], ++globalCurrent);
     Assert.AreEqual(evt["Global.Host"], Environment.MachineName);
      }
 }
Exemplo n.º 60
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            Username     = config.Username;
            Password     = config.Password;
            DisplayName  = config.DisplayName;
            ChatResponse = config.ChatResponse;
            MaximumTradeTime = config.MaximumTradeTime;
            MaximiumActionGap = config.MaximumActionGap;
            DisplayNamePrefix = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            Admins       = config.Admins;
            this.apiKey  = apiKey;
            AuthCode     = null;
            log          = new Log (config.LogFile, this);
            CreateHandler = handlerCreator;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug ("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();
            log.Info ("Connecting...");
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback (true);
                    HandleSteamMessage (msg);
                }
            });

            new Thread(() => // Trade Polling if needed
            {
                while (true)
                {
                    Thread.Sleep (TradePollingInterval);
                    if (CurrentTrade != null)
                    {
                        try
                        {
                            CurrentTrade.Poll ();
                        }
                        catch (Exception e)
                        {
                            log.Error ("Error Polling Trade: " + e);
                        }
                    }
                }
            }).Start ();

            CallbackThread.Start();
            log.Success ("Done Loading Bot!");
            CallbackThread.Join();
        }