Пример #1
0
        public async Task <IActionResult> Post()
        {
            string       response = string.Empty;
            const string SmsDeliveryReportEvent = "Microsoft.Communication.SMSDeliveryReportReceived";
            string       requestContent         = await new StreamReader(Request.Body).ReadToEndAsync();

            _logger.LogInformation($"Received events: {requestContent}");

            EventGridSubscriber eventGridSubscriber = new EventGridSubscriber();

            eventGridSubscriber.AddOrUpdateCustomEventMapping(SmsDeliveryReportEvent, typeof(SmsDeliveryReportEventData));
            EventGridEvent[] eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestContent);

            foreach (EventGridEvent eventGridEvent in eventGridEvents)
            {
                if (eventGridEvent.Data is SubscriptionValidationEventData eventData)
                {
                    _logger.LogInformation($"Got SubscriptionValidation event data, validation code: {eventData.ValidationCode}, topic: {eventGridEvent.Topic}");
                    // Do any additional validation (as required) and then return back the below response

                    var responseData = new SubscriptionValidationResponse()
                    {
                        ValidationResponse = eventData.ValidationCode
                    };
                    return(new OkObjectResult(responseData));
                }
                else if (eventGridEvent.Data is SmsDeliveryReportEventData deliveryReportEventData)
                {
                    _logger.LogInformation($"Got SmsDeliveryReport event data, messageId: {deliveryReportEventData.MessageId}, DeliveryStatus: {deliveryReportEventData.DeliveryStatus}");
                    return(new OkObjectResult(deliveryReportEventData.MessageId));
                }
            }
            return(new OkObjectResult(response));
        }
        public async Task <IActionResult> ReceiveEvents()
        {
            using var reader = new StreamReader(Request.Body, Encoding.UTF8);
            string requestContent = await reader.ReadToEndAsync().ConfigureAwait(false);

            logger.LogInformation($"Received events: {requestContent}");

            var eventGridSubscriber = new EventGridSubscriber();

            foreach (var key in acceptedEventTypes.Keys)
            {
                eventGridSubscriber.AddOrUpdateCustomEventMapping(key, typeof(EventGridEventData));
            }

            var eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestContent);

            foreach (var eventGridEvent in eventGridEvents)
            {
                if (!Guid.TryParse(eventGridEvent.Id, out Guid eventId))
                {
                    throw new InvalidDataException($"Invalid Guid for EventGridEvent.Id '{eventGridEvent.Id}'");
                }

                if (eventGridEvent.Data is SubscriptionValidationEventData subscriptionValidationEventData)
                {
                    logger.LogInformation($"Got SubscriptionValidation event data, validationCode: {subscriptionValidationEventData!.ValidationCode},  validationUrl: {subscriptionValidationEventData.ValidationUrl}, topic: {eventGridEvent.Topic}");

                    // Do any additional validation (as required) such as validating that the Azure resource ID of the topic matches
                    // the expected topic and then return back the below response
                    var responseData = new SubscriptionValidationResponse()
                    {
                        ValidationResponse = subscriptionValidationEventData.ValidationCode,
                    };

                    return(Ok(responseData));
                }
                else if (eventGridEvent.Data is EventGridEventData eventGridEventData)
                {
                    if (!Guid.TryParse(eventGridEventData.ItemId, out Guid contentId))
                    {
                        throw new InvalidDataException($"Invalid Guid for EventGridEvent.Data.ItemId '{eventGridEventData.ItemId}'");
                    }

                    var cacheOperation = acceptedEventTypes[eventGridEvent.EventType];

                    logger.LogInformation($"Got Event Id: {eventId}: {eventGridEvent.EventType}: Cache operation: {cacheOperation} {eventGridEventData.Api}");

                    var result = await webhookService.ProcessMessageAsync(cacheOperation, eventId, contentId, eventGridEventData.Api).ConfigureAwait(false);

                    LogResult(eventId, contentId, result);
                }
                else
                {
                    throw new InvalidDataException($"Invalid event type '{eventGridEvent.EventType}' received for Event Id: {eventId}, should be one of '{string.Join(",", acceptedEventTypes.Keys)}'");
                }
            }

            return(Ok());
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"C# HTTP trigger function begun");
            string response = string.Empty;

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            log.LogInformation($"Received events: {requestBody}");

            EventGridSubscriber eventGridSubscriber = new EventGridSubscriber();

            eventGridSubscriber.AddOrUpdateCustomEventMapping("eventTypeSms", typeof(SmsContent));

            EventGridEvent[] eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestBody);

            List <string> outputs = new List <string>();

            foreach (EventGridEvent eventGridEvent in eventGridEvents)
            {
                if (eventGridEvent.Data is SmsContent)
                {
                    var eventData = (SmsContent)eventGridEvent.Data;
                    log.LogInformation($"Got SubscriptionValidation event data, data: '{eventData}', topic: {eventGridEvent.Topic}");

                    outputs.Add(eventData.ToString());
                }

                // NEEDED TO SUBSCRIBE OUR WEBHOOK
                if (eventGridEvent.Data is SubscriptionValidationEventData)
                {
                    var eventData = (SubscriptionValidationEventData)eventGridEvent.Data;
                    log.LogInformation($"Got SubscriptionValidation event data, validation code: {eventData.ValidationCode}, topic: {eventGridEvent.Topic}");
                    // Do any additional validation (as required) and then return back the below response

                    var responseData = new SubscriptionValidationResponse()
                    {
                        ValidationResponse = eventData.ValidationCode
                    };

                    return(new OkObjectResult(responseData));
                }
            }

            return(new OkObjectResult(outputs));
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"C# HTTP trigger function begun");
            string       response         = string.Empty;
            const string CustomTopicEvent = "Contoso.Items.ItemReceived";

            string requestContent = await req.Content.ReadAsStringAsync();

            log.Info($"Received events: {requestContent}");

            EventGridSubscriber eventGridSubscriber = new EventGridSubscriber();

            eventGridSubscriber.AddOrUpdateCustomEventMapping(CustomTopicEvent, typeof(ContosoItemReceivedEventData));
            EventGridEvent[] eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestContent);

            foreach (EventGridEvent eventGridEvent in eventGridEvents)
            {
                if (eventGridEvent.Data is SubscriptionValidationEventData)
                {
                    var eventData = (SubscriptionValidationEventData)eventGridEvent.Data;
                    log.Info($"Got SubscriptionValidation event data, validationCode: {eventData.ValidationCode},  validationUrl: {eventData.ValidationUrl}, topic: {eventGridEvent.Topic}");
                    // Do any additional validation (as required) such as validating that the Azure resource ID of the topic matches
                    // the expected topic and then return back the below response
                    var responseData = new SubscriptionValidationResponse()
                    {
                        ValidationResponse = eventData.ValidationCode
                    };

                    return(req.CreateResponse(HttpStatusCode.OK, responseData));
                }
                else if (eventGridEvent.Data is StorageBlobCreatedEventData)
                {
                    var eventData = (StorageBlobCreatedEventData)eventGridEvent.Data;
                    log.Info($"Got BlobCreated event data, blob URI {eventData.Url}");
                }
                else if (eventGridEvent.Data is ContosoItemReceivedEventData)
                {
                    var eventData = (ContosoItemReceivedEventData)eventGridEvent.Data;
                    log.Info($"Got ContosoItemReceived event data, item SKU {eventData.ItemSku}");
                }
            }

            return(req.CreateResponse(HttpStatusCode.OK, response));
        }
Пример #5
0
        public static IEnumerable <T> Parse <T>(HttpRequestMessage request)
        {
            string requestContent = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            EventGridSubscriber eventGridSubscriber = new EventGridSubscriber();

            eventGridSubscriber.AddOrUpdateCustomEventMapping(typeof(T).FullName, typeof(T));
            EventGridEvent[] eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestContent);

            foreach (EventGridEvent eventGridEvent in eventGridEvents)
            {
                if (eventGridEvent.Data is SubscriptionValidationEventData)
                {
                    var eventData = (SubscriptionValidationEventData)eventGridEvent.Data;
                }
                else if (eventGridEvent.Data.GetType() == typeof(T))
                {
                    yield return((T)eventGridEvent.Data);
                }
            }
        }
Пример #6
0
        public WebhookRequestModel ExtractEvent(string requestBody)
        {
            var webhookRequestModel = new WebhookRequestModel();

            logger.LogInformation($"Received events: {requestBody}");

            var eventGridSubscriber = new EventGridSubscriber();

            foreach (var key in acceptedEventTypes.Keys)
            {
                eventGridSubscriber.AddOrUpdateCustomEventMapping(key, typeof(EventGridEventData));
            }

            var eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestBody);

            foreach (var eventGridEvent in eventGridEvents)
            {
                if (!Guid.TryParse(eventGridEvent.Id, out Guid eventId))
                {
                    throw new InvalidDataException($"Invalid Guid for EventGridEvent.Id '{eventGridEvent.Id}'");
                }

                if (eventGridEvent.Data is SubscriptionValidationEventData subscriptionValidationEventData)
                {
                    logger.LogInformation($"Got SubscriptionValidation event data, validationCode: {subscriptionValidationEventData!.ValidationCode},  validationUrl: {subscriptionValidationEventData.ValidationUrl}, topic: {eventGridEvent.Topic}");

                    webhookRequestModel.WebhookCommand = WebhookCommand.SubscriptionValidation;
                    webhookRequestModel.SubscriptionValidationResponse = new SubscriptionValidationResponse()
                    {
                        ValidationResponse = subscriptionValidationEventData.ValidationCode,
                    };

                    return(webhookRequestModel);
                }
                else if (eventGridEvent.Data is EventGridEventData eventGridEventData)
                {
                    if (!Guid.TryParse(eventGridEventData.ItemId, out Guid contentId))
                    {
                        throw new InvalidDataException($"Invalid Guid for EventGridEvent.Data.ItemId '{eventGridEventData.ItemId}'");
                    }

                    if (!Uri.TryCreate(eventGridEventData.Api, UriKind.Absolute, out Uri? url))
                    {
                        throw new InvalidDataException($"Invalid Api url '{eventGridEventData.Api}' received for Event Id: {eventId}");
                    }

                    var cacheOperation = acceptedEventTypes[eventGridEvent.EventType];

                    logger.LogInformation($"Got Event Id: {eventId}: {eventGridEvent.EventType}: Cache operation: {cacheOperation} {url}");

                    var messageContentType = DetermineMessageContentType(url.ToString());
                    if (messageContentType == MessageContentType.None)
                    {
                        logger.LogError($"Event Id: {eventId} got unknown message content type - {messageContentType} - {url}");
                        return(webhookRequestModel);
                    }

                    webhookRequestModel.WebhookCommand = DetermineWebhookCommand(messageContentType, cacheOperation);
                    webhookRequestModel.EventId        = eventId;
                    webhookRequestModel.EventType      = eventGridEvent.EventType;
                    webhookRequestModel.ContentId      = contentId;
                    webhookRequestModel.Url            = url;
                }
                else
                {
                    throw new InvalidDataException($"Invalid event type '{eventGridEvent.EventType}' received for Event Id: {eventId}, should be one of '{string.Join(",", acceptedEventTypes.Keys)}'");
                }
            }

            return(webhookRequestModel);
        }
Пример #7
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            // parse query parameter
            var          content          = req.Content;
            const string CustomTopicEvent = "Contoso.Items.ItemReceived";

            // Get content
            string jsonContent = await content.ReadAsStringAsync();

            log.Info($"Received Event with payload: {jsonContent}");

            EventGridSubscriber eventGridSubscriber = new EventGridSubscriber();

            eventGridSubscriber.AddOrUpdateCustomEventMapping(CustomTopicEvent, typeof(GridEvent));

            EventGridEvent[] eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(jsonContent);

            foreach (EventGridEvent eventGridEvent in eventGridEvents)
            {
                if (eventGridEvent.Data is SubscriptionValidationEventData)
                {
                    var eventData = (SubscriptionValidationEventData)eventGridEvent.Data;
                    log.Info($"Got SubscriptionValidation event data, validationCode: {eventData.ValidationCode},  validationUrl: {eventData.ValidationUrl}, topic: {eventGridEvent.Topic}");
                    // Do any additional validation (as required) such as validating that the Azure resource ID of the topic matches
                    // the expected topic and then return back the below response
                    var responseData = new SubscriptionValidationResponse()
                    {
                        ValidationResponse = eventData.ValidationCode
                    };

                    return(req.CreateResponse(HttpStatusCode.OK, responseData));
                }
                else if (eventGridEvent.Data is StorageBlobCreatedEventData)
                {
                    var eventData = (StorageBlobCreatedEventData)eventGridEvent.Data;
                    log.Info($"Got BlobCreated event data, blob URI {eventData.Url}");
                }
                else if (eventGridEvent.Data is GridEvent)
                {
                    var eventData = (GridEvent)eventGridEvent.Data;
                    ReceiveAndProcess(log, eventData).GetAwaiter().GetResult();
                    log.Info($"Got ContosoItemReceived event data, item Topic {eventData.Topic}");
                }
            }

            /*
             * IEnumerable<string> headerValues;
             * if (req.Headers.TryGetValues("Aeg-Event-Type", out headerValues))
             * {
             *  // Handle Subscription validation (Whenever you create a new subscription we send a new validation message)
             *  var validationHeaderValue = headerValues.FirstOrDefault();
             *  if (validationHeaderValue == "SubscriptionValidation")
             *  {
             *      var events = JsonConvert.DeserializeObject<GridEvent[]>(jsonContent);
             *      var code = events[0].Data["validationCode"];
             *      return req.CreateResponse(HttpStatusCode.OK,
             *      new { validationResponse = code });
             *  }
             *  // React to new messages and receive
             *  else
             *  {
             *      ReceiveAndProcess(log, JsonConvert.DeserializeObject<GridEvent[]>(jsonContent)).GetAwaiter().GetResult();
             *  }
             * }
             */
            return(jsonContent == null
            ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
            : req.CreateResponse(HttpStatusCode.OK, "Hello " + jsonContent));
        }
Пример #8
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function)] HttpRequestMessage req, TraceWriter log)
        {
            var          content          = req.Content;
            const string CustomTopicEvent = "EventGridDoc-Topic";

            string jsonContent = await content.ReadAsStringAsync();

            /*
             * jsonContent = @"[{'data':
             * {
             *  'Date1':'12/12/2018 6:11:21 PM',
             *  'Date2':null,
             *  'Event':10,
             *  'IsForce':false,
             *  'PropertyID':'10139104',
             *  'JobID': '12345'
             * },
             * 'eventTime':'12/12/2018 6:11:21 PM',
             * 'eventType':'allEvents',
             * 'id':'6d740f89-90e3-4652-9a82-1bb0117e7864',
             * 'subject':'Turn Process : JOB_AND_CONTRACTS_SUBMITTED_TO_YARDI',
             * 'topic':''
             * }]";
             *
             * jsonContent = @"[{'data':
             * {
             *  'Date1':'12/12/2018 6:11:21 PM',
             *  'Date2':null,
             *  'Event':1001,
             *  'IsForce':false,
             *  'PropertyID':'10139104'
             * },
             * 'eventTime':'12/12/2018 6:11:21 PM',
             * 'eventType':'allEvents',
             * 'id':'6d740f89-90e3-4652-9a82-1bb0117e7864',
             * 'subject':'Turn Process : ASSIGN_PROJECT_MANAGER',
             * 'topic':''
             * }]";
             */
            log.Info($"Received Event with payload: {jsonContent}");
            //CRMCall(log);
            EventGridSubscriber eventGridSubscriber = new EventGridSubscriber();

            eventGridSubscriber.AddOrUpdateCustomEventMapping(CustomTopicEvent, typeof(GridEvent <DataPayLoad>));

            EventGridEvent[] eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(jsonContent);

            foreach (EventGridEvent eventGridEvent in eventGridEvents)
            {
                if (eventGridEvent.Data is SubscriptionValidationEventData)
                {
                    var eventData = (SubscriptionValidationEventData)eventGridEvent.Data;
                    log.Info($"Got SubscriptionValidation event data, validationCode: {eventData.ValidationCode},  validationUrl: {eventData.ValidationUrl}, topic: {eventGridEvent.Topic}");
                    // Do any additional validation (as required) such as validating that the Azure resource ID of the topic matches
                    // the expected topic and then return back the below response
                    var responseData = new SubscriptionValidationResponse()
                    {
                        ValidationResponse = eventData.ValidationCode
                    };

                    return(req.CreateResponse(HttpStatusCode.OK, responseData));
                }
                else if (eventGridEvent.Data is StorageBlobCreatedEventData)
                {
                    var eventData = (StorageBlobCreatedEventData)eventGridEvent.Data;
                    log.Info($"Got BlobCreated event data, blob URI {eventData.Url}");
                }
                else if (eventGridEvent.Data is object)
                {
                    DataPayLoad tr = JsonConvert.DeserializeObject <DataPayLoad>(eventGridEvent.Data.ToString());
                    if (tr is DataPayLoad)
                    {
                        OrganizationWebProxyClient _service = CRMCall(log);
                        if (_service is OrganizationWebProxyClient)
                        {
                            Entity azrIntegrationCallEntity = new Entity(Constants.AzureIntegrationCalls.LogicalName);
                            azrIntegrationCallEntity[Constants.AzureIntegrationCalls.EventName] = tr.Event.ToString();
                            azrIntegrationCallEntity[Constants.AzureIntegrationCalls.EventData] = jsonContent;

                            azrIntegrationCallEntity.Id = _service.Create(azrIntegrationCallEntity);
                            log.Info($"Event Successfully Posted to D365 with Integration Call ID : {azrIntegrationCallEntity.Id.ToString()}");
                        }
                    }
                    log.Info($"Got ContosoItemReceived event data, item Topic {eventGridEvent.Topic}");
                }
            }


            return(jsonContent == null
            ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
            : req.CreateResponse(HttpStatusCode.OK, "Hello " + jsonContent));
        }