예제 #1
0
        public async Task <ApiResult <bool> > Save(SubscriptionEvent m)
        {
            try
            {
                SubscriptionEvent se = new()
                {
                    Creator        = User.GetUserId(),
                    EventName      = m.EventName,
                    EventDesc      = m.EventDesc,
                    EventNameSpace = m.EventNameSpace,
                    EventParam     = m.EventParam,
                    EventTag       = m.EventTag,
                    Type           = m.Type,
                    CreateDateTime = DateTime.Now,
                    EventStatus    = 1
                };
                _context.JustFill(this, se);
                _context.SubscriptionEvents.Add(se);
                await this._context.SaveChangesAsync();

                return(new ApiResult <bool>(ApiCode.Success, "OK", true));
            }
            catch (Exception e)
            {
                return(new ApiResult <bool>(ApiCode.Exception, e.Message, false));
            }
        }
예제 #2
0
        public override int OnSubscriptionEvent(SubscriptionEvent e)
        {
            short code = e.getCode();
            tsip_subscribe_event_type_t type    = e.getType();
            SubscriptionSession         session = e.getSession();
            SipMessage message = e.getSipMessage();

            switch (type)
            {
            case tsip_subscribe_event_type_t.tsip_ao_subscribe:
            case tsip_subscribe_event_type_t.tsip_ao_unsubscribe:
                break;

            case tsip_subscribe_event_type_t.tsip_i_notify:
                byte[] content = message.getSipContent();
                if (content != null)
                {
                    Console.WriteLine("Notify Content ==> {0}", Encoding.UTF8.GetString(content));
                }
                break;
            }

            Console.WriteLine("OnSubscriptioChanged() ==> {0}:{1}", code, e.getPhrase());

            return(0);
        }
예제 #3
0
        internal override void DispatchSubscription(SubscriptionEvent subscriptionData)
        {
            EventHandler <SubscriptionEvent> subscriptionEvent =
                (EventHandler <SubscriptionEvent>)eventHandlerList[subscriptionEventKey];

            subscriptionEvent?.Invoke(this, subscriptionData);
        }
예제 #4
0
        private void OnSubscriptionEvent(object sender, SubscriptionEvent subscriptionEvent)
        {
            switch (subscriptionEvent.Action)
            {
            case SubscriptionAction.Add:
                if (subscriptionEvent is SubscriptionAddEvent)
                {
                    Add(((SubscriptionAddEvent)subscriptionEvent).SubscriptionData);
                }
                break;

            case SubscriptionAction.Remove:
                if (subscriptionEvent is SubscriptionRemoveEvent)
                {
                    Remove(((SubscriptionRemoveEvent)subscriptionEvent).Predicate);
                }
                break;

            case SubscriptionAction.Clear:
                Clear();
                break;

            default: break;
            }
        }
        public async Task SubscribedReceiveer_TwoEvents_DoesReceiveBothEventsOnce()
        {
            var receiver = new Mock <ISubscriptionEventReceiver>();

            receiver.Setup(x => x.ReceiveEvent(It.IsAny <SubscriptionEvent>())).Returns(Task.CompletedTask);

            var router = new DefaultSubscriptionEventRouter();

            var evt = new SubscriptionEvent()
            {
                SchemaTypeName = typeof(GraphSchema).FullName,
                EventName      = "bobEvent5",
                DataTypeName   = typeof(TwoPropertyObject).FullName,
                Data           = new TwoPropertyObject(),
            };

            var evt2 = new SubscriptionEvent()
            {
                SchemaTypeName = typeof(GraphSchema).FullName,
                EventName      = "bobEvent6",
                DataTypeName   = typeof(TwoPropertyObject).FullName,
                Data           = new TwoPropertyObject(),
            };

            // add two events but remove the one being raised
            // to ensure its not processed
            router.AddReceiver(evt.ToSubscriptionEventName(), receiver.Object);
            router.AddReceiver(evt2.ToSubscriptionEventName(), receiver.Object);
            await router.RaiseEvent(evt);

            await router.RaiseEvent(evt2);

            receiver.Verify(x => x.ReceiveEvent(evt), Times.Once);
            receiver.Verify(x => x.ReceiveEvent(evt2), Times.Once);
        }
        public async Task UnsubscribedAllReceiver_DoesNotReceivesRaisedEvent()
        {
            var receiver = new Mock <ISubscriptionEventReceiver>();

            receiver.Setup(x => x.ReceiveEvent(It.IsAny <SubscriptionEvent>())).Returns(Task.CompletedTask);

            var router = new DefaultSubscriptionEventRouter();

            var evt = new SubscriptionEvent()
            {
                SchemaTypeName = typeof(GraphSchema).FullName,
                EventName      = "bobEvent5",
                DataTypeName   = typeof(TwoPropertyObject).FullName,
                Data           = new TwoPropertyObject(),
            };

            var evt2 = new SubscriptionEvent()
            {
                SchemaTypeName = typeof(GraphSchema).FullName,
                EventName      = "bobEvent6",
                DataTypeName   = typeof(TwoPropertyObject).FullName,
                Data           = new TwoPropertyObject(),
            };

            // add two events and ensure both are removed when not directly named
            router.AddReceiver(evt.ToSubscriptionEventName(), receiver.Object);
            router.AddReceiver(evt2.ToSubscriptionEventName(), receiver.Object);
            router.RemoveReceiver(receiver.Object);
            await router.RaiseEvent(evt);

            await router.RaiseEvent(evt2);

            receiver.Verify(x => x.ReceiveEvent(evt), Times.Never);
            receiver.Verify(x => x.ReceiveEvent(evt2), Times.Never);
        }
        public async Task ReceiveEvent_WithARegisteredClient_ClientRecievesEvent()
        {
            (var server, var socketClient, var apolloClient) = await this.CreateConnection();

            // start the sub on the client
            var startMessage = new ApolloClientStartMessage()
            {
                Id      = "abc",
                Payload = new GraphQueryData()
                {
                    Query = "subscription {  apolloSubscription { watchForPropObject { property1 } } }",
                },
            };

            await apolloClient.DispatchMessage(startMessage);

            var evt = new SubscriptionEvent()
            {
                Data           = new TwoPropertyObject(),
                DataTypeName   = SchemaExtensions.RetrieveFullyQualifiedDataObjectTypeName(typeof(TwoPropertyObject)),
                SchemaTypeName = SchemaExtensions.RetrieveFullyQualifiedSchemaTypeName(typeof(GraphSchema)),
                EventName      = "[subscription]/ApolloSubscription/WatchForPropObject",
            };

            var count = await server.ReceiveEvent(evt);

            Assert.AreEqual(1, count);

            socketClient.AssertApolloResponse(ApolloMessageType.DATA, "abc");
        }
 /// <summary>
 /// Recorded by this instance's <see cref="ISubscriptionEventRouter"/> when it receives a new subscription event from
 /// an externally connected source such as a message queue or service or bus. For single server configurations this event
 /// is recorded when an event is passed from the internal publishing queue directly to the <see cref="ISubscriptionEventRouter"/>.
 /// </summary>
 /// <param name="logger">The logger doing the logging.</param>
 /// <param name="eventData">The event data that was received from a data source.</param>
 public static void SubscriptionEventReceived(
     this IGraphEventLogger logger,
     SubscriptionEvent eventData)
 {
     logger.Log(
         LogLevel.Debug,
         () => new SubscriptionEventReceivedLogEntry(eventData));
 }
 /// <summary>
 /// Recorded when an Apollo Subscription Server instance receives an event
 /// from the listener configured for this ASP.NET server instance.
 /// </summary>
 /// <param name="eventRecieved">The event that was recieved from the global listener.</param>
 /// <param name="clientsToReceive">The filtered list of clients that will receive the event
 /// from the server.</param>
 public void EventReceived(
     SubscriptionEvent eventRecieved,
     IReadOnlyList <ApolloClientProxy <TSchema> > clientsToReceive)
 {
     _logger.Log(
         LogLevel.Trace,
         () => new ApolloServerSubscriptionEventReceived <TSchema>(_server, eventRecieved, clientsToReceive));
 }
예제 #10
0
        public void Signal()
        {
            if (_isDisposed)
            {
                ThrowObjectDisposedException();
            }

            SubscriptionEvent?.Invoke();
        }
예제 #11
0
파일: IStep.cs 프로젝트: nongfang55/Sofia
        private async Task<SubscriptionEvent> AddEvent(Subscription subscription)
        {
            var @event = new SubscriptionEvent();
            subscription.AddEvent(@event);
            Subscription.ScanningStatus = MidConditionStatus;

            await DbContext.SaveChangesAsync();
            return @event;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SubscriptionEventPublishedLogEntry" /> class.
 /// </summary>
 /// <param name="eventPublished">The event that was recieved.</param>
 public SubscriptionEventPublishedLogEntry(SubscriptionEvent eventPublished)
     : base(SubscriptionLogEventIds.GlobalEventPublished)
 {
     _shortEventName            = eventPublished.EventName;
     this.SchemaType            = eventPublished.SchemaTypeName;
     this.DataType              = eventPublished.DataTypeName;
     this.SubscriptionEventId   = eventPublished.Id;
     this.SubscriptionEventName = eventPublished.EventName;
     this.MachineName           = Environment.MachineName;
 }
        public void GeneralPropertyCheck()
        {
            var eventData = new SubscriptionEvent()
            {
                Data           = new object(),
                DataTypeName   = "dataType",
                SchemaTypeName = "schemaType",
                EventName      = "eventName",
            };

            Assert.AreEqual(new SubscriptionEventName("schemaType", "eventName"), eventData.ToSubscriptionEventName());
        }
        /// <summary>
        /// Dispatches the event to all registered clients wishing to receive it.
        /// </summary>
        /// <param name="eventData">The event data.</param>
        /// <returns>The total number of clients notified of the event.</returns>
        public async Task <int> ReceiveEvent(SubscriptionEvent eventData)
        {
            if (eventData == null)
            {
                return(0);
            }

            var eventRoute = _schema.RetrieveSubscriptionFieldPath(eventData.ToSubscriptionEventName());

            if (eventRoute == null)
            {
                return(0);
            }

            // grab a reference to all clients that need the event
            var clientList = new List <ApolloClientProxy <TSchema> >();

            lock (_syncLock)
            {
                if (_subCountByName.TryGetValue(eventData.ToSubscriptionEventName(), out var clients))
                {
                    clientList.AddRange(clients);
                }
            }

            _logger?.EventReceived(eventData, clientList);
            if (clientList.Count == 0)
            {
                return(0);
            }

            var cancelSource = new CancellationTokenSource();

            // TODO: Add some timing wrappers with cancel token to ensure no spun out
            // comms.
            var allTasks = clientList.Select((client) =>
                                             this.ExecuteSubscriptionEvent(
                                                 client,
                                                 eventRoute,
                                                 eventData.Data,
                                                 cancelSource.Token)).ToList();

            await Task.WhenAll(allTasks).ConfigureAwait(false);

            // re-await any faulted tasks so tehy can unbubble any exceptions
            foreach (var task in allTasks.Where(x => x.IsFaulted))
            {
                await task.ConfigureAwait(false);
            }

            return(allTasks.Count);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ApolloServerSubscriptionEventReceived{TSchema}" /> class.
 /// </summary>
 /// <param name="server">The server instance that received the event.</param>
 /// <param name="eventRecieved">The event that was recieved from the global listener.</param>
 /// <param name="clientsToReceive">The filtered list of clients that will receive the event
 /// from the server.</param>
 public ApolloServerSubscriptionEventReceived(
     ApolloSubscriptionServer <TSchema> server,
     SubscriptionEvent eventRecieved,
     IReadOnlyList <ApolloClientProxy <TSchema> > clientsToReceive)
     : base(ApolloLogEventIds.ServerSubcriptionEventReceived)
 {
     this.SchemaTypeName        = eventRecieved.SchemaTypeName;
     this.SubscriptionEventName = eventRecieved.EventName;
     this.SubscriptionEventId   = eventRecieved.Id;
     this.ClientCount           = clientsToReceive.Count;
     this.ServerId  = server.Id;
     this.ClientIds = clientsToReceive.Select(x => x.Id).ToList();
 }
예제 #16
0
        public void RunOnSubscribeCallback(SubscriptionEvent subEvent)
        {
            var re_subscribed = (subEvent.Subtype == "sub") ? "subscribed" : "resubscribed";

            BotLogger.LogMessage($"{subEvent.Username} {re_subscribed} the channel: #{subEvent.Channel}");
            foreach (var callback in this.Callbacks_Subscrition)
            {
                if (callback(subEvent) == CallbackAction.SKIP_OTHERS)
                {
                    break;
                }
            }
        }
예제 #17
0
        public async Task PublishEvent_ForwardsEventToRouter()
        {
            var router = new Mock <ISubscriptionEventRouter>();

            router.Setup(x => x.RaiseEvent(It.IsAny <SubscriptionEvent>())).Returns(Task.CompletedTask);

            var publisher = new InProcessSubscriptionPublisher(router.Object);

            var eventData = new SubscriptionEvent();
            await publisher.PublishEvent(eventData);

            router.Verify(x => x.RaiseEvent(It.IsAny <SubscriptionEvent>()), Times.Once(), "failed to raise the event");
        }
예제 #18
0
        public override int OnSubscriptionEvent(SubscriptionEvent e)
        {
            switch (e.getType())
            {
            case tsip_subscribe_event_type_t.tsip_i_notify:
                String ev = e.getSipMessage().getSipHeaderValue("Event");
                Console.WriteLine("Event=%s", ev);
                break;

            default:
                break;
            }
            return(base.OnSubscriptionEvent(e));
        }
        public async Task ReceiveEvent_WithNoClients_YieldsNothing()
        {
            (var server, var socketClient, var apolloClient) = await this.CreateConnection();

            var evt = new SubscriptionEvent()
            {
                Data           = null,
                DataTypeName   = typeof(TwoPropertyObject).FullName,
                SchemaTypeName = typeof(GraphSchema).FullName,
                EventName      = "fakeEvent",
            };

            var count = await server.ReceiveEvent(evt);

            Assert.AreEqual(0, count);
        }
        public virtual SubscriptionEvent ToModel(SubscriptionEvent subscriptionEvent)
        {
            if (subscriptionEvent == null)
            {
                throw new ArgumentNullException(nameof(subscriptionEvent));
            }

            subscriptionEvent.Id             = Id;
            subscriptionEvent.CreatedBy      = CreatedBy;
            subscriptionEvent.CreatedDate    = CreatedDate;
            subscriptionEvent.ModifiedBy     = ModifiedBy;
            subscriptionEvent.ModifiedDate   = ModifiedDate;
            subscriptionEvent.EventId        = EventId;
            subscriptionEvent.SubscriptionId = SubscriptionId;

            return(subscriptionEvent);
        }
        public void TestSubscriptionEventSerializationCycle()
        {
            // fake an event from graphql aspnet
            // that would be recieved by the publisher
            var widget = new TestWidget()
            {
                Id          = 5,
                Name        = "Widget5Name",
                Description = "Widget5Description"
            };

            var evt = new SubscriptionEvent()
            {
                Id             = Guid.NewGuid().ToString(),
                EventName      = "testEvent",
                DataTypeName   = typeof(TestWidget).AssemblyQualifiedName,
                Data           = widget,
                SchemaTypeName = typeof(GraphSchema).AssemblyQualifiedName,
            };

            var options = new JsonSerializerOptions();

            options.PropertyNameCaseInsensitive = true;
            options.WriteIndented = true;
            options.Converters.Add(new SubscriptionEventConverter());

            // serialize then deserialize the object
            var serailizedData = JsonSerializer.Serialize(evt, typeof(SubscriptionEvent), options);
            var deserialized   = JsonSerializer.Deserialize <SubscriptionEvent>(serailizedData, options);

            // test all properties were translated correctly
            Assert.IsNotNull(deserialized);
            Assert.AreEqual(evt.Id, deserialized.Id);
            Assert.AreEqual(evt.EventName, deserialized.EventName);
            Assert.AreEqual(evt.SchemaTypeName, deserialized.SchemaTypeName);
            Assert.AreEqual(evt.DataTypeName, deserialized.DataTypeName);

            var converted = deserialized.Data as TestWidget;

            Assert.IsNotNull(converted);
            Assert.AreEqual(converted.Id, widget.Id);
            Assert.AreEqual(converted.Name, widget.Name);
            Assert.AreEqual(converted.Description, widget.Description);
        }
        public virtual SubscriptionEventEntity FromModel(SubscriptionEvent subscriptionEvent, PrimaryKeyResolvingMap pkMap)
        {
            if (subscriptionEvent == null)
            {
                throw new ArgumentNullException(nameof(subscriptionEvent));
            }

            Id             = subscriptionEvent.Id;
            CreatedBy      = subscriptionEvent.CreatedBy;
            CreatedDate    = subscriptionEvent.CreatedDate;
            ModifiedBy     = subscriptionEvent.ModifiedBy;
            ModifiedDate   = subscriptionEvent.ModifiedDate;
            EventId        = subscriptionEvent.EventId;
            SubscriptionId = subscriptionEvent.SubscriptionId;

            pkMap.AddPair(subscriptionEvent, this);

            return(this);
        }
        private async Task HandleMessageAsync(SubscriptionEvent message, CancellationToken cancellation)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                // possible room for expansion?
                // var subscriptionService = scope.ServiceProvider.GetRequiredService<ISubscriptionService>();
                // var test = await testService.GetTestAsync(message.subscription.Id, cancellation);

                // Change color to make msg stand out
                Console.BackgroundColor = ConsoleColor.Green;
                Console.ForegroundColor = ConsoleColor.Black;

                // Print the received message
                Console.WriteLine($"Message with traceid: {message.Header.TraceId} bevat subscription met naam: {message.subscription.Name}");

                // Change back color to default
                Console.ResetColor();
            }
        }
예제 #24
0
        public override async Task<int> UpdateLastConsumedSubscriptionEvent(SubscriptionEvent subscriptionEvent)
        {
            var query = "INSERT INTO LastConsumedSubscriptionEvent (SubscriptionId, FunctionalKey, PublicationDateUtc)" +
                " VALUES(@subscriptionId, @functionalKey, @publicationDateUtc)" +
                " ON DUPLICATE KEY UPDATE PublicationDateUtc = @publicationDateUtc";

            try
            {
                return await TranExecuteAsync(query, new Dictionary<string, object>
                {
                    { "@subscriptionId", subscriptionEvent.SubscriptionId },
                    { "@functionalKey", subscriptionEvent.FunctionalKey },
                    { "@publicationDateUtc", subscriptionEvent.PublicationDateUtc },
                }).ConfigureAwait(false);
            }
            catch (DbException dbEx)
            {
                throw new RepoException(dbEx);
            }
        }
        /// <summary>
        /// Invokes this middleware component allowing it to perform its work against the supplied context.
        /// </summary>
        /// <param name="context">The context containing the request passed through the pipeline.</param>
        /// <param name="next">The delegate pointing to the next piece of middleware to be invoked.</param>
        /// <param name="cancelToken">The cancel token.</param>
        /// <returns>Task.</returns>
        public Task InvokeAsync(
            GraphQueryExecutionContext context,
            GraphMiddlewareInvocationDelegate <GraphQueryExecutionContext> next,
            CancellationToken cancelToken)
        {
            if (context?.Items != null && context.IsValid && !context.IsCancelled)
            {
                // if a context item for the subscription event key was added by one of the extension methods
                // inspect it to try and find the events that were registered
                if (context.Items.ContainsKey(SubscriptionConstants.RAISED_EVENTS_COLLECTION_KEY))
                {
                    var collection = context.Items[SubscriptionConstants.RAISED_EVENTS_COLLECTION_KEY] as IList <SubscriptionEventProxy>;

                    if (collection == null)
                    {
                        throw new GraphExecutionException(
                                  $"Unable to cast the context item '{SubscriptionConstants.RAISED_EVENTS_COLLECTION_KEY}' into " +
                                  $"{typeof(IList<SubscriptionEventProxy>).FriendlyName()}. Published subscription events could not be raised.",
                                  SourceOrigin.None);
                    }
                    else
                    {
                        foreach (var proxy in collection)
                        {
                            var eventData = new SubscriptionEvent()
                            {
                                Id             = Guid.NewGuid().ToString(),
                                SchemaTypeName = SchemaExtensions.RetrieveFullyQualifiedSchemaTypeName(typeof(TSchema)),
                                Data           = proxy.DataObject,
                                DataTypeName   = SchemaExtensions.RetrieveFullyQualifiedDataObjectTypeName(proxy.DataObject?.GetType()),
                                EventName      = proxy.EventName?.Trim(),
                            };

                            _eventQueue.Enqueue(eventData);
                        }
                    }
                }
            }

            return(next(context, cancelToken));
        }
        public async Task SubscribedReceiver_ReceivesRaisedEvent()
        {
            var receiver = new Mock <ISubscriptionEventReceiver>();

            receiver.Setup(x => x.ReceiveEvent(It.IsAny <SubscriptionEvent>())).Returns(Task.CompletedTask);

            var router = new DefaultSubscriptionEventRouter();

            var evt = new SubscriptionEvent()
            {
                SchemaTypeName = typeof(GraphSchema).FullName,
                EventName      = "bobEvent5",
                DataTypeName   = typeof(TwoPropertyObject).FullName,
                Data           = new TwoPropertyObject(),
            };

            router.AddReceiver(evt.ToSubscriptionEventName(), receiver.Object);
            await router.RaiseEvent(evt);

            receiver.Verify(x => x.ReceiveEvent(evt));
        }
        public void ApolloServerSubscriptionEventReceived_PropertyCheck()
        {
            var router = new Mock <ISubscriptionEventRouter>();
            var server = new ApolloSubscriptionServer <GraphSchema>(
                new GraphSchema(),
                new SubscriptionServerOptions <GraphSchema>(),
                router.Object);

            var eventData = new SubscriptionEvent()
            {
                Id             = "id1",
                SchemaTypeName = "schema1",
                EventName      = "event1",
                DataTypeName   = "data1",
                Data           = new object(),
            };

            var connection = new Mock <IClientConnection>();
            var proxy      = new ApolloClientProxy <GraphSchema>(
                connection.Object,
                new SubscriptionServerOptions <GraphSchema>(),
                new AspNet.Apollo.Messages.Converters.ApolloMessageConverterFactory());

            var clients = new List <ApolloClientProxy <GraphSchema> >();

            clients.Add(proxy);

            var entry = new ApolloServerSubscriptionEventReceived <GraphSchema>(
                server,
                eventData,
                clients);

            Assert.AreEqual(eventData.SchemaTypeName, entry.SchemaTypeName);
            Assert.AreEqual(eventData.EventName, entry.SubscriptionEventName);
            Assert.AreEqual(1, entry.ClientCount);
            Assert.AreEqual("id1", entry.SubscriptionEventId);
            CollectionAssert.AreEquivalent(clients.Select(x => x.Id).ToList(), entry.ClientIds);
            Assert.AreEqual(server.Id, entry.ServerId);
            Assert.AreNotEqual(entry.GetType().Name, entry.ToString());
        }
예제 #28
0
        public override async Task <int> UpdateLastConsumedSubscriptionEvent(SubscriptionEvent subscriptionEvent)
        {
            var query = "MERGE LastConsumedSubscriptionEvent AS target" +
                        " USING(SELECT @subscriptionId, @functionalKey) as source(SubscriptionId, FunctionalKey)" +
                        " ON(target.SubscriptionId = source.SubscriptionId AND target.FunctionalKey = source.FunctionalKey)" +
                        " WHEN MATCHED THEN UPDATE SET PublicationDateUtc = @publicationDateUtc" +
                        " WHEN NOT MATCHED THEN INSERT(SubscriptionId, FunctionalKey, PublicationDateUtc) VALUES(source.SubscriptionId, source.FunctionalKey, @publicationDateUtc);";

            try
            {
                return(await TranExecuteAsync(query, new Dictionary <string, object>
                {
                    { "@subscriptionId", subscriptionEvent.SubscriptionId },
                    { "@functionalKey", subscriptionEvent.FunctionalKey },
                    { "@publicationDateUtc", subscriptionEvent.PublicationDateUtc },
                }).ConfigureAwait(false));
            }
            catch (DbException dbEx)
            {
                throw new RepoException(dbEx);
            }
        }
예제 #29
0
        /// <summary>
        /// Raises a new event in a manner such that a compatible <see cref="ISubscriptionEventRouter" /> could
        /// receive it for processing.
        /// </summary>
        /// <param name="eventData">The event to publish.</param>
        /// <returns>Task.</returns>
        public async Task PublishEvent(SubscriptionEvent eventData)
        {
            Validation.ThrowIfNull(eventData, nameof(eventData));

            await using (ServiceBusClient sbClient = new ServiceBusClient(_cnnString))
            {
                var sender = sbClient.CreateSender(_topic);

                // Serialization of data objects (those contained within the event)
                // can be complex. There is no one correct method for data object serialization
                // and you'll likely need to write your own converters to facilitate the process
                var serializedData = JsonSerializer.Serialize(
                    eventData,
                    typeof(SubscriptionEvent),
                    _serializationOptions);

                var message = new ServiceBusMessage(serializedData);
                await sender.SendMessageAsync(message);

                _logger?.LogDebug($"ASB Message Published: Topic: {_topic}");
            }
        }
예제 #30
0
 private void OnSubscriptionEvent(SubscriptionEvent obj)
 {
     if (obj.Payload.Subjects.Any())
     {
         if (m_Socket != null && m_Socket.Connected)
         {
             Send(Encoding.ASCII.GetBytes(obj.Payload.Subjects[0].Value));
             if (LoggingLevel == 1)
             {
                 OnLogWriteEntry(EventLogEntryCodes.SocketClientSending, new string[] { string.Empty });
             }
             else if (LoggingLevel == 2)
             {
                 OnLogWriteEntry(EventLogEntryCodes.SocketClientSending, new string[] { obj.Payload.Subjects[0].Value });
             }
         }
         else
         {
             m_MessageBuffer.Enqueue(obj.Payload.Subjects[0].Value, obj.Payload.TimeToLive);
         }
     }
 }
예제 #31
0
 public override int OnSubscriptionEvent(SubscriptionEvent e)
 {
     switch (e.getType())
     {
         case tsip_subscribe_event_type_t.tsip_i_notify:
             String ev = e.getSipMessage().getSipHeaderValue("Event");
             Console.WriteLine("Event=%s", ev);
             break;
         default:
             break;
     }
     return base.OnSubscriptionEvent(e);
 }