private void DoCallback(Log.LogLevel level, string tag, string msg)
 {
     if (_logCallback != null)
     {
         _logCallback(level, tag, msg);
     }
 }
        public int TestOverrideLogLevel(Log.LogLevel inputLevel)
        {
            var count = 0;

            Log.Level = Log.LogLevel.None;
            Log.Domains.Database.Level = inputLevel;
            _logCallback = (level, tag, msg) =>
            {
                Console.WriteLine("Received {0} message from {1}", level, tag);
                if (tag == String.Format("DATABASE ({0})", TAG))
                {
                    count++;
                }

                Assert.IsTrue(inputLevel.HasFlag(level));
            };

            Log.To.Database.V(TAG, "TEST");
            Log.To.Database.D(TAG, "TEST");
            Log.To.Database.I(TAG, "TEST");
            Log.To.Database.W(TAG, "TEST");
            Log.To.Database.E(TAG, "TEST");

            _logCallback = (level, tag, msg) => { };

            return(count);
        }
Exemple #3
0
 /// <summary>
 /// 设置日志提供工具
 /// </summary>
 /// <param name="LogLevel"></param>
 /// <param name="Provider"></param>
 public static void SetLogger(String LogLevel = "debug", String Provider = "file")
 {
     _level    = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), LogLevel, true);
     _provider = Provider;
     Config.SetConfigs("WLN_LOG_LEVEL", LogLevel);
     Config.SetConfigs("WLN_LOG_PROVIDER", Provider);
 }
Exemple #4
0
 /// <summary>
 /// 重新初始化状态
 /// </summary>
 public static void Init()
 {
     Config.Clear();
     XServer.Common.Init();
     _log_level = Log.LogLevel.None;
     _console   = true;
 }
Exemple #5
0
        static void printMethod(MethodPrinter methodPrinter, MethodDefinition method)
        {
            const Log.LogLevel dumpLogLevel = Log.LogLevel.verbose;

            if (!Log.isAtLeast(dumpLogLevel))
            {
                return;
            }

            Log.indent();

            Log.v("Locals:");
            Log.indent();
            for (int i = 0; i < method.Body.Variables.Count; i++)
            {
                Log.v("#{0}: {1}", i, method.Body.Variables[i].VariableType);
            }
            Log.deIndent();

            Log.v("Code:");
            Log.indent();
            methodPrinter.print(dumpLogLevel, method.Body.Instructions, method.Body.ExceptionHandlers);
            Log.deIndent();

            Log.deIndent();
        }
Exemple #6
0
        void deobfuscate(MethodDefinition method, BlocksCflowDeobfuscator cflowDeobfuscator, MethodPrinter methodPrinter)
        {
            if (!hasNonEmptyBody(method))
            {
                return;
            }

            var blocks             = new Blocks(method);
            int numRemovedLocals   = 0;
            int oldNumInstructions = method.Body.Instructions.Count;

            deob.deobfuscateMethodBegin(blocks);
            if (options.ControlFlowDeobfuscation)
            {
                cflowDeobfuscator.init(blocks);
                cflowDeobfuscator.deobfuscate();
            }

            if (deob.deobfuscateOther(blocks) && options.ControlFlowDeobfuscation)
            {
                cflowDeobfuscator.deobfuscate();
            }

            if (options.ControlFlowDeobfuscation)
            {
                numRemovedLocals = blocks.optimizeLocals();
                blocks.repartitionBlocks();
            }

            deobfuscateStrings(blocks);
            deob.deobfuscateMethodEnd(blocks);

            IList <Instruction>      allInstructions;
            IList <ExceptionHandler> allExceptionHandlers;

            blocks.getCode(out allInstructions, out allExceptionHandlers);
            DotNetUtils.restoreBody(method, allInstructions, allExceptionHandlers);

            if (numRemovedLocals > 0)
            {
                Log.v("Removed {0} unused local(s)", numRemovedLocals);
            }
            int numRemovedInstructions = oldNumInstructions - method.Body.Instructions.Count;

            if (numRemovedInstructions > 0)
            {
                Log.v("Removed {0} dead instruction(s)", numRemovedInstructions);
            }

            const Log.LogLevel dumpLogLevel = Log.LogLevel.veryverbose;

            if (Log.isAtLeast(dumpLogLevel))
            {
                Log.log(dumpLogLevel, "Deobfuscated code:");
                Log.indent();
                methodPrinter.print(dumpLogLevel, allInstructions, allExceptionHandlers);
                Log.deIndent();
            }
        }
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName          = config.DisplayName;
            MaximumTradeTime     = config.MaximumTradeTime;
            MaximiumActionGap    = config.MaximumActionGap;
            DisplayNamePrefix    = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            Admins           = config.Admins;
            BackpackUrl      = config.Backpack;
            sNumberTradeFile = config.TradeNumberSaveFile;
            this.apiKey      = apiKey;
            this.isprocess   = process;
            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;
            BotControlClass = config.BotControlClass;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;
            dReserved = new Dictionary <ulong, SteamID>();
            dDonated  = new Dictionary <ulong, SteamID>();
            log.Debug("Initializing Steam Bot...");
            SteamClient          = new SteamClient();
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            craftHandler         = new CraftingHandler(this);
            informHandler        = new InformHandler(this, BotControlClass.Substring(9));
            AdvertiseHandler     = new AdvertiseHandler(this, BotControlClass.Substring(9), clsFunctions.BotGroup);
            backgroundWorker     = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };

            if (!Directory.Exists(FriendsFolder))
            {
                Directory.CreateDirectory(FriendsFolder);
            }


            this.FriendActivity                  = FriendActivity.LoadFriendActivity(FriendsFolder + logOnDetails.Username + ".json");
            backgroundWorker.DoWork             += BackgroundWorkerOnDoWork;
            backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            backgroundWorker.RunWorkerAsync();
        }
Exemple #8
0
        private bool ShouldLog(Log.LogLevel level)
        {
            if (Log.Logger == null || Log.Disabled)
            {
                return(false);
            }

            return(Level >= level);
        }
Exemple #9
0
 /// <summary>
 /// 设置是否使用XCoreSessionStateStore来存储会话状态
 /// </summary>
 /// <param name="use"></param>
 /// <returns></returns>
 public static Boolean SetXCoreLoger(Log.LogLevel level = Log.LogLevel.All, Boolean inRealTime = true)
 {
     try
     {
         String str = "logLevel:" + level.ToString().ToLower() + "\nlogFile:log/log.txt\ninRealTime:" + (inRealTime ? "true" : "false");
         file.Write(PathHelper.Map(ConfigRoot + "/log.config"), str);
         return(true);
     }
     catch { return(false); }
 }
 void remoteLog(Log.LogLevel level, string message, string detail = null)
 {
     object postData = new {
         HotelId = Config.HotelId,
         Level   = level,
         Message = message,
         Detail  = detail
     };
     var _ = HttpPost.PostAsync(Config.RemoteLogUrl, postData);
 }
Exemple #11
0
        public BotControlForm(Configuration.BotInfo config, string apiKey, bool debug = false)
        {
            InitializeComponent();


            foreach (EPersonaState state in Enum.GetValues(typeof(EPersonaState)))
            {
                this.cbxPersonaState.Items.Add(state);
            }


            SetStatus("Setting variables...");

            logOnDetails = new SteamUser.LogOnDetails
            {
                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;
            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;
            BotControlClass = config.BotControlClass;

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


            SteamClient  = new SteamClient();
            SteamTrade   = SteamClient.GetHandler <SteamTrading>();
            SteamUser    = SteamClient.GetHandler <SteamUser>();
            SteamFriends = SteamClient.GetHandler <SteamFriends>();

            SetStatus("Connecting to Steam...");

            SteamClient.Connect();

            masterThread = new Thread(this.pollSteam);
            masterThread.Start();
        }
Exemple #12
0
 public async void ManageLog(string Message, Log.LogLevel Level = Log.LogLevel.Success, string Detail = null)
 {
     ctx.Logs.Add(new Log
     {
         DateTime = DateTime.Now,
         Detail   = Detail,
         Message  = Message,
         Level    = Level
     });
     await ctx.SaveChangesAsync();
 }
Exemple #13
0
        public async Task RecordLog(Log.LogLevel level, string message, string detail = null)
        {
            Log log = new Log {
                Level   = level,
                Message = message,
                Detail  = detail
            };

            ctx.Logs.Add(log);
            await ctx.SaveChangesAsync();
        }
Exemple #14
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="level"></param>
 /// <returns></returns>
 public static Level ToLog4NetLevel(this Log.LogLevel level)
 {
     return(level switch
     {
         Log.LogLevel.Info => Level.Info,
         Log.LogLevel.Debug => Level.Debug,
         Log.LogLevel.Error => Level.Error,
         Log.LogLevel.Critical => Level.Critical,
         Log.LogLevel.Warn => Level.Warn,
         _ => Level.Off
     });
Exemple #15
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                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;
            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;
            BotControlClass = config.BotControlClass;

            // 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);
                }
            });

            CallbackThread.Start();
            log.Success ("Done Loading Bot!");
            CallbackThread.Join();
        }
Exemple #16
0
        private void ReceiveLogMessage(string logMessage, Log.LogLevel level)
        {
            //Thread safing
            //Taken from http://stackoverflow.com/questions/418845/c-thread-safe-richtextbox-event-logging-method
            if (rbLogTxt.InvokeRequired)
            {
                rbLogTxt.BeginInvoke(new Action(delegate
                {
                    ReceiveLogMessage(logMessage, level);
                }));
                return;
            }

            switch (level)
            {
            case Log.LogLevel.TRACE:
                rbLogTxt.SelectionColor = Color.LightCyan;
                break;

            case Log.LogLevel.DEBUG:
                rbLogTxt.SelectionColor = Color.Yellow;
                break;

            case Log.LogLevel.INFO:
                rbLogTxt.SelectionColor = Color.White;
                break;

            case Log.LogLevel.WARN:
                rbLogTxt.SelectionColor = Color.Orange;
                break;

            case Log.LogLevel.ERROR:
                rbLogTxt.SelectionColor = Color.Tomato;
                break;

            case Log.LogLevel.FATAL:
                rbLogTxt.SelectionColor = Color.Red;
                break;
            }

            rbLogTxt.SelectedText += logMessage + '\n';


            //Taken from http://stackoverflow.com/questions/2196097/elegant-log-window-in-winforms-c-sharp (m_eiman)
            if (rbLogTxt.Lines.Length > MaxBufferSize)
            {
                rbLogTxt.Select(0, rbLogTxt.Text.IndexOf('\n') + 1);
                rbLogTxt.SelectedRtf    = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1053\\uc1 }";
                rbLogTxt.SelectionStart = rbLogTxt.Text.Length;
            }

            rbLogTxt.ScrollToCaret();
        }
Exemple #17
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                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;
            SchemaLang           = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en";
            Admins         = config.Admins;
            this.ApiKey    = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
            this.isprocess = process;

            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;
            BotControlClass = config.BotControlClass;
            SteamWeb        = new SteamWeb();

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

            log.Debug("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamClient.AddHandler(new SteamNotifications());
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            SteamNotifications   = SteamClient.GetHandler <SteamNotifications>();

            backgroundWorker = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            backgroundWorker.DoWork             += BackgroundWorkerOnDoWork;
            backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            backgroundWorker.RunWorkerAsync();
        }
Exemple #18
0
        public static void printStackTrace(Exception ex, Log.LogLevel logLevel = Log.LogLevel.error)
        {
            var line = new string('-', 78);

            Log.log(logLevel, "\n\n");
            Log.log(logLevel, line);
            Log.log(logLevel, "Stack trace:\n{0}", ex.StackTrace);
            Log.log(logLevel, "\n\nERROR: Caught an exception:\n");
            Log.log(logLevel, line);
            Log.log(logLevel, "Message:");
            Log.log(logLevel, "  {0}", ex.Message);
            Log.log(logLevel, "Type:");
            Log.log(logLevel, "  {0}", ex.GetType());
            Log.log(logLevel, line);
        }
Exemple #19
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, Interface gui, bool debug = false)
        {
            while (Interface.loginClicked == false)
            {
                // Wait for user to login
            }

            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = Interface.username,
                Password = Interface.password
            };
            Admins      = new ulong[1];
            Admins[0]   = 123456789;
            this.apiKey = apiKey;
            LogLevel    = Log.LogLevel.Info;
            //log = new Log(config.LogFile, this.DisplayName, LogLevel);
            CreateHandler   = handlerCreator;
            BotControlClass = config.BotControlClass;

            // 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>();
            gui.UpdateLog("\r\nConnecting, please wait...");
            ////log.Info("Connecting...");
            SteamClient.Connect();

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

                    HandleSteamMessage(msg, gui);
                }
            });

            CallbackThread.Start();
            ////log.Success("Done Loading Bot!");
            CallbackThread.Join();
        }
Exemple #20
0
 public void print(Log.LogLevel logLevel, IList<Instruction> allInstructions, IList<ExceptionHandler> allExceptionHandlers)
 {
     try {
         this.logLevel = logLevel;
         this.allInstructions = allInstructions;
         this.allExceptionHandlers = allExceptionHandlers;
         lastExInfo = new ExInfo();
         print();
     }
     finally {
         this.allInstructions = null;
         this.allExceptionHandlers = null;
         targets.Clear();
         labels.Clear();
         exInfos.Clear();
         lastExInfo = null;
     }
 }
Exemple #21
0
 public void print(Log.LogLevel logLevel, IList <Instruction> allInstructions, IList <ExceptionHandler> allExceptionHandlers)
 {
     try {
         this.logLevel             = logLevel;
         this.allInstructions      = allInstructions;
         this.allExceptionHandlers = allExceptionHandlers;
         lastExInfo = new ExInfo();
         print();
     }
     finally {
         this.allInstructions      = null;
         this.allExceptionHandlers = null;
         targets.Clear();
         labels.Clear();
         exInfos.Clear();
         lastExInfo = null;
     }
 }
Exemple #22
0
        /// <summary>
        /// Event Handler for logging.
        /// This event gets called if logging is done from Core or from Plugin.
        /// </summary>
        /// <param name="logLevel">Log level</param>
        /// <param name="format">Format</param>
        /// <param name="args">Arguments</param>
        private void OnNewLog(Log.LogLevel logLevel, string format, params object[] args)
        {
            switch (logLevel)
            {
            case Log.LogLevel.Debug:
                ServiceRegistration.Get <ILogger>().Debug(String.Format(format, args));
                break;

            case Log.LogLevel.Warn:
                ServiceRegistration.Get <ILogger>().Warn(String.Format(format, args));
                break;

            case Log.LogLevel.Info:
                ServiceRegistration.Get <ILogger>().Info(String.Format(format, args));
                break;

            case Log.LogLevel.Error:
                ServiceRegistration.Get <ILogger>().Error(String.Format(format, args));
                break;
            }
        }
Exemple #23
0
        public override void Log(Log.LogLevel level, string msg, params object[] args)
        {
            switch (level)
            {
            case FellowOakDicom.Log.LogLevel.Debug:
                _aspnetLogger.LogDebug(msg, args);
                break;

            case FellowOakDicom.Log.LogLevel.Error:
            case FellowOakDicom.Log.LogLevel.Fatal:
                _aspnetLogger.LogError(msg, args);
                break;

            case FellowOakDicom.Log.LogLevel.Info:
                _aspnetLogger.LogInformation(msg, args);
                break;

            case FellowOakDicom.Log.LogLevel.Warning:
                _aspnetLogger.LogWarning(msg, args);
                break;
            }
        }
Exemple #24
0
        private void PerformLog(Action <ILogger> callback, Log.LogLevel level)
        {
            if (callback == null)
            {
                return;
            }

            var loggers = Log.Loggers;

            if (loggers == null)
            {
                return;
            }

            if (ShouldLog(level))
            {
                foreach (var logger in loggers)
                {
                    callback(logger);
                }
            }
        }
Exemple #25
0
        private void WriteFormattedLog(Log.LogLevel level, string text)
        {
            string str;

            switch (level)
            {
            case Log.LogLevel.TRACE:
                str = DateTime.Now.ToString(this.datetimeFormat) + " [TRACE]   ";
                break;

            case Log.LogLevel.INFO:
                str = DateTime.Now.ToString(this.datetimeFormat) + " [INFO]    ";
                break;

            case Log.LogLevel.DEBUG:
                str = DateTime.Now.ToString(this.datetimeFormat) + " [DEBUG]   ";
                break;

            case Log.LogLevel.WARNING:
                str = DateTime.Now.ToString(this.datetimeFormat) + " [WARNING] ";
                break;

            case Log.LogLevel.ERROR:
                str = DateTime.Now.ToString(this.datetimeFormat) + " [ERROR]   ";
                break;

            case Log.LogLevel.FATAL:
                str = DateTime.Now.ToString(this.datetimeFormat) + " [FATAL]   ";
                break;

            default:
                str = "";
                break;
            }
            this.WriteLine(str + text);
        }
        public LogConfigSection(XmlNode data)
        {
            var enabledStr = CouchbaseConfigSection.GetNamedAttribute(data, "enabled");

            if (enabledStr == null || !Boolean.TryParse(enabledStr, out _enabled))
            {
                _enabled = true;
            }

            var verbosityStr = CouchbaseConfigSection.GetNamedAttribute(data, "verbosity");

            if (enabledStr == null || !Enum.TryParse <Log.LogLevel> (verbosityStr, true, out _logLevel))
            {
                _logLevel = Log.LogLevel.Base;
            }

            var scrubSensitivityStr = CouchbaseConfigSection.GetNamedAttribute(data, "scrubSensitivity");

            if (scrubSensitivityStr == null || !Enum.TryParse <LogScrubSensitivity> (scrubSensitivityStr, true, out _scrubSensitivity))
            {
                _scrubSensitivity = LogScrubSensitivity.NoInsecure;
            }

            _verbositySettings = new LogDomainVerbosityCollection();
            foreach (XmlNode childNode in data.ChildNodes)
            {
                if (childNode.Name == "domains")
                {
                    _verbositySettings = new LogDomainVerbosityCollection(childNode.ChildNodes);
                }
                else
                {
                    Log.To.NoDomain.W(Tag, "Unknown element {0} found in configuration file", childNode.Name);
                }
            }
        }
        public int TestLogLevel(Log.LogLevel inputLevel)
        {
            var count = 0;

            Log.Level    = inputLevel;
            _logCallback = (level, tag, msg) =>
            {
                Console.WriteLine("Received {0} message from {1}", level, tag);
                if (tag == TAG)
                {
                    count++;
                }

                Assert.IsTrue(Log.Level.HasFlag(level));
            };

            Log.To.NoDomain.V(TAG, "TEST");
            Log.To.NoDomain.D(TAG, "TEST");
            Log.To.NoDomain.I(TAG, "TEST");
            Log.To.NoDomain.W(TAG, "TEST");
            Log.To.NoDomain.E(TAG, "TEST");

            return(count);
        }
Exemple #28
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, Interface gui, bool debug = false)
        {
            while (Interface.loginClicked == false)
            {
                // Wait for user to login
            }

            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = Interface.username,
                Password = Interface.password
            };
            Admins = new ulong[1];
            Admins[0] = 123456789;
            this.apiKey = apiKey;
            LogLevel = Log.LogLevel.Info;
            //log = new Log(config.LogFile, this.DisplayName, LogLevel);
            CreateHandler = handlerCreator;
            BotControlClass = config.BotControlClass;

            // 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>();
            gui.UpdateLog("\r\nConnecting, please wait...");
            ////log.Info("Connecting...");
            SteamClient.Connect();

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

                    HandleSteamMessage(msg, gui);
                }
            });

            CallbackThread.Start();
            ////log.Success("Done Loading Bot!");
            CallbackThread.Join();
        }
Exemple #29
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                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;
            this.isprocess = process;
            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;
            BotControlClass = config.BotControlClass;

            // 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>();
            SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>();

            backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = true };
            backgroundWorker.DoWork += BackgroundWorkerOnDoWork;
            backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            backgroundWorker.RunWorkerAsync();
        }
        public LogConfigSection(XmlNode data)
        {
            var enabledStr = CouchbaseConfigSection.GetNamedAttribute(data, "enabled");
            if (enabledStr == null || !Boolean.TryParse (enabledStr, out _enabled)) {
                _enabled = true;
            }

            var verbosityStr = CouchbaseConfigSection.GetNamedAttribute (data, "verbosity");
            if (enabledStr == null || !Enum.TryParse<Log.LogLevel> (verbosityStr, true, out _logLevel)) {
                _logLevel = Log.LogLevel.Base;
            }

            var scrubSensitivityStr = CouchbaseConfigSection.GetNamedAttribute (data, "scrubSensitivity");
            if (scrubSensitivityStr == null || !Enum.TryParse<LogScrubSensitivity> (scrubSensitivityStr, true, out _scrubSensitivity)) {
                _scrubSensitivity = LogScrubSensitivity.NoInsecure;
            }

            _verbositySettings = new LogDomainVerbosityCollection();
            foreach (XmlNode childNode in data.ChildNodes) {
                if (childNode.Name == "domains") {
                    _verbositySettings = new LogDomainVerbosityCollection(childNode.ChildNodes);
                } else {
                    Log.To.NoDomain.W(Tag, "Unknown element {0} found in configuration file", childNode.Name);
                }
            }
        }
Exemple #31
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
        {
            userHandlers = new Dictionary <SteamID, UserHandler>();
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName          = config.DisplayName;
            ChatResponse         = config.ChatResponse;
            MaximumTradeTime     = config.MaximumTradeTime;
            MaximumActionGap     = config.MaximumActionGap;
            DisplayNamePrefix    = config.DisplayNamePrefix;
            tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            schemaLang           = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en";
            Admins     = config.Admins;
            ApiKey     = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
            isProccess = process;
            try
            {
                if (config.LogLevel != null)
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
                    Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName);
                }
                else
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
                consoleLogLevel = Log.LogLevel.Info;
            }

            try
            {
                fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
                fileLogLevel = Log.LogLevel.Info;
            }

            logFile = config.LogFile;
            CreateLog();
            createHandler   = handlerCreator;
            BotControlClass = config.BotControlClass;
            SteamWeb        = new SteamWeb();

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

            Log.Debug("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamClient.AddHandler(new SteamNotifications());
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            SteamNotifications   = SteamClient.GetHandler <SteamNotifications>();

            botThread = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            botThread.DoWork             += BackgroundWorkerOnDoWork;
            botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            botThread.RunWorkerAsync();
        }
Exemple #32
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();
        }
Exemple #33
0
        /// <summary>
        /// This is the very first method that needs to be called before using any of the Goblin
        /// XNA framework.
        /// </summary>
        /// <param name="graphics">GraphicsDeviceManager object from the main Game class</param>
        /// <param name="content">ContentManager object from the main Game class</param>
        /// <param name="settingFile">
        /// The full path of the setting file in XML format. Setting file is used, for example,
        /// to specify where the model files are stored if not directly under "Content" directory.
        /// You can also add your own setting variable with certain value, and retrieve the value
        /// using GetSettingVariable method.
        ///
        /// Can be an empty string, in which case, a template setting file (template_setting.xml)
        /// that contains all of the setting variables used in Goblin XNA will be generated.
        /// If you don't specify the setting file, then all of the resource files (e.g., models,
        /// textures, spritefonts, etc) should be directly stored under the "Content" directory,
        /// so Goblin XNA can figure out where to load those resources.
        /// </param>
        /// <see cref="GetSettingVariable"/>
        /// <exception cref="GoblinException"></exception>
        public static void InitGoblin(IGraphicsDeviceService graphics, ContentManager content,
                                      String settingFile)
        {
            if (graphics == null || content == null)
            {
                throw new GoblinException("graphics or content can not be null");
            }

            _graphics              = graphics;
            _device                = graphics.GraphicsDevice;
            _graphics.DeviceReset += new EventHandler <EventArgs>(graphics_DeviceReset);
            _content               = content;
            initialized            = true;
            spriteBatch            = new SpriteBatch(_device);
            // creates a blank texture for 2D primitive drawing when texture is not needed
            blankTexture = new Texture2D(_device, 1, 1, false, SurfaceFormat.Bgra5551);

            // puts a white pixel in this blank texture to make a 1x1 blank texture
            ushort[] texData = new ushort[1];
            texData[0] = (ushort)0xFFFF;
            blankTexture.SetData(texData);
            viewMatrix = Matrix.Identity;
            projMatrix = Matrix.Identity;

            // bounding box color for drawing 3D models' bounding box
            boundingBoxColor = Color.Red;

            DebugShapeRenderer.Initialize();

            settings = new Dictionary <string, string>();

            if (settingFile.Length != 0)
            {
                LoadSettings(settingFile);
            }
#if WINDOWS
            else
            {
                try
                {
                    WriteSettingTemplate();
                }
                catch (Exception) { }
            }
#endif

            printLevel = Log.LogLevel.Error;
            nextNodeID = 0;

            showFPS           = false;
            showNotifications = false;
            showTriangleCount = false;
            debugTextColor    = Color.White;

            enableNetworking  = false;
            isServer          = false;
            numWaitForClients = 0;

            cameraTransform = Matrix.Identity;

            threadOption = 0;
        }
Exemple #34
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false,
                   bool process = false)
        {
            userHandlers = new Dictionary <SteamID, UserHandler>();
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = _sec_RetrievePassword(config.Username)
            };
            DisplayName           = config.DisplayName;
            ChatResponse          = config.ChatResponse;
            MaximumTradeTime      = config.MaximumTradeTime;
            MaximumActionGap      = config.MaximumActionGap;
            DisplayNamePrefix     = config.DisplayNamePrefix;
            _tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            schemaLang            = config.SchemaLang != null ? config.SchemaLang : "en_US";
            Admins     = config.Admins;
            ApiKey     = !string.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
            isProccess = process;
            try
            {
                if (config.LogLevel != null)
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
                    Console.WriteLine("(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be " +
                                      "removed in future versions. Please use ConsoleLogLevel instead.", DisplayName);
                }
                else
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine("(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to 'Info'", DisplayName);
                consoleLogLevel = Log.LogLevel.Info;
            }

            try
            {
                fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to 'Info'", DisplayName);
                fileLogLevel = Log.LogLevel.Info;
            }

            logFile         = config.LogFile;
            Log             = new Log(logFile, DisplayName, consoleLogLevel, fileLogLevel);
            createHandler   = handlerCreator;
            BotControlClass = config.BotControlClass;
            SteamWeb        = new SteamWeb();

            Orders = OrderManager.Load(Log);

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

            Log.Debug("Initializing Steam Bot...");

            SteamClient = new SteamClient();
            SteamClient.AddHandler(new SteamNotifications());
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            SteamNotifications   = SteamClient.GetHandler <SteamNotifications>();

            CallbackMgr = new CallbackManager(SteamClient);

            EventMgr = new EventManager(this, CallbackMgr);

            botSteamThread = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            botSteamThread.DoWork             += _backgroundWorkerOnDoWork;
            botSteamThread.RunWorkerCompleted += _backgroundWorkerOnRunWorkerCompleted;
            botSteamThread.RunWorkerAsync();

            heartBeatThread      = new Thread(HeartbeatLoop);
            heartBeatThread.Name = "bp.tf Heartbeat Thread: " + config.Username;
            heartBeatThread.Start();

            crafterThread      = new Thread(CrafterLoop);
            crafterThread.Name = "Crafting Loop Thread: " + config.Username;
            crafterThread.Start();
        }
        public BotControlForm(Configuration.BotInfo config, string apiKey, bool debug = false)
        {
            
            InitializeComponent();


            foreach(EPersonaState state in Enum.GetValues(typeof(EPersonaState)))
            {
                this.cbxPersonaState.Items.Add(state);
            }


            SetStatus("Setting variables...");
            
            logOnDetails = new SteamUser.LogOnDetails
            {
                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;
            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;
            BotControlClass = config.BotControlClass;

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

            
            SteamClient = new SteamClient();
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();

            SetStatus("Connecting to Steam...");

            SteamClient.Connect();

            masterThread = new Thread(this.pollSteam);
            masterThread.Start();


        }
Exemple #36
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 = 50;
            Admins      = new ulong[1];
            Admins[0]   = 123456789;
            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();
            SteamTrade   = SteamClient.GetHandler <SteamTrading>();
            SteamUser    = SteamClient.GetHandler <SteamUser>();
            SteamFriends = SteamClient.GetHandler <SteamFriends>();
            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);

                    HandleSteamMessage(msg);
                }
            });

            CallbackThread.Start();
            CallbackThread.Join();
            log.Success("Done loading account!");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Done loading account!";
            }));
        }
Exemple #37
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!";
            }));
        }
Exemple #38
0
        private Config()
        {
            //ConfigurationManager.AppSettings["ConnectionString"].ToString();
            ConnectionString = ConfigurationManager.AppSettings["ConnectionString"].ToString();

            try { Cartellini = LeggiTxt(".\\Resources\\cartellini.txt"); }
            catch { /*MessageBox.Show("Impossibile leggere il file dei cartellini");*/ Cartellini = new String[0]; }


            try { TipologiaCorsi = LeggiTxt(".\\Resources\\tipicorso.txt"); }
            catch { /*MessageBox.Show("Impossibile leggere il file dei cartellini");*/ TipologiaCorsi = new String[0]; }

            try { ModalitaPagamento = LeggiTxt(".\\Resources\\modalitapagamenti.txt"); }
            catch { ModalitaPagamento = new String[0]; }

            try { RefreshAnagrafica = Int32.Parse(ConfigurationManager.AppSettings["RefreshAnagrafica"].ToString()); }
            catch { RefreshAnagrafica = 2000; }

            try { IVA = Double.Parse(ConfigurationManager.AppSettings["IVA"].ToString()); }
            catch { IVA = 21.0f; }

            try { RefreshAltre = Int32.Parse(ConfigurationManager.AppSettings["RefreshAltre"].ToString()); }
            catch { RefreshAltre = 2000; }

            try { ShowColumnDovuto = ConfigurationManager.AppSettings["ShowColumnDovuto"].ToString().Equals("true"); }
            catch { ShowColumnDovuto = false; }

            try { ShowRefreshTime = ConfigurationManager.AppSettings["ShowRefreshTime"].ToString().Equals("true"); }
            catch { ShowRefreshTime = false; }

            try { QuitWordAfterPrintCartellino = ConfigurationManager.AppSettings["QuitWordAfterPrintCartellino"].ToString().Equals("true"); }
            catch { QuitWordAfterPrintCartellino = false; }

            try { QuitWordAfterPrintPagamento = ConfigurationManager.AppSettings["QuitWordAfterPrintPagamento"].ToString().Equals("true"); }
            catch { QuitWordAfterPrintPagamento = false; }

            try { QuitWordAfterPrintLibroSoci = ConfigurationManager.AppSettings["QuitWordAfterPrintLibroSoci"].ToString().Equals("true"); }
            catch { QuitWordAfterPrintLibroSoci = false; }

            try { QuitWordAfterPrintIngressiGiorno = ConfigurationManager.AppSettings["QuitWordAfterPrintIngressiGiorno"].ToString().Equals("true"); }
            catch { QuitWordAfterPrintIngressiGiorno = false; }

            try { ShowErrors = ConfigurationManager.AppSettings["ShowErrors"].ToString().Equals("true"); }
            catch { ShowErrors = false; }

            try { promptBackupOnExit = ConfigurationManager.AppSettings["promptBackupOnExit"].ToString().Equals("true"); }
            catch { promptBackupOnExit = false; }

            try { writeLogOnExit = ConfigurationManager.AppSettings["writeLogOnExit"].ToString().Equals("true"); }
            catch { writeLogOnExit = false; }

            try { ColorNonPagato = Color.FromName(ConfigurationManager.AppSettings["ColorNonPagato"].ToString()); }
            catch { ColorNonPagato = Color.Red; }


            try { LogFilename = ConfigurationManager.AppSettings["LogFilename"].ToString(); }
            catch { LogFilename = "unf_log.txt"; }

            try { LogLevel = Log.Name2Loglevel(ConfigurationManager.AppSettings["LogLevel"].ToString()); }
            catch { LogLevel = Log.LogLevel.Warning; }
        }
Exemple #39
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
        {
            userHandlers = new Dictionary<SteamID, UserHandler>();
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName  = config.DisplayName;
            ChatResponse = config.ChatResponse;
            MaximumTradeTime = config.MaximumTradeTime;
            MaximumActionGap = config.MaximumActionGap;
            DisplayNamePrefix = config.DisplayNamePrefix;
            tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            schemaLang = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en";
            Admins = config.Admins;
            ApiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
            isProccess = process;
            try
            {
                if( config.LogLevel != null )
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
                    Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName);
                }
                else consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
                consoleLogLevel = Log.LogLevel.Info;
            }

            try
            {
                fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
                fileLogLevel = Log.LogLevel.Info;
            }

            logFile = config.LogFile;
            Log = new Log(logFile, DisplayName, consoleLogLevel, fileLogLevel);
            createHandler = handlerCreator;
            BotControlClass = config.BotControlClass;
            SteamWeb = new SteamWeb();

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

            Log.Debug ("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamClient.AddHandler(new SteamNotifications());
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>();
            SteamNotifications = SteamClient.GetHandler<SteamNotifications>();

            botThread = new BackgroundWorker { WorkerSupportsCancellation = true };
            botThread.DoWork += BackgroundWorkerOnDoWork;
            botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            botThread.RunWorkerAsync();
        }
Exemple #40
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                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;
            hatBuyPrice= config.HatBuyPrice;
            hatSellPrice= config.HatSellPrice;
            maxRequestTime= config.MaxRequestTime;
            craftHatSellPrice = config.CraftHatSellPrice;
            Admins       = config.Admins;
            this.apiKey  = apiKey;
            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;
            BotControlClass = config.BotControlClass;

            // 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(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(1000);
                        if (currentRequest.User != null)
                        {
                            DateTime RequestTimeout = RequestTime.AddSeconds(maxRequestTime);
                            int untilTradeTimeout = (int)Math.Round((RequestTimeout - DateTime.Now).TotalSeconds);
                            if (untilTradeTimeout <= 0 && (MySQL.getItem().User != null))
                            {
                                SteamFriends.SendChatMessage(currentRequest.User, EChatEntryType.ChatMsg, "Sorry, but your request took too long");
                                NewRequest(MySQL.RequestStatus.Timedout);
                                log.Warn("Request timedout");
                            }
                        }
                    }
                }).Start();
            CallbackThread.Start();
            log.Success ("Done Loading Bot!");
            CallbackThread.Join();
        }