Ejemplo n.º 1
0
    private void AddAccountAndPassword()
    {
        if (OnLogMessage != null)
        {
            OnLogMessage.Invoke("AddAccountAndPassword Start");
        }
        //Any time we attempt to register a player, first silently authenticate the player.
        //This will retain the players True Origination (Android, iOS, Desktop)
        SilentlyAuthenticate((result) => {
            if (result == null)
            {
                //something went wrong with Silent Authentication, Check the debug console.
                OnPlayFabError.Invoke(new PlayFabError()
                {
                    Error        = PlayFabErrorCode.UnknownError,
                    ErrorMessage = "Silent Authentication by Device failed"
                });
                RegisterAuthenticate(result);
            }

            //Note: If silent auth is success, which is should always be and the following
            //below code fails because of some error returned by the server ( like invalid email or bad password )
            //this is okay, because the next attempt will still use the same silent account that was already created.

            //Now add our username & password.
            PlayFabClientAPI.AddUsernamePassword(new AddUsernamePasswordRequest()
            {
                Username = !string.IsNullOrEmpty(Username) ? Username : result.PlayFabId, //Because it is required & Unique and not supplied by User.
                Email    = Email,
                Password = Password,
            }, (addResult) => {
                if (OnLoginSuccess != null)
                {
                    //Store identity and session
                    _playFabId     = result.PlayFabId;
                    _sessionTicket = result.SessionTicket;

                    //Report login result back to subscriber.
                    OnLoginSuccess.Invoke();
                    if (OnLogMessage != null)
                    {
                        OnLogMessage.Invoke("AddUsernamePassword Success");
                    }
                }
            }, (error) => {
                if (OnPlayFabError != null)
                {
                    //Report error result back to subscriber
                    if (OnLogMessage != null)
                    {
                        OnLogMessage.Invoke("AddUsernamePassword Fail");
                    }
                }
                if (error.Error == PlayFabErrorCode.AccountAlreadyLinked)
                {
                    RegisterAuthenticate(result);
                }
            });
        });
    }
Ejemplo n.º 2
0
        static void LogMsg(string textMsg, string channel, WriteStrFunc logger)
        {
            Msg msg = Msg.MakeMsg(textMsg, channel);

            if (StoreLogs)
            {
                _logs.Add(msg);
            }

            string outText = ShowTimeStamp ? msg.TextWithTimeStamp : msg.Text;

            if (_writer != null)
            {
                if (_writer.AutoFlush)  // no reason to do async, since we want to make sure each msg is done before continuing
                {
                    _writer.WriteLine(outText);
                }
                //else   // Unity does not support this
                //    _writer.WriteLineAsync(outText);
            }

            if (OnLogMessage != null)
            {
                OnLogMessage.Invoke(outText);
            }

            if (LogToDiagnostics)
            {
                logger(outText);
                //System.Diagnostics.Debug.Print(outText);
            }
        }
Ejemplo n.º 3
0
    private void RegisterAuthenticate(LoginResult result)
    {
        if (OnLogMessage != null)
        {
            OnLogMessage.Invoke("RegisterAuthenticate Start");
        }
        PlayFabClientAPI.RegisterPlayFabUser(new RegisterPlayFabUserRequest()
        {
            Username = Email.Replace("@", "").Replace(".", ""), //Because it is required & Unique and not supplied by User.
            Email    = Email,
            Password = Password,
        }, (registerResult) =>
        {
            if (OnLoginSuccess != null)
            {
                //Store identity and session
                _playFabId     = registerResult.PlayFabId;
                _sessionTicket = registerResult.SessionTicket;

                //Report login result back to subscriber.
                OnLoginSuccess.Invoke();
                if (OnLogMessage != null)
                {
                    OnLogMessage.Invoke("RegisterAuthenticate Success");
                }
                //AuthenticateEmailPassword();
            }
        }, (Registererror) =>
        {
            if (OnLogMessage != null)
            {
                OnLogMessage.Invoke("RegisterAuthenticate Fail");
            }
        });
    }
Ejemplo n.º 4
0
        public static void Log(string message, bool logAnyways = false)
        {
            try
            {
                if (logAnyways || (_logEnabled ?? false))
                {
                    var msg = $"{DateTime.UtcNow:yyyy/MM/dd HH:mm:ss,fff}/GMT StackifyLib: {message}";

                    OnLogMessage?.Invoke(msg);

                    if (_logger != null)
                    {
                        _logger.Write(msg);
                    }
                    else
                    {
                        Debug.WriteLine(msg);

                        lock (LoggerDefaultLock)
                        {
                            if (_loggerDefault == null)
                            {
                                _loggerDefault = new StreamWriter(new FileStream(DefaultLoggerPathAndFile, FileMode.Append, FileAccess.Write, FileShare.Read));
                            }
                        }

                        _loggerDefault.WriteLine(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"#StackifyAPILogger #Log failed\r\n{ex}");
            }
        }
Ejemplo n.º 5
0
        public override bool Initialize(OnMessageReceived pOnPublishMessage, OnLogMessage pOnLogMsg, string configFile)
        {
            try
            {
                this.ModuleConfigFile  = configFile;
                this.DoPublishMessage += pOnPublishMessage;
                this.OnLogMsg         += pOnLogMsg;

                if (LoadConfig(configFile))
                {
                    MissingTags   = new Dictionary <string, string>();
                    MessageOk     = new Dictionary <string, object>();
                    ExtraTags     = new Dictionary <string, string>();
                    TimeoutOrders = new Dictionary <string, DateTime>();

                    Thread runTestsThread = new Thread(RunTestsThread);
                    runTestsThread.Start();

                    Thread processTimeouts = new Thread(ProcessTimeouts);
                    processTimeouts.Start(new object[] { Configuration.Name, Configuration.TimeoutInSeconds });

                    return(true);
                }
                else
                {
                    DoLog("Error initializing config file " + configFile, Constants.MessageType.Error);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                DoLog("Critic error initializing " + configFile + ":" + ex.Message, Constants.MessageType.Error);
                return(false);
            }
        }
Ejemplo n.º 6
0
        public static void LogMessage(string format, params object[] args)
        {
            if (OnLogMessage != null)
            {
                if (format == null)
                {
                    throw new ArgumentNullException(nameof(format));
                }

                string message = string.Format(CultureInfo.InvariantCulture, format, args);

                // Making sure all event handlers are called in sync on same thread.
                foreach (var invoker in OnLogMessage.GetInvocationList())
                {
                    try
                    {
                        invoker.GetMethodInfo().Invoke(invoker.Target, new object[] { message });
                    }
                    catch (Exception)
                    {
                        // Catch and ignore all exceptions thrown by event handlers.
                    }
                }
            }
        }
Ejemplo n.º 7
0
 private void LogMessage(string message)
 {
     OnLogMessage?.Invoke(this, new LogMessageEventArgs()
     {
         Message = message
     });
 }
Ejemplo n.º 8
0
        private void OnVoiceServerLogMessage(string message, LogLevel logLevel)
        {
            LogCat logCat;

            switch (logLevel)
            {
            case LogLevel.Trace:
                logCat = LogCat.Trace;
                break;

            case LogLevel.Debug:
                logCat = LogCat.Debug;
                break;

            case LogLevel.Warning:
                logCat = LogCat.Warn;
                break;

            case LogLevel.Error:
                logCat = LogCat.Error;
                break;

            default:
                logCat = LogCat.Info;
                break;
            }

            OnLogMessage?.Invoke(logCat, message);
        }
Ejemplo n.º 9
0
        protected void AbsoluteResetBroadcast(Ticker ticker, TickerState oldState, TickerState newState, string tickerDescription, CheckState tickerChecked)
        {
            if (tickerChecked == CheckState.Unchecked)
            {
                return;
            }

            string notification = null;

            if (oldState == TickerState.Uninitialized)
            {
                if (ConfigurationManager.Instance.Settings.ResetBriefingsAllowed)
                {
                    string remainingTime = newState == TickerState.Disabling ? "soon" : $"in {Utilities.ReadableTimeSpan(ticker.TimeLeft, false)}";
                    notification = $"{tickerDescription} will be resetting {remainingTime}.";
                }
            }
            else
            {
                if (newState == TickerState.Disabled)
                {
                    notification = $"{tickerDescription} have reset for the day.";
                    OnLogMessage?.Invoke("Reset", notification);
                }
                else if (newState == TickerState.Disabling)
                {
                    notification = $"{tickerDescription} will be resetting soon.";
                }
            }

            if (!string.IsNullOrEmpty(notification))
            {
                Broadcast(notification);
            }
        }
Ejemplo n.º 10
0
        public Task StopStress(CancellationTokenSource cancellationTokenAtSource)
        {
            return(Task.Run(() =>
            {
                try
                {
                    cancellationTokenForStress.Cancel();

                    countdownEventForStress.Wait(TimeSpan.FromMinutes(1));

                    OnLogMessage?.Invoke(new EventMessageInfo("Worker is stopping stress test ...", MessageType.Info));

                    statusUpdater.RunOnce();

                    cancellationTokenAtSource.Cancel();

                    OnLogMessage?.Invoke(new EventMessageInfo("Stress test stopped succesfully", MessageType.Info));
                }
                catch (Exception ex)
                {
                    OnLogMessage?.Invoke(new EventMessageInfo("Failed to start stress test", MessageType.Error));
                    logger.Error(ex);
                    throw;
                }
            }));
        }
Ejemplo n.º 11
0
        private void Broadcast(JObject json)
        {
            string type = json["type"].ToString();

            switch (type)
            {
            case "cluster_created":
                OnClusterCreated?.Invoke(this, json.ToObject <ClusterEventArgs <ClusterCreated> >());
                break;

            case "processing_started":
                OnProcessingStarted?.Invoke(this, json.ToObject <ClusterEventArgs <ProcessingStarted> >());
                break;

            case "job_status_changed":
                OnJobStatusChanged?.Invoke(this, json.ToObject <ClusterEventArgs <JobStatusChanged> >());
                break;

            case "processing_done":
                OnProcessingDone?.Invoke(this, json.ToObject <ClusterEventArgs <ProcessingDone> >());
                break;

            case "cluster_finalized":
                OnClusterFinalized?.Invoke(this, json.ToObject <ClusterEventArgs <ClusterFinalized> >());
                break;

            case "log_message":
                OnLogMessage?.Invoke(this, json.ToObject <ClusterEventArgs <LogMessage> >());
                break;

            default:
                break;
            }
        }
Ejemplo n.º 12
0
        public Task Stop(CancellationTokenSource cancellationTokenAtSource)
        {
            return(Task.Run(async() =>
            {
                try
                {
                    cancellationTokenForRun.Cancel();

                    countdownEventForRun.Wait(TimeSpan.FromMinutes(1));

                    OnLogMessage?.Invoke(new EventMessageInfo("Worker is stopping connections ...", MessageType.Info));

                    if (!_clients.IsEmpty)
                    {
                        foreach (var client in _clients)
                        {
                            await Task.Run(() => client.StopConnection());
                        }
                    }

                    statusUpdater.RunOnce();

                    cancellationTokenAtSource.Cancel();

                    OnLogMessage?.Invoke(new EventMessageInfo("Connections stopped succesfully", MessageType.Info));
                }
                catch (Exception ex)
                {
                    OnLogMessage?.Invoke(new EventMessageInfo("Failed to stop the connections", MessageType.Error));
                    logger.Error(ex);
                    throw;
                }
            }));
        }
        public override bool Initialize(OnMessageReceived pOnPublishMessage, OnLogMessage pOnLogMsg, string configFile)
        {
            try
            {
                this.ModuleConfigFile  = configFile;
                this.DoPublishMessage += pOnPublishMessage;
                this.OnLogMsg         += pOnLogMsg;

                if (LoadConfig(configFile))
                {
                    OrdersSent           = new Dictionary <string, Order>();
                    TimeoutOrders        = new Dictionary <string, DateTime>();
                    LastProcessedCounter = new Dictionary <string, int>();

                    Thread runTestsThread = new Thread(RunTestsThread);
                    runTestsThread.Start();

                    Thread processTimeouts = new Thread(ProcessTimeouts);
                    processTimeouts.Start(Configuration.Name);

                    return(true);
                }
                else
                {
                    DoLog("Error initializing config file " + configFile, Constants.MessageType.Error);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                DoLog("Critic error initializing " + configFile + ":" + ex.Message, Constants.MessageType.Error);
                return(false);
            }
        }
Ejemplo n.º 14
0
        private void HandleMessage(MessageRecievedEventArgs message)
        {
            switch (message.Status)
            {
            case MessageTypeEnum.P_SEND:
            case MessageTypeEnum.P_SENDALL:
                GetPhotos?.Invoke(this, message);
                break;

            case MessageTypeEnum.P_DELETE:
                PhotoPackage photo = PhotoPackage.Deserialize(message.Message);
                OnDeletePhoto(this, photo);
                break;

            case MessageTypeEnum.SETTINGS:
                Settings settings = Settings.Deserialize(message.Message);
                SetSettings?.Invoke(this, settings);
                break;

            case MessageTypeEnum.REMOVE_HANDLER:
                OnHandelRemove?.Invoke(this, message.Message);
                break;

            case MessageTypeEnum.L_FAIL:
            case MessageTypeEnum.L_INFO:
            case MessageTypeEnum.L_WARNING:
                OnLogMessage?.Invoke(this, message);
                break;

            default:
                break;
            }
        }
Ejemplo n.º 15
0
        public MainApp(ILogSource p_LogIncommingHost, ILogSource p_LogOutgoingHost, ILogSource p_LogSource, string configFile,
                       OnLogMessage onLog)
        {
            try
            {
                this.MessageIncomingLogger = p_LogIncommingHost;
                this.MessageOutgoingLogger = p_LogOutgoingHost;
                this.appLogger             = p_LogSource;
                this.OnLogMsg += onLog;

                if (!String.IsNullOrWhiteSpace(configFile))
                {
                    ConfigFile = configFile;
                }

                State = Bussiness.ApplicationBase.ApplicationState.Created;

                bool result = LoadConfig(ConfigFile);

                if (!string.IsNullOrEmpty(Config.OutgoingModule))
                {
                    var typeOutgoingModule = Type.GetType(Config.OutgoingModule);
                    if (typeOutgoingModule != null)
                    {
                        OutgoingModule = (ICommunicationModule)Activator.CreateInstance(typeOutgoingModule);
                    }
                    else
                    {
                        Log("assembly not found: " + Config.OutgoingModule);
                    }
                }
                else
                {
                    Log("Outgoing Module not found. It will not be initialized");
                }

                if (!string.IsNullOrEmpty(Config.IncomingModule))
                {
                    var typeIncomingModule = Type.GetType(Config.IncomingModule);
                    if (typeIncomingModule != null)
                    {
                        IncomingModule = (ICommunicationModule)Activator.CreateInstance(typeIncomingModule);
                    }
                    else
                    {
                        Log("Assembly not found: " + Config.IncomingModule);
                    }
                }
                else
                {
                    Log("Incoming Module not found. It will not be initialized");
                }
            }
            catch (Exception e)
            {
                Log("Error initializing service: " + e.Message);
                EventLog.WriteEntry(Config.Name, e.Message + e.StackTrace.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }
Ejemplo n.º 16
0
        public static void DebugLog(object message)
        {
            if (LOG_LEVEL == LogLevel.Debug)
            {
                OnLogMessage?.Invoke(message, LogLevel.Debug);

                LogInstance.Debug(message);
            }
        }
Ejemplo n.º 17
0
        public async Task Run(Tuple <string, Func <string, Task <object[]> > > methodToInvoke = null)
        {
            try
            {
                OnLogMessage?.Invoke(new EventMessageInfo($"Ramping up {arguments.Connections} connections to target address {arguments.Url}", MessageType.Info));

                statusUpdater = new WorkerStatusUpdater(countdownEventForRun, _clients, arguments.Connections)
                {
                    OnLogMessage = OnLogMessageReceived,
                    OnConnectionStatusChanged = OnConnectionStatusChangedReceived
                };

                statusUpdater.RunPolling();

                for (int count = 0; count < arguments.Connections; count++)
                {
                    if (!cancellationTokenForRun.IsCancellationRequested)
                    {
                        try
                        {
                            var     clientId = (count + 1).ToString();
                            IClient client   = ClientFactory.GetClient(arguments.ClientType, clientId);
                            client.OnLogMessage += OnLogMessageReceived;

                            await client.CreateAndStartConnection(arguments, methodToInvoke);

                            _clients.Add(client);
                        }
                        catch (Exception ex)
                        {
                            OnLogMessage?.Invoke(new EventMessageInfo("Failed to start the connnection for a client", MessageType.Error));
                            logger.Error(ex);
                        }
                    }
                    else
                    {
                        OnLogMessage?.Invoke(new EventMessageInfo($"Worker recieved cancellation request. Aborting ramp up ...", MessageType.Info));
                        countdownEventForRun.Signal();
                        break;
                    }
                }

                if (!cancellationTokenForRun.IsCancellationRequested)
                {
                    OnLogMessage?.Invoke(new EventMessageInfo("Ramp up competed.....", MessageType.Info));
                    countdownEventForRun.Signal();
                }
            }
            catch (Exception ex)
            {
                OnLogMessage?.Invoke(new EventMessageInfo("Failed to ramp up connections", MessageType.Error));
                logger.Error(ex);
                throw;
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Sends a log message to the Log4net logging engine.
        /// </summary>
        /// <param name="message">The message to be logged.</param>
        /// <param name="level">The severity of the log entry.</param>
        /// <param name="exception">The exception that was raised.</param>
        public static void Log(object message, LogLevel level, Exception exception)
        {
            OnLogMessage?.Invoke(message, level);

            switch (level)
            {
            case LogLevel.Debug:
                if (LOG_LEVEL == LogLevel.Debug)
                {
                    LogInstance.Debug(message, exception);
                }
                break;

            case LogLevel.Info:
                if (LOG_LEVEL == LogLevel.Debug ||
                    LOG_LEVEL == LogLevel.Info)
                {
                    LogInstance.Info(message, exception);
                }
                break;

            case LogLevel.Warning:
                if (LOG_LEVEL == LogLevel.Debug ||
                    LOG_LEVEL == LogLevel.Info ||
                    LOG_LEVEL == LogLevel.Warning)
                {
                    LogInstance.Warn(message, exception);
                }
                break;

            case LogLevel.Error:
                if (LOG_LEVEL == LogLevel.Debug ||
                    LOG_LEVEL == LogLevel.Info ||
                    LOG_LEVEL == LogLevel.Warning ||
                    LOG_LEVEL == LogLevel.Error)
                {
                    LogInstance.Error(message, exception);
                }
                break;

            case LogLevel.Fatal:
                if (LOG_LEVEL == LogLevel.Debug ||
                    LOG_LEVEL == LogLevel.Info ||
                    LOG_LEVEL == LogLevel.Warning ||
                    LOG_LEVEL == LogLevel.Error ||
                    LOG_LEVEL == LogLevel.Fatal)
                {
                    LogInstance.Fatal(message, exception);
                }
                break;

            default:
                break;
            }
        }
Ejemplo n.º 19
0
    public void SilentlyAuthenticate(System.Action <LoginResult> callback = null)
    {
        if (OnLogMessage != null)
        {
            OnLogMessage.Invoke("SilentlyAuthenticate Start");
        }
        PlayFabClientAPI.LoginWithCustomID(new LoginWithCustomIDRequest()
        {
            TitleId               = PlayFabSettings.TitleId,
            CustomId              = PlayFabSettings.DeviceUniqueIdentifier,
            CreateAccount         = true,
            InfoRequestParameters = InfoRequestParams
        }, (result) =>
        {
            //Store Identity and session
            _playFabId     = result.PlayFabId;
            _sessionTicket = result.SessionTicket;

            //check if we want to get this callback directly or send to event subscribers.
            if (callback == null && OnLoginSuccess != null)
            {
                //report login result back to the subscriber
                OnLoginSuccess.Invoke();
            }
            else if (callback != null)
            {
                //report login result back to the caller
                callback.Invoke(result);
            }
            if (OnLogMessage != null)
            {
                OnLogMessage.Invoke("SilentlyAuthenticate Success");
            }
        }, (error) =>
        {
            if (OnLogMessage != null)
            {
                OnLogMessage.Invoke("PlayFab authenticating using Custom ID...");
            }
            //report errro back to the subscriber
            if (callback == null && OnPlayFabError != null)
            {
                if (OnLogMessage != null)
                {
                    OnLogMessage.Invoke("SilentlyAuthenticate Fail");
                }
            }
            else
            {
                //make sure the loop completes, callback with null
                callback.Invoke(null);
            }
        });
    }
Ejemplo n.º 20
0
        private static void Log(LogMessageType type, Color color, string message, string caller = "")
        {
            message = !string.IsNullOrEmpty(caller) ? $"[{caller}] " + message : message;

            OnLogMessage?.Invoke(message, new LogMessageArgs
            {
                Type      = type,
                Color     = color,
                Timestamp = DateTime.UtcNow.ToLocalTime()
            });

            WriteToLog(message);
        }
Ejemplo n.º 21
0
        void Log(LogType type, string str, DateTime datetime)
        {
            var args = new LogMessageEventArgs()
            {
                Logger  = this,
                LogTime = datetime,
                LogType = type,
                Message = str,
            };

            var logtext = GetMessage(args);

            OnLogMessage?.Invoke(this, args);
            OnGlobalLogMessage?.Invoke(this, args);

            if (WriteConsoleLog && GlobalWriteConsoleLog)
            {
                var col = Console.ForegroundColor;
                switch (type)
                {
                case LogType.Info:
                    Console.ForegroundColor = ConsoleColor.White;
                    break;

                case LogType.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;

                case LogType.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;

                case LogType.Fatal:
                    Console.ForegroundColor = ConsoleColor.Magenta;
                    break;

                case LogType.Debug:
                    Console.ForegroundColor = ConsoleColor.Gray;
                    break;

                default:
                    break;
                }
                Console.WriteLine(logtext);
                Console.ForegroundColor = col;
            }
            if (SaveFileLog)
            {
                System.IO.File.AppendAllText(LogFilename, logtext + "\n");
            }
        }
Ejemplo n.º 22
0
        public override bool Initialize(OnMessageReceived pOnMessageRcv, OnLogMessage pOnLogMsg, string configFile)
        {
            try
            {
                this.ModuleConfigFile = configFile;
                this.OnMessageRcv    += pOnMessageRcv;
                this.OnLogMsg        += pOnLogMsg;

                if (LoadConfig(configFile))
                {
                    tLock = new object();

                    BitMexActiveOrders = new Dictionary <string, Order>();
                    OrderIdMappers     = new Dictionary <string, string>();
                    OrderManager       = new DataAccessLayer.OrderManager(BitmexConfiguration.RESTURL, BitmexConfiguration.ApiKey, BitmexConfiguration.Secret);
                    WSOrderManager     = new DataAccessLayer.Websockets.OrderManager(BitmexConfiguration.WebsocketURL, new UserCredentials()
                    {
                        BitMexID = BitmexConfiguration.ApiKey, BitMexSecret = BitmexConfiguration.Secret
                    });
                    SecurityListConverter = new StrategyHandler.Common.Converters.SecurityListConverter();

                    WSOrderManager.SubscribeResponseRequest(
                        DataAccessLayer.Websockets.OrderManager._EXECUTIONS,
                        ExecutionReportSubscriptionResponse,
                        new object[] { });

                    WSOrderManager.SubscribeEvents(DataAccessLayer.Websockets.OrderManager._EXECUTIONS, ProcessExecutionReports);

                    WSOrderManager.SubscribeExecutions();

                    SecurityListRequestWrapper slWrapper = new SecurityListRequestWrapper(SecurityListRequestType.AllSecurities, null);
                    OnMessageRcv(slWrapper);

                    CanceledOrders = new List <string>();


                    return(true);
                }
                else
                {
                    DoLog(string.Format("@{0}:Error initializing config file " + configFile, BitmexConfiguration.Name), Main.Common.Util.Constants.MessageType.Error);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                DoLog(string.Format("@{0}:Critic error initializing " + configFile + ":" + ex.Message, BitmexConfiguration.Name), Main.Common.Util.Constants.MessageType.Error);
                return(false);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Logs to console / window output and to log file
        /// </summary>
        /// <param name="format"></param>
        /// <param name="args"></param>
        internal void Log(string format, params object[] args)
        {
            var line = string.Format(format, args);

            WriteToLog(line);
            if (IsConsole)
            {
                Console.WriteLine(line);
            }
            else
            {
                OnLogMessage?.Invoke(line);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Send a log message to the logging engine
        /// </summary>
        /// <param name="message">The log message</param>
        /// <param name="level">The severity of the log entry</param>
        /// <param name="client">Instance of the client</param>
        /// <param name="exception">Exception that was raised</param>
        public static void Log(object message, Helpers.LogLevel level, GridClient client, Exception exception)
        {
            if (client != null && client.Settings.LOG_NAMES)
            {
                message = $"<{client.Self.Name}>: {message}";
            }

            OnLogMessage?.Invoke(message, level);

            switch (level)
            {
            case Helpers.LogLevel.Debug:
                if (Settings.LOG_LEVEL == Helpers.LogLevel.Debug)
                {
                    LogInstance.Debug(message, exception);
                }
                break;

            case Helpers.LogLevel.Info:
                if (Settings.LOG_LEVEL == Helpers.LogLevel.Debug ||
                    Settings.LOG_LEVEL == Helpers.LogLevel.Info)
                {
                    LogInstance.Info(message, exception);
                }
                break;

            case Helpers.LogLevel.Warning:
                if (Settings.LOG_LEVEL == Helpers.LogLevel.Debug ||
                    Settings.LOG_LEVEL == Helpers.LogLevel.Info ||
                    Settings.LOG_LEVEL == Helpers.LogLevel.Warning)
                {
                    LogInstance.Warn(message, exception);
                }
                break;

            case Helpers.LogLevel.Error:
                if (Settings.LOG_LEVEL == Helpers.LogLevel.Debug ||
                    Settings.LOG_LEVEL == Helpers.LogLevel.Info ||
                    Settings.LOG_LEVEL == Helpers.LogLevel.Warning ||
                    Settings.LOG_LEVEL == Helpers.LogLevel.Error)
                {
                    LogInstance.Error(message, exception);
                }
                break;

            default:
                break;
            }
        }
        public void Log(LogLevel logLevel, string message)
        {
            try
            {
                if (logLevel > _minimumLogLevel)
                {
                    return;
                }

                OnLogMessage?.Invoke(message, logLevel);
            }
            catch
            {
                // We can't do anything if an exception occurs here...
            }
        }
Ejemplo n.º 26
0
        public static void DebugLog(object message, GridClient client)
        {
            if (Settings.LOG_LEVEL != Helpers.LogLevel.Debug)
            {
                return;
            }

            if (client != null && client.Settings.LOG_NAMES)
            {
                message = $"<{client.Self.Name}>: {message}";
            }

            OnLogMessage?.Invoke(message, Helpers.LogLevel.Debug);

            LogInstance.Debug(message);
        }
Ejemplo n.º 27
0
        public override bool Initialize(OnMessageReceived pOnMessageRcv, OnLogMessage pOnLogMsg, string configFile)
        {
            try
            {
                this.OnMessageRcv += pOnMessageRcv;
                this.OnLogMsg     += pOnLogMsg;

                if (LoadConfig(configFile))
                {
                    var singletonHandlerClass = Type.GetType(SingletonModuleConfiguration.SingletonAssembly);
                    if (singletonHandlerClass != null)
                    {
                        SingletonHandler = (ISingletonModule)singletonHandlerClass.GetMethod("GetInstance").Invoke(null, new object[] { pOnLogMsg, SingletonModuleConfiguration.SingletonConfigFile });

                        if (SingletonModuleConfiguration.ModuleDirection == ModuleDirection.Incoming)
                        {
                            SingletonHandler.SetIncomingEvent(pOnMessageRcv);
                        }
                        else if (SingletonModuleConfiguration.ModuleDirection == ModuleDirection.Outgoing)
                        {
                            SingletonHandler.SetOutgoingEvent(pOnMessageRcv);
                        }
                        else
                        {
                            throw new Exception(string.Format("Unkown module direction for {0}", SingletonModuleConfiguration.ModuleDirection));
                        }
                    }
                    else
                    {
                        DoLog("assembly not found: " + SingletonModuleConfiguration.SingletonAssembly, Main.Common.Util.Constants.MessageType.Error);
                        return(false);
                    }

                    return(true);
                }
                else
                {
                    DoLog("Error initializing config file " + configFile, Main.Common.Util.Constants.MessageType.Error);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                DoLog("Critic error initializing " + configFile + ":" + ex.Message, Main.Common.Util.Constants.MessageType.Error);
                return(false);
            }
        }
Ejemplo n.º 28
0
        public async Task CreateAndStartConnection(ConnectionArgument argument, Tuple <string, Func <string, Task <object[]> > > methodToInvoke = null)
        {
            string url = string.Empty;

            if (argument.Url.EndsWith("/"))
            {
                url = argument.Url + argument.Hub;
            }
            else
            {
                url = $"{argument.Url}/{argument.Hub}";
            }

            connection = new HubConnectionBuilder()
                         .WithUrl(url, GetTransportType(argument.Transport))
                         .Build();

            token = new CancellationToken();

            connection.Closed += _connection_Closed;

            for (int connectCount = 0; connectCount < 2; connectCount++)
            {
                if (!token.IsCancellationRequested)
                {
                    try
                    {
                        await connection.StartAsync(token);

                        connectionStatus = ConnectionStatus.Connected;

                        break;
                    }
                    catch (Exception ex)
                    {
                        OnLogMessage?.Invoke(new EventMessageInfo("Failed to create connection. Will attempt to reconnect...", MessageType.Error));
                        logger.Error(ex);
                    }

                    await Task.Delay(1000);
                }
            }
        }
Ejemplo n.º 29
0
    public void AuthenticateEmailPassword()
    {
        if (OnLogMessage != null)
        {
            OnLogMessage.Invoke("AuthenticateEmailPassword Start");
        }
        //We have not opted for remember me in a previous session, so now we have to login the user with email & password.
        PlayFabClientAPI.LoginWithEmailAddress(new LoginWithEmailAddressRequest()
        {
            TitleId  = PlayFabSettings.TitleId,
            Email    = Email,
            Password = Password,
            InfoRequestParameters = InfoRequestParams
        }, (result) =>
        {
            //store identity and session
            _playFabId     = result.PlayFabId;
            _sessionTicket = result.SessionTicket;

            if (OnLoginSuccess != null)
            {
                //report login result back to subscriber
                OnLoginSuccess.Invoke();
                if (OnLogMessage != null)
                {
                    OnLogMessage.Invoke("AuthenticateEmailPassword Success");
                }
            }
        }, (error) =>
        {
            if (OnPlayFabError != null)
            {
                if (OnLogMessage != null)
                {
                    OnLogMessage.Invoke("AuthenticateEmailPassword Fail");
                }
            }
            if (error.Error == PlayFabErrorCode.AccountNotFound)
            {
                AddAccountAndPassword();
            }
        });
    }
Ejemplo n.º 30
0
        public override bool Initialize(OnMessageReceived pOnPublishMessage, OnLogMessage pOnLogMsg, string configFile)
        {
            try
            {
                this.ModuleConfigFile  = configFile;
                this.DoPublishMessage += pOnPublishMessage;
                this.OnLogMsg         += pOnLogMsg;

                if (LoadConfig(configFile))
                {
                    SentOrders     = new Dictionary <string, string>();
                    SendersDict    = new Dictionary <int, string>();
                    KeysDict       = new Dictionary <int, string>();
                    TestingModules = new Dictionary <string, ICommunicationModule>();

                    FIXMessageCreator = new FIXMessageCreator();

                    string path = Configuration.InitiatorCfg;
                    TestingModulesInitialized = false;

                    SessionSettings  = new SessionSettings(path);
                    FileStoreFactory = new FileStoreFactory(SessionSettings);
                    ScreenLogFactory = new ScreenLogFactory(SessionSettings);
                    MessageFactory   = new QuickFix.FIX44.MessageFactory();

                    Initiator = new SocketInitiator(this, FileStoreFactory, SessionSettings, ScreenLogFactory);

                    Initiator.Start();

                    return(true);
                }
                else
                {
                    DoLog("Error initializing config file " + configFile, Constants.MessageType.Error);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                DoLog("Critic error initializing " + configFile + ":" + ex.Message, Constants.MessageType.Error);
                return(false);
            }
        }