Last active
April 20, 2022 12:58
-
-
Save for-shariq/210008366dd9bf1686b286192989bc60 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Azure.EventGrid; | |
using Microsoft.Azure.EventGrid.Models; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
namespace EventGridPublisher | |
{ | |
public class ApplicationSettings | |
{ | |
public string TopicEndpoint { get; set; } | |
public string TopicId { get; set; } | |
public string TopicName { get; set; } | |
} | |
public class Employee | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
public string Email { get; set; } | |
} | |
class Program | |
{ | |
public static IConfigurationRoot Configuration { get; set; } | |
static void Main(string[] args) | |
{ | |
var devEnvironmentVariable = Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT"); | |
var isDevelopment = string.IsNullOrEmpty(devEnvironmentVariable) || | |
devEnvironmentVariable.ToLower() == "development"; | |
var builder = new ConfigurationBuilder() | |
.SetBasePath(Directory.GetCurrentDirectory()) | |
.AddJsonFile("appsetting.json", optional: true, reloadOnChange: true); | |
//only add secrets in development | |
if (isDevelopment) | |
{ | |
builder.AddUserSecrets<Program>(); | |
} | |
Configuration = builder.Build(); | |
var topicEndpoint = Configuration["ApplicationSettings:TopicEndpoint"]; | |
string topicKey = Configuration["ApplicationSettings:TopicKey"]; | |
string topicHostname = new Uri(topicEndpoint).Host; | |
TopicCredentials topicCredentials = new TopicCredentials(topicKey); | |
EventGridClient client = new EventGridClient(topicCredentials); | |
client.PublishEventsAsync(topicHostname, GetEventsList()).GetAwaiter().GetResult(); | |
Console.Write("Published events to Event Grid topic."); | |
Console.ReadLine(); | |
} | |
static IList<EventGridEvent> GetEventsList() | |
{ | |
List<EventGridEvent> eventsList = new List<EventGridEvent>(); | |
for (int i = 0; i < 1; i++) | |
{ | |
eventsList.Add(new EventGridEvent() | |
{ | |
Id = Guid.NewGuid().ToString(), | |
EventType = "EmployeeAdded", | |
Data = new Employee() | |
{ | |
Id = 1, | |
Name = "Shariq Nasir", | |
Email = "forshariq@gmail.com" | |
}, | |
EventTime = DateTime.Now, | |
Subject = "Department/Engineering", | |
DataVersion = "2.0" | |
}); | |
} | |
return eventsList; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Azure.EventGrid; | |
using Microsoft.Azure.EventGrid.Models; | |
using Microsoft.Azure.WebJobs; | |
using Microsoft.Azure.WebJobs.Extensions.Http; | |
using Microsoft.Extensions.Logging; | |
using Newtonsoft.Json; | |
using System.Net; | |
using System.Net.Http; | |
using System.Net.Http.Formatting; | |
using System.Threading.Tasks; | |
namespace EmployeeSubscriber | |
{ | |
public static class NewEmployeeHandler | |
{ | |
public class Employee | |
{ | |
public int Id { get; set; } | |
[JsonProperty(PropertyName = "name")] | |
public string Name { get; set; } | |
public string Email { get; set; } | |
} | |
[FunctionName("newemployeehandler")] | |
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log) | |
{ | |
log.LogInformation($"C# HTTP trigger function begun"); | |
string response = string.Empty; | |
const string CustomTopicEvent = "https://hrapplicationtopic.eastus-1.eventgrid.azure.net/api/events"; | |
string requestContent = await req.Content.ReadAsStringAsync(); | |
log.LogInformation($"Received events: {requestContent}"); | |
EventGridSubscriber eventGridSubscriber = new EventGridSubscriber(); | |
eventGridSubscriber.AddOrUpdateCustomEventMapping(CustomTopicEvent, typeof(Employee)); | |
EventGridEvent[] eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestContent); | |
foreach (EventGridEvent eventGridEvent in eventGridEvents) | |
{ | |
if (eventGridEvent.Data is SubscriptionValidationEventData) | |
{ | |
var eventData = (SubscriptionValidationEventData)eventGridEvent.Data; | |
log.LogInformation($"Got SubscriptionValidation event data, validationCode: {eventData.ValidationCode}, validationUrl: {eventData.ValidationUrl}, topic: {eventGridEvent.Topic}, eventType: { eventGridEvent.EventType}"); | |
// 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 | |
}; | |
///log.LogInformation($"Echo response: {JsonConvert.SerializeObject(req.CreateResponse(HttpStatusCode.OK, responseData))}"); | |
//return req.CreateResponse(HttpStatusCode.OK, responseData); | |
return req.CreateResponse(HttpStatusCode.OK, new { validationResponse = responseData.ValidationResponse }, | |
new JsonMediaTypeFormatter()); | |
} | |
else if (eventGridEvent.Data is StorageBlobCreatedEventData) | |
{ | |
var eventData = (StorageBlobCreatedEventData)eventGridEvent.Data; | |
log.LogInformation($"Got BlobCreated event data, blob URI {eventData.Url}"); | |
} | |
else if (eventGridEvent.Data is Employee) | |
{ | |
var eventData = (Employee)eventGridEvent.Data; | |
log.LogInformation($"Got Employee event data {eventData.Name}"); | |
} | |
} | |
return req.CreateResponse(HttpStatusCode.OK, response); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment