public async Task <ActionResult> GetRecordingFile([FromBody] object request) { try { var httpContent = new BinaryData(request.ToString()).ToStream(); EventGridEvent cloudEvent = EventGridEvent.ParseMany(BinaryData.FromStream(httpContent)).FirstOrDefault(); if (cloudEvent.EventType == SystemEventNames.EventGridSubscriptionValidation) { var eventData = cloudEvent.Data.ToObjectFromJson <SubscriptionValidationEventData>(); Logger.LogInformation("Microsoft.EventGrid.SubscriptionValidationEvent response -- >" + cloudEvent.Data); var responseData = new SubscriptionValidationResponse { ValidationResponse = eventData.ValidationCode }; if (responseData.ValidationResponse != null) { return(Ok(responseData)); } } if (cloudEvent.EventType == SystemEventNames.AcsRecordingFileStatusUpdated) { Logger.LogInformation($"Event type is -- > {cloudEvent.EventType}"); Logger.LogInformation("Microsoft.Communication.RecordingFileStatusUpdated response -- >" + cloudEvent.Data); var eventData = cloudEvent.Data.ToObjectFromJson <AcsRecordingFileStatusUpdatedEventData>(); Logger.LogInformation("Start processing metadata -- >"); await ProcessFile(eventData.RecordingStorageInfo.RecordingChunks[0].MetadataLocation, eventData.RecordingStorageInfo.RecordingChunks[0].DocumentId, FileFormat.Json, FileDownloadType.Metadata); Logger.LogInformation("Start processing recorded media -- >"); await ProcessFile(eventData.RecordingStorageInfo.RecordingChunks[0].ContentLocation, eventData.RecordingStorageInfo.RecordingChunks[0].DocumentId, string.IsNullOrWhiteSpace(recFileFormat)?FileFormat.Mp4 : recFileFormat, FileDownloadType.Recording); } return(Ok()); } catch (Exception ex) { return(Json(new { Exception = ex })); } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("IoT Hub Device connection status."); BinaryData events = await BinaryData.FromStreamAsync(req.Body); EventGridEvent[] eventGridEvents = EventGridEvent.ParseMany(events); foreach (EventGridEvent eventGridEvent in eventGridEvents) { // Handle system events if (eventGridEvent.TryGetSystemEventData(out object eventData)) { // Handle the subscription validation event if (eventData is SubscriptionValidationEventData subscriptionValidationEventData) { log.LogInformation($"Got SubscriptionValidation event data, validation code: {subscriptionValidationEventData.ValidationCode}, topic: {eventGridEvent.Topic}"); // Do any additional validation (as required) and then return back the below response var responseData = new SubscriptionValidationResponse() { ValidationResponse = subscriptionValidationEventData.ValidationCode }; return(new OkObjectResult(responseData)); } } var data = eventGridEvent.Data.ToString(); // "data": { // "deviceConnectionStateEventInfo": { // "sequenceNumber": "000000000000000001D4132452F67CE200000002000000000000000000000001" // }, // "hubName": "townbroadcast-hub", // "deviceId": "LogicAppTestDevice" // } log.LogInformation($"eventGridEvent.Data: {eventGridEvent.Data.ToString()}"); var eventdata = JsonConvert.DeserializeObject <EventGridData>(data); log.LogInformation($"{eventdata.deviceId} is {(eventGridEvent.EventType == "Microsoft.Devices.DeviceConnected" ? "Connected" : "Disconnected")}"); switch (eventGridEvent.EventType) { case "Microsoft.Devices.DeviceDisconnected": break; case "Microsoft.Devices.DeviceConnected": break; } } return(new OkObjectResult("")); }
public void NonGenericReceiveAndDeserializeEventGridEvents() { var httpContent = new BinaryData(jsonPayloadSampleOne).ToStream(); #region Snippet:EGEventParseJson // Parse the JSON payload into a list of events EventGridEvent[] egEvents = EventGridEvent.ParseMany(BinaryData.FromStream(httpContent)); #endregion // Iterate over each event to access event properties and data #region Snippet:DeserializePayloadUsingAsSystemEventData foreach (EventGridEvent egEvent in egEvents) { // If the event is a system event, TryGetSystemEventData will return the deserialized system event if (egEvent.TryGetSystemEventData(out object systemEvent)) { switch (systemEvent) { case SubscriptionValidationEventData subscriptionValidated: Console.WriteLine(subscriptionValidated.ValidationCode); break; case StorageBlobCreatedEventData blobCreated: Console.WriteLine(blobCreated.BlobType); break; // Handle any other system event type default: Console.WriteLine(egEvent.EventType); // we can get the raw Json for the event using Data Console.WriteLine(egEvent.Data.ToString()); break; } } else { switch (egEvent.EventType) { case "MyApp.Models.CustomEventType": TestPayload deserializedEventData = egEvent.Data.ToObjectFromJson <TestPayload>(); Console.WriteLine(deserializedEventData.Name); break; // Handle any other custom event type default: Console.Write(egEvent.EventType); Console.WriteLine(egEvent.Data.ToString()); break; } } } #endregion }
public void HandleEventGridNotification(string data) { var events = EventGridEvent.ParseMany(new BinaryData(data)); foreach (EventGridEvent eventGridEvent in events) { if (eventGridEvent.TryGetSystemEventData(out object systemData) && systemData is AppConfigurationKeyValueModifiedEventData valueModifiedEventData) { SharedConfigurationClient.UpdateSyncToken(valueModifiedEventData.SyncToken); Response <ConfigurationSetting> updatedSetting = SharedConfigurationClient.GetConfigurationSetting(valueModifiedEventData.Key, valueModifiedEventData.Label); Console.WriteLine($"Setting was updated. Key: {updatedSetting.Value.Key} Value: {updatedSetting.Value.Value}"); } } }
/// <summary> /// Validates Azure event subscription and calls the appropriate event handler. Responds HttpOk. /// </summary> /// <param name="request">HttpRequest received from Azure</param> /// <param name="eventTypeHandlers">Dictionary of eventType strings and their associated handlers.</param> /// <returns>OkObjectResult</returns> /// <remarks>Reference https://docs.microsoft.com/en-us/azure/event-grid/receive-events</remarks> public async static Task <ObjectResult> HandleAzureEvents(HttpRequest request, Dictionary <string, Func <EventGridEvent, Task> > eventTypeHandlers) { var queryKey = request.Query["key"]; if (!CoreHelpers.FixedTimeEquals(queryKey, EventGridKey)) { return(new UnauthorizedObjectResult("Authentication failed. Please use a valid key.")); } var response = string.Empty; var requestData = await BinaryData.FromStreamAsync(request.Body); var eventGridEvents = EventGridEvent.ParseMany(requestData); foreach (var eventGridEvent in eventGridEvents) { if (eventGridEvent.TryGetSystemEventData(out object systemEvent)) { if (systemEvent is SubscriptionValidationEventData eventData) { // Might want to enable additional validation: subject, topic etc. var responseData = new SubscriptionValidationResponse() { ValidationResponse = eventData.ValidationCode }; return(new OkObjectResult(responseData)); } } if (eventTypeHandlers.ContainsKey(eventGridEvent.EventType)) { await eventTypeHandlers[eventGridEvent.EventType](eventGridEvent); } } return(new OkObjectResult(response)); }