Exemplo n.º 1
0
        /// <summary>
        /// Given JSON-encoded events, parses the event envelope and returns an array of EventGridEvents.
        /// </summary>
        /// <param name="requestContent"> The JSON-encoded representation of either a single event or an array or events, encoded in the EventGridEvent schema. </param>
        /// <returns> A list of <see cref="EventGridEvent"/>. </returns>
        public static EventGridEvent[] Parse(string requestContent)
        {
            List <EventGridEventInternal> egEventsInternal = new List <EventGridEventInternal>();
            List <EventGridEvent>         egEvents         = new List <EventGridEvent>();
            JsonDocument requestDocument = JsonDocument.Parse(requestContent);

            // Parse JsonElement into separate events, deserialize event envelope properties
            if (requestDocument.RootElement.ValueKind == JsonValueKind.Object)
            {
                egEventsInternal.Add(EventGridEventInternal.DeserializeEventGridEventInternal(requestDocument.RootElement));
            }
            else if (requestDocument.RootElement.ValueKind == JsonValueKind.Array)
            {
                foreach (JsonElement property in requestDocument.RootElement.EnumerateArray())
                {
                    egEventsInternal.Add(EventGridEventInternal.DeserializeEventGridEventInternal(property));
                }
            }

            foreach (EventGridEventInternal egEventInternal in egEventsInternal)
            {
                egEvents.Add(new EventGridEvent(egEventInternal));
            }

            return(egEvents.ToArray());
        }
Exemplo n.º 2
0
        /// <summary> Publishes a batch of EventGridEvents to an Azure Event Grid topic. </summary>
        /// <param name="events"> An array of events to be published to Event Grid. </param>
        /// <param name="async">Whether to invoke the operation asynchronously.</param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        private async Task <Response> PublishEventsInternal(IEnumerable <EventGridEvent> events, bool async, CancellationToken cancellationToken = default)
        {
            using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(EventGridPublisherClient)}.{nameof(SendEvents)}");
            scope.Start();

            try
            {
                // List of events cannot be null
                Argument.AssertNotNull(events, nameof(events));

                List <EventGridEventInternal> eventsWithSerializedPayloads = new List <EventGridEventInternal>();
                foreach (EventGridEvent egEvent in events)
                {
                    // Individual events cannot be null
                    Argument.AssertNotNull(egEvent, nameof(egEvent));

                    MemoryStream stream = new MemoryStream();
                    _dataSerializer.Serialize(stream, egEvent.Data, egEvent.Data.GetType(), cancellationToken);
                    stream.Position = 0;
                    JsonDocument data = JsonDocument.Parse(stream);

                    EventGridEventInternal newEGEvent = new EventGridEventInternal(
                        egEvent.Id,
                        egEvent.Subject,
                        data.RootElement,
                        egEvent.EventType,
                        egEvent.EventTime,
                        egEvent.DataVersion)
                    {
                        Topic = egEvent.Topic
                    };

                    eventsWithSerializedPayloads.Add(newEGEvent);
                }
                if (async)
                {
                    // Publish asynchronously if called via an async path
                    return(await _serviceRestClient.PublishEventsAsync(
                               _hostName,
                               eventsWithSerializedPayloads,
                               cancellationToken).ConfigureAwait(false));
                }
                else
                {
                    return(_serviceRestClient.PublishEvents(
                               _hostName,
                               eventsWithSerializedPayloads,
                               cancellationToken));
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Given a single JSON-encoded event, parses the event envelope and returns an EventGridEvent.
        /// </summary>
        /// <param name="binaryData"> Specifies the instance of <see cref="BinaryData"/>. </param>
        /// <returns> An <see cref="EventGridEvent"/>. </returns>
        public static EventGridEvent ToEventGridEvent(this BinaryData binaryData)
        {
            // Deserialize JsonElement to single event, parse event envelope properties
            JsonDocument           requestDocument = JsonDocument.Parse(binaryData.ToMemory());
            EventGridEventInternal egEventInternal = EventGridEventInternal.DeserializeEventGridEventInternal(requestDocument.RootElement);

            EventGridEvent egEvent = new EventGridEvent(egEventInternal);

            return(egEvent);
        }
Exemplo n.º 4
0
        internal EventGridEvent(EventGridEventInternal eventGridEventInternal)
        {
            Argument.AssertNotNull(eventGridEventInternal.Subject, nameof(eventGridEventInternal.Subject));
            Argument.AssertNotNull(eventGridEventInternal.EventType, nameof(eventGridEventInternal.EventType));
            Argument.AssertNotNull(eventGridEventInternal.DataVersion, nameof(eventGridEventInternal.DataVersion));
            Argument.AssertNotNull(eventGridEventInternal.Id, nameof(eventGridEventInternal.Id));

            Subject     = eventGridEventInternal.Subject;
            EventType   = eventGridEventInternal.EventType;
            DataVersion = eventGridEventInternal.DataVersion;
            EventTime   = eventGridEventInternal.EventTime;
            Id          = eventGridEventInternal.Id;
            Topic       = eventGridEventInternal.Topic;
            Data        = new BinaryData(eventGridEventInternal.Data);
        }
        /// <inheritdoc cref="JsonConverter{EventGridEvent}.Write(Utf8JsonWriter, EventGridEvent, JsonSerializerOptions)"/>
        public override void Write(Utf8JsonWriter writer, EventGridEvent value, JsonSerializerOptions options)
        {
            JsonDocument data = JsonDocument.Parse(value.Data.ToStream());
            var          eventGridEventInternal = new EventGridEventInternal(
                value.Id,
                value.Subject,
                data.RootElement,
                value.EventType,
                value.EventTime,
                value.DataVersion)
            {
                Topic = value.Topic
            };

            ((IUtf8JsonSerializable)eventGridEventInternal).Write(writer);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Given a single JSON-encoded event, parses the event envelope and returns an EventGridEvent.
        /// </summary>
        /// <param name="binaryData"> Specifies the instance of <see cref="BinaryData"/>. </param>
        /// <returns> An <see cref="EventGridEvent"/>. </returns>
        public static EventGridEvent ToEventGridEvent(this BinaryData binaryData)
        {
            // Deserialize JsonElement to single event, parse event envelope properties
            JsonDocument           requestDocument = JsonDocument.Parse(binaryData.ToBytes());
            EventGridEventInternal egEventInternal = EventGridEventInternal.DeserializeEventGridEventInternal(requestDocument.RootElement);

            EventGridEvent egEvent = new EventGridEvent(
                egEventInternal.Data,
                egEventInternal.Subject,
                egEventInternal.EventType,
                egEventInternal.DataVersion,
                egEventInternal.EventTime,
                egEventInternal.Id);

            return(egEvent);
        }
        /// <summary>
        /// Given a single JSON-encoded event, parses the event envelope and returns an EventGridEvent.
        /// </summary>
        /// <param name="binaryData"> Specifies the instance of <see cref="BinaryData"/>. </param>
        /// <returns> An <see cref="EventGridEvent"/>. </returns>
        public static EventGridEvent ToEventGridEvent(this BinaryData binaryData)
        {
            // Deserialize JsonElement to single event, parse event envelope properties
            JsonDocument           requestDocument = JsonDocument.Parse(binaryData.Bytes);
            EventGridEventInternal egEventInternal = EventGridEventInternal.DeserializeEventGridEventInternal(requestDocument.RootElement);

            EventGridEvent egEvent = new EventGridEvent()
            {
                Subject        = egEventInternal.Subject,
                EventType      = egEventInternal.EventType,
                DataVersion    = egEventInternal.DataVersion,
                Id             = egEventInternal.Id,
                EventTime      = egEventInternal.EventTime,
                SerializedData = egEventInternal.Data
            };

            return(egEvent);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Given JSON-encoded events, parses the event envelope and returns an array of EventGridEvents.
        /// If the content is not valid JSON, or events are missing required properties, an exception is thrown.
        /// </summary>
        /// <param name="json">An instance of <see cref="BinaryData"/> containing the JSON for one or more EventGridEvents.</param>
        /// <returns> An array of <see cref="EventGridEvent"/> instances.</returns>
        public static EventGridEvent[] ParseMany(BinaryData json)
        {
            Argument.AssertNotNull(json, nameof(json));

            EventGridEvent[] egEvents = null;
            using JsonDocument requestDocument = JsonDocument.Parse(json);

            // Parse JsonElement into separate events, deserialize event envelope properties
            if (requestDocument.RootElement.ValueKind == JsonValueKind.Object)
            {
                egEvents    = new EventGridEvent[1];
                egEvents[0] = (new EventGridEvent(EventGridEventInternal.DeserializeEventGridEventInternal(requestDocument.RootElement)));
            }
            else if (requestDocument.RootElement.ValueKind == JsonValueKind.Array)
            {
                egEvents = new EventGridEvent[requestDocument.RootElement.GetArrayLength()];
                int i = 0;
                foreach (JsonElement property in requestDocument.RootElement.EnumerateArray())
                {
                    egEvents[i++] = new EventGridEvent(EventGridEventInternal.DeserializeEventGridEventInternal(property));
                }
            }
            return(egEvents ?? Array.Empty <EventGridEvent>());
        }
        private static List <EventGridEvent> DeserializeRequest(Request request)
        {
            var content = request.Content;
            var stream  = new MemoryStream();

            content.WriteTo(stream, CancellationToken.None);
            stream.Position = 0;
            JsonDocument requestDocument = JsonDocument.Parse(stream);
            var          egEvents        = new List <EventGridEvent>();

            // Parse JsonElement into separate events, deserialize event envelope properties
            if (requestDocument.RootElement.ValueKind == JsonValueKind.Object)
            {
                egEvents.Add(new EventGridEvent(EventGridEventInternal.DeserializeEventGridEventInternal(requestDocument.RootElement)));
            }
            else if (requestDocument.RootElement.ValueKind == JsonValueKind.Array)
            {
                foreach (JsonElement property in requestDocument.RootElement.EnumerateArray())
                {
                    egEvents.Add(new EventGridEvent(EventGridEventInternal.DeserializeEventGridEventInternal(property)));
                }
            }
            return(egEvents);
        }
        /// <summary>
        /// Gets or sets the serializer to use for the data portion of the <see cref="EventGridEvent"/>. If not specified,
        /// JsonObjectSerializer is used.
        /// </summary>
        /// <inheritdoc cref="JsonConverter{EventGridEvent}.Read(ref Utf8JsonReader, Type, JsonSerializerOptions)"/>
        public override EventGridEvent Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            JsonDocument requestDocument = JsonDocument.ParseValue(ref reader);

            return(new EventGridEvent(EventGridEventInternal.DeserializeEventGridEventInternal(requestDocument.RootElement)));
        }
        private async Task <EventGridEvent[]> DeserializeEventGridEventsInternal(string requestContent, bool async, CancellationToken cancellationToken = default)
        {
            List <EventGridEventInternal> egInternalEvents = new List <EventGridEventInternal>();
            List <EventGridEvent>         egEvents         = new List <EventGridEvent>();

            // Deserialize raw JSON string into separate events, deserialize event envelope properties
            JsonDocument requestDocument = await ParseJsonToDocument(requestContent, async, cancellationToken).ConfigureAwait(false);

            foreach (JsonElement property in requestDocument.RootElement.EnumerateArray())
            {
                egInternalEvents.Add(EventGridEventInternal.DeserializeEventGridEventInternal(property));
            }

            // Deserialize 'Data' property from JsonElement for each event
            foreach (EventGridEventInternal egEventInternal in egInternalEvents)
            {
                JsonElement dataElement = egEventInternal.Data;
                object      egEventData = null;

                // Reserialize JsonElement to stream
                MemoryStream dataStream = SerializePayloadToStream(dataElement, cancellationToken);

                // First, let's attempt to find the mapping for the event type in the custom event mapping.
                if (_customEventTypeMappings.TryGetValue(egEventInternal.EventType, out Type typeOfEventData))
                {
                    if (!TryGetPrimitiveFromJsonElement(dataElement, out egEventData))
                    {
                        if (async)
                        {
                            egEventData = await _dataSerializer.DeserializeAsync(dataStream, typeOfEventData, cancellationToken).ConfigureAwait(false);
                        }
                        else
                        {
                            egEventData = _dataSerializer.Deserialize(dataStream, typeOfEventData, cancellationToken);
                        }
                    }
                }
                // If a custom mapping doesn't exist, let's attempt to find the mapping for the deserialization function in the system event type mapping.
                else if (SystemEventTypeMappings.SystemEventDeserializers.TryGetValue(egEventInternal.EventType, out Func <JsonElement, object> systemDeserializationFunction))
                {
                    egEventData = systemDeserializationFunction(dataElement);
                }
                else
                {
                    // If event data is not a primitive/string, return as BinaryData
                    if (!TryGetPrimitiveFromJsonElement(dataElement, out egEventData))
                    {
                        egEventData = BinaryData.FromStream(dataStream);
                    }
                }

                egEvents.Add(new EventGridEvent(
                                 egEventInternal.Subject,
                                 egEventData,
                                 egEventInternal.EventType,
                                 egEventInternal.DataVersion)
                {
                    Id        = egEventInternal.Id,
                    EventTime = egEventInternal.EventTime
                });
            }

            return(egEvents.ToArray());
        }