Skip to content

Commit

Permalink
feat: Add dockerized event webhook consumer example (#812)
Browse files Browse the repository at this point in the history
  • Loading branch information
KoditkarVedant committed Aug 3, 2020
1 parent e2e18f2 commit 11fbf1e
Show file tree
Hide file tree
Showing 33 changed files with 1,225 additions and 0 deletions.
21 changes: 21 additions & 0 deletions examples/eventwebhook/consumer/Dockerfile
@@ -0,0 +1,21 @@
FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /App

# copy csproj and restore as distinct layers
COPY *.sln .
COPY Src/EventWebhook/*.csproj ./Src/EventWebhook/
COPY Tests/EventWebhook.Tests/*.csproj ./Tests/EventWebhook.Tests/
RUN dotnet restore

# copy everything else and build app
COPY Src/EventWebhook/. ./Src/EventWebhook/
WORKDIR /App/Src/EventWebhook
RUN dotnet publish -c Release -o Out

FROM microsoft/dotnet:2.1-aspnetcore-runtime AS runtime
WORKDIR /App
COPY --from=build /App/Src/EventWebhook/Out ./

RUN echo "ASPNETCORE_URLS=http://0.0.0.0:\$PORT\nDOTNET_RUNNING_IN_CONTAINER=true" > /App/SetupHerokuEnv.sh && chmod +x /App/SetupHerokuEnv.sh

CMD /bin/bash -c "source /App/SetupHerokuEnv.sh && dotnet EventWebhook.dll"
99 changes: 99 additions & 0 deletions examples/eventwebhook/consumer/README.md
@@ -0,0 +1,99 @@
# sendgrid-events-webhook-consumer
This is dockerized SendGrid Event webhook consumer.
# Overview

SendGrid has an [Event Webhook](https://sendgrid.com/docs/API_Reference/Event_Webhook/event.html) which posts events related to your email activity to a URL of your choice. This is an easily deployable solution that allows for customers to easiy get up and running processing (parse and save) their event webhooks.

This is docker-based solution which can be deployed on cloud services like Heroku out of the box.

# Table of Content
- [Prerequisite](#prerequisite)
- [Deploy locally](#deploy_locally)
- [Deploy Heroku](#deploy_heroku)
- [Testing the Source Code](#testing_the_source_code)

<a name="prerequisite"></a>
## Prerequisite

Clone the repository
```
git clone https://github.com/sendgrid/sendgrid-csharp.git
```

Move into the clonned repository
```
cd sendgrid-csharp/examples/eventwebhook/consumer
```

Restore the Packages
```
dotnet restore
```

<a name="deploy_locally"></a>
## Deploy locally
Setup your MX records. Depending on your domain name host, you may need to wait up to 48 hours for the settings to propagate.

Run the Event Webhook Parse listener in your terminal:
```
git clone https://github.com/sendgrid/sendgrid-csharp.git
cd sendgrid-csharp/examples/eventwebhook/consumer
dotnet restore
dotnet run --project .\Src\EventWebhook\EventWebhook.csproj
```
Above will start server listening on a random port like below

In another terminal, use ngrok to allow external access to your machine:
```
ngrok http PORT_NUMBER
```

You can use setup the Event Webhook please refer [this](https://sendgrid.com/docs/API_Reference/Event_Webhook/getting_started_event_webhook.html#-Getting-started)

<a name="deploy_heroku"></a>
## Deploy to Heroku

[Create](https://signup.heroku.com/) Heruko account if not already present

Install the Heroku CLI

Download and install the [Heroku CLI](https://devcenter.heroku.com/articles/heroku-command-line).

If you haven't already, log in to your Heroku account and follow the prompts to create a new SSH public key.
```
$ heroku login
```

Now you can sign into Container Registry.
```
$ heroku container:login
```

Create app in heroku
```
$ heroku apps:create UNIQUE_APP_NAME
```

Create docker image
```
$ docker image -t DOCKER_IMAGE_NAME .
```

Push your Docker-based app
Build the Dockerfile in the current directory and push the Docker image.
```
$ heroku container:push web --app UNIQUE_APP_NAME
```

Deploy the changes
Release the newly pushed images to deploy your app.
```
$ heroku container:release web --app UNIQUE_APP_NAME
```

<a name="testing_the_source_code"></a>
## Testing the Source Code
You can get all the test cases inside the `Tests` folder.
56 changes: 56 additions & 0 deletions examples/eventwebhook/consumer/SendGridEventWebhookConsumer.sln
@@ -0,0 +1,56 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26124.0
MinimumVisualStudioVersion = 15.0.26124.0
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Src", "Src", "{B08185CF-3F2E-4638-877B-587F5F60CA74}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventWebhook", "Src\EventWebhook\EventWebhook.csproj", "{3897C29A-AE26-4FE5-8421-71896EC935C5}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{81CAC535-9854-47AD-9D3E-385AC2668C35}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventWebhook.Tests", "Tests\EventWebhook.Tests\EventWebhook.Tests.csproj", "{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Debug|x64.ActiveCfg = Debug|Any CPU
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Debug|x64.Build.0 = Debug|Any CPU
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Debug|x86.ActiveCfg = Debug|Any CPU
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Debug|x86.Build.0 = Debug|Any CPU
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Release|Any CPU.Build.0 = Release|Any CPU
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Release|x64.ActiveCfg = Release|Any CPU
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Release|x64.Build.0 = Release|Any CPU
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Release|x86.ActiveCfg = Release|Any CPU
{3897C29A-AE26-4FE5-8421-71896EC935C5}.Release|x86.Build.0 = Release|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Debug|x64.ActiveCfg = Debug|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Debug|x64.Build.0 = Debug|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Debug|x86.ActiveCfg = Debug|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Debug|x86.Build.0 = Debug|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Release|Any CPU.Build.0 = Release|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Release|x64.ActiveCfg = Release|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Release|x64.Build.0 = Release|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Release|x86.ActiveCfg = Release|Any CPU
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{3897C29A-AE26-4FE5-8421-71896EC935C5} = {B08185CF-3F2E-4638-877B-587F5F60CA74}
{5C6AA0EB-57B7-4E76-804A-70F7A7DF4FC0} = {81CAC535-9854-47AD-9D3E-385AC2668C35}
EndGlobalSection
EndGlobal
@@ -0,0 +1,34 @@
using EventWebhook.Models;
using EventWebhook.Parser;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace EventWebhook.Controllers
{
[Route("/")]
public class EventWebhookController : Controller
{
/// <summary>
/// GET : Index page
/// </summary>
[Route("")]
public IActionResult Index()
{
return View();
}

/// <summary>
/// POST : Event webhook handler
/// </summary>
/// <returns></returns>
[Route("/events")]
[HttpPost]
public async Task<IActionResult> Events()
{
IEnumerable<Event> events = await EventParser.ParseAsync(Request.Body);

return Ok();
}
}
}
@@ -0,0 +1,50 @@
using EventWebhook.Models;
using Newtonsoft.Json;
using System;
using System.Linq;

namespace EventWebhook.Converters
{
public class CategoryConverter : JsonConverter
{
private readonly Type[] _types;

public CategoryConverter()
{
_types = new Type[] { typeof(string), typeof(string[]) };
}

public override bool CanConvert(Type objectType)
{
return _types.Any(t => t == objectType);
}

public override bool CanWrite => true;

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartArray)
{
return new Category(serializer.Deserialize<string[]>(reader), JsonToken.StartArray);
}
else
{
return new Category(new[] { serializer.Deserialize<string>(reader) }, reader.TokenType);
}
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is Category category)
{
if (category.IsArray)
{
serializer.Serialize(writer, category);
} else
{
serializer.Serialize(writer, category.Value[0]);
}
}
}
}
}
@@ -0,0 +1,40 @@
using Newtonsoft.Json;
using System;

namespace EventWebhook.Converters
{
public class UriConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => objectType == typeof(string);

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}

if (reader.TokenType == JsonToken.String)
{
return new Uri((string)reader.Value);
}

throw new InvalidOperationException("Invalid Url");
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (null == value)
{
writer.WriteNull();
return;
}

if (value is Uri)
{
writer.WriteValue(((Uri)value).OriginalString);
return;
}
}
}
}
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Folder Include="Util\" />
<Folder Include="wwwroot\" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.1" />
</ItemGroup>

</Project>
@@ -0,0 +1,11 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace EventWebhook.Models
{
public class BounceEvent : DroppedEvent
{
[JsonConverter(typeof(StringEnumConverter))]
public BounceEventType BounceType { get; set; }
}
}
@@ -0,0 +1,9 @@
namespace EventWebhook.Models
{
public enum BounceEventType
{
Bounce,
Blocked,
Expired
}
}
19 changes: 19 additions & 0 deletions examples/eventwebhook/consumer/Src/EventWebhook/Models/Category.cs
@@ -0,0 +1,19 @@
using Newtonsoft.Json;

namespace EventWebhook.Models
{
public class Category
{
public string[] Value { get; }
private JsonToken _jsonToken;

public Category(string[] value, JsonToken jsonToken)
{
Value = value;
_jsonToken = jsonToken;
}

[JsonIgnore]
public bool IsArray => _jsonToken == JsonToken.StartArray;
}
}
@@ -0,0 +1,12 @@
using EventWebhook.Converters;
using Newtonsoft.Json;
using System;

namespace EventWebhook.Models
{
public class ClickEvent : OpenEvent
{
[JsonConverter(typeof(UriConverter))]
public Uri Url { get; set; }
}
}
@@ -0,0 +1,8 @@
namespace EventWebhook.Models
{
public class DeferredEvent : DeliveredEvent
{
public int Attempt { get; set; }

}
}
@@ -0,0 +1,7 @@
namespace EventWebhook.Models
{
public class DeliveredEvent : Event
{
public string Response { get; set; }
}
}

0 comments on commit 11fbf1e

Please sign in to comment.