public void ApplicationPoolStop(HostType hostType)
        {
            var serverInstance = new NotificationServer();

            serverInstance.StartNotificationService();
            try
            {
                using (ApplicationDeployer deployer = new ApplicationDeployer())
                {
                    string applicationUrl = deployer.Deploy(hostType, Configuration);
                    Assert.True(HttpClientUtility.GetResponseTextFromUrl(applicationUrl) == "SUCCESS");

                    if (hostType == HostType.IIS)
                    {
                        string webConfig        = deployer.GetWebConfigPath();
                        string webConfigContent = File.ReadAllText(webConfig);
                        File.WriteAllText(webConfig, webConfigContent);
                    }
                }

                bool receivedNotification = serverInstance.NotificationReceived.WaitOne(20 * 1000);
                Assert.True(receivedNotification, "Cancellation token was not issued on closing host");
            }
            finally
            {
                serverInstance.Dispose();
            }
        }
Esempio n. 2
0
        public void OwinCallCancelled(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var serverInstance = new NotificationServer();
                serverInstance.StartNotificationService();

                string applicationUrl = deployer.Deploy(hostType, Configuration);

                try
                {
                    Trace.WriteLine(string.Format("Making a request to url : ", applicationUrl));
                    HttpClient httpClient = new HttpClient();
                    Task <HttpResponseMessage> response = httpClient.GetAsync(applicationUrl);
                    response.Wait(1 * 1000);
                    httpClient.CancelPendingRequests();
                    bool receivedNotification = serverInstance.NotificationReceived.WaitOne(20 * 1000);
                    Assert.True(receivedNotification, "CallCancelled CancellationToken was not issued on cancelling the call");
                }
                finally
                {
                    serverInstance.Dispose();
                }
            }
        }
Esempio n. 3
0
        public void Configuration(IAppBuilder app)
        {
            app.Run(context =>
            {
                Stopwatch stopWatch = new Stopwatch();
                Trace.WriteLine("Received client call. Starting stop watch now.");
                stopWatch.Start();

                context.Request.CallCancelled.Register(() =>
                {
                    stopWatch.Stop();
                    Trace.WriteLine(string.Format("Cancellation token triggered. Elapsed time : {0}. Test should succeed", stopWatch.Elapsed));
                    NotificationServer.NotifyClient();
                });

                int retryCount = 0;
                while (retryCount < 3)
                {
                    Thread.CurrentThread.Join(5 * 1000);
                    if (context.Request.CallCancelled.IsCancellationRequested)
                    {
                        break;
                    }
                    retryCount++;
                }

                return(context.Response.WriteAsync("FAILURE"));
            });
        }
Esempio n. 4
0
        public void FixtureTeardown()
        {
            WebApiServer.Stop();
            NotificationServer.Stop();
            TestSignalRServer.Stop();

            HttpClient.Dispose();
        }
        public void Send(string message, string target)
        {
            var server = new NotificationServer();

            server.Connect("test-server");
            var token = server.Authenticate("appId", "key");

            server.Send(token, new Message(message), target);
        }
Esempio n. 6
0
        public void Send(string message, string target)
        {
            var server  = new NotificationServer();
            var connect = server.Connect("ip");
            var token   = server.Authenticate("AppId", "Key");

            server.Send(token, new Message(message), "target");
            connect.DisConnect();
        }
Esempio n. 7
0
        public void Send(string message, string target)
        {
            var notificationServer = new NotificationServer();
            var connection         = notificationServer.Connect("ip");
            var authToken          = notificationServer.Authenticate("appId", "appKey");

            notificationServer.Send(authToken, new Message(message), target);
            connection.Disconnect();
        }
        private NotificationServer GetNextNotificationServer()
        {
            NotificationServer result = null;
            int index;

            lock (this)
            {
                index = _NotificationServerIndex = (_NotificationServerIndex + 1) % _NotificationServers.Count;
            }
            result = _NotificationServers[index];
            return(result);
        }
Esempio n. 9
0
        public void CreateLogger(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var service = new NotificationServer();
                service.StartNotificationService();

                string applicationUrl = deployer.Deploy(hostType, CreateLoggerConfiguration);

                Assert.Equal("SUCCESS", HttpClientUtility.GetResponseTextFromUrl(applicationUrl));
                Assert.True(service.NotificationReceived.WaitOne(1 * 2000), "Did not receive all expected traces within expected time");
                service.Dispose();
            }
        }
Esempio n. 10
0
        public bool WriteCore(TraceEventType eventType, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
        {
            if (expectedMessages.Contains(state.ToString()) &&
                state.ToString().Contains(eventType.ToString()))
            {
                expectedMessages.Remove(state.ToString());
            }

            if (expectedMessages.Count == 0)
            {
                NotificationServer.NotifyClient();
            }

            return(true);
        }
Esempio n. 11
0
        public async Task RunNotifier()
        {
            var notification = new NotificationServer();
            List <StockDataPoint> dataPoints = new List <StockDataPoint>();
            decimal alertOver  = 290; //used to send notifications when passes certain price
            decimal alertUnder = 284;

            if (DateTime.Now.TimeOfDay < MarketOpen) // wait for market to open
            {
                var waitTime = MarketOpen - DateTime.Now.TimeOfDay;
                await Task.Delay(waitTime);
            }

            while (DateTime.Now.TimeOfDay < MarketClose)
            {
                var data = await APIObj.RequestDailyTimeSeriesAsync(Ticker);

                var latest = data.DataPoints.First();
                dataPoints.Add(latest);

                ///////////////////////////TESTING
                //notification.Publish("Test", "test notification");
                ///////////////////////////TESTING


                if (DateTime.Now.TimeOfDay.Minutes == 0)
                {
                    notification.Publish($"Hourly {Ticker} update", $"{latest.ClosingPrice}");
                }
                if (latest.ClosingPrice > alertOver)
                {
                    notification.Publish($"{Ticker} alert", $"{latest.ClosingPrice} has passed alertOver:{alertOver}");
                    alertOver = 999; //so that it gets ignored on future passes
                }
                if (latest.ClosingPrice < alertUnder)
                {
                    notification.Publish($"{Ticker} alert", $"{latest.ClosingPrice} has dropped below alertUnder:{alertUnder}");
                    alertUnder = 0; //so that it gets ignored on future passes
                }

                await Task.Delay(TimeSpan.FromSeconds(60));
            }

            //one last check for market closed
            var lastData = await APIObj.RequestDailyTimeSeriesAsync(Ticker);

            notification.Publish("Market closed", $"{Ticker} final price: {lastData.DataPoints.First().ClosingPrice}");
        }
Esempio n. 12
0
        private static bool StartServers()
        {
            Console.Write("Loading User Database...");

            //String path = @"C:\Documents and Settings\David\My Documents\Visual Studio Projects\W3b.MsnpServer\Data\PinkEgoBox.sqlite";
            //String path = @"D:\Users\David\My Documents\Visual Studio Projects\Solutions\W3b.MsnpServer\Data\PinkEgoBox.sqlite";
            _dbPath = UtilityMethods.FindFile(new DirectoryInfo(Environment.CurrentDirectory), "PinkEgoBox.sqlite", 5);
            if (_dbPath == null)
            {
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Unable to locate database file");
                Console.ResetColor();
                return(false);
            }

            User.LoadDatabase(_dbPath);

            Console.WriteLine("Done");

            Console.WriteLine("Starting Servers...");

            _dispatchServer = DispatchServer.Instance;
            _dispatchServer.Start();

            Console.ForegroundColor = _dispatchServer.ConsoleColor;
            Console.WriteLine("Dispatch Server started, listening on " + _dispatchServer.EndPoint.ToString2());

            //////////////////////

            _notificationServer = NotificationServer.Instance;
            _notificationServer.Start();

            Console.ForegroundColor = _notificationServer.ConsoleColor;
            Console.WriteLine("Notification Server started, listening on " + _notificationServer.EndPoint.ToString2());

            //////////////////////

            _switchboardServer = SwitchboardServer.Instance;
            _switchboardServer.Start();

            Console.ForegroundColor = _switchboardServer.ConsoleColor;
            Console.WriteLine("Switchboard Server started, listening on " + _switchboardServer.EndPoint.ToString2());
            Console.ResetColor();

            return(true);
        }
        private bool SetupNotification(NotificationClient notificationClient, int attemptsCount)
        {
            bool result = false;
            NotificationServer notificationServer = null;
            int count = 0;

            while ((notificationServer == null) && (count < attemptsCount))
            {
                notificationServer = GetNextNotificationServer();
                if ((notificationServer != null) && (notificationServer.AllowConnectionAfter > DateTime.Now))
                {
                    notificationServer = null;
                }
                else if ((notificationServer == null) || !notificationServer.Connected || !notificationServer.TcpClient.Connected)
                {
                    if (!Connect(notificationServer, true))
                    {
                        notificationServer = null;
                    }
                }
                if (notificationServer != null)
                {
                    byte[] buffer = Encoding.ASCII.GetBytes(string.Concat(SETUP_NOTIFICATION, notificationClient.TableName, "|"));
                    try
                    {
                        Send(notificationServer.TcpClient, buffer);
                        Interlocked.Increment(ref _NotificationClientCount);
                        notificationClient.Enabled = true;
                        lock (notificationServer)
                        {
                            notificationServer.AddClient(notificationClient);
                        }
                        result = true;
                    }
                    catch (Exception ex)
                    {
                        ApplicationEventLog.WriteEntry("Flow", string.Format("DALChangeNotification::SetupNotification {0}", ex), System.Diagnostics.EventLogEntryType.Error);
                        notificationServer = null;
                    }
                }
                count = (count + 1) % int.MaxValue;
            }
            return(result);
        }
        internal void Configuration(IAppBuilder app)
        {
            appDisposingTokenOnHostProperties = app.Properties.Get <CancellationToken>("host.OnAppDisposing");
            appDisposingTokenOnHostProperties.Register(() =>
            {
                NotificationServer.NotifyClient();
            });

            app.Run(context =>
            {
                var perRequestHostDisposingToken = context.Get <CancellationToken>("host.OnAppDisposing");
                if (perRequestHostDisposingToken.GetHashCode() != this.appDisposingTokenOnHostProperties.GetHashCode())
                {
                    return(context.Response.WriteAsync("FAILURE"));
                }

                return(context.Response.WriteAsync("SUCCESS"));
            });
        }
        public DALChangeNotification(List <Uri> notificationServers)
        {
            _NotificationServersToReconnect = new List <NotificationServer>();
            _NotificationServers            = new List <NotificationServer>();
            _TableChangeClients             = new ConcurrentDictionary <string, List <NotificationClient> >();
            _NotificationClients            = new ConcurrentDictionary <string, NotificationClient>();
            _NotificationsToRepair          = new Queue <NotificationClient>(64);
            _NotifyClientsCallback          = new AsyncCallback(NotifyClientsCallback);
            _ReceiveCallback = new AsyncCallback(ReceiveCallback);
            _SendCallback    = new AsyncCallback(SendCallback);

            _TriggerNotificationRepair       = new ManualResetEvent(false);
            _ProcessNotificationRepairThread = new Thread(new ThreadStart(ProcessNotificationsToRepair));
            if (_ProcessNotificationRepairThread.Name == null)
            {
                _ProcessNotificationRepairThread.Name = "ProcessNotificationsToRepair";
            }
            _ProcessNotificationRepairThread.IsBackground = true;
            _ProcessNotificationRepairThread.Start();

            foreach (Uri server in notificationServers)
            {
                NotificationServer notificationServer;
                notificationServer            = new NotificationServer();
                notificationServer.ServerName = server.DnsSafeHost;
                if (server.Port == -1)
                {
                    notificationServer.Port = 14050;
                }
                else
                {
                    notificationServer.Port = server.Port;
                }
                notificationServer.Connected = false;
                _NotificationServers.Add(notificationServer);
                _NotificationServersToReconnect.Add(notificationServer);
            }

            if (_NotificationServersToReconnect.Count > 0)
            {
                _TriggerNotificationRepair.Set();
            }
        }
        public DALChangeNotification(List<Uri> notificationServers)
        {
            _NotificationServersToReconnect = new List<NotificationServer>();
            _NotificationServers = new List<NotificationServer>();
            _TableChangeClients = new ConcurrentDictionary<string, List<NotificationClient>>();
            _NotificationClients = new ConcurrentDictionary<string, NotificationClient>();
            _NotificationsToRepair = new Queue<NotificationClient>(64);
            _NotifyClientsCallback = new AsyncCallback(NotifyClientsCallback);
            _ReceiveCallback = new AsyncCallback(ReceiveCallback);
            _SendCallback = new AsyncCallback(SendCallback);

            _TriggerNotificationRepair = new ManualResetEvent(false);
            _ProcessNotificationRepairThread = new Thread(new ThreadStart(ProcessNotificationsToRepair));
            if (_ProcessNotificationRepairThread.Name == null)
                _ProcessNotificationRepairThread.Name = "ProcessNotificationsToRepair";
            _ProcessNotificationRepairThread.IsBackground = true;
            _ProcessNotificationRepairThread.Start();

            foreach (Uri server in notificationServers)
            {
                NotificationServer notificationServer;
                notificationServer = new NotificationServer();
                notificationServer.ServerName = server.DnsSafeHost;
                if (server.Port == -1)
                    notificationServer.Port = 14050;
                else
                    notificationServer.Port = server.Port;
                notificationServer.Connected = false;
                _NotificationServers.Add(notificationServer);
                _NotificationServersToReconnect.Add(notificationServer);
            }

            if (_NotificationServersToReconnect.Count > 0)
                _TriggerNotificationRepair.Set();
        }
Esempio n. 17
0
 public Msnp2NotificationProtocol(NotificationServer server) : base("MSNP2", 2, server)
 {
 }
        private bool Connect(NotificationServer notificationServer, bool autoRepair)
        {
            bool connected = false;
            //NotificationServer result = null;
            DateTime timeOutTime = DateTime.Now.AddSeconds(5);

            while (!connected && DateTime.Now < timeOutTime)
            {
                try
                {
                    Socket      tcpClient     = null;
                    IPAddress[] hostAddresses = Dns.GetHostAddresses(notificationServer.ServerName);
                    foreach (IPAddress address in hostAddresses)
                    {
                        if ((address.AddressFamily == AddressFamily.InterNetwork))                         // || (address.AddressFamily == AddressFamily.InterNetworkV6)
                        {
                            tcpClient = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                            tcpClient.Connect(address, notificationServer.Port);
                            tcpClient.NoDelay = true;
                            break;
                        }
                    }
                    if (tcpClient != null)
                    {
                        notificationServer.TcpClient = tcpClient;
                        notificationServer.Connected = true;
                        if (notificationServer.TableChangeClients.Count > 0)
                        {
                            StringBuilder tables = new StringBuilder();
                            for (int index = 0; index < notificationServer.TableChangeClients.Count; index++)
                            {
                                tables.Append(SETUP_NOTIFICATION);
                                tables.Append(notificationServer.TableChangeClients[index].TableName);
                                tables.Append("|");
                            }
                            byte[] buffer = Encoding.ASCII.GetBytes(tables.ToString());
                            tcpClient.Send(buffer);
                        }
                        ReceiveStateObject stateObject = new ReceiveStateObject();
                        stateObject.Client             = tcpClient;
                        stateObject.NotificationServer = notificationServer;
                        SocketError socketError;
                        tcpClient.BeginReceive(stateObject.Buffer, 0, ReceiveStateObject.BufferSize, SocketFlags.None, out socketError, _ReceiveCallback, stateObject);
                    }
                    connected = true;
                }
                catch
                {
                }
                if (!connected)
                {
                    System.Threading.Thread.Sleep(500);
                }
            }
            if (!connected)
            {
                lock (notificationServer)
                {
                    notificationServer.Connected            = false;
                    notificationServer.AllowConnectionAfter = DateTime.Now.AddSeconds(10);
                    AddNotificationToRepair(notificationServer.TableChangeClients);
                    notificationServer.TableChangeClients.Clear();
                    if (autoRepair)
                    {
                        lock (_NotificationServersToReconnect)
                        {
                            _NotificationServersToReconnect.Add(notificationServer);
                        }
                        _TriggerNotificationRepair.Set();
                    }
                }
            }
            return(connected);
        }
 public Msnp3NotificationProtocol(NotificationServer server) : base("MSNP3", 3, server)
 {
 }
 protected Msnp4NotificationProtocol(String name, int pref, NotificationServer server) : base(name, pref, server)
 {
 }
 public Msnp4NotificationProtocol(NotificationServer server) : base("MSNP4", 4, server)
 {
 }
Esempio n. 22
0
 protected NotificationProtocol(String name, int pref, NotificationServer server) : base(name, pref)
 {
     Server = server;
 }
        private bool Connect(NotificationServer notificationServer, bool autoRepair)
        {
            bool connected = false;
            //NotificationServer result = null;
            DateTime timeOutTime = DateTime.Now.AddSeconds(5);
            while (!connected && DateTime.Now < timeOutTime)
            {
                try
                {
                    Socket tcpClient = null;
                    IPAddress[] hostAddresses = Dns.GetHostAddresses(notificationServer.ServerName);
                    foreach (IPAddress address in hostAddresses)
                    {
                        if ((address.AddressFamily == AddressFamily.InterNetwork)) // || (address.AddressFamily == AddressFamily.InterNetworkV6)
                        {
                            tcpClient = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                            tcpClient.Connect(address, notificationServer.Port);
                            tcpClient.NoDelay = true;
                            break;
                        }
                    }
                    if (tcpClient != null)
                    {
                        notificationServer.TcpClient = tcpClient;
                        notificationServer.Connected = true;
                        if (notificationServer.TableChangeClients.Count > 0)
                        {
                            StringBuilder tables = new StringBuilder();
                            for (int index = 0; index < notificationServer.TableChangeClients.Count; index++)
                            {
                                tables.Append(SETUP_NOTIFICATION);
                                tables.Append(notificationServer.TableChangeClients[index].TableName);
                                tables.Append("|");
                            }
                            byte[] buffer = Encoding.ASCII.GetBytes(tables.ToString());
                            tcpClient.Send(buffer);
                        }
                        ReceiveStateObject stateObject = new ReceiveStateObject();
                        stateObject.Client = tcpClient;
                        stateObject.NotificationServer = notificationServer;
                        SocketError socketError;
                        tcpClient.BeginReceive(stateObject.Buffer, 0, ReceiveStateObject.BufferSize, SocketFlags.None, out socketError, _ReceiveCallback, stateObject);
                    }
                    connected = true;
                }
                catch
                {

                }
                if (!connected)
                    System.Threading.Thread.Sleep(500);
            }
            if (!connected)
            {
                lock (notificationServer)
                {
                    notificationServer.Connected = false;
                    notificationServer.AllowConnectionAfter = DateTime.Now.AddSeconds(10);
                    AddNotificationToRepair(notificationServer.TableChangeClients);
                    notificationServer.TableChangeClients.Clear();
                    if (autoRepair)
                    {
                        lock (_NotificationServersToReconnect)
                        {
                            _NotificationServersToReconnect.Add(notificationServer);
                        }
                        _TriggerNotificationRepair.Set();
                    }
                }
            }
            return connected;
        }
Esempio n. 24
0
        private static int Main(string[] args)
        {
            var p = new OptionSet {
                { "u|url=", $"The {{url}} to bind to, including port. (Default: {_url})", v => _url = v }, {
                    "w", $"Flag to indicate that logs should not be written to disk (Default: {_writeToDisk})",
                    v => _writeToDisk = v == null
                }, {
                    "t|threads=", $"The max number of {{threads}} the server will run on. (Default: {_threads})",
                    v => _threads = int.Parse(v)
                }, {
                    "v|verbosity=", $"The {{verbosity}} of the server. (Default: {Logger.VerbosityThreshhold})",
                    v => Logger.VerbosityThreshhold = int.Parse(v)
                },
                { "c|clienttest", $"Run a stress test on the server, posing as a client.", v => _clientTest = v != null },
                { "h|?|help", "Show this dialog", v => _help = v != null }
            };

            List <string> unknownCommands;

            try {
                unknownCommands = p.Parse(args);
            }
            catch (Exception e) {
                Logger.Log($"Unable to parse commands:{e.Message}");
                return(1);
            }

            if (unknownCommands.Count > 0)
            {
                Console.WriteLine($"Unknown commands: {string.Join(", ", unknownCommands)}");
            }

            if (_help)
            {
                p.WriteOptionDescriptions(Console.Out);
                return(0);
            }

            if (_clientTest)
            {
                RunClientTest(_threads);
                return(0);
            }

            var server = new NotificationServer(_url, _threads, _writeToDisk);

            #region commands

            var commands = new Dictionary <string, Action>();
            commands.Add("list",
                         () => Console.WriteLine($"Active Notifications: " +
                                                 $"{Environment.NewLine}{NotificationInfoLoader.ToString()}"));
            commands.Add("restart", server.Restart);
            commands.Add("reload", NotificationInfoLoader.Reload);
            commands.Add("exit", () => { _running = false; });
#if DEBUG
            commands.Add("help", () => Console.WriteLine($"Commands: {string.Join(", ", commands.Keys)}"));
            commands.Add("crashall", () => server.CrashServer());
            commands.Add("testlog", () => Logger.Log("Test log"));
            commands.Add("testlogwarning", () => Logger.LogWarning("Test warning log"));
            commands.Add("testlogerror", () => Logger.LogError("Test error log"));
#endif

            #endregion

            server.Start();
            Thread.Sleep(100);
            //touchey touchey (Forces static ctor to trigger)
            NotificationInfoLoader.ToString();
            Console.WriteLine(Environment.NewLine + "Type 'help' for a list of commands");
            while (_running)
            {
                Console.Write('>');
                var command = Console.ReadLine()?.ToLower();
                if (command == null)
                {
                    continue;
                }
                Console.WriteLine();
                if (!commands.TryGetValue(command, out var action))
                {
                    action = () => Console.WriteLine("Invalid command. Type 'help' for a list of commands.");
                }
                action();
                Thread.Sleep(300);
            }

            server.Stop();
            Logger.Log("Server shut down successfully.");
            return(0);
        }