public void Publish(PubSubMessage e) { if (SubscriptionManager.Subscribers == null) { return; } Type type = typeof(IPublishingService); MethodInfo publishMethodInfo = type.GetMethod("Publish"); if (SubscriptionManager.Subscribers.Count > 0) { foreach (var subscriber in SubscriptionManager.Subscribers) { try { publishMethodInfo.Invoke(subscriber, new object[] { e }); Console.WriteLine("Message {0} send to subscriber", e.MessageNum); } catch { Console.WriteLine("Error publishing to subscriber"); } } } else { Console.WriteLine("No subscribers for message {0}", e.MessageNum); } }
public async Task <XtResult <TMessage> > PublishAsync <TMessage>(TMessage message) where TMessage : class, new() { PublisherSocket publisherSocket = null; try { publisherSocket = new PublisherSocket(); publisherSocket.Connect(_configuration.Address()); return(await Task.Run(() => { try { var msg = new PubSubMessage <TMessage>(_configuration, message); publisherSocket.SendMultipartMessage(msg); } catch (System.Exception ex) { return XtResult <TMessage> .Failed(ex, "publish"); } return XtResult <TMessage> .Success(message, "publish"); })); } catch (System.Exception ex) { return(XtResult <TMessage> .Failed(ex, "publish")); } finally { publisherSocket?.Dispose(); } }
async Task <PubSubMessage> RunOnOutputQueue(string subscriberId, Func <IReliableQueue <PubSubMessage>, ITransaction, Task <ConditionalValue <PubSubMessage> > > callOnQueue) { var queueName = $"queue_{subscriberId}"; var queue = await this.StateManager.GetOrAddAsync <IReliableQueue <PubSubMessage> >(queueName).ConfigureAwait(false); var lst = await this.StateManager.GetOrAddAsync <IReliableDictionary <string, bool> >("queueList").ConfigureAwait(false); PubSubMessage msg = null; using (var tx = this.StateManager.CreateTransaction()) { if (!await lst.ContainsKeyAsync(tx, queueName).ConfigureAwait(false)) { await lst.AddAsync(tx, queueName, true).ConfigureAwait(false); } var msgCV = await callOnQueue(queue, tx).ConfigureAwait(false); //var msgCV = await q.TryDequeueAsync(tx).ConfigureAwait(false); if (msgCV.HasValue) { msg = msgCV.Value; } await tx.CommitAsync().ConfigureAwait(false); } ServiceEventSource.Current.ServiceMessage(this.Context, $"DEQUEUE FOR {subscriberId} : {msg?.Message}"); return(msg); }
public void Receive(PubSubMessage m) { switch (m.Topic) { case ETopic.NetworkModelChanged: HandleNetworkModelChange((NetworkModelChanged)m); break; case ETopic.MeasurementValuesChanged: HandleMeasurementValuesChange((MeasurementValuesChanged)m); break; case ETopic.TopologyChanged: HandleTopologyChange((TopologyChanged)m); break; case ETopic.LoadFlowChanged: HandleLoadFlowChange((LoadFlowChanged)m); break; case ETopic.MarkedSwitchesChanged: HandleMarkedSwitchesChange((MarkedSwitchesChanged)m); break; } }
//Notify all currency pair subscribers with the new update static public void Notify(PubSubMessage msg) { try { //Get subscribers var sublist = GetSubscribers(msg.CurrencyPairName); if (sublist == null) { return; } //Open threads equal to the number of subscribers sublist.AsParallel().ForAll(callback => { if (((ICommunicationObject)callback).State == CommunicationState.Opened) { callback.Publish(msg); } else { sublist.Remove(callback); } } ); } catch (Exception ex) { //Log Exception throw ex; } }
private PubSubMessage PrepareEvent() { PubSubMessage msg = new PubSubMessage(); msg.CurrencyPairName = txtPairName.Text; msg.CurrencyPairData = txtPairData.Text; return(msg); }
private void OnDisplayEvent(DisplayEventBase displayEvent, Envelope request, IJupyterMessageSender jupyterMessageSender) { var transient = CreateTransient(displayEvent.ValueId); var formattedValues = displayEvent .FormattedValues .ToDictionary(k => k.MimeType, v => v.Value); var value = displayEvent.Value; PubSubMessage dataMessage = null; CreateDefaultFormattedValueIfEmpty(formattedValues, value); switch (displayEvent) { case DisplayedValueProduced _: dataMessage = new DisplayData( transient: transient, data: formattedValues); break; case DisplayedValueUpdated _: dataMessage = new UpdateDisplayData( transient: transient, data: formattedValues); break; case ReturnValueProduced _: dataMessage = new ExecuteResult( _executionCount, transient: transient, data: formattedValues); break; case StandardOutputValueProduced _: dataMessage = Stream.StdOut(GetPlainTextValueOrDefault(formattedValues, value?.ToString() ?? string.Empty)); break; case StandardErrorValueProduced _: dataMessage = Stream.StdErr(GetPlainTextValueOrDefault(formattedValues, value?.ToString() ?? string.Empty)); break; default: throw new ArgumentException("Unsupported event type", nameof(displayEvent)); } var isSilent = ((ExecuteRequest)request.Content).Silent; if (!isSilent) { // send on io jupyterMessageSender.Send(dataMessage); } }
public void Publish(PubSubMessage msg) { if (msg != null) { int itemNum = (lstData.Items.Count < 1) ? 0 : lstData.Items.Count; lstData.Items.Add(itemNum.ToString()); lstData.Items[itemNum].SubItems.AddRange(new string[] { msg.CurrencyPairName.ToString(), msg.CurrencyPairData }); } }
// POST api/tenantId/topicName //public async Task<HttpResponseMessage> Post(string tenantId, string topicName) //{ // HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError); // // Assuming the message body will contain the content for the data to put to the topic. // string messageBody = await this.Request.Content.ReadAsStringAsync(); // HttpServiceUriBuilder builder = new HttpServiceUriBuilder() // { // PortNumber = await GetReverseProxyPortAsync(), // ServiceName = $"{tenantId}/{TenantApplicationTopicServiceName}/{topicName}/api/" // }; // HttpResponseMessage topicResponseMessage; // using (HttpClient httpClient = new HttpClient()) // { // HttpContent postContent = new StringContent(messageBody); // postContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); // topicResponseMessage = await httpClient.PostAsync(builder.Build(), postContent); // } // if (topicResponseMessage != null && topicResponseMessage.IsSuccessStatusCode) // { // responseMessage.StatusCode = HttpStatusCode.Accepted; // var msg = await topicResponseMessage.Content.ReadAsStringAsync(); // System.Diagnostics.Debug.WriteLine($"Received response of '{msg}'."); // } // else // { // responseMessage.StatusCode = topicResponseMessage?.StatusCode ?? HttpStatusCode.InternalServerError; // responseMessage.ReasonPhrase = topicResponseMessage?.ReasonPhrase ?? "Internal error"; // } // return responseMessage; //} // GET api/tenantId/topicName/subscriber public async Task <HttpResponseMessage> Get(string tenantId, string topicName, string subscriberName) { try { ServiceEventSource.Current.Message($"[Router] Message read for {tenantId}/{topicName}/{subscriberName}"); HttpServiceUriBuilder builder = new HttpServiceUriBuilder() { PortNumber = await FrontEndHelper.FrontEndHelper.GetReverseProxyPortAsync(), ServiceName = $"{tenantId}/{TenantApplicationTopicServiceName}/{topicName}/{subscriberName}/api" }; HttpResponseMessage msg; PubSubMessage pubSubMsg = null; using (HttpClient httpClient = new HttpClient()) { string pubSubMsgJson = await httpClient.GetStringAsync(builder.Build()); if (!String.IsNullOrEmpty(pubSubMsgJson)) { pubSubMsg = JsonConvert.DeserializeObject <PubSubMessage>(pubSubMsgJson); } } HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK); if (pubSubMsg != null) { string msgJson = JsonConvert.SerializeObject(pubSubMsg.Message, new JsonSerializerSettings { Formatting = Formatting.Indented }); responseMessage.Content = new StringContent(msgJson); } else { responseMessage.StatusCode = HttpStatusCode.NoContent; } return(responseMessage); //using remoting //var topicSvc = ServiceProxy.Create<ISubscriberService>(new Uri($"fabric:/{tenantId}/{TenantApplicationTopicServiceName}/{topicName}/{subscriberName}")); //var msg = await topicSvc.Pop(); //string msgJson = JsonConvert.SerializeObject(msg.Content, // new JsonSerializerSettings // { // Formatting = Formatting.Indented // }); //responseMessage.Content = new StringContent(msgJson); } catch (Exception ex) { return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } }
public Task Publish(PubSubMessage message) { Subscription subscription = new Subscription(); using (var publisher = new Publisher(subscription.Topic, subscription.ConnectionString)) { publisher.SendMessage(message); } return(Task.CompletedTask); }
private static void SendOneMessage() { PubSubMessage message = new PubSubMessage() { MessageNum = _messageNum++, Content = "[Message content here]" }; Thread.Sleep(1000); // Pause one seconnds between messages _publishingClient.Publish(message); }
private void NotifySubscriber(ISubscription subscriber, PubSubMessage message) { try { subscriber.Receive(message); } catch { // This normally happens when the subscriber is closed without un-subscribing } }
private static void SendDisplayData(PubSubMessage messageMessage, Envelope request, IJupyterMessageSender ioPubChannel) { var isSilent = ((ExecuteRequest)request.Content).Silent; if (!isSilent) { // send on io ioPubChannel.Send(messageMessage); } }
/// <summary> /// Adds the new message to list. /// </summary> /// <param name="message">The message.</param> private void AddNewMessageToList(PubSubMessage message) { if (message != null) { var plainMessage = this.SimpleEncryption.Decrypt(message.EventData); var itemNum = (this.lstEvents.Items.Count < 1) ? 0 : this.lstEvents.Items.Count; this.lstEvents.Items.Add((itemNum + 1).ToString()); this.lstEvents.Items[itemNum].SubItems.AddRange(new string[] { message.TopicName.ToString(), plainMessage, message.EventDate.ToString() }); this.EventsCount++; } }
public void Receive(PubSubMessage m) { switch (m.Topic) { case ETopic.NetworkModelChanged: DownloadModel(); break; case ETopic.TopologyChanged: TopologyUpdated(); break; } }
public async Task <HttpResponseMessage> Post(string tenantId, string topicName, string message) { try { ServiceEventSource.Current.Message($"[Router] New Message received for {tenantId}/{topicName}: {message}"); HttpServiceUriBuilder builder = new HttpServiceUriBuilder() { PortNumber = await FrontEndHelper.FrontEndHelper.GetReverseProxyPortAsync(), ServiceName = $"{tenantId}/{TenantApplicationTopicServiceName}/{topicName}/api" }; HttpResponseMessage msg; PubSubMessage pubsubMessage = new PubSubMessage() { Message = message }; using (HttpClient httpClient = new HttpClient()) { string msgJson = JsonConvert.SerializeObject(pubsubMessage, new JsonSerializerSettings { Formatting = Formatting.Indented }); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header msg = await httpClient.PostAsync( builder.Build(), new StringContent(msgJson, Encoding.UTF8, "application/json") ); } HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK); if (!msg.IsSuccessStatusCode) { responseMessage.StatusCode = HttpStatusCode.InternalServerError; } return(responseMessage); //using remoting //var msg = new PubSubMessage() { Message = message }; //var topicSvc = ServiceProxy.Create<ITopicService>(new Uri($"fabric:/{tenantId}/{TenantApplicationTopicServiceName}/{topicName}")); //await topicSvc.Push(msg); } catch (Exception ex) { return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } }
private bool TryApplyTransaction() { try { Thread.Sleep(TimeSpan.FromSeconds(20)); TransactionManagerServiceProxy proxyForTM = new TransactionManagerServiceProxy(ConfigurationManager.AppSettings["TM"]); bool pom = false; while (!pom) { pom = proxyForTM.StartEnlist().GetAwaiter().GetResult(); } proxyForTM.Enlist().GetAwaiter().GetResult(); NDSModelProxy proxyForScada = new NDSModelProxy(ConfigurationManager.AppSettings["SCADAM"]); CEModelProxy proxyForCE = new CEModelProxy(ConfigurationManager.AppSettings["CEM"]); bool success = false; if (proxyForScada.ModelUpdate(affectedEntities).GetAwaiter().GetResult()) { success = true; } if (proxyForCE.ModelUpdate(affectedEntities).GetAwaiter().GetResult()) { success = true; } proxyForTM.EndEnlist(success).GetAwaiter().GetResult(); try { var subscription = new Subscription(); var publisher = new Publisher(subscription.Topic, subscription.ConnectionString); var dtos = DtoConverter.Convert(networkDataModelCopy); var json = JsonTool.Serialize(new ModelUpdateEvent(dtos)); var msg = new PubSubMessage() { Content = json, ContentType = ContentType.NMS_UPDATE, Sender = Sender.NMS }; publisher.SendMessage(msg).ConfigureAwait(false).GetAwaiter().GetResult(); } catch { } return(true); } catch (Exception) { return(false); } }
/// <summary> /// Enqueue a new message in the topic /// </summary> /// <param name="msg"></param> /// <returns></returns> public async Task Push(PubSubMessage msg) { var lst = await this.StateManager.GetOrAddAsync <IReliableDictionary <string, bool> >("queueList").ConfigureAwait(false); var inputQueue = await this.StateManager.GetOrAddAsync <IReliableConcurrentQueue <PubSubMessage> >("inputQueue"); using (var tx = this.StateManager.CreateTransaction()) { await inputQueue.EnqueueAsync(tx, msg).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); } ServiceEventSource.Current.ServiceMessage(this.Context, $"INPUT QUEUE: {msg.Message}"); }
/// <summary> /// Publishes the specified e. /// </summary> /// <param name="message">The message.</param> /// <param name="topic">The topic.</param> public void Publish(PubSubMessage message, string topic) { this.proxyManager.NotifyHost(string.Format("New message is published for the topic {0}.", topic)); var subscribers = this.GetSubscribers(topic); if (subscribers != null) { foreach (var subscriber in subscribers) { this.NotifySubscriber(subscriber, message); } } }
void Publish(PubSubMessage msg) { Client <IPublishing> pubClient = new Client <IPublishing>("publishingEndpoint"); pubClient.Connect(); pubClient.Call <bool>(pub => { pub.Publish(msg); return(true); }, out _); pubClient.Disconnect(); }
private void InnerOnChange(PubSubMessage message) { lock (this) { if (!monitorDisposed) { this.filter.UnregisterForTopics(this.InnerOnChange, topics); try { base.OnChanged(message); } catch (Exception ex) { OSTrace.Error($"Error notifing PubSubMonitor change for topic: {UniqueId}. Possible due to Application Unload.", ex); } } } }
public async Task <PubSubMessage> Pop() { PubSubMessage msg = null; var queue = await this.StateManager.GetOrAddAsync <IReliableQueue <PubSubMessage> >("messages").ConfigureAwait(false); using (var tx = this.StateManager.CreateTransaction()) { var msgCV = await queue.TryDequeueAsync(tx).ConfigureAwait(false); if (msgCV.HasValue) { msg = msgCV.Value; } await tx.CommitAsync().ConfigureAwait(false); } return(msg); }
public async Task Push(PubSubMessage msg) { ServiceEventSource.Current.Message($"Topic Push called: {msg.Message}"); msg.MessageID = Guid.NewGuid(); // generating a new unique ID for the incoming message. var lst = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, bool> >("queueList").ConfigureAwait(false); var inputQueue = await this.stateManager.GetOrAddAsync <IReliableQueue <PubSubMessage> >("inputQueue"); using (var tx = this.stateManager.CreateTransaction()) { await inputQueue.EnqueueAsync(tx, msg).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); } //ServiceEventSource.Current.ServiceMessage(context, $"Input queue: {msg.Message}"); }
// POST api/values public async Task Push([FromBody] string value) { string name = FabricRuntime.GetActivationContext() .GetConfigurationPackageObject("Config") .Settings .Sections["WebApiConfigSection"] .Parameters["TopicName"] .Value; var msg = new PubSubMessage() { Message = value }; var stockSvc = ServiceProxy.Create <ITopicService>(new Uri("fabric:/PubSubTransactionPoC/" + name), new ServicePartitionKey(0)); await stockSvc.Push(msg); }
static async Task Main(string[] args) { Console.WriteLine("Starting"); var RabbitMqUserName = "******"; var RabbitMqPassword = "******"; using (var bus = RabbitHutch.CreateBus($"host=rabbitmq;username={RabbitMqUserName};password={RabbitMqPassword}")) { int I = 1; while (true) { var PubSubMsg = new PubSubMessage($"Pub/Sub message {I}"); var QueueMsg = new QueueMessage($"Queue message {I}"); try { bus.PubSub.Publish(PubSubMsg); Console.WriteLine($"Published message: '{PubSubMsg.Text}'"); } catch { Console.WriteLine($"Erro publishing message: '{PubSubMsg.Text}'"); } try { bus.PubSub.Publish(QueueMsg); Console.WriteLine($"Published message: '{QueueMsg.Text}'"); } catch { Console.WriteLine($"Erro publishing message: '{QueueMsg.Text}'"); } await Task.Delay(500); I++; } } }
public void Publish(PubSubMessage m) { lock (clients) { foreach (KeyValuePair <IPubSubClient, List <ETopic> > client in clients) { if (!client.Value.Contains(m.Topic)) { continue; } try { client.Key.Receive(m); } catch (Exception e) { } } } }
private void btnPublish_Click(object sender, EventArgs e) { try { string pairName = txtPairName.Text.Trim(); if (string.IsNullOrEmpty(pairName)) { MessageBox.Show("Please Enter a Pair Name"); return; } PubSubMessage alertData = PrepareEvent(); _PubProxy.Publish(alertData); MessageBox.Show("Message Sent"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public async Task <PubSubMessage> Pop() { PubSubMessage msg = null; var queue = await this.stateManager.GetOrAddAsync <IReliableQueue <PubSubMessage> >("messages").ConfigureAwait(false); using (var tx = this.stateManager.CreateTransaction()) { var msgCV = await queue.TryDequeueAsync(tx).ConfigureAwait(false); if (msgCV.HasValue) { msg = msgCV.Value; ServiceEventSource.Current.Message($"Subscribed Pop called. Message found: {msg.Message}"); } else { ServiceEventSource.Current.Message($"Subscribed Pop called. No Messages available"); } await tx.CommitAsync().ConfigureAwait(false); } return(msg); }
/// <summary> /// Enqueue a new message in the topic /// </summary> /// <param name="msg"></param> /// <returns></returns> public async Task Push(PubSubMessage msg) { var lst = await this.StateManager.GetOrAddAsync <IReliableDictionary <string, bool> >("queueList").ConfigureAwait(false); using (var tx = this.StateManager.CreateTransaction()) { IAsyncEnumerable <KeyValuePair <string, bool> > asyncEnumerable = await lst.CreateEnumerableAsync(tx); using (IAsyncEnumerator <KeyValuePair <string, bool> > asyncEnumerator = asyncEnumerable.GetAsyncEnumerator()) { while (await asyncEnumerator.MoveNextAsync(CancellationToken.None)) { var queue = await this.StateManager.GetOrAddAsync <IReliableQueue <PubSubMessage> >(asyncEnumerator.Current.Key).ConfigureAwait(false); await queue.EnqueueAsync(tx, msg); } } await tx.CommitAsync().ConfigureAwait(false); ServiceEventSource.Current.ServiceMessage(this.Context, $"ENQUEUE: {msg.Message}"); } }
private void UpdateGraph() { if (points > 0) { CeGraphicalEvent newGraph = new CeGraphicalEvent(); newGraph.PumpsValues.Pump1.XAxes = graph.PumpsValues.Pump1.XAxes.Take(indexGraph).ToList(); newGraph.PumpsValues.Pump1.YAxes = graph.PumpsValues.Pump1.YAxes.Take(indexGraph).ToList(); newGraph.PumpsValues.Pump2.XAxes = graph.PumpsValues.Pump2.XAxes.Take(indexGraph).ToList(); newGraph.PumpsValues.Pump2.YAxes = graph.PumpsValues.Pump2.YAxes.Take(indexGraph).ToList(); newGraph.PumpsValues.Pump3.XAxes = graph.PumpsValues.Pump3.XAxes.Take(indexGraph).ToList(); newGraph.PumpsValues.Pump3.YAxes = graph.PumpsValues.Pump3.YAxes.Take(indexGraph).ToList(); var json = JsonTool.Serialize <CeGraphicalEvent>(newGraph); PubSubMessage ev = new PubSubMessage() { ContentType = ContentType.CE_HISTORY_GRAPH, Content = json, Sender = Sender.CE }; pubsub.SendMessage(ev).ConfigureAwait(false); } }