public static void StartServer(TestContext ctx) { var serverSetup = new IpcBinaryServerProtocolSetup("OneWayTest"); ZyanHost = new ZyanComponentHost("OneWayServer", serverSetup); ZyanHost.RegisterComponent<ISampleServer, SampleServer>(); ZyanConnection = new ZyanConnection("ipc://OneWayTest/OneWayServer"); }
public static void StartServer(TestContext ctx) { var serverSetup = new IpcBinaryServerProtocolSetup("StreamsTest"); ZyanHost = new ZyanComponentHost("SampleStreamServer", serverSetup); ZyanHost.RegisterComponent<IStreamService, StreamService>(); ZyanConnection = new ZyanConnection("ipc://StreamsTest/SampleStreamServer"); }
/// <summary> /// Initializes a new instance of the <see cref="ZyanProxy"/> class. /// </summary> /// <param name="uniqueName">Unique component name.</param> /// <param name="type">Component interface type.</param> /// <param name="connection"><see cref="ZyanConnection"/> instance.</param> /// <param name="implicitTransactionTransfer">Specifies whether transactions should be passed implicitly.</param> /// <param name="keepSynchronizationContext">Specifies whether callbacks and event handlers should use the original synchronization context.</param> /// <param name="sessionID">Session ID.</param> /// <param name="componentHostName">Name of the remote component host.</param> /// <param name="autoLoginOnExpiredSession">Specifies whether Zyan should login automatically with cached credentials after the session is expired.</param> /// <param name="activationType">Component activation type</param> public ZyanProxy(string uniqueName, Type type, ZyanConnection connection, bool implicitTransactionTransfer, bool keepSynchronizationContext, Guid sessionID, string componentHostName, bool autoLoginOnExpiredSession, ActivationType activationType) : base(type) { if (type == null) throw new ArgumentNullException("type"); if (connection == null) throw new ArgumentNullException("connection"); if (string.IsNullOrEmpty(uniqueName)) _uniqueName = type.FullName; else _uniqueName = uniqueName; _sessionID = sessionID; _connection = connection; _componentHostName = componentHostName; _interfaceType = type; _activationType = activationType; _remoteDispatcher = _connection.RemoteDispatcher; _implicitTransactionTransfer = implicitTransactionTransfer; _autoLoginOnExpiredSession = autoLoginOnExpiredSession; _delegateCorrelationSet = new List<DelegateCorrelationInfo>(); // capture synchronization context for callback execution if (keepSynchronizationContext) { _synchronizationContext = SynchronizationContext.Current; } }
private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { if (_connection != null) { _connection.Dispose(); _connection = null; } }
protected override void Dispose(bool disposing) { if (disposing && connection != null) { connection.Dispose(); connection = null; } }
/// <summary> /// Initializes a new instance of the <see cref="ZyanComposablePartDefinition" /> class. /// </summary> /// <param name="connection">The connection.</param> /// <param name="componentInterfaceName">Name of the component interface.</param> /// <param name="uniqueName">Unique name of the published component.</param> /// <param name="transferTransactions">if set to <c>true</c>, then ambient transaction transfer is enabled.</param> public ZyanComposablePartDefinition(ZyanConnection connection, string componentInterfaceName, string uniqueName, bool transferTransactions) { Connection = connection; ComponentUniqueName = uniqueName; ComponentInterfaceName = GetTypeFullName(componentInterfaceName); ComponentInterface = new Lazy<Type>(() => TypeHelper.GetType(componentInterfaceName, true)); ImplicitTransactionTransfer = transferTransactions; }
/// <summary> /// Initializes a new instance of the <see cref="ZyanCatalog"/> class. /// </summary> /// <param name="connection">The <see cref="ZyanConnection"/> to pull remote components from.</param> /// <param name="transferTransactions">Enable ambient transactions support for created proxies.</param> /// <param name="keepSynchronizationContext">Keep synchronization context for the callbacks and event handlers.</param> public ZyanCatalog(ZyanConnection connection, bool transferTransactions, bool keepSynchronizationContext) { if (connection == null) throw new ArgumentNullException("connection"); Connection = connection; ImplicitTransactionTransfer = transferTransactions; KeepSynchronizationContext = keepSynchronizationContext; }
/// <summary> /// Creates ZyanClientQueryHandler instance. /// </summary> /// <param name="serverUrl">URL where the Remote Objects will be published.</param> public ZyanClientQueryHandler(string serverUrl) { if (string.IsNullOrEmpty(serverUrl)) { throw new ArgumentNullException("serverUrl"); } Connection = new ZyanConnection(serverUrl); }
/// <summary> /// Creates ZyanClientQueryHandler instance. /// </summary> /// <param name="connection">Zyan connection.</param> public ZyanClientQueryHandler(ZyanConnection connection) { if (connection == null) { throw new ArgumentNullException("connection"); } Connection = connection; }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing && ZyanConnection != null) { ZyanConnection.Dispose(); ZyanConnection = null; } }
static void Main(string[] args) { var connection = new ZyanConnection("tcp://localhost:12800/ZyanDemo"); // Create HelloWorldService proxy var proxy = connection.CreateProxy<IHellow>(); proxy.Say("HelloWorld").Wait(); var msg = proxy.Create(new Message() { ID = 4 }); Console.WriteLine(msg.ID); Console.ReadLine(); }
static void Main(string[] args) { System.Console.Write("Nickname: "); _nickName = System.Console.ReadLine(); System.Console.WriteLine("-----------------------------------------------"); Hashtable credentials = new Hashtable(); credentials.Add("nickname", _nickName); ZyanConnection connection = null; TcpDuplexClientProtocolSetup protocol = new TcpDuplexClientProtocolSetup(true); try { connection = new ZyanConnection(Properties.Settings.Default.ServerUrl, protocol, credentials, false, true); } catch (SecurityException ex) { System.Console.WriteLine(ex.Message); System.Console.ReadLine(); return; } connection.CallInterceptors.For<IMiniChat>().Add( (IMiniChat chat, string nickname, string message) => chat.SendMessage(nickname, message), (data, nickname, message) => { if (message.Contains("f**k") || message.Contains("sex")) { System.Console.WriteLine("TEXT CONTAINS FORBIDDEN WORDS!"); data.Intercepted = true; } }); connection.CallInterceptionEnabled = true; IMiniChat chatProxy = connection.CreateProxy<IMiniChat>(); chatProxy.MessageReceived += new Action<string, string>(chatProxy_MessageReceived); string text = string.Empty; while (text.ToLower() != "quit") { text = System.Console.ReadLine(); chatProxy.SendMessage(_nickName, text); } chatProxy.MessageReceived -= new Action<string, string>(chatProxy_MessageReceived); connection.Dispose(); }
/// <summary> /// Erstellt eine neue Instanz von ComponentInvokerProxy. /// </summary> /// <param name="type">Schnittstelle der entfernten Komponente</param> /// <param name="connection">Zyan-Verbindungsobjekt</param> public ComponentInvokerProxy(Type type, ZyanConnection connection) : base(type) { // Wenn kein Typ angegeben wurde ... if (type.Equals(null)) // Ausnahme werfen throw new ArgumentNullException("type"); // Wenn keine Verbindung angegeben wurde ... if (connection == null) // Ausnahme werfen throw new ArgumentNullException("connection"); // Verbindung übernehmen _connection = connection; }
static void Main(string[] args) { System.Threading.Thread.Sleep(2000); using (var transport = new WcfClientTransportAdapter() { BaseAddress = "net.tcp://localhost:9091" }) { var protocol = ClientProtocolSetup.WithTransportAdapter(x => transport); using (var connection = new ZyanConnection(transport.BaseAddress, protocol)) { var proxy = connection.CreateProxy<IEchoService>(); Console.WriteLine(proxy.Echo("Hello WCF")); Console.ReadLine(); } } }
public void CreateDisposeAndRecreateConnectionUsingTcpDuplexChannel() { var url = "tcpex://localhost:8092/TcpExConnectionLockRegressionTestHost_TcpDuplex"; var protocol = new TcpDuplexClientProtocolSetup(true); var lessThanTimeout = 10; using (var connection = new ZyanConnection(url, protocol)) { var sw = Stopwatch.StartNew(); var proxy = connection.CreateProxy <ISampleServer>("SampleServer"); var badConnectionInitiated = false; for (var i = 0; i < 100; i++) { var echo = "Hi" + i; Assert.AreEqual(echo, proxy.Echo(echo)); Thread.Sleep(10); // make sure that proxy is already created and runs if (i == 3) { Trace.WriteLine("** Spawning a thread for another tcpex connection **"); ThreadPool.QueueUserWorkItem(x => { badConnectionInitiated = true; try { // this connection should time out in more than lessThanTimeout seconds new ZyanConnection(url.Replace("localhost", "example.com"), protocol); } catch (Exception ex) { // this exception is expected Trace.WriteLine("** Connection failed as expected **:" + ex.Message); } }); } } sw.Stop(); Assert.IsTrue(badConnectionInitiated); Assert.IsTrue(sw.Elapsed.TotalSeconds < lessThanTimeout); Trace.WriteLine("** CreateDisposeAndRecreateConnectionUsingTcpDuplexChannel test finished **"); } }
public void EventsOnSingletonComponentsWorkGlobally() { var nullProtocol = new NullClientProtocolSetup(); // start two new sessions using (var conn2 = new ZyanConnection(ZyanConnection.ServerUrl, nullProtocol)) using (var conn3 = new ZyanConnection(ZyanConnection.ServerUrl, nullProtocol)) { var proxy1 = ZyanConnection.CreateProxy <ISampleServer>("Singleton"); var proxy2 = conn2.CreateProxy <ISampleServer>("Singleton"); var proxy3 = conn3.CreateProxy <ISampleServer>("Singleton"); var proxy1handled = false; var handler1 = new EventHandler((sender, args) => proxy1handled = true); proxy1.TestEvent += handler1; var proxy2handled = false; var handler2 = new EventHandler((sender, args) => proxy2handled = true); proxy2.TestEvent += handler2; var proxy3handled = false; var handler3 = new EventHandler((sender, args) => { proxy3handled = true; throw new Exception(); }); proxy3.TestEvent += handler3; proxy1.RaiseTestEvent(); Assert.IsTrue(proxy1handled); Assert.IsTrue(proxy2handled); Assert.IsTrue(proxy3handled); proxy1handled = false; proxy2handled = false; proxy3handled = false; proxy2.RaiseTestEvent(); Assert.IsTrue(proxy1handled); Assert.IsTrue(proxy2handled); Assert.IsFalse(proxy3handled); proxy1handled = false; proxy2handled = false; proxy3.RaiseTestEvent(); Assert.IsTrue(proxy1handled); Assert.IsTrue(proxy2handled); Assert.IsFalse(proxy3handled); } }
public static void StartServer(TestContext ctx) { ZyanSettings.LegacyBlockingEvents = true; ZyanSettings.LegacyBlockingSubscriptions = true; ZyanSettings.LegacyUnprotectedEventHandlers = true; var serverSetup = new NullServerProtocolSetup(2345); ZyanHost = new ZyanComponentHost("EventsServer", serverSetup); ZyanHost.RegisterComponent <ISampleServer, SampleServer <int> >("Singleton", ActivationType.Singleton); ZyanHost.RegisterComponent <ISampleServer, SampleServer <short> >("Singleton2", ActivationType.Singleton); ZyanHost.RegisterComponent <ISampleServer, SampleServer <long> >("Singleton3", ActivationType.Singleton); ZyanHost.RegisterComponent <ISampleServer, SampleServer <byte> >("SingleCall", ActivationType.SingleCall); ZyanHost.RegisterComponent <ISampleServer, SampleServer <char> >("SingletonExternal", new SampleServer <char>()); ZyanConnection = new ZyanConnection("null://NullChannel:2345/EventsServer"); }
/* * internal static bool ConectarServidor() * { * const string methodName = "ConectarServidor"; * * try * { * Log.WriteEntry(ClassName, methodName, TraceEventType.Information, "Conectando con servidor."); * * var connection = new ZyanConnection(_connString); * var service = connection.CreateProxy<IMessageHandler>(); * * _connection = connection; * _proxy = service; * * Log.WriteEntry(ClassName, methodName, TraceEventType.Information, "Conexion realizada con exito."); * return true; * } * catch (Exception ex) * { * Log.WriteEntry(ClassName, methodName, TraceEventType.Error, string.Format("Error: {0}", ex.Message)); * return false; * } * } */ internal static bool ConectarServidor() { const string methodName = "ConectarServidor"; try { Log.WriteEntry(ClassName, methodName, TraceEventType.Information, "Conectando con servidor."); var connection = new ZyanConnection(_connString); var service = connection.CreateProxy <IMessageHandler>(); _connection = connection; _proxy = service; // Conectando input y output. // Las acciones de salida, a metodos del proxy, para su transmision remota al servidor. // Comandos Out_AsistenciaUpdateCommand = Asynchronizer <AsistenciaUpdateCommand> .WireUp(_proxy.In_AsistenciaUpdateCommand); // Consultas Out_AsistenciaQuery = Asynchronizer <AsistenciaQuery> .WireUp(_proxy.In_AsistenciaQuery); // La respuesta del servidor remoto, a acciones de entrada. // Comandos _proxy.Out_AsistenciaUpdateCommandResult = SyncContextSwitcher <CommandStatus> .WireUp(In_AsistenciaUpdateCommandResult); // Consultas _proxy.Out_AsistenciaQuery = SyncContextSwitcher <AsistenciaQueryResult> .WireUp(In_AsistenciaQueryResult); // Estableciendo controlador de sesion. _connection.Disconnected += _zyanConn_Disconnected; // Estableciendo monitoreo de la conexion. _connection.PollingInterval = TimeSpan.FromSeconds(3); _connection.PollingEnabled = true; Log.WriteEntry(ClassName, methodName, TraceEventType.Information, "Conexion realizada con exito."); return(true); } catch (Exception ex) { Log.WriteEntry(ClassName, methodName, TraceEventType.Error, string.Format("Error: {0}", ex.Message)); return(false); } }
/// <summary> /// Konstruktor. /// </summary> /// <param name="type">Schnittstelle der entfernten Komponente</param> /// <param name="connection">Verbindungsobjekt</param> /// <param name="implicitTransactionTransfer">Implizite Transaktionsübertragung</param> /// <param name="sessionID">Sitzungsschlüssel</param> /// <param name="componentHostName">Name des entfernten Komponentenhosts</param> /// <param name="autoLoginOnExpiredSession">Gibt an, ob sich der Proxy automatisch neu anmelden soll, wenn die Sitzung abgelaufen ist</param> /// <param name="autoLogoninCredentials">Optional! Anmeldeinformationen, die nur benötigt werden, wenn autoLoginOnExpiredSession auf Wahr eingestellt ist</param> /// <param name="activationType">Aktivierungsart</param> public ZyanProxy(Type type, ZyanConnection connection, bool implicitTransactionTransfer, Guid sessionID, string componentHostName, bool autoLoginOnExpiredSession, Hashtable autoLogoninCredentials, ActivationType activationType) : base(type) { // Wenn kein Typ angegeben wurde ... if (type.Equals(null)) // Ausnahme werfen throw new ArgumentNullException("type"); // Wenn kein Verbindungsobjekt angegeben wurde ... if (connection == null) // Ausnahme werfen throw new ArgumentNullException("connection"); // Sitzungsschlüssel übernehmen _sessionID = sessionID; // Verbindungsobjekt übernehmen _connection = connection; // Name des Komponentenhosts übernehmen _componentHostName = componentHostName; // Schnittstellentyp übernehmen _interfaceType = type; // Aktivierungsart übernehmen _activationType = activationType; // Aufrufer von Verbindung übernehmen _remoteInvoker = _connection.RemoteComponentFactory; // Schalter für implizite Transaktionsübertragung übernehmen _implicitTransactionTransfer = implicitTransactionTransfer; // Schalter für automatische Anmeldung bei abgelaufender Sitzung übernehmen _autoLoginOnExpiredSession = autoLoginOnExpiredSession; // Wenn automatische Anmeldung aktiv ist ... if (_autoLoginOnExpiredSession) // Anmeldeinformationen speichern _autoLoginCredentials = autoLogoninCredentials; // Sammlung für Korrelationssatz erzeugen _delegateCorrelationSet = new List<DelegateCorrelationInfo>(); }
static void Main(string[] args) { // print information Console.WriteLine("Connecting to Zyan Server on localhost:4567 and creating Proxy..."); // connect to the Zyan ComponentHost and create a new Proxy for the service using (var connection = new ZyanConnection("tcp://localhost:4567/DynamicEbcResponses")) using (var service = connection.CreateProxy <IService>()) { // Example 1: convert a number to a spelledNumber Example1(service); // Example 2: divide two integers Example2(service); } Console.ReadLine(); }
static void Main(string[] args) { // print information Console.WriteLine("Connecting to Zyan Server on localhost:4567 and creating Proxy..."); // connect to the Zyan ComponentHost and create a new Proxy for the service using (var connection = new ZyanConnection("tcp://localhost:4567/DynamicEbcResponses")) using (var service = connection.CreateProxy<IService>()) { // Example 1: convert a number to a spelledNumber Example1(service); // Example 2: divide two integers Example2(service); } Console.ReadLine(); }
public void InvalidLoginUsingTcpSimplexChannel_NoAuthClient() { var url = "tcp://*****:*****@", "Hello" } }; Assert.Throws <SecurityException>(() => { using (var connection = new ZyanConnection(url, protocol, credentials, true, true)) { var proxy1 = connection.CreateProxy <ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy1.Echo("Hallo")); proxy1 = null; } }); }
public void CreateDisposeAndRecreateConnectionUsingTcpSimplexChannel() { string url = "tcp://localhost:8085/RecreateClientConnectionTestHost_TcpSimplex"; var protocol = new TcpCustomClientProtocolSetup(true); using (var connection = new ZyanConnection(url, protocol)) { var proxy1 = connection.CreateProxy <ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy1.Echo("Hallo")); proxy1 = null; } using (var connection = new ZyanConnection(url, protocol)) { var proxy2 = connection.CreateProxy <ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy2.Echo("Hallo")); } }
static void Main(string[] args) { System.Threading.Thread.Sleep(2000); using (var transport = new WcfClientTransportAdapter() { BaseAddress = "net.tcp://localhost:9091" }) { var protocol = ClientProtocolSetup.WithTransportAdapter(x => transport); using (var connection = new ZyanConnection(transport.BaseAddress, protocol)) { var proxy = connection.CreateProxy <IEchoService>(); Console.WriteLine(proxy.Echo("Hello WCF")); Console.ReadLine(); } } }
private static ZyanConnection LoginAndConnect() { HttpCustomClientProtocolSetup protocol = new HttpCustomClientProtocolSetup(true); ZyanConnection connection = null; bool success = false; string message = string.Empty; while (!success) { LoginForm loginForm = new LoginForm(); if (!string.IsNullOrEmpty(message)) { loginForm.Message = message; } DialogResult result = loginForm.ShowDialog(); if (result == DialogResult.OK) { Hashtable credentials = new Hashtable(); credentials.Add(AuthRequestMessage.CREDENTIAL_USERNAME, loginForm.UserName); credentials.Add(AuthRequestMessage.CREDENTIAL_PASSWORD, loginForm.Password); try { connection = new ZyanConnection("http://localhost:8081/EbcCalc", protocol, credentials, false, true); success = true; } catch (Exception ex) { message = ex.Message; } } else { return(null); } } return(connection); }
public void ValidLoginUsingTcpSimplexChannel() { var url = "tcp://localhost:8091/CustomAuthenticationTestHost_TcpSimplex"; var protocol = new TcpCustomClientProtocolSetup(true); var credentials = new SrpCredentials(UserName, Password, CustomSrpParameters); using (var connection = new ZyanConnection(url, protocol, credentials, true, true)) { var proxy1 = connection.CreateProxy <ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy1.Echo("Hallo")); proxy1 = null; } // reconnect using (var connection = new ZyanConnection(url, protocol, credentials, true, true)) { var proxy2 = connection.CreateProxy <ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy2.Echo("Hallo")); } }
public void ValidLoginUsingTcpDuplexChannel() { var url = "tcpex://localhost:8088/CustomAuthenticationTestHost_TcpDuplex"; var protocol = new TcpDuplexClientProtocolSetup(true); var credentials = new CustomAuthenticationClient("Hello"); using (var connection = new ZyanConnection(url, protocol, credentials, true, true)) { var proxy1 = connection.CreateProxy <ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy1.Echo("Hallo")); proxy1 = null; } // reconnect using the same credentials using (var connection = new ZyanConnection(url, protocol, credentials, true, true)) { var proxy2 = connection.CreateProxy <ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy2.Echo("Hallo")); } }
private static void Init() { Zyan.Communication.Protocols.Ipc.IpcBinaryClientProtocolSetup ps = new Zyan.Communication.Protocols.Ipc.IpcBinaryClientProtocolSetup(); string url = ps.FormatUrl("ZyanSample", "ZyanSample"); ZyanConnection connection = new ZyanConnection(url, ps); IMessageService proxy = connection.CreateProxy <IMessageService>(); bool success = proxy.Register(userName, (fromName, message) => { Console.WriteLine("{0} whispers to you: {1}", fromName, message.Content); }); if (success) { Console.WriteLine("Press a key to send a message..."); Console.ReadKey(); for (int i = 0; true; i++) { string randomName = userName; while (randomName == userName) { randomName = random.Next(0, 3).ToString(); } proxy.Send(userName, randomName, new Message { Id = i, Content = "Hello from client " + userName }); Console.WriteLine("Press a key to send a message..."); Console.ReadKey(); } } else { Console.WriteLine("Can not register."); } }
private bool Connect(string arg) { try { if (_zConnection != null) { _zConnection.Dispose(); } TcpDuplexClientProtocolSetup protocol = new TcpDuplexClientProtocolSetup(true); Hashtable credentials = new Hashtable(); credentials.Add(AuthRequestMessage.CREDENTIAL_USERNAME, "zc"); credentials.Add(AuthRequestMessage.CREDENTIAL_PASSWORD, "zc"); _zConnection = new ZyanConnection(arg, protocol, credentials, false, true); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); this.chkConect.Checked = false; return(false); } this.chkConect.Checked = true; IMonitor relMonitor = _zConnection.CreateProxy <IMonitor>(); //this.Out_GetClient = Asynchronizer<int>.WireUp(relMonitor.In_RequestClientDataList); //this.Out_GetSystem = Asynchronizer<int>.WireUp(relMonitor.In_RequestSystemConfigData); this.Out_GetAllData = Asynchronizer <RequestDataEvent> .WireUp(relMonitor.In_RequestData); relMonitor.Out_SendClientDataList = SyncContextSwitcher <ClientDataList> .WireUp(this.In_GetClient); relMonitor.Out_SendSystemConfigData = SyncContextSwitcher <SystemConfigData> .WireUp(this.In_GetSys); return(true); }
public void CreateDisposeAndReceateConnectionUsingTcpDuplexChannel() { string url = "tcpex://localhost:8084/RecreateClientConnectionTestHost_TcpDuplex"; var protocol = new TcpDuplexClientProtocolSetup(true); ZyanConnection connection = new ZyanConnection(url, protocol); var proxy1 = connection.CreateProxy <ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy1.Echo("Hallo")); proxy1 = null; connection.Dispose(); connection = new ZyanConnection(url, protocol); var proxy2 = connection.CreateProxy <ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy2.Echo("Hallo")); connection.Dispose(); }
public void SessionVariablesAreStoredWithinTheCurrentSession() { var server = new NullServerProtocolSetup(123); var client = new NullClientProtocolSetup(); using (var host = new ZyanComponentHost("SessionSample", server)) { host.RegisterComponent <ISessionSample, SessionSample>(); using (var conn = new ZyanConnection(client.FormatUrl(123, "SessionSample"), client)) { var proxy = conn.CreateProxy <ISessionSample>(); proxy.Set("Hello", "World"); Assert.AreEqual("World", proxy.Get("Hello")); var temp = proxy.Get("Undefined"); Assert.IsNull(temp); proxy.Set("Undefined", "Defined"); Assert.AreEqual("Defined", proxy.Get("Undefined")); } } }
public void HeartbeatSessionShouldBeValid() { var heartbeatsReceived = 0; var nullSession = false; var userIdentity = default(IIdentity); // set up heartbeat event handler ZyanHost.PollingEventTracingEnabled = true; ZyanHost.ClientHeartbeatReceived += (s, e) => { heartbeatsReceived++; if (ServerSession.CurrentSession != null) { userIdentity = ServerSession.CurrentSession.Identity; } else { nullSession = true; } }; // set up the connection using (var conn = new ZyanConnection("null://NullChannel:5678/HeartbeatServer")) { // the code below uses actual heartbeat timer to send heartbeats: //conn.PollingInterval = TimeSpan.FromMilliseconds(5); //conn.PollingEnabled = true; // use the internal method to avoid using timer in unit tests conn.SendHeartbeat(null); Thread.Sleep(500); } // validate heartbeat Assert.IsTrue(heartbeatsReceived > 0); Assert.IsFalse(nullSession); Assert.AreEqual(JohnGaltIdentity.DefaultName, userIdentity.Name); }
private static ZyanConnection LoginAndConnect() { HttpCustomClientProtocolSetup protocol = new HttpCustomClientProtocolSetup(true); ZyanConnection connection = null; bool success = false; string message = string.Empty; while (!success) { LoginForm loginForm = new LoginForm(); if (!string.IsNullOrEmpty(message)) loginForm.Message = message; DialogResult result = loginForm.ShowDialog(); if (result == DialogResult.OK) { Hashtable credentials = new Hashtable(); credentials.Add(AuthRequestMessage.CREDENTIAL_USERNAME, loginForm.UserName); credentials.Add(AuthRequestMessage.CREDENTIAL_PASSWORD, loginForm.Password); try { connection = new ZyanConnection("http://localhost:8081/EbcCalc", protocol, credentials, false, true); success = true; } catch (Exception ex) { message = ex.Message; } } else return null; } return connection; }
private static bool ConectarServidor() { const string methodName = "ConectarServidor"; try { Log.WriteEntry(ClassName, methodName, TraceEventType.Information, "Conectando con servidor."); var connection = new ZyanConnection(_connString); var service = connection.CreateProxy <IMessageHandler>(); _connection = connection; _proxy = service; Log.WriteEntry(ClassName, methodName, TraceEventType.Information, "Conexion realizada con exito."); return(true); } catch (Exception ex) { Log.WriteEntry(ClassName, methodName, TraceEventType.Error, string.Format("Error: {0}", ex.Message)); return(false); } }
/// <summary> /// Initializes a new instance of the <see cref="ZyanProxy"/> class. /// </summary> /// <param name="uniqueName">Unique component name.</param> /// <param name="type">Component interface type.</param> /// <param name="connection"><see cref="ZyanConnection"/> instance.</param> /// <param name="implicitTransactionTransfer">Specifies whether transactions should be passed implicitly.</param> /// <param name="sessionID">Session ID.</param> /// <param name="componentHostName">Name of the remote component host.</param> /// <param name="autoLoginOnExpiredSession">Specifies whether Zyan should login automatically with cached credentials after the session is expired.</param> /// <param name="activationType">Component activation type</param> public ZyanProxy(string uniqueName, Type type, ZyanConnection connection, bool implicitTransactionTransfer, Guid sessionID, string componentHostName, bool autoLoginOnExpiredSession, ActivationType activationType) : base(type) { if (type.Equals(null)) throw new ArgumentNullException("type"); if (connection == null) throw new ArgumentNullException("connection"); if (string.IsNullOrEmpty(uniqueName)) _uniqueName = type.FullName; else _uniqueName = uniqueName; _sessionID = sessionID; _connection = connection; _componentHostName = componentHostName; _interfaceType = type; _activationType = activationType; _implicitTransactionTransfer = implicitTransactionTransfer; _autoLoginOnExpiredSession = autoLoginOnExpiredSession; _delegateCorrelationSet = new List<DelegateCorrelationInfo>(); }
public void EventsWithArgumentsDerivedFromSessionBoundEvents_AreBoundToSessions() { // start a new session using (var conn = new ZyanConnection(ZyanConnection.ServerUrl, new NullClientProtocolSetup())) { var proxy1 = ZyanConnection.CreateProxy <ISampleServer>(); var proxy2 = conn.CreateProxy <ISampleServer>(); var handled1 = 0; var handled2 = 0; proxy1.CustomSessionBoundEvent += (s, args) => handled1 = args.Value; proxy2.CustomSessionBoundEvent += (s, args) => handled2 = args.Value; proxy1.RaiseCustomSessionBoundEvent(123); Assert.AreEqual(123, handled1); Assert.AreEqual(0, handled2); proxy2.RaiseCustomSessionBoundEvent(321); Assert.AreEqual(123, handled1); Assert.AreEqual(321, handled2); } }
public void EventsWithArgumentsDerivedFromSessionBoundEvents_CanListenToOtherSessions() { var nullProtocol = new NullClientProtocolSetup(); // start two new sessions using (var conn2 = new ZyanConnection(ZyanConnection.ServerUrl, nullProtocol)) using (var conn3 = new ZyanConnection(ZyanConnection.ServerUrl, nullProtocol)) { var proxy1 = ZyanConnection.CreateProxy <ISampleServer>(); var proxy2 = conn2.CreateProxy <ISampleServer>(); var proxy3 = conn3.CreateProxy <ISampleServer>(); var sessions13 = new[] { ZyanConnection.SessionID, conn3.SessionID }; // session2 is not included var handled1 = 0; var handled2 = 0; var handled3 = 0; proxy1.CustomSessionBoundEvent += (s, args) => handled1 = args.Value; proxy2.CustomSessionBoundEvent += FilteredEventHandler.Create <CustomEventArgs>((s, args) => handled2 = args.Value, new SessionEventFilter(sessions13)); proxy3.CustomSessionBoundEvent += (s, args) => handled3 = args.Value; proxy1.RaiseCustomSessionBoundEvent(123); Assert.AreEqual(123, handled1); Assert.AreEqual(123, handled2); // proxy2 receives event from session1 Assert.AreEqual(0, handled3); proxy2.RaiseCustomSessionBoundEvent(321); Assert.AreEqual(123, handled1); Assert.AreEqual(123, handled2); // proxy2 doesn't receive events from session2 Assert.AreEqual(0, handled3); proxy3.RaiseCustomSessionBoundEvent(111); Assert.AreEqual(123, handled1); Assert.AreEqual(111, handled2); // proxy2 receives event from session3 Assert.AreEqual(111, handled3); } }
public void ChannelRegistrationRaceConditionTest() { var url = "tcpex://localhost:8084/RecreateClientConnectionTestHost_TcpDuplex"; var protocol = new TcpDuplexClientProtocolSetup(true); var errors = new ConcurrentDictionary <Exception, Exception>(); for (var i = 0; i < 10; i++) { ThreadPool.QueueUserWorkItem(x => { try { using (var conn = new ZyanConnection(url, protocol)) { } } catch (Exception ex) { errors[ex] = ex; } }); } Thread.Sleep(100); Assert.DoesNotThrow(() => { if (errors.Any()) { #if FX3 throw errors.Values.First(); #else throw new AggregateException(errors.Values); #endif } }); }
public void ZyanComponentHostBeforeInvokeAfterInvokeEventsAreFired() { var beforeInvoke = false; var beforeInterfaceName = string.Empty; var beforeMethodName = string.Empty; ZyanHost.BeforeInvoke += (s, e) => { beforeInvoke = true; beforeInterfaceName = e.InterfaceName; beforeMethodName = e.MethodName; }; var afterInvoke = false; var afterInterfaceName = string.Empty; var afterMethodName = string.Empty; ZyanHost.AfterInvoke += (s, e) => { afterInvoke = true; afterInterfaceName = e.InterfaceName; afterMethodName = e.MethodName; }; var proxy = ZyanConnection.CreateProxy <ISampleServer>("SingleCall"); proxy.RaiseTestEvent(); Assert.IsTrue(beforeInvoke); Assert.AreEqual("SingleCall", beforeInterfaceName); Assert.AreEqual("RaiseTestEvent", beforeMethodName); Assert.IsTrue(afterInvoke); Assert.AreEqual("SingleCall", afterInterfaceName); Assert.AreEqual("RaiseTestEvent", afterMethodName); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); string nickname = string.Empty; string serverUrl = string.Empty; LoginForm loginForm = new LoginForm(); while (string.IsNullOrEmpty(nickname) || string.IsNullOrEmpty(serverUrl)) { if (loginForm.ShowDialog() != DialogResult.OK) break; nickname = loginForm.Nickname; serverUrl = loginForm.ServerUrl; } if (string.IsNullOrEmpty(nickname)) return; Credentials = new Hashtable(); Credentials.Add("nickname", nickname); TcpDuplexClientProtocolSetup protocol = new TcpDuplexClientProtocolSetup(true); try { using (Connection = new ZyanConnection(serverUrl, protocol, Credentials, false, true)) { Connection.PollingInterval = new TimeSpan(0, 0, 30); Connection.PollingEnabled = true; Connection.Disconnected += new EventHandler<DisconnectedEventArgs>(Connection_Disconnected); Connection.NewLogonNeeded += new EventHandler<NewLogonNeededEventArgs>(Connection_NewLogonNeeded); Connection.Error += new EventHandler<ZyanErrorEventArgs>(Connection_Error); Connection.CallInterceptors.For<IMiniChat>() .Add<string, string>( (chat, nickname2, text) => chat.SendMessage(nickname2, text), (data, nickname2, text) => { if (text.Contains("f**k") || text.Contains("sex")) { MessageBox.Show("TEXT CONTAINS FORBIDDEN WORDS!"); data.Intercepted = true; } }); Connection.CallInterceptionEnabled = true; Application.Run(new ChatForm(nickname)); } } catch (SecurityException ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Creates ZyanClientQueryHandler instance. /// </summary> /// <param name="connection">Zyan connection.</param> /// <param name="unqiueName">Unique component name</param> public ZyanClientQueryHandler(ZyanConnection connection, string unqiueName) : this(connection) { _uniqueName = unqiueName; }
public static int RunTest() { var protocol = new TcpCustomClientProtocolSetup(true) { CompressionThreshold = 1, // compress data packets of any size CompressionMethod = CompressionMethod.LZF }; _connection = new ZyanConnection("tcp://localhost:8083/TcpCustomEventTest", protocol); _proxySingleton = _connection.CreateProxy<IEventComponentSingleton>(); _proxySingleCall = _connection.CreateProxy<IEventComponentSingleCall>(); _proxyCallbackSingleton = _connection.CreateProxy<ICallbackComponentSingleton>(); _proxyCallbackSingleCall = _connection.CreateProxy<ICallbackComponentSingleCall>(); _proxyRequestResponseSingleCall = _connection.CreateProxy<IRequestResponseCallbackSingleCall>(); int successCount = 0; _proxyCallbackSingleton.Out_Callback = CallBackSingleton; _proxyCallbackSingleCall.Out_Callback = CallBackSingleCall; _proxyCallbackSingleton.DoSomething(); if (_callbackCountSingleton == 1) { successCount++; Console.WriteLine("[TCP Custom] Singleton Callback Test passed."); } _proxyCallbackSingleCall.DoSomething(); if (_callbackCountSingleCall == 1) { successCount++; Console.WriteLine("[TCP Custom] SingleCall Callback Test passed."); } RegisterEvents(); if (_registrationsSingleton == _proxySingleton.Registrations) successCount++; if (_registrationsSingleCall == _proxySingleCall.Registrations) successCount++; _proxySingleton.TriggerEvent(); if (_firedCountSingleton == 1) { successCount++; Console.WriteLine("[TCP Custom] Singleton Event Test passed."); } _proxySingleCall.TriggerEvent(); if (_firedCountSingleCall == 1) { successCount++; Console.WriteLine("[TCP Custom] SingleCall Event Test passed."); } UnregisterEvents(); if (_registrationsSingleton == _proxySingleton.Registrations) successCount++; if (_registrationsSingleCall == _proxySingleCall.Registrations) successCount++; RequestResponseResult requestResponseResult = new RequestResponseResult("TCP Custom"); _proxyRequestResponseSingleCall.DoRequestResponse("Success", requestResponseResult.ReceiveResponseSingleCall); Thread.Sleep(1000); if (requestResponseResult.Count == 1) successCount++; _connection.Dispose(); if (successCount == 9) return 0; else return 1; }
public static int Main(string[] args) { AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); _serverAppDomain = AppDomain.CreateDomain("Server", null, setup); _serverAppDomain.Load("Zyan.Communication"); CrossAppDomainDelegate serverWork = new CrossAppDomainDelegate(() => { EventServer server = EventServer.Instance; }); _serverAppDomain.DoCallBack(serverWork); //TcpCustomClientProtocolSetup protocol = new TcpCustomClientProtocolSetup(true); MsmqClientProtocolSetup protocol = new MsmqClientProtocolSetup(); //_connection = new ZyanConnection("tcp://*****:*****@"msmq://private$/reqchannel/EventTest", protocol); _proxySingleton = _connection.CreateProxy <IEventComponentSingleton>(); _proxySingleCall = _connection.CreateProxy <IEventComponentSingleCall>(); _proxyCallbackSingleton = _connection.CreateProxy <ICallbackComponentSingleton>(); _proxyCallbackSingleCall = _connection.CreateProxy <ICallbackComponentSingleCall>(); _proxyRequestResponseSingleCall = _connection.CreateProxy <IRequestResponseCallbackSingleCall>(); int successCount = 0; _proxyCallbackSingleton.Out_Callback = CallBackSingleton; _proxyCallbackSingleCall.Out_Callback = CallBackSingleCall; _proxyCallbackSingleton.DoSomething(); if (_callbackCountSingleton == 1) { successCount++; Console.WriteLine("Singleton Callback Test passed."); } _proxyCallbackSingleCall.DoSomething(); if (_callbackCountSingleCall == 1) { successCount++; Console.WriteLine("SingleCall Callback Test passed."); } RegisterEvents(); if (_registrationsSingleton == _proxySingleton.Registrations) { successCount++; } if (_registrationsSingleCall == _proxySingleCall.Registrations) { successCount++; } _proxySingleton.TriggerEvent(); if (_firedCountSingleton == 1) { successCount++; Console.WriteLine("Singleton Event Test passed."); } _proxySingleCall.TriggerEvent(); if (_firedCountSingleCall == 1) { successCount++; Console.WriteLine("SingleCall Event Test passed."); } UnregisterEvents(); if (_registrationsSingleton == _proxySingleton.Registrations) { successCount++; } if (_registrationsSingleCall == _proxySingleCall.Registrations) { successCount++; } RequestResponseResult requestResponseResult = new RequestResponseResult(); _proxyRequestResponseSingleCall.DoRequestResponse("Success", requestResponseResult.ReceiveResponseSingleCall); Thread.Sleep(1000); if (requestResponseResult.Count == 1) { successCount++; } _connection.Dispose(); EventServerLocator locator = _serverAppDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "IntegrationTest_DistributedEvents.EventServerLocator") as EventServerLocator; locator.GetEventServer().Dispose(); AppDomain.Unload(_serverAppDomain); if (successCount == 9) { return(0); } else { return(1); } }
public void EventsOnSingletonComponentsWorkGlobally() { var nullProtocol = new NullClientProtocolSetup(); // start two new sessions using (var conn2 = new ZyanConnection(ZyanConnection.ServerUrl, nullProtocol)) using (var conn3 = new ZyanConnection(ZyanConnection.ServerUrl, nullProtocol)) { var proxy1 = ZyanConnection.CreateProxy<ISampleServer>("Singleton"); var proxy2 = conn2.CreateProxy<ISampleServer>("Singleton"); var proxy3 = conn3.CreateProxy<ISampleServer>("Singleton"); var proxy1handled = false; var handler1 = new EventHandler((sender, args) => proxy1handled = true); proxy1.TestEvent += handler1; var proxy2handled = false; var handler2 = new EventHandler((sender, args) => proxy2handled = true); proxy2.TestEvent += handler2; var proxy3handled = false; var handler3 = new EventHandler((sender, args) => { proxy3handled = true; throw new Exception(); }); proxy3.TestEvent += handler3; proxy1.RaiseTestEvent(); Assert.IsTrue(proxy1handled); Assert.IsTrue(proxy2handled); Assert.IsTrue(proxy3handled); proxy1handled = false; proxy2handled = false; proxy3handled = false; proxy2.RaiseTestEvent(); Assert.IsTrue(proxy1handled); Assert.IsTrue(proxy2handled); Assert.IsFalse(proxy3handled); proxy1handled = false; proxy2handled = false; proxy3.RaiseTestEvent(); Assert.IsTrue(proxy1handled); Assert.IsTrue(proxy2handled); Assert.IsFalse(proxy3handled); } }
static void Main(string[] args) { using (var conn = new ZyanConnection(Settings.Default.ServerUrl)) { // add global error handler conn.Error += ConnectionErrorHandler; // create proxy for the default queryable service var proxy = conn.CreateProxy<ISampleSource>(); // system assemblies loaded by server var assemblies = from asm in proxy.GetProcessInfo<Assembly>() where asm.FullName.ToLower().StartsWith("system") orderby asm.GetName().Name.Length ascending select asm; Console.WriteLine("System assemblies loaded by server (ordered by name length):"); foreach (var asm in assemblies) { Console.WriteLine(" {0} -> {1}", asm.GetName().Name, asm.ManifestModule.Name); } Console.WriteLine(); // requesting list of files in server's current folder var files = from file in proxy.GetProcessInfo<FileInfo>() where file.Length > (2 << 12) select new { file.Name, file.Length }; Console.WriteLine("Files larger than 8 kb:"); foreach (var fi in files) { Console.WriteLine("{0,15:#,0} | {1}", fi.Length, fi.Name); } Console.WriteLine(); // request files in server's desktop folder var links = from file in proxy.GetDesktopInfo<FileInfo>() where file.Name.EndsWith(".lnk") orderby file.Name.Length select file.Name; Console.WriteLine("Desktop links:"); foreach (var link in links) { Console.WriteLine("\t{0}", link); } Console.WriteLine(); Console.WriteLine("Exception handling demo."); // test error handling var buggyProxy = conn.CreateProxy<INamedService>("BuggyService"); Console.WriteLine("BuggyService.Name returns: {0}", buggyProxy.Name ?? "null"); Console.WriteLine(); Console.WriteLine("Press ENTER to quit."); Console.ReadLine(); } }
public void CreateDisposeAndReceateConnectionUsingTcpDuplexChannel() { string url = "tcpex://localhost:8084/RecreateClientConnectionTestHost_TcpDuplex"; var protocol = new TcpDuplexClientProtocolSetup(true); ZyanConnection connection = new ZyanConnection(url, protocol); var proxy1 = connection.CreateProxy<ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy1.Echo("Hallo")); proxy1 = null; connection.Dispose(); connection = new ZyanConnection(url, protocol); var proxy2 = connection.CreateProxy<ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy2.Echo("Hallo")); connection.Dispose(); }
public static int RunTest() { // Duplex TCP Channel var protocol = new TcpDuplexClientProtocolSetup(true) { CompressionThreshold = 1, // compress data packets of any size CompressionMethod = CompressionMethod.DeflateStream }; _connectionDuplex = new ZyanConnection("tcpex://localhost:8084/TcpDuplexEventTest", protocol); _proxySingletonDuplex = _connectionDuplex.CreateProxy <IEventComponentSingleton>(); _proxySingleCallDuplex = _connectionDuplex.CreateProxy <IEventComponentSingleCall>(); _proxyCallbackSingletonDuplex = _connectionDuplex.CreateProxy <ICallbackComponentSingleton>(); _proxyCallbackSingleCallDuplex = _connectionDuplex.CreateProxy <ICallbackComponentSingleCall>(); _proxyRequestResponseSingleCallDuplex = _connectionDuplex.CreateProxy <IRequestResponseCallbackSingleCall>(); _proxyTimerTriggeredEvent = _connectionDuplex.CreateProxy <ITimerTriggeredEvent>(); _proxyTimerTriggeredEvent.StartTimer(); List <int> stepsDone = new List <int>(); _proxyCallbackSingletonDuplex.Out_Callback = CallBackSingletonDuplex; _proxyCallbackSingleCallDuplex.Out_Callback = CallBackSingleCallDuplex; _proxyCallbackSingletonDuplex.DoSomething(); if (_callbackCountSingletonDuplex == 1) { stepsDone.Add(1); Console.WriteLine("[TCP Duplex] Singleton Callback Test passed."); } _proxyCallbackSingleCallDuplex.DoSomething(); if (_callbackCountSingleCallDuplex == 1) { stepsDone.Add(2); Console.WriteLine("[TCP Duplex] SingleCall Callback Test passed."); } RegisterEventsDuplex(); if (_registrationsSingletonDuplex == _proxySingletonDuplex.Registrations) { stepsDone.Add(3); } if (_registrationsSingleCallDuplex == _proxySingleCallDuplex.Registrations) { stepsDone.Add(4); } _proxySingletonDuplex.TriggerEvent(); if (_firedCountSingletonDuplex == 1) { stepsDone.Add(5); Console.WriteLine("[TCP Duplex] Singleton Event Test passed."); } _proxySingleCallDuplex.TriggerEvent(); if (_firedCountSingleCallDuplex == 1) { stepsDone.Add(6); Console.WriteLine("[TCP Duplex] SingleCall Event Test passed."); } Thread.Sleep(1000); if (_firedTimerTriggeredEvent > 1) { stepsDone.Add(7); Console.WriteLine("[TCP Duplex] Timer triggered Event Test passed."); } UnregisterEventsDuplex(); if (_registrationsSingletonDuplex == _proxySingletonDuplex.Registrations) { stepsDone.Add(8); } if (_registrationsSingleCallDuplex == _proxySingleCallDuplex.Registrations) { stepsDone.Add(9); } RequestResponseResult requestResponseResult = new RequestResponseResult("TCP Duplex"); _proxyRequestResponseSingleCallDuplex.DoRequestResponse("Success", requestResponseResult.ReceiveResponseSingleCall); Thread.Sleep(1000); if (requestResponseResult.Count == 1) { stepsDone.Add(10); } _connectionDuplex.Dispose(); if (stepsDone.Count == 10) { return(0); } else { return(1); } }
static void Main(string[] args) { using (var conn = new ZyanConnection(Settings.Default.ServerUrl)) { // add global error handler conn.Error += ConnectionErrorHandler; // create proxy for the default queryable service var proxy = conn.CreateProxy <ISampleSource>(); // system assemblies loaded by server var assemblies = from asm in proxy.GetProcessInfo <Assembly>() where asm.FullName.ToLower().StartsWith("system") orderby asm.GetName().Name.Length ascending select asm; Console.WriteLine("System assemblies loaded by server (ordered by name length):"); foreach (var asm in assemblies) { Console.WriteLine(" {0} -> {1}", asm.GetName().Name, asm.ManifestModule.Name); } Console.WriteLine(); // requesting list of files in server's current folder var files = from file in proxy.GetProcessInfo <FileInfo>() where file.Length > (2 << 12) select new { file.Name, file.Length }; Console.WriteLine("Files larger than 8 kb:"); foreach (var fi in files) { Console.WriteLine("{0,15:#,0} | {1}", fi.Length, fi.Name); } Console.WriteLine(); // request files in server's desktop folder var links = from file in proxy.GetDesktopInfo <FileInfo>() where file.Name.EndsWith(".lnk") orderby file.Name.Length select file.Name; Console.WriteLine("Desktop links:"); foreach (var link in links) { Console.WriteLine("\t{0}", link); } Console.WriteLine(); Console.WriteLine("Exception handling demo."); // test error handling var buggyProxy = conn.CreateProxy <INamedService>("BuggyService"); Console.WriteLine("BuggyService.Name returns: {0}", buggyProxy.Name ?? "null"); Console.WriteLine(); Console.WriteLine("Press ENTER to quit."); Console.ReadLine(); } }
public void CallInterceptionBug() { const string instanceName = "FirstTestServer"; const int port = 18888; var namedService1 = nameof(NamedService1); var namedService2 = nameof(NamedService2); using (var host = new ZyanComponentHost(instanceName, port)) { // register 3 service instances by the same interface: 2 with unique name, one is unnamed // named service1 has reference to service2 as child host.RegisterComponent <ITestService, NamedService1>(namedService1, ActivationType.Singleton); host.RegisterComponent <ITestService, NamedService2>(namedService2, ActivationType.Singleton); host.RegisterComponent <ITestService, UnnamedService>(ActivationType.Singleton); using (var connection = new ZyanConnection($"tcp://127.0.0.1:{port}/{instanceName}") { CallInterceptionEnabled = true }) { // add a call interceptor for the TestService.TestMethod connection.CallInterceptors.Add(CallInterceptor.For <ITestService>() .WithUniqueNameFilter(@"NamedService\d+") .Action(service => service.TestMethod(), data => { data.ReturnValue = $"intercepted_{data.MakeRemoteCall()}"; data.Intercepted = true; })); // for unnamed service connection.CallInterceptors .For <ITestService>() .Add(c => c.TestMethod(), data => { data.ReturnValue = $"intercepted_unnamed_{data.MakeRemoteCall()}"; data.Intercepted = true; }); connection.CallInterceptors .For <ITestService>() .WithUniqueNameFilter(".*") // for all services does not matter named or not .Add(c => c.EnumerateProcedure(), action => { var result = (IEnumerable <string>)action.MakeRemoteCall(); var intercepted = result.Select(r => $"intercepted_{r}"); action.ReturnValue = intercepted.ToList(); action.Intercepted = true; }); // intercept and return children like a collection of proxies on client side // suppress remote call connection.CallInterceptors.For <ITestService>() .WithUniqueNameFilter(".*") .Add(c => c.GetChildren(), action => { action.Intercepted = true; var childNames = connection.CreateProxy <ITestService>(action.InvokerUniqueName)? .GetChildrenName() .ToList(); var children = new List <ITestService>(); foreach (var childName in childNames) { children.Add(connection.CreateProxy <ITestService>(childName)); } // prevent remote call //action.MakeRemoteCall(); action.ReturnValue = children; }); var namedClient1 = connection.CreateProxy <ITestService>(namedService1); var namedClient2 = connection.CreateProxy <ITestService>(namedService2); var unnamedClient = connection.CreateProxy <ITestService>(); // assert names Assert.AreEqual(namedClient1.Name, namedService1); Assert.AreEqual(namedClient2.Name, namedService2); Assert.AreEqual(unnamedClient.Name, nameof(UnnamedService)); // assert method class interception result var named1_TestMethod_Result = namedClient1.TestMethod(); var named2_TestMethod_Result = namedClient2.TestMethod(); var unnamed_TestMethod_Result = unnamedClient.TestMethod(); Assert.AreEqual($"intercepted_{namedService1}", named1_TestMethod_Result); Assert.AreEqual($"intercepted_{namedService2}", named2_TestMethod_Result); Assert.AreEqual($"intercepted_unnamed_{nameof(UnnamedService)}", unnamed_TestMethod_Result); // enumerate procedure: all class are handled by single interceptor var named1_enumerate_result = namedClient1.EnumerateProcedure(); var named2_enumerate_result = namedClient2.EnumerateProcedure(); var unnnamed_enumerate_result = unnamedClient.EnumerateProcedure(); Assert.AreEqual(1, named1_enumerate_result.Count()); Assert.IsTrue(named1_enumerate_result.All(r => string.Equals(r, $"intercepted_{namedService1}"))); Assert.AreEqual(2, named2_enumerate_result.Count()); Assert.IsTrue(named2_enumerate_result.All(r => string.Equals(r, $"intercepted_{namedService2}"))); Assert.IsFalse(unnnamed_enumerate_result.Any()); } } }
private void MainForm_Shown(object sender, EventArgs e) { var protocol = new TcpDuplexClientProtocolSetup(true); _connection = new ZyanConnection(Properties.Settings.Default.ServerUrl, protocol); _proxy = _connection.CreateProxy<IWhisperChatService>(); }
public void CreateDisposeAndRecreateConnectionUsingTcpSimplexChannel() { string url = "tcp://localhost:8085/RecreateClientConnectionTestHost_TcpSimplex"; var protocol = new TcpCustomClientProtocolSetup(true); using (var connection = new ZyanConnection(url, protocol)) { var proxy1 = connection.CreateProxy<ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy1.Echo("Hallo")); proxy1 = null; } using (var connection = new ZyanConnection(url, protocol)) { var proxy2 = connection.CreateProxy<ISampleServer>("SampleServer"); Assert.AreEqual("Hallo", proxy2.Echo("Hallo")); } }
public static void StartServer(TestContext ctx) { ZyanHost = CreateZyanHost(2345, "EventsServer"); ZyanConnection = CreateZyanConnection(2345, "EventsServer"); }
public void RefreshRegisteredComponentsTest() { using (var host = new ZyanComponentHost("RefreshTest", new NullServerProtocolSetup(123))) using (var conn = new ZyanConnection("null://NullChannel:123/RefreshTest")) { // this component is registered after connection is established var componentName = Guid.NewGuid().ToString(); host.RegisterComponent<ISampleServer, SampleServer>(componentName); try { // proxy cannot be created because connection doesn't know about the component var proxy1 = conn.CreateProxy<ISampleServer>(componentName); Assert.Fail("Component is not yet known for ZyanConnection."); } catch (ApplicationException) { } // refresh the list of registered components and create a proxy conn.RefreshRegisteredComponents(); var proxy2 = conn.CreateProxy<ISampleServer>(componentName); var echoString = "Hello there"; var result = proxy2.Echo(echoString); Assert.AreEqual(echoString, result); } }
public void ZyanHostSubscriptionRelatedEventsAreRaised() { Trace.WriteLine("ZyanHostSubscriptionRelatedEventsAreRaised"); ZyanSettings.LegacyBlockingEvents = true; // set up server-side event handlers var subscriptionAdded = false; ZyanHost.SubscriptionAdded += (s, e) => subscriptionAdded = true; var subscriptionRemoved = false; ZyanHost.SubscriptionRemoved += (s, e) => subscriptionRemoved = true; var subscriptionCanceled = false; var clientSideException = default(Exception); var canceledHandler = new EventHandler <SubscriptionEventArgs>((s, e) => { subscriptionCanceled = true; clientSideException = e.Exception; }); ZyanHost.SubscriptionCanceled += canceledHandler; // set up client event handler var handled = false; var message = "Secret message"; var eventHandler = new EventHandler((s, e) => { if (handled) { handled = false; throw new Exception(message); } handled = true; }); // create proxy, attach event handler var proxy = ZyanConnection.CreateProxy <ISampleServer>("Singleton"); proxy.TestEvent += eventHandler; Assert.IsTrue(subscriptionAdded); // raise the event proxy.RaiseTestEvent(); Assert.IsTrue(handled); // detach event handler proxy.TestEvent -= eventHandler; Assert.IsTrue(subscriptionRemoved); // reattach event handler, raise an event, catch the exception and unsubscribe automatically proxy.TestEvent += eventHandler; proxy.RaiseTestEvent(); Assert.IsFalse(handled); Assert.IsTrue(subscriptionCanceled); Assert.IsNotNull(clientSideException); Assert.AreEqual(message, clientSideException.Message); // detach event handler ZyanHost.SubscriptionCanceled -= canceledHandler; }
public static void StopServer() { ZyanConnection.Dispose(); ZyanHost.Dispose(); DataWrapper.Dispose(); }
public static void StartServer(TestContext ctx) { ZyanComponentHost.LegacyBlockingEvents = true; var serverSetup = new NullServerProtocolSetup(2345); ZyanHost = new ZyanComponentHost("EventsServer", serverSetup); ZyanHost.RegisterComponent<ISampleServer, SampleServer>("Singleton", ActivationType.Singleton); ZyanHost.RegisterComponent<ISampleServer, SampleServer>("SingleCall", ActivationType.SingleCall); ZyanConnection = new ZyanConnection("null://NullChannel:2345/EventsServer"); }
internal ZyanMessageSender(Uri serviceUri) { var serverUrl = string.Format("tcp://{0}:{1}/OrderService", serviceUri.Host, serviceUri.Port); connection = new ZyanConnection(serverUrl); proxy = connection.CreateProxy<IMessageReceiver>(); }
public static int RunTest() { var protocol = new TcpBinaryClientProtocolSetup(); protocol.AddClientSinkAfterFormatter(new CompressionClientChannelSinkProvider(1, CompressionMethod.LZF)); _connection = new ZyanConnection("tcp://localhost:8082/TcpBinaryEventTest", protocol); _proxySingleton = _connection.CreateProxy<IEventComponentSingleton>(); _proxySingleCall = _connection.CreateProxy<IEventComponentSingleCall>(); _proxyCallbackSingleton = _connection.CreateProxy<ICallbackComponentSingleton>(); _proxyCallbackSingleCall = _connection.CreateProxy<ICallbackComponentSingleCall>(); _proxyRequestResponseSingleCall = _connection.CreateProxy<IRequestResponseCallbackSingleCall>(); int successCount = 0; _proxyCallbackSingleton.Out_Callback = CallBackSingleton; _proxyCallbackSingleCall.Out_Callback = CallBackSingleCall; _proxyCallbackSingleton.DoSomething(); if (_callbackCountSingleton == 1) { successCount++; Console.WriteLine("[TCP Binary] Singleton Callback Test passed."); } _proxyCallbackSingleCall.DoSomething(); if (_callbackCountSingleCall == 1) { successCount++; Console.WriteLine("[TCP Binary] SingleCall Callback Test passed."); } RegisterEvents(); if (_registrationsSingleton == _proxySingleton.Registrations) successCount++; if (_registrationsSingleCall == _proxySingleCall.Registrations) successCount++; _proxySingleton.TriggerEvent(); if (_firedCountSingleton == 1) { successCount++; Console.WriteLine("[TCP Binary] Singleton Event Test passed."); } _proxySingleCall.TriggerEvent(); if (_firedCountSingleCall == 1) { successCount++; Console.WriteLine("[TCP Binary] SingleCall Event Test passed."); } UnregisterEvents(); if (_registrationsSingleton == _proxySingleton.Registrations) successCount++; if (_registrationsSingleCall == _proxySingleCall.Registrations) successCount++; RequestResponseResult requestResponseResult = new RequestResponseResult("TCP Binary"); _proxyRequestResponseSingleCall.DoRequestResponse("Success", requestResponseResult.ReceiveResponseSingleCall); Thread.Sleep(1000); if (requestResponseResult.Count == 1) successCount++; _connection.Dispose(); if (successCount == 9) return 0; else return 1; }
public static int RunTest() { var protocol = new TcpBinaryClientProtocolSetup(); protocol.AddClientSinkAfterFormatter(new CompressionClientChannelSinkProvider(1, CompressionMethod.LZF)); _connection = new ZyanConnection("tcp://localhost:8082/TcpBinaryEventTest", protocol); _proxySingleton = _connection.CreateProxy <IEventComponentSingleton>(); _proxySingleCall = _connection.CreateProxy <IEventComponentSingleCall>(); _proxyCallbackSingleton = _connection.CreateProxy <ICallbackComponentSingleton>(); _proxyCallbackSingleCall = _connection.CreateProxy <ICallbackComponentSingleCall>(); _proxyRequestResponseSingleCall = _connection.CreateProxy <IRequestResponseCallbackSingleCall>(); int successCount = 0; _proxyCallbackSingleton.Out_Callback = CallBackSingleton; _proxyCallbackSingleCall.Out_Callback = CallBackSingleCall; _proxyCallbackSingleton.DoSomething(); if (_callbackCountSingleton == 1) { successCount++; Console.WriteLine("[TCP Binary] Singleton Callback Test passed."); } _proxyCallbackSingleCall.DoSomething(); if (_callbackCountSingleCall == 1) { successCount++; Console.WriteLine("[TCP Binary] SingleCall Callback Test passed."); } RegisterEvents(); if (_registrationsSingleton == _proxySingleton.Registrations) { successCount++; } if (_registrationsSingleCall == _proxySingleCall.Registrations) { successCount++; } _proxySingleton.TriggerEvent(); if (_firedCountSingleton == 1) { successCount++; Console.WriteLine("[TCP Binary] Singleton Event Test passed."); } _proxySingleCall.TriggerEvent(); if (_firedCountSingleCall == 1) { successCount++; Console.WriteLine("[TCP Binary] SingleCall Event Test passed."); } UnregisterEvents(); if (_registrationsSingleton == _proxySingleton.Registrations) { successCount++; } if (_registrationsSingleCall == _proxySingleCall.Registrations) { successCount++; } RequestResponseResult requestResponseResult = new RequestResponseResult("TCP Binary"); _proxyRequestResponseSingleCall.DoRequestResponse("Success", requestResponseResult.ReceiveResponseSingleCall); Thread.Sleep(1000); if (requestResponseResult.Count == 1) { successCount++; } _connection.Dispose(); if (successCount == 9) { return(0); } else { return(1); } }