コード例 #1
0
ファイル: Service.cs プロジェクト: orangeswim/OCTGN
        static void Main(string[] args)
        {
            Environment.ExitCode = -69;

            LoggerFactory.DefaultMethod = (con) => new Log4NetLogger(con.Name);
            Log = LoggerFactory.Create(nameof(Service));

            //This will catch any exceptions that happen after this line
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
            Signal.OnException += Signal_OnException;

            AppDomain.CurrentDomain.AssemblyLoad    += CurrentDomain_AssemblyLoad;
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            ApiClient.DefaultUrl = new Uri(AppConfig.Instance.ApiUrl);

            HostedGames.Init();

            var handshaker        = new DefaultHandshaker();
            var connectionCreator = new TcpConnectionCreator(handshaker);

            Client = new GameServiceClient(connectionCreator);
            Client.ReconnectRetryCount = int.MaxValue; //retry forever basically

            using (_service = new Service()) {
                _service.Run(args);
            }

            ConsoleUtils.TryWaitForKey();
        }
コード例 #2
0
ファイル: ConnectionCreator.cs プロジェクト: abd0ahmed/xeus
        public ConnectionCreator(string basePath, BufferPool bufferPool)
        {
            var settingsPath = Path.Combine(basePath, "Settings");
            var childrenPath = Path.Combine(basePath, "Children");

            _bufferPool           = bufferPool;
            _tcpConnectionCreator = new TcpConnectionCreator(Path.Combine(childrenPath, nameof(TcpConnectionCreator)), bufferPool);
        }
コード例 #3
0
        public Node()
        {
            _version    = typeof(Node).Assembly.GetName().Version;
            _handshaker = new DefaultHandshaker();

            var connectionCreator = new TcpConnectionCreator(_handshaker);
            var config            = new LibraryCommunicationClientConfig(connectionCreator);

            _client = new Library.Communication.Client(config, _version);
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: wlk0/OCTGN
        internal static void Start(string[] args, bool isTestRelease)
        {
            Log.Info("Start");
            IsReleaseTest           = isTestRelease;
            GameMessage.MuteChecker = () =>
            {
                if (Program.Client == null)
                {
                    return(false);
                }
                return(Program.Client.Muted != 0);
            };

            Log.Info("Setting SSL Validation Helper");
            SSLHelper = new SSLValidationHelper();

            Log.Info("Setting api path");
            Octgn.Site.Api.ApiClient.DefaultUrl = new Uri(AppConfig.WebsitePath);
            try
            {
                Log.Debug("Setting rendering mode.");
                RenderOptions.ProcessRenderMode = Prefs.UseHardwareRendering ? RenderMode.Default : RenderMode.SoftwareOnly;
            }
            catch (Exception)
            {
                // if the system gets mad, best to leave it alone.
            }

            Log.Info("Setting temp main window");
            Application.Current.MainWindow = new Window();
            try
            {
                Log.Info("Checking if admin");
                var isAdmin = UacHelper.IsProcessElevated && UacHelper.IsUacEnabled;
                if (isAdmin)
                {
                    MessageBox.Show(
                        "You are currently running OCTGN as Administrator. It is recommended that you run as a standard user, or you will most likely run into problems. Please exit OCTGN and run as a standard user.",
                        "WARNING",
                        MessageBoxButton.OK,
                        MessageBoxImage.Exclamation);
                }
            }
            catch (Exception e)
            {
                Log.Warn("Couldn't check if admin", e);
            }

            Log.Info("Creating Lobby Client");
            var handshaker        = new DefaultHandshaker();
            var connectionCreator = new TcpConnectionCreator(handshaker);
            var lobbyClientConfig = new LibraryCommunicationClientConfig(connectionCreator);

            LobbyClient = new Octgn.Library.Communication.Client(lobbyClientConfig, typeof(Program).Assembly.GetName().Version);

            //Log.Info("Adding trace listeners");
            //Debug.Listeners.Add(DebugListener);
            //DebugTrace.Listeners.Add(DebugListener);
            //Trace.Listeners.Add(DebugListener);
            //ChatLog = new CacheTraceListener();
            //Trace.Listeners.Add(ChatLog);
            Log.Info("Creating Game Message Dispatcher");
            GameMess = new GameMessageDispatcher();
            GameMess.ProcessMessage(
                x =>
            {
                for (var i = 0; i < x.Arguments.Length; i++)
                {
                    var arg       = x.Arguments[i];
                    var cardModel = arg as DataNew.Entities.Card;
                    var cardId    = arg as CardIdentity;
                    var card      = arg as Card;
                    if (card != null && (card.FaceUp || card.MayBeConsideredFaceUp))
                    {
                        cardId = card.Type;
                    }

                    if (cardId != null || cardModel != null)
                    {
                        ChatCard chatCard = null;
                        if (cardId != null)
                        {
                            chatCard = new ChatCard(cardId);
                        }
                        else
                        {
                            chatCard = new ChatCard(cardModel);
                        }
                        if (card != null)
                        {
                            chatCard.SetGameCard(card);
                        }
                        x.Arguments[i] = chatCard;
                    }
                    else
                    {
                        x.Arguments[i] = arg == null ? "[?]" : arg.ToString();
                    }
                }
                return(x);
            });

            Log.Info("Registering versioned stuff");

            //BasePath = Path.GetDirectoryName(typeof (Program).Assembly.Location) + '\\';
            Log.Info("Setting Games Path");
            GameSettings = new GameSettings();
            if (shutDown)
            {
                Log.Info("Shutdown Time");
                if (Application.Current.MainWindow != null)
                {
                    Application.Current.MainWindow.Close();
                }
                return;
            }

            Log.Info("Decide to ask about wine");
            if (Prefs.AskedIfUsingWine == false)
            {
                Log.Info("Asking about wine");
                var res = MessageBox.Show("Are you running OCTGN on Linux or a Mac using Wine?", "Using Wine",
                                          MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (res == MessageBoxResult.Yes)
                {
                    Prefs.AskedIfUsingWine      = true;
                    Prefs.UsingWine             = true;
                    Prefs.UseHardwareRendering  = false;
                    Prefs.UseGameFonts          = false;
                    Prefs.UseWindowTransparency = false;
                }
                else if (res == MessageBoxResult.No)
                {
                    Prefs.AskedIfUsingWine      = true;
                    Prefs.UsingWine             = false;
                    Prefs.UseHardwareRendering  = true;
                    Prefs.UseGameFonts          = true;
                    Prefs.UseWindowTransparency = true;
                }
            }
            // Check for desktop experience
            if (Prefs.UsingWine == false)
            {
                try
                {
                    Log.Debug("Checking for Desktop Experience");
                    var objMC = new ManagementClass("Win32_ServerFeature");
                    // Expected Exception: System.Management.ManagementException
                    // Additional information: Not found
                    var  objMOC = objMC.GetInstances();
                    bool gotIt  = false;
                    foreach (var objMO in objMOC)
                    {
                        if ((UInt32)objMO["ID"] == 35)
                        {
                            Log.Debug("Found Desktop Experience");
                            gotIt = true;
                            break;
                        }
                    }
                    if (!gotIt)
                    {
                        var res =
                            MessageBox.Show(
                                "You are running OCTGN without the windows Desktop Experience installed. This WILL cause visual, gameplay, and sound issues. Though it isn't required, it is HIGHLY recommended. \n\nWould you like to be shown a site to tell you how to turn it on?",
                                "Windows Desktop Experience Missing", MessageBoxButton.YesNo,
                                MessageBoxImage.Exclamation);
                        if (res == MessageBoxResult.Yes)
                        {
                            LaunchUrl(
                                "http://blogs.msdn.com/b/findnavish/archive/2012/06/01/enabling-win-7-desktop-experience-on-windows-server-2008.aspx");
                        }
                        else
                        {
                            MessageBox.Show("Ok, but you've been warned...", "Warning", MessageBoxButton.OK,
                                            MessageBoxImage.Warning);
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Warn(
                        "Check desktop experience error. An error like 'Not Found' is normal and shouldn't be worried about",
                        e);
                }
            }
            // Send off user/computer stats
            try
            {
                var osver    = System.Environment.OSVersion.VersionString;
                var osBit    = Win32.Is64BitOperatingSystem;
                var procBit  = Win32.Is64BitProcess;
                var issubbed = SubscriptionModule.Get().IsSubscribed;
                var iswine   = Prefs.UsingWine;
                // Use the API to submit info
            }
            catch (Exception e)
            {
                Log.Warn("Sending stats error", e);
            }
            //var win = new ShareDeck();
            //win.ShowDialog();
            //return;
            Log.Info("Getting Launcher");
            Launchers.ILauncher launcher = CommandLineHandler.Instance.HandleArguments(Environment.GetCommandLineArgs());
            DeveloperMode = CommandLineHandler.Instance.DevMode;

            Versioned.Setup(Program.DeveloperMode);
            /* This section is automatically generated from the file Scripting/ApiVersions.xml. So, if you enjoy not getting pissed off, don't modify it.*/
            //START_REPLACE_API_VERSION
            Versioned.RegisterVersion(Version.Parse("3.1.0.0"), DateTime.Parse("2014-1-12"), ReleaseMode.Live);
            Versioned.RegisterVersion(Version.Parse("3.1.0.1"), DateTime.Parse("2014-1-22"), ReleaseMode.Live);
            Versioned.RegisterVersion(Version.Parse("3.1.0.2"), DateTime.Parse("2015-8-26"), ReleaseMode.Live);
            Versioned.RegisterFile("PythonApi", "pack://application:,,,/Scripting/Versions/3.1.0.0.py", Version.Parse("3.1.0.0"));
            Versioned.RegisterFile("PythonApi", "pack://application:,,,/Scripting/Versions/3.1.0.1.py", Version.Parse("3.1.0.1"));
            Versioned.RegisterFile("PythonApi", "pack://application:,,,/Scripting/Versions/3.1.0.2.py", Version.Parse("3.1.0.2"));
            //END_REPLACE_API_VERSION
            Versioned.Register <ScriptApi>();

            launcher.Launch().Wait();

            if (launcher.Shutdown)
            {
                if (Application.Current.MainWindow != null)
                {
                    Application.Current.MainWindow.Close();
                }
                return;
            }
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: kellyelton/OCTGN
        internal static void Start(string[] args, bool isTestRelease)
        {
            Log.Info("Start");
            IsReleaseTest = isTestRelease;

            Log.Info("Setting SSL Validation Helper");
            SSLHelper = new SSLValidationHelper();

            Log.Info("Setting api path");
            Octgn.Site.Api.ApiClient.DefaultUrl = new Uri(AppConfig.WebsitePath);

            JodsEngine = new JodsEngineIntegration();

            Log.Info("Configuring game feeds");
            ConfigureGameFeedTimeout();

            try
            {
                Log.Debug("Setting rendering mode.");
                RenderOptions.ProcessRenderMode = Prefs.UseHardwareRendering ? RenderMode.Default : RenderMode.SoftwareOnly;
            }
            catch (Exception)
            {
                // if the system gets mad, best to leave it alone.
            }

            Log.Info("Setting temp main window");
            Application.Current.MainWindow = new Window();
            try
            {
                Log.Info("Checking if admin");
                var isAdmin = UacHelper.IsProcessElevated && UacHelper.IsUacEnabled;
                if (isAdmin)
                {
                    MessageBox.Show(
                        "You are currently running OCTGN as Administrator. It is recommended that you run as a standard user, or you will most likely run into problems. Please exit OCTGN and run as a standard user.",
                        "WARNING",
                        MessageBoxButton.OK,
                        MessageBoxImage.Exclamation);
                }
            }
            catch (Exception e)
            {
                Log.Warn("Couldn't check if admin", e);
            }

            Log.Info("Creating Lobby Client");
            var handshaker        = new DefaultHandshaker();
            var connectionCreator = new TcpConnectionCreator(handshaker);
            var lobbyClientConfig = new LibraryCommunicationClientConfig(connectionCreator);

            LobbyClient = new Octgn.Library.Communication.Client(
                lobbyClientConfig,
                typeof(Program).Assembly.GetName().Version
                );

            //Log.Info("Adding trace listeners");
            //Debug.Listeners.Add(DebugListener);
            //DebugTrace.Listeners.Add(DebugListener);
            //Trace.Listeners.Add(DebugListener);
            //ChatLog = new CacheTraceListener();
            //Trace.Listeners.Add(ChatLog);

            Log.Info("Setting Games Path");
            GameSettings = new GameSettings();
            if (shutDown)
            {
                Log.Info("Shutdown Time");
                if (Application.Current.MainWindow != null)
                {
                    Application.Current.MainWindow.Close();
                }
                return;
            }

            Log.Info("Decide to ask about wine");
            if (Prefs.AskedIfUsingWine == false)
            {
                Log.Info("Asking about wine");
                var res = MessageBox.Show("Are you running OCTGN on Linux or a Mac using Wine?", "Using Wine",
                                          MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (res == MessageBoxResult.Yes)
                {
                    Prefs.AskedIfUsingWine      = true;
                    Prefs.UsingWine             = true;
                    Prefs.UseHardwareRendering  = false;
                    Prefs.UseGameFonts          = false;
                    Prefs.UseWindowTransparency = false;
                }
                else if (res == MessageBoxResult.No)
                {
                    Prefs.AskedIfUsingWine      = true;
                    Prefs.UsingWine             = false;
                    Prefs.UseHardwareRendering  = true;
                    Prefs.UseGameFonts          = true;
                    Prefs.UseWindowTransparency = true;
                }
            }
            // Check for desktop experience
            if (Prefs.UsingWine == false)
            {
                try
                {
                    Log.Debug("Checking for Desktop Experience");
                    var objMC = new ManagementClass("Win32_ServerFeature");
                    // Expected Exception: System.Management.ManagementException
                    // Additional information: Not found
                    var  objMOC = objMC.GetInstances();
                    bool gotIt  = false;
                    foreach (var objMO in objMOC)
                    {
                        if ((UInt32)objMO["ID"] == 35)
                        {
                            Log.Debug("Found Desktop Experience");
                            gotIt = true;
                            break;
                        }
                    }
                    if (!gotIt)
                    {
                        var res =
                            MessageBox.Show(
                                "You are running OCTGN without the windows Desktop Experience installed. This WILL cause visual, gameplay, and sound issues. Though it isn't required, it is HIGHLY recommended. \n\nWould you like to be shown a site to tell you how to turn it on?",
                                "Windows Desktop Experience Missing", MessageBoxButton.YesNo,
                                MessageBoxImage.Exclamation);
                        if (res == MessageBoxResult.Yes)
                        {
                            LaunchUrl(
                                "http://blogs.msdn.com/b/findnavish/archive/2012/06/01/enabling-win-7-desktop-experience-on-windows-server-2008.aspx");
                        }
                        else
                        {
                            MessageBox.Show("Ok, but you've been warned...", "Warning", MessageBoxButton.OK,
                                            MessageBoxImage.Warning);
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Warn(
                        "Check desktop experience error. An error like 'Not Found' is normal and shouldn't be worried about",
                        e);
                }
            }
            // Send off user/computer stats
            try
            {
                var osver    = System.Environment.OSVersion.VersionString;
                var osBit    = Win32.Is64BitOperatingSystem;
                var procBit  = Win32.Is64BitProcess;
                var issubbed = SubscriptionModule.Get().IsSubscribed;
                var iswine   = Prefs.UsingWine;
                // Use the API to submit info
            }
            catch (Exception e)
            {
                Log.Warn("Sending stats error", e);
            }

            Log.Info("Getting Launcher");
            Launchers.ILauncher launcher = CommandLineHandler.Instance.HandleArguments(Environment.GetCommandLineArgs());
            DeveloperMode = CommandLineHandler.Instance.DevMode;

            launcher.Launch().Wait();

            if (launcher.Shutdown)
            {
                if (Application.Current.MainWindow != null)
                {
                    Application.Current.MainWindow.Close();
                }
                return;
            }
        }
コード例 #6
0
        public async Task TooLongLength_ClosesConnection_ButDoesNotSignal()
        {
            var port = NextPort;

            var endpoint = new IPEndPoint(IPAddress.Loopback, port);

            var handshaker = new FakeHandshaker("0");

            var serializer = new XmlSerializer();

            var connectionCreated = new TaskCompletionSource <IConnection>();

            using (var server = new Server(new TcpListener(endpoint, handshaker), serializer)) {
                server.Listener.ConnectionCreated += (sender, args) => {
                    connectionCreated.SetResult(args.Connection);
                };

                server.Initialize();

                var connectionCreator = new TcpConnectionCreator(handshaker);

                var client = new Client(connectionCreator, serializer);

                await client.Connect($"localhost:{port}");

                var serverConnection = (TcpConnection)await connectionCreated.Task;

                var tcpConnection = (TcpConnection)client.Connection;

                var tcpClient = tcpConnection.TcpClient;

                var clientStream = tcpClient.GetStream();

                clientStream.Write(new byte[8], 0, 8);

                var len = BitConverter.GetBytes(SerializedPacket.MAX_DATA_SIZE + 1);

                clientStream.Write(len, 0, len.Length);

                using (var timeoutCancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(100))) {
                    while (!(serverConnection.LastPacketReadingException is InvalidDataLengthException))
                    {
                        if (timeoutCancellation.IsCancellationRequested)
                        {
                            Assert.Fail("Timed out waiting for exception");
                        }

                        await Task.Delay(3);
                    }

                    while (tcpClient.Connected)
                    {
                        if (timeoutCancellation.IsCancellationRequested)
                        {
                            Assert.Fail("Timed out waiting for client to disconnect");
                        }

                        await Task.Delay(3);

                        try {
                            tcpClient.Client.Poll(1, System.Net.Sockets.SelectMode.SelectRead);
                        } catch (ObjectDisposedException) { }
                    }

                    while (serverConnection.State != ConnectionState.Closed)
                    {
                        if (timeoutCancellation.IsCancellationRequested)
                        {
                            Assert.Fail("Timed out waiting for server to disconnect");
                        }

                        await Task.Delay(3);
                    }
                }
            }

            Assert.AreEqual(0, SignalErrors.Count);
        }
コード例 #7
0
        public async Task ClientDisconnectBeforeSendingEntirePacket_ClosesConnection_ButDoesNotSignal()
        {
            var port = NextPort;

            var endpoint = new IPEndPoint(IPAddress.Loopback, port);

            var handshaker = new FakeHandshaker("0");

            var serializer = new XmlSerializer();

            var connectionCreated = new TaskCompletionSource <IConnection>();

            using (var server = new Server(new TcpListener(endpoint, handshaker), serializer)) {
                server.Listener.ConnectionCreated += (sender, args) => {
                    connectionCreated.SetResult(args.Connection);
                };

                server.Initialize();

                var connectionCreator = new TcpConnectionCreator(handshaker);

                var client = new Client(connectionCreator, serializer);

                await client.Connect($"localhost:{port}");

                var serverConnection = (TcpConnection)await connectionCreated.Task;

                var tcpConnection = (TcpConnection)client.Connection;

                var tcpClient = tcpConnection.TcpClient;

                var clientStream = tcpClient.GetStream();

                // Write half of a packet id
                clientStream.Write(new byte[4], 0, 4);

                tcpConnection.Close();

                Assert.IsFalse(client.IsConnected);

                using (var timeoutCancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(100))) {
                    while (!(serverConnection.LastPacketReadingException is DisconnectedException))
                    {
                        if (timeoutCancellation.IsCancellationRequested)
                        {
                            Assert.Fail("Timed out waiting for DisconnectedException");
                        }

                        await Task.Delay(3);
                    }

                    while (serverConnection.State != ConnectionState.Closed)
                    {
                        if (timeoutCancellation.IsCancellationRequested)
                        {
                            Assert.Fail("Timed out waiting for server to disconnect");
                        }

                        await Task.Delay(3);
                    }
                }
            }

            Assert.AreEqual(0, SignalErrors.Count);
        }