Esempio n. 1
0
 /// <summary>
 /// Hemera 服务器平台应用程序入口点。
 /// </summary>
 /// <param name="args">应用程序参数</param>
 static void Main(string[] args)
 {
     //启动Remoting服务
     RemotingServer.Start();
     Console.WriteLine("Press Enter to Exit.");
     Console.ReadLine();
 }
        public static void Configure(string fileName = "", Credential[] credentials = null)
        {
            Configuration configuration =
                string.IsNullOrWhiteSpace(fileName)
                    ? ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
                    : ConfigurationManager.OpenMappedExeConfiguration(
                    fileMap: new ExeConfigurationFileMap()
            {
                ExeConfigFilename = fileName
            },
                    userLevel: ConfigurationUserLevel.None);

            var configSection = (CoreRemotingConfigSection)
                                configuration.Sections["coreRemoting"];

            foreach (ServerInstanceConfigElement serverInstanceConfig in configSection.ServerInstances)
            {
                var serverConfig = serverInstanceConfig.ToServerConfig();
                var server       = new RemotingServer(serverConfig);
                server.Start();
            }

            foreach (WellKnownServiceConfigElement serviceConfigElement in configSection.Services)
            {
                var entry = serviceConfigElement.ToWellKnownServiceTypeEntry();
                RegisterWellKnownServiceType(entry);
            }

            foreach (ClientInstanceConfigElement clientInstanceConfig in configSection.ClientInstances)
            {
                var clientConfig = clientInstanceConfig.ToClientConfig();
                clientConfig.Credentials = credentials;
                var client = new RemotingClient(clientConfig);
            }
        }
Esempio n. 3
0
        public void CallContext_should_flow_from_client_to_server_and_back()
        {
            var testService =
                new TestService
            {
                TestMethodFake = _ =>
                {
                    CallContext.SetData("test", "Changed");
                    return(CallContext.GetData("test"));
                }
            };

            var serverConfig =
                new ServerConfig()
            {
                NetworkPort            = 9093,
                RegisterServicesAction = container =>
                                         container.RegisterService <ITestService>(
                    factoryDelegate: () => testService,
                    lifetime: ServiceLifetime.Singleton)
            };

            using var server = new RemotingServer(serverConfig);
            server.Start();

            var clientThread =
                new Thread(() =>
            {
                CallContext.SetData("test", "CallContext");

                var client =
                    new RemotingClient(new ClientConfig()
                {
                    ServerPort        = 9093,
                    ConnectionTimeout = 0
                });

                client.Connect();

                var localCallContextValueBeforeRpc = CallContext.GetData("test");

                var proxy  = client.CreateProxy <ITestService>();
                var result = (string)proxy.TestMethod("x");

                var localCallContextValueAfterRpc = CallContext.GetData("test");

                Assert.NotEqual(localCallContextValueBeforeRpc, result);
                Assert.Equal("Changed", result);
                Assert.Equal("Changed", localCallContextValueAfterRpc);

                client.Dispose();
            });

            clientThread.Start();
            clientThread.Join();

            server.Dispose();
        }
Esempio n. 4
0
        public void StartFwRemoteDatabaseConnector()
        {
            RemotingServer.Start();

            var connectString = String.Format("tcp://{0}:{1}/FwRemoteDatabaseConnector.Db4oServerInfo",
                                              "localhost", Db4OPorts.ServerPort);

            m_db4OServerInfo = (Db4oServerInfo)Activator.GetObject(typeof(Db4oServerInfo), connectString);
        }
Esempio n. 5
0
 public void Init()
 {
     // Allow db4o client server unit test to work without running the window service.
     RemotingServer.Start();
     if (Db4oServerInfo.AreProjectsShared_Internal)
     {
         m_fResetSharedProjectValue = true;
         Db4oServerInfo.AreProjectsShared_Internal = false;
     }
 }
Esempio n. 6
0
        public void StartFwRemoteDatabaseConnector()
        {
            FdoTestHelper.SetupStaticFdoProperties();
            m_sharedProject = true;
            RemotingServer.Start(FwDirectoryFinder.RemotingTcpServerConfigFile, FwDirectoryFinder.FdoDirectories, () => m_sharedProject, v => m_sharedProject = v);

            var connectString = String.Format("tcp://{0}:{1}/FwRemoteDatabaseConnector.Db4oServerInfo",
                                              "localhost", Db4OPorts.ServerPort);

            m_db4OServerInfo = (Db4oServerInfo)Activator.GetObject(typeof(Db4oServerInfo), connectString);
        }
Esempio n. 7
0
        public void Delegate_invoked_on_server_should_callback_client()
        {
            string argumentFromServer = null;

            var testService = new TestService();

            var serverConfig =
                new ServerConfig()
            {
                NetworkPort            = 9095,
                RegisterServicesAction = container =>
                                         container.RegisterService <ITestService>(
                    factoryDelegate: () => testService,
                    lifetime: ServiceLifetime.Singleton)
            };

            int serverErrorCount = 0;

            using var server = new RemotingServer(serverConfig);
            server.Error    += (sender, e) => serverErrorCount++;
            server.Start();

            void ClientAction()
            {
                try
                {
                    using var client = new RemotingClient(
                              new ClientConfig()
                    {
                        ConnectionTimeout = 0,
                        ServerPort        = 9095,
                    });

                    client.Connect();

                    var proxy = client.CreateProxy <ITestService>();
                    proxy.TestMethodWithDelegateArg(arg => argumentFromServer = arg);
                }
                catch (Exception e)
                {
                    _testOutputHelper.WriteLine(e.ToString());
                    throw;
                }
            }

            var clientThread = new Thread(ClientAction);

            clientThread.Start();
            clientThread.Join();

            Assert.Equal("test", argumentFromServer);
            Assert.Equal(0, serverErrorCount);
        }
Esempio n. 8
0
        protected override void OnStart(string[] args)
        {
            try
            {
                RemotingServer.Start();
            }
            catch (Exception e)
            {
                // TODO: remove this debugging message.
                System.Windows.Forms.MessageBox.Show(e.ToString());
            }

            m_clientListenerThread = new Thread(ThreadStartListenForClients);
            m_clientListenerThread.Start();
        }
        public void Marshal_should_register_a_service_instance()
        {
            var testService = new TestService();

            using var server = new RemotingServer();
            server.Start();

            string serviceName =
                RemotingServices.Marshal(testService, "test", typeof(ITestService), server.UniqueServerInstanceName);

            var registeredServiceInstance = server.ServiceRegistry.GetService(serviceName);

            Assert.Same(testService, registeredServiceInstance);
            Assert.True(registeredServiceInstance is ITestService);
        }
        public void Server_Creating()
        {
            // Prepare
            RemotingServer server = this._Provider.GetRequiredService <RemotingServer>();

            // Pre-validate
            Assert.False(server.IsEnable());

            // Perform
            server.Start();

            // Post-validate
            Assert.True(server.IsEnable());

            server.Stop();
        }
        public void Test_Exception()
        {
            // Prepare
            RemotingServer server = this._Provider.GetRequiredService <RemotingServer>();

            server.Start();
            IMyService service = this._Provider.GetRequiredService <IMyService>();

            // Pre-validate
            Assert.True(server != null && service != null);

            // Perform
            Exception ex = Assert.Throws <Exception>(() => { service.CheckUnitNotNull(null); });

            // Post-validate
            Assert.Equal("Value cannot be null.\r\nParameter name: Argument must declared!", ex.Message);
        }
        public void Connect_should_create_a_proxy_for_a_remote_service()
        {
            var testService =
                new TestService
            {
                TestMethodFake = arg =>
                                 arg
            };

            using var server =
                      new RemotingServer(new ServerConfig
            {
                NetworkPort = 9199,
                IsDefault   = true
            });

            RemotingServices.Marshal(testService, "test", typeof(ITestService));
            server.Start();

            var clientThread = new Thread(() =>
            {
                // ReSharper disable once ObjectCreationAsStatement
                new RemotingClient(new ClientConfig {
                    ServerPort = 9199, IsDefault = true
                });

                var proxy =
                    RemotingServices.Connect(
                        typeof(ITestService),
                        "test",
                        string.Empty);

                Assert.True(RemotingServices.IsTransparentProxy(proxy));

                object result = ((ITestService)proxy).TestMethod(1);

                RemotingClient.DefaultRemotingClient.Dispose();

                Assert.Equal(1, Convert.ToInt32(result));
            });

            clientThread.Start();
            clientThread.Join();

            server.Dispose();
        }
Esempio n. 13
0
        /// <summary>
        /// Server application entry point.
        /// </summary>
        static void Main()
        {
            // Create an configure a CoreRemoting server
            using var server = new RemotingServer(new ServerConfig()
            {
                HostName               = "localhost",
                NetworkPort            = 9090,
                RegisterServicesAction = container =>
                {
                    container.RegisterService <ISayHelloService, SayHelloService>(ServiceLifetime.Singleton);
                }
            });

            // Start server
            server.Start();

            Console.WriteLine("Server is running.");
            Console.ReadLine();
        }
        public void StartFwRemoteDatabaseConnector()
        {
            // Change the Project Directory to some temporary directory to ensure, other units tests don't add projects
            // which would slow these tests down.
            m_oldProjectDirectory             = DirectoryFinder.ProjectsDirectory;
            DirectoryFinder.ProjectsDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(DirectoryFinder.ProjectsDirectory);

            RemotingServer.Start();

            var connectString = String.Format("tcp://{0}:{1}/FwRemoteDatabaseConnector.Db4oServerInfo",
                                              "127.0.0.1", Db4OPorts.ServerPort);

            m_db4OServerInfo = (Db4oServerInfo)Activator.GetObject(typeof(Db4oServerInfo), connectString);

            // Arbitrary method call to ensure db4oServerInfo is created on server.
            m_db4OServerInfo.AreProjectShared();

            m_progress = new DummyProgressDlg();
        }
Esempio n. 15
0
        public void Events_should_work_remotly()
        {
            var testService = new TestService();

            var serverConfig =
                new ServerConfig()
            {
                NetworkPort            = 9096,
                RegisterServicesAction = container =>
                                         container.RegisterService <ITestService>(
                    factoryDelegate: () => testService,
                    lifetime: ServiceLifetime.Singleton)
            };

            int  serverErrorCount   = 0;
            bool serviceEventCalled = false;

            using var server = new RemotingServer(serverConfig);
            server.Error    += (sender, e) => serverErrorCount++;
            server.Start();

            using var client = new RemotingClient(
                      new ClientConfig()
            {
                ConnectionTimeout = 0,
                ServerPort        = 9096
            });

            client.Connect();

            var proxy = client.CreateProxy <ITestService>();

            proxy.ServiceEvent += () =>
                                  serviceEventCalled = true;

            proxy.FireServiceEvent();

            Assert.True(serviceEventCalled);
            Assert.Equal(0, serverErrorCount);
        }
        public void Server_Client_Start_Stop()
        {
            int i = 0;

            while (i < 3)
            {
                // Prepare
                RemotingServer server = this._Provider.GetRequiredService <RemotingServer>();
                server.Start();
                IRemotingClient client = this._Provider.GetRequiredService <IRemotingClient>();

                // Pre-validate
                client.CheckBindings();


                // Perform
                client.Dispose();
                server.Stop();

                // Post-validate
                Assert.False(server.IsEnable());
            }
        }
        public void Server_Method_Invocation(int valueInt, string valueString, Unit unit)
        {
            EventHandler <Part> onDetect = (sender, e) => {
                Debug.WriteLine($"{e.GetType().ToString()} detected: {e}");
                Assert.NotNull(e);
            };

            RemotingServer server = this._Provider.GetRequiredService <RemotingServer>();

            server.Start();

            IRemotingClient client = this._Provider.GetRequiredService <IRemotingClient>();

            client.CheckBindings();

            IMyService service = this._Provider.GetRequiredService <IMyService>();

            service.OnSomeBDetect += onDetect;

            Assert.NotNull(service.Do(valueInt, valueString, unit));

            client.Dispose();
            server.Stop();
        }
Esempio n. 18
0
 public void Init()
 {
     // Allow db4o client server unit test to work without running the window service.
     RemotingServer.Start(FwDirectoryFinder.RemotingTcpServerConfigFile, FwDirectoryFinder.FdoDirectories, () => false, v => {});
 }
Esempio n. 19
0
        public void External_types_should_work_as_remote_service_parameters()
        {
            bool      remoteServiceCalled = false;
            DataClass parameterValue      = null;

            var testService =
                new TestService()
            {
                TestExternalTypeParameterFake = arg =>
                {
                    remoteServiceCalled = true;
                    parameterValue      = arg;
                }
            };

            var serverConfig =
                new ServerConfig()
            {
                NetworkPort            = 9097,
                RegisterServicesAction = container =>
                                         container.RegisterService <ITestService>(
                    factoryDelegate: () => testService,
                    lifetime: ServiceLifetime.Singleton)
            };

            int serverErrorCount = 0;

            using var server = new RemotingServer(serverConfig);
            server.Error    += (sender, e) => serverErrorCount++;
            server.Start();

            void ClientAction()
            {
                try
                {
                    using var client = new RemotingClient(new ClientConfig()
                    {
                        ConnectionTimeout = 0,
                        ServerPort        = 9097
                    });

                    client.Connect();

                    var proxy = client.CreateProxy <ITestService>();
                    proxy.TestExternalTypeParameter(new DataClass()
                    {
                        Value = 42
                    });

                    Assert.Equal(42, parameterValue.Value);
                }
                catch (Exception e)
                {
                    _testOutputHelper.WriteLine(e.ToString());
                    throw;
                }
            }

            var clientThread = new Thread(ClientAction);

            clientThread.Start();
            clientThread.Join();

            Assert.True(remoteServiceCalled);
            Assert.Equal(0, serverErrorCount);
        }
Esempio n. 20
0
 protected override void OnStart(string[] args)
 {
     RemotingServer.Start(FwDirectoryFinder.RemotingTcpServerConfigFile, FwDirectoryFinder.FdoDirectories, GetSharedProject, SetSharedProject);
     m_clientListenerThread = new Thread(ThreadStartListenForClients);
     m_clientListenerThread.Start();
 }
Esempio n. 21
0
        public void Executing101RpcCalls_should_not_bloat_memory()
        {
            int executionCount = 0;

            var testService =
                new TestService()
            {
                TestMethodFake = arg =>
                {
                    Interlocked.Increment(ref executionCount);
                    return(arg);
                }
            };

            var serverConfig =
                new ServerConfig()
            {
                NetworkPort            = 9094,
                RegisterServicesAction = container =>
                                         container.RegisterService <ITestService>(
                    factoryDelegate: () => testService,
                    lifetime: ServiceLifetime.Singleton)
            };

            using var server = new RemotingServer(serverConfig);
            server.Start();

            var onlyOneCall = true;

            void ClientAction()
            {
                using var client = new RemotingClient(new ClientConfig()
                {
                    ConnectionTimeout = 0,
                    ServerPort        = 9094
                });

                client.Connect();
                var proxy = client.CreateProxy <ITestService>();

                // ReSharper disable once AccessToModifiedClosure
                if (onlyOneCall)
                {
                    proxy.TestMethod("test");
                }
                else
                {
                    Parallel.For(0, 100, _ =>
                                 proxy.TestMethod("test"));
                }

                client.Disconnect();
            }

            var firstClientThread = new Thread(ClientAction);

            firstClientThread.Start();
            firstClientThread.Join();

            onlyOneCall = false;

            long consumedMemoryAfterOneCall = Process.GetCurrentProcess().PrivateMemorySize64;

            _testOutputHelper.WriteLine("{0} = {1} MB", nameof(consumedMemoryAfterOneCall), consumedMemoryAfterOneCall / 1024 / 1024);

            var secondClientThread = new Thread(ClientAction);

            secondClientThread.Start();
            secondClientThread.Join();

            long consumedMemoryAfter101Calls = Process.GetCurrentProcess().PrivateMemorySize64;

            _testOutputHelper.WriteLine("{0} = {1} MB", nameof(consumedMemoryAfter101Calls), consumedMemoryAfter101Calls / 1024 / 1024);
            _testOutputHelper.WriteLine("Difference: {0} MB", (consumedMemoryAfter101Calls - consumedMemoryAfterOneCall) / 1024 / 1024);

            Assert.Equal(101, executionCount);
            Assert.True((consumedMemoryAfter101Calls - consumedMemoryAfterOneCall) < (128 * 1024 * 1024)); // 128 MB
        }
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// If a test overrides this, it should call the base implementation.
 /// </summary>
 /// ------------------------------------------------------------------------------------
 public override void FixtureSetup()
 {
     RemotingServer.Start();
     base.FixtureSetup();
 }
Esempio n. 23
0
        public void Client_Connect_should_throw_exception_on_invalid_auth_credentials()
        {
            var testService  = new TestService();
            var authProvider =
                new FakeAuthProvider()
            {
                AuthenticateFake = credentials => credentials[1].Value == "secret"
            };

            var serverConfig =
                new ServerConfig()
            {
                AuthenticationProvider = authProvider,
                AuthenticationRequired = true,
                NetworkPort            = 9092,
                RegisterServicesAction = container =>
                                         container.RegisterService <ITestService>(
                    factoryDelegate: () => testService,
                    lifetime: ServiceLifetime.Singleton)
            };

            int serverErrorCount = 0;

            using var server = new RemotingServer(serverConfig);
            server.Error    += (sender, e) => serverErrorCount++;
            server.Start();

            var clientAction = new Action <string, bool>((password, shouldThrow) =>
            {
                using var client =
                          new RemotingClient(new ClientConfig()
                {
                    ConnectionTimeout = 0,
                    ServerPort        = 9092,
                    Credentials       = new []
                    {
                        new Credential()
                        {
                            Name = "User", Value = "tester"
                        },
                        new Credential()
                        {
                            Name = "Password", Value = password
                        }
                    }
                });

                if (shouldThrow)
                {
                    Assert.Throws <SecurityException>(() => client.Connect());
                }
                else
                {
                    client.Connect();
                }
            });

            var clientThread1 = new Thread(() => clientAction("wrong", true));

            clientThread1.Start();
            clientThread1.Join();

            var clientThread2 = new Thread(() => clientAction("secret", false));

            clientThread2.Start();
            clientThread2.Join();

            Assert.Equal(0, serverErrorCount);
        }
Esempio n. 24
0
        public void Client_Connect_should_create_new_session_AND_Disconnect_should_close_session()
        {
            var testService =
                new TestService();

            var serverConfig =
                new ServerConfig()
            {
                NetworkPort            = 9091,
                RegisterServicesAction = container =>
                                         container.RegisterService <ITestService>(
                    factoryDelegate: () => testService,
                    lifetime: ServiceLifetime.Singleton)
            };

            using var server = new RemotingServer(serverConfig);
            server.Start();

            var connectedWaitHandles = new[]
            {
                new AutoResetEvent(false),
                new AutoResetEvent(false)
            };

            var quitWaitHandle = new ManualResetEventSlim();

            var clientAction = new Action <int>(index =>
            {
                var client =
                    new RemotingClient(new ClientConfig()
                {
                    ConnectionTimeout = 0,
                    ServerPort        = 9091
                });

                Assert.False(client.HasSession);
                client.Connect();

                connectedWaitHandles[index].Set();

                Assert.True(client.HasSession);

                quitWaitHandle.Wait();

                client.Dispose();
            });

            var clientThread1 = new Thread(() => clientAction(0));
            var clientThread2 = new Thread(() => clientAction(1));

            Assert.Empty(server.SessionRepository.Sessions);

            // Start two clients to create two sessions
            clientThread1.Start();
            clientThread2.Start();

            // Wait for connection of both clients
            WaitHandle.WaitAll(connectedWaitHandles);

            Assert.Equal(2, server.SessionRepository.Sessions.Count());

            quitWaitHandle.Set();

            clientThread1.Join();
            clientThread2.Join();

            // There should be no sessions left, after both clients disconnedted
            Assert.Empty(server.SessionRepository.Sessions);
        }
Esempio n. 25
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// If a test overrides this, it should call the base implementation.
 /// </summary>
 /// ------------------------------------------------------------------------------------
 public override void FixtureSetup()
 {
     RemotingServer.Start(FwDirectoryFinder.RemotingTcpServerConfigFile, FwDirectoryFinder.FdoDirectories, () => false, v => { });
     base.FixtureSetup();
 }
Esempio n. 26
0
        public void Call_on_Proxy_should_be_invoked_on_remote_service_without_MessageEncryption()
        {
            bool remoteServiceCalled = false;

            var testService =
                new TestService()
            {
                TestMethodFake = arg =>
                {
                    remoteServiceCalled = true;
                    return(arg);
                }
            };

            var serverConfig =
                new ServerConfig()
            {
                MessageEncryption      = false,
                NetworkPort            = 9094,
                RegisterServicesAction = container =>
                                         container.RegisterService <ITestService>(
                    factoryDelegate: () => testService,
                    lifetime: ServiceLifetime.Singleton)
            };

            int serverErrorCount = 0;

            using var server = new RemotingServer(serverConfig);
            server.Error    += (sender, e) => serverErrorCount++;
            server.Start();

            void ClientAction()
            {
                try
                {
                    using var client = new RemotingClient(new ClientConfig()
                    {
                        ConnectionTimeout = 0,
                        ServerPort        = 9094,
                        MessageEncryption = false
                    });

                    client.Connect();

                    var proxy  = client.CreateProxy <ITestService>();
                    var result = proxy.TestMethod("test");

                    Assert.Equal("test", result);
                }
                catch (Exception e)
                {
                    _testOutputHelper.WriteLine(e.ToString());
                    throw;
                }
            }

            var clientThread = new Thread(ClientAction);

            clientThread.Start();
            clientThread.Join();

            Assert.True(remoteServiceCalled);
            Assert.Equal(0, serverErrorCount);
        }
Esempio n. 27
0
        public void Run()
        {
            _Log.Info("AccountServer is starting");

            _Log.Info("Reading configuration");
            _ConfigTree.FromConfigFile("Config/AccountServer.cfg");

            _Log.Info("Connecting to database");
            _DatabaseConnection = new MySqlConnection(BuildConnectionString());

            try
            {
                _DatabaseConnection.Open();
            }
            catch (Exception ex)
            {
                _Log.Fatal("Error connecting to database!", ex);
                return;
            }

            _RemotingServer = new RemotingServer(_ConfigTree.Get("inter.uri", "net.tcp://localhost:5401/"));
            _RemotingServer.ExposeType<CharServerService>("CharServer", typeof(ICharServerService));
            _RemotingServer.Start();
            _Log.InfoFormat("Accepting CharServer connections at {0}", _RemotingServer.BaseUri);

            IPAddress bindAddress = IPAddress.Parse(_ConfigTree.Get("network.interface.ip", "0.0.0.0"));
            int bindPort = _ConfigTree.Get("network.interface.port", 5500);
            _Log.InfoFormat("Accepting connections at {0}:{1}", bindAddress, bindPort);
            _Listener.Bind(bindAddress, bindPort);
            _Listener.Listen();

            _Running = true;
            while (_Running)
                Thread.Yield();

            _RemotingServer.Stop();
        }