public bool Reconnect() { clientLock.EnterWriteLock(); try { if (this.client != null) { this.client.Disconnect(); } DuplexClient <ISubscribing, IPubSubClient> client = new DuplexClient <ISubscribing, IPubSubClient>("callbackEndpoint", this); client.Connect(); if (!client.Call <bool>(sub => { sub.Subscribe(ETopic.NetworkModelChanged); sub.Subscribe(ETopic.MeasurementValuesChanged); sub.Subscribe(ETopic.TopologyChanged); sub.Subscribe(ETopic.LoadFlowChanged); sub.Subscribe(ETopic.MarkedSwitchesChanged); return(true); }, out _)) { return(false); } this.client = client; } finally { clientLock.ExitWriteLock(); } return(true); }
public bool ApplyUpdate(List <long> inserted, List <long> updated, List <long> deleted) { if (inserted == null || updated == null || deleted == null) { return(false); } lock (updateLock) { if (CalculationEngineService.inserted != null) { return(false); } bool ok; DuplexClient <ITransactionManager, ITransaction> client = new DuplexClient <ITransactionManager, ITransaction>("callbackEndpoint", this); client.Connect(); if (!client.Call <bool>(tm => tm.Enlist(), out ok) || !ok) { client.Disconnect(); return(false); } CalculationEngineService.inserted = inserted; CalculationEngineService.updated = updated; CalculationEngineService.deleted = deleted; return(true); } }
public void Dispose() { if (_presentationClient != null) { _presentationClient.Dispose(); _presentationClient = null; } }
static void Main(string[] args) { ClientCallback clCallback = new ClientCallback(); InstanceContext instCtx = new InstanceContext(clCallback); DuplexClient client = new DuplexClient(instCtx); client.Request(2000, 5); Console.ReadLine(); }
public RemotePresentationClient(IPresentationNotifier presentationNotifier, IClientConfiguration clientConfiguration, ISourceDAL sourceDAL, IDeviceSourceDAL deviceSourceDAL) { _sourceDAL = sourceDAL; _deviceSourceDAL = deviceSourceDAL; _presentationNotifier = presentationNotifier; _configuration = clientConfiguration; _presentationClient = new DuplexClient<IPresentationService>(new InstanceContext(presentationNotifier), clientConfiguration.PingInterval); _presentationClient.Open(); _presentationClient.OnChanged += new EventHandler<ClientState>(_presentationClient_OnChanged); _deviceDescriptorCache = new DeviceDescriptorCache(presentationNotifier); }
public Simulator() { modbusServer = new ModbusTCPServer(); modbusServer.Subscribe(this); stopSignal = new ManualResetEvent(false); analogs = new Dictionary <long, Analog>(); discretes = new Dictionary <long, Discrete>(); readWriteMeasurementAddresses = new HashSet <int>(); commands = new ConcurrentQueue <CommandParams>(); modelLock = new ReaderWriterLockSlim(); client = new DuplexClient <ISubscribing, IPubSubClient>("callbackEndpoint", this); reclosers = new List <Tuple <Recloser, long, long, int> >(); loadProfiles = DailyLoadProfile.LoadFromXML("Daily_load_profiles.xml"); energyConsumers = new Dictionary <long, EnergyConsumer>(); }
static void Main(string[] args) { Console.WriteLine("启动客户端"); //var client = new RequestResponseClient(new NetTcpBinding(), // new EndpointAddress(new Uri("net.tcp://localhost:8888/service"))); //var client = new OneWayClient(new NetTcpBinding(), // new EndpointAddress(new Uri("net.tcp://localhost:8888/service"))); var context = new InstanceContext(new DuplexCallback()); var client = new DuplexClient(context, new NetTcpBinding(), new EndpointAddress(new Uri("net.tcp://localhost:8888/service"))); client.SayHello("Client"); //var replay = client.SayHello2("Client"); //Console.WriteLine(replay); Console.Read(); }
public void Disconnect() { clientLock.EnterWriteLock(); try { if (client == null) { return; } client.Disconnect(); client = null; } finally { clientLock.ExitWriteLock(); } }
public void Done() { if (_svc != null) { try { _svc.Channel.UnSubscribeForNotification(Thread.CurrentPrincipal as UserIdentity); } catch (Exception ex) { _configuration.EventLog.WriteError(String.Format("ShowClient.Done(): {0}", ex)); } finally { _svc.Dispose(); _svc = null; } } }
public void TestConcurrency() { var queue = new Loggers.Queue(); var props = new List<String>() { "Event.Type", "Event.Source", "Event.Message", "Wcf.SessionID", "Wcf.LocalAddress", "Wcf.RemoteAddress", }; using ( Log.RegisterInstance( new Instance() { Logger = queue, Synchronous = false, Buffer = 0, Properties = props } ) ) { Event evt; // service context using (var client = new SimplexClient(binding, TestServiceUri)) { Parallel.For(0, TestParallelIterations, i => client.Server.ManualLog("test") ); Log.Flush(); for (Int32 i = 0; i < TestParallelIterations; i++) { evt = queue.Dequeue().First(); Assert.AreEqual(evt["Event.Type"], EventType.Info); Assert.AreEqual(evt["Event.Source"], typeof(Server)); Assert.AreEqual(evt["Event.Message"], "test"); Assert.AreEqual(evt["Wcf.SessionID"], client.Context.SessionId); Assert.AreEqual(evt["Wcf.LocalAddress"].ToString(), TestServiceUri); Assert.IsNotNull(evt["Wcf.RemoteAddress"]); } } Assert.IsFalse(queue.Dequeue().Any()); // callback context using (var client = new DuplexClient(binding, TestServiceUri)) { Parallel.For(0, TestParallelIterations, i => client.Server.CallbackManualLog("test") ); Log.Flush(); for (Int32 i = 0; i < TestParallelIterations; i++) { evt = queue.Dequeue().First(); Assert.AreEqual(evt["Event.Type"], EventType.Info); Assert.AreEqual(evt["Event.Source"], typeof(DuplexClient.Callback)); Assert.AreEqual(evt["Event.Message"], "test"); Assert.AreEqual(evt["Wcf.SessionID"], client.Context.SessionId); Assert.IsNotNull(evt["Wcf.LocalAddress"]); Assert.AreEqual(evt["Wcf.RemoteAddress"].ToString(), TestServiceUri); } } Assert.IsFalse(queue.Dequeue().Any()); } }
public bool Authenticate(UserIdentity previousId) { if (_loginServiceClient == null) { _callBack = new LoginServiceCallback(_userCollection); _loginServiceClient = new DuplexClient<ILoginService>(new InstanceContext(_callBack), _configuration.PingInterval); _loginServiceClient.Open(); _loginServiceClient.OnChanged += new EventHandler<ClientState>(_loginServiceClient_OnChanged); } UserIdentity principal = loginService.Login(previousId.User.Name, previousId.User.Hash, Environment.MachineName); if (principal == null || !principal.IsAuthenticated) { return false; } AppDomain.CurrentDomain.SetThreadPrincipal(principal); loginService.Subscribe(principal); _userCollection.AddRange(loginService.GetUserLoginCollection()); return true; }
void TopologyUpdated() { Client <ICalculationEngineServiceContract> client = new Client <ICalculationEngineServiceContract>("endpointCE"); client.Connect(); List <Tuple <long, List <Tuple <long, long> >, List <Tuple <long, long> > > > result = null; bool success; if (!client.Call <bool>(ce => { result = ce.GetLineEnergization(); return(true); }, out success) || !success) { client.Disconnect(); return; } client.Disconnect(); modelLock.EnterReadLock(); Dictionary <long, EEnergization> cnStates = new Dictionary <long, EEnergization>(reclosers.Count * 2); foreach (Tuple <Recloser, long, long, int> r in reclosers) { cnStates[r.Item2] = EEnergization.NotEnergized; cnStates[r.Item3] = EEnergization.NotEnergized; } List <long> reclosersWithoutSCADA = new List <long>(); try { foreach (Tuple <long, List <Tuple <long, long> >, List <Tuple <long, long> > > source in result) { foreach (Tuple <long, long> energizedLine in source.Item2) { if (cnStates.ContainsKey(energizedLine.Item1)) { cnStates[energizedLine.Item1] = EEnergization.Energized; } if (cnStates.ContainsKey(energizedLine.Item2)) { cnStates[energizedLine.Item2] = EEnergization.Energized; } } foreach (Tuple <long, long> unknownLine in source.Item3) { EEnergization state; if (cnStates.TryGetValue(unknownLine.Item1, out state) && state == EEnergization.Unknown) { cnStates[unknownLine.Item1] = EEnergization.Unknown; } if (cnStates.TryGetValue(unknownLine.Item2, out state) && state == EEnergization.Unknown) { cnStates[unknownLine.Item2] = EEnergization.Unknown; } } } foreach (Tuple <Recloser, long, long, int> r in reclosers) { EEnergization[] states = new EEnergization[] { cnStates[r.Item2], cnStates[r.Item3] }; if (states[0] == EEnergization.Unknown || states[1] == EEnergization.Unknown) { continue; } if (states[0] != states[1]) { if (r.Item4 < 0) { reclosersWithoutSCADA.Add(r.Item1.GID); } else { SetDiscreteInput(r.Item4, 0); } } } } finally { modelLock.ExitReadLock(); } if (reclosersWithoutSCADA.Count <= 0) { return; } client = new Client <ICalculationEngineServiceContract>("endpointCE"); client.Connect(); client.Call <bool>(ce => { foreach (long gid in reclosersWithoutSCADA) { ce.MarkSwitchState(gid, false); } return(true); }, out success); client.Disconnect(); }
public static void Initialize(bool skipServer = false) { uint desktopPID; PInvoke.GetWindowThreadProcessId(WindowUtils.GetShellTrayWnd(), out desktopPID); isServer = desktopPID == PInvoke.GetCurrentProcessId(); const string PipeName = "QTTabBarPipe"; string address = "net.pipe://localhost/" + PipeName + desktopPID; Thread thread = null; // WFC channels should never be opened on any thread that has a message loop! // Otherwise reentrant calls will deadlock, for some reason. // So, create a new thread and open the channels there. thread = new Thread(() => { if (isServer && !skipServer) { serviceHost = new ServiceHost( typeof(CommService), new Uri[] { new Uri(address) }); serviceHost.AddServiceEndpoint( typeof(ICommService), new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) { ReceiveTimeout = TimeSpan.MaxValue, ReaderQuotas = { MaxArrayLength = int.MaxValue }, MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue, }, new Uri(address)); serviceHost.Open(); } commClient = new DuplexClient(new InstanceContext(new CommClient()), new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) { ReceiveTimeout = TimeSpan.MaxValue, ReaderQuotas = { MaxArrayLength = int.MaxValue }, MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue, }, new EndpointAddress(address)); try { commClient.Open(); commClient.Channel.Subscribe(); using (new Keychain(rwLockTabBar, false)) { foreach (IntPtr handle in sdTabHandles.Keys) { commClient.Channel.PushInstance(handle); } } } catch (EndpointNotFoundException) { } lock (thread) { Monitor.Pulse(thread); } // Yes, we can just let the thread die here. }); thread.Start(); lock (thread) { Monitor.Wait(thread); } }
public bool InitializeFromPlayer(IPlayerConfiguration configuration) { _configuration = configuration; _showNotifier = new ShowNotifier(_configuration); _showNotifier.OnPreparationFinished += _showNotifier_OnPreparationFinished; _showNotifier.OnProgressChanged += _showNotifier_OnProgressChanged; _showNotifier.OnReceiveAgentResourcesList += _showNotifier_OnReceiveAgentResourcesList; _showNotifier.OnUploadSpeed +=new Action<double,string, string>(_showNotifier_OnUploadSpeed); _showNotifier.OnPreparationForDisplayEnded += new Action<string, bool>(_showNotifier_OnPreparationForDisplayEnded); _showNotifier.OnEquipmentStateChanged += _showNotifier_OnEquipmentStateChanged; _showNotifier.OnNotEnoughSpace += _showNotifier_OnNotEnoughSpace; _showNotifier.OnLogMessage += new Action<string>(_showNotifier_OnLogMessage); _showNotifier.OnExternalSystemCommand += _showNotifier_OnExternalSystemCommand; _svc = new DuplexClient<IShowCommon>(new InstanceContext(_showNotifier), configuration.PingInterval); try { _svc.Open(); } catch (Exception /*ex*/) { _svc.Dispose(); _svc = null; return false; } return true; }
public static void InitDuplexServer() { var server = new DuplexServer(GetIpAddress()); server.RegisterHandler <CustomEventData, string>((session, e) => { Console.WriteLine(string.Concat("Server: ", e.FirstName)); return("OK from Server"); }); server.RegisterHandler <string, string>((session, e) => { Console.WriteLine(string.Concat("Server: ", e)); return("OK from Server"); }); server.Start(); var client = new DuplexClient(GetIpAddress()); client.RegisterHandler <CustomEventData, string>((session, e) => { Console.WriteLine(string.Concat("Client: ", e.FirstName)); return("OK from Client"); }); client.RegisterHandler <string, string>((session, e) => { Console.WriteLine(string.Concat("Client: ", e)); return("OK from Client"); }); client.Connect(); while (true) { var watch = new Stopwatch(); watch.Start(); var r1 = client.Send <CustomEventData, object>(new CustomEventData() { FirstName = "Stefan", LastName = "Heim", //Data = File.ReadAllBytes(@"c:\temp\Aktueller Mandant.pdf") }); Console.WriteLine(string.Concat("Server response: ", r1)); var r3 = client.Send <string, object>("Das ist ein Test"); Console.WriteLine(string.Concat("Server response: ", r3)); server.Send(new CustomEventData() { FirstName = "Stefan", LastName = "Heim", //Data = File.ReadAllBytes(@"c:\temp\Aktueller Mandant.pdf") }); server.Send("Das ist ein Test"); watch.Stop(); Console.WriteLine(string.Concat(watch.ElapsedMilliseconds, "ms")); Console.ReadLine(); } }
public bool Authenticate(IUserCredential tool, string role) { if (IsStandAlone) { UserIdentity principal = new UserIdentity(UserInfo.Empty, true, new TimeSpan(0), "local"); AppDomain.CurrentDomain.SetThreadPrincipal(principal); _userCollection.Add(principal); } else { if (_loginServiceClient == null) { _callBack = new LoginServiceCallback(_userCollection); _loginServiceClient = new DuplexClient<ILoginService>(new InstanceContext(_callBack), _configuration.PingInterval); _loginServiceClient.Open(); _loginServiceClient.OnChanged += new EventHandler<ClientState>(_loginServiceClient_OnChanged); } string loginName, password; again: ; if (tool.GetUserCredential(out loginName, out password)) { byte[] hash = SecurityUtils.PasswordToHash(password); UserIdentity principal = loginService.Login(loginName, hash, Environment.MachineName); if (principal == null || !principal.IsAuthenticated) { tool.FailedLogin(); goto again; } if (role != null && !principal.IsInRole(role)) { tool.FailedRole(role); loginService.Logoff(principal); goto again; } AppDomain.CurrentDomain.SetThreadPrincipal(principal); loginService.Subscribe(principal); _userCollection.AddRange(loginService.GetUserLoginCollection()); } else { return false; //throw new ApplicationException("User cancel"); } } return true; }
public void Done() { if (IsStandAlone) return; UserIdentity identity = Thread.CurrentPrincipal as UserIdentity; if (_loginServiceClient != null) { try { if (identity != null) { loginService.UnSubscribe(identity); loginService.Logoff(identity); } } catch (Exception ex) { _configuration.EventLog.WriteError(String.Format("DesignerClient.Done(): {0}", ex)); } finally { _loginServiceClient.Dispose(); _loginServiceClient = null; } } if (_remotePresentationClient != null) { try { if (identity != null) { PresentationWorker.UnSubscribeForGlobalMonitoring(); } } catch (Exception ex) { _configuration.EventLog.WriteError(String.Format("DesignerClient.Done(): {0}", ex)); } finally { _remotePresentationClient.Dispose(); _remotePresentationClient = null; } } }
//!! Метод Вызывается из Дизайнера!! public void InitializeFromDisigner(IClientConfiguration configuration) { try { _configuration = configuration; _showNotifier = new ShowNotifier(_configuration); _showNotifier.OnPreparationFinished += _showNotifier_OnPreparationFinished; _showNotifier.OnProgressChanged += _showNotifier_OnProgressChanged; _showNotifier.OnEquipmentStateChanged += _showNotifier_OnEquipmentStateChanged; _showNotifier.OnNotEnoughSpace += _showNotifier_OnNotEnoughSpace; _showNotifier.OnShownStatusChanged += (_showNotifier_OnShownStatusChanged); _showNotifier.OnReceiveAgentResourcesList += _showNotifier_OnReceiveAgentResourcesList; _showNotifier.OnUploadSpeed += new Action<double, string, string>(_showNotifier_OnUploadSpeed); _showNotifier.OnPreparationForDisplayEnded += new Action<string, bool>(_showNotifier_OnPreparationForDisplayEnded); _showNotifier.OnLogMessage+=new Action<string>(_showNotifier_OnLogMessage); _svc = new DuplexClient<IShowCommon>(new InstanceContext(_showNotifier), _pingInterval); _svc.Open(); _created = true; } catch (CommunicationException) { _svc.Dispose(); _svc = null; _created = false; } }
private DuplexClient<IDuplexServer, IDuplexCallback> ConnectDuplex(Int32 portOffset) { var client = new DuplexClient<IDuplexServer, IDuplexCallback>( new ClientCallback(), new CustomBinding( new ReliableSessionBindingElement(false) { MaxPendingChannels = 16384 }, new CompositeDuplexBindingElement() { ClientBaseAddress = new Uri( String.Format( "udp://{0}:{1}/", System.Net.Dns.GetHostName(), 43000 + portOffset ) ) }, new WcfEx.Udp.BindingElement() ), DuplexClientUri ); client.Open(); return client; }
public UpdateResult ApplyUpdate(Delta delta) { lock (updateLock) { bool ok; DuplexClient <ITransactionManager, ITransaction> client = new DuplexClient <ITransactionManager, ITransaction>("callbackEndpoint", this); client.Connect(); if (!client.Call <bool>(tm => tm.StartEnlist(), out ok) || !ok) //TM.StartEnlist() { client.Disconnect(); return(new UpdateResult(ResultType.Failure)); } NetworkModel tModel = new NetworkModel(model); Tuple <Dictionary <long, long>, List <long>, List <long> > result = tModel.ApplyUpdate(delta); if (result == null) { client.Call <bool>(tm => tm.EndEnlist(false), out ok); //TM.EndEnlist(false) client.Disconnect(); return(new UpdateResult(ResultType.Failure)); } lock (modelLock) { transactionModel = tModel; } if (!client.Call <bool>(tm => tm.Enlist(), out ok) || !ok) //TM.Enlist() { lock (modelLock) { transactionModel = model; } client.Call <bool>(tm => tm.EndEnlist(false), out ok); //TM.EndEnlist(false) client.Disconnect(); return(new UpdateResult(ResultType.Failure)); } { Client <ISCADAServiceContract> scadaClient = new Client <ISCADAServiceContract>("SCADAEndpoint"); // Call SCADA scadaClient.Connect(); if (!scadaClient.Call <bool>(scada => scada.ApplyUpdate(new List <long>(result.Item1.Values), result.Item2, result.Item3), out ok) || !ok) { scadaClient.Disconnect(); lock (modelLock) { transactionModel = model; } client.Call <bool>(tm => tm.EndEnlist(false), out ok); //TM.EndEnlist(false) client.Disconnect(); return(new UpdateResult(ResultType.Failure)); } scadaClient.Disconnect(); } { Client <ICalculationEngineServiceContract> ceClient = new Client <ICalculationEngineServiceContract>("CEEndpoint"); // Call CE ceClient.Connect(); if (!ceClient.Call <bool>(ce => ce.ApplyUpdate(new List <long>(result.Item1.Values), result.Item2, result.Item3), out ok) || !ok) { ceClient.Disconnect(); lock (modelLock) { transactionModel = model; } client.Call <bool>(tm => tm.EndEnlist(false), out ok); //TM.EndEnlist(false) client.Disconnect(); return(new UpdateResult(ResultType.Failure)); } ceClient.Disconnect(); } if (!client.Call <bool>(tm => tm.EndEnlist(true), out ok) || !ok) //TM.EndEnlist(true) { lock (modelLock) { transactionModel = model; } client.Disconnect(); return(new UpdateResult(ResultType.Failure)); } client.Disconnect(); bool success; lock (modelLock) { success = model == tModel; } if (success) { Client <IPublishing> pubClient = new Client <IPublishing>("publishingEndpoint"); pubClient.Connect(); pubClient.Call <bool>(pub => { pub.Publish(new NetworkModelChanged()); return(true); }, out ok); pubClient.Disconnect(); } return(success ? new UpdateResult(ResultType.Success, null, result.Item1, result.Item2, result.Item3) : new UpdateResult(ResultType.Failure)); } }