Stream GridEventHandler(Stream input)
        {
            // Check Auth and return immediately if no valid code is provided
            if (!AuthorizedRequest(WebOperationContext.Current))
            {
                Console.WriteLine("Received unauthorized request");
                return(UnauthorizedStream(WebOperationContext.Current));
            }

            string body = new StreamReader(input).ReadToEnd();

            PrintRequest(WebOperationContext.Current, body);

            AzureEventGridEvent[] events = AzureEventGridEvent.DeserializeAzureEventGridEvents(body);

            // If event received is a SubscriptionValidationEvent, handle it appropriately
            if (events.Length == 1 && events[0].EventType == "Microsoft.EventGrid.SubscriptionValidationEvent")
            {
                // For a validation event, return the cookie embedded in the data.validationCode field.
                return(ValidationResponseStream(WebOperationContext.Current, events[0]));
            }

            // For any event which is not a SubscriptionValidateEvent, just return 200 - Got It
            return(GotItStream(WebOperationContext.Current));
        }
        Stream ValidationResponseStream(WebOperationContext ctx, AzureEventGridEvent validationEvent)
        {
            string validationCode = (string)((JObject)validationEvent.Data)["validationCode"];

            ctx.OutgoingResponse.ContentType = "application/json";
            string responseBody = "{\"validationResponse\": \"" + validationCode + "\"}";
            Stream output       = new MemoryStream(Encoding.UTF8.GetBytes(responseBody));

            output.Position = 0;
            return(output);
        }