Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code updates & SignalR support #40

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion Serverless/SignalR/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
{
"version": "0.2.0",
"configurations": [
"configurations":
[
{
"name": "Docker .NET Core Attach (Preview)",
"type": "docker",
"request": "attach",
"platform": "netCore",
"sourceFileMap": {
"/src": "${workspaceFolder}"
}
},
{
"name": "Attach to .NET Functions",
"type": "coreclr",
Expand Down
2 changes: 1 addition & 1 deletion Serverless/SignalR/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"azureFunctions.deploySubpath": "bin/Release/netcoreapp3.1/publish",
"azureFunctions.deploySubpath": "bin/Release/netcoreapp3.0/publish",
"azureFunctions.projectLanguage": "C#",
"azureFunctions.projectRuntime": "~3",
"debug.internalConsoleOptions": "neverOpen",
Expand Down
2 changes: 1 addition & 1 deletion Serverless/SignalR/.vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
"type": "func",
"dependsOn": "build",
"options": {
"cwd": "${workspaceFolder}/bin/Debug/netcoreapp3.1"
"cwd": "${workspaceFolder}/bin/Debug/netcoreapp3.0"
},
"command": "host start",
"isBackground": true,
Expand Down
56 changes: 20 additions & 36 deletions Serverless/SignalR/HttpGetTrigger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,54 +9,38 @@
using MongoDB.Driver;
using Newtonsoft.Json;

namespace Serverless
namespace Serverless
{
public static class HttpGetTrigger
public static partial class Functions
{
[FunctionName("HttpGetTrigger")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
ILogger log = null)
[FunctionName (nameof(HttpGetTrigger))]
public static async Task<IActionResult> HttpGetTrigger (
[HttpTrigger (AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
ILogger log = null)
{
log.LogInformation("C# HTTP trigger function processed a request.");
log.LogInformation ("C# HTTP trigger function processed a request.");

bool parsed;
bool displayErrors = bool.TryParse(req.Query["displayErrors"].ToString(), out parsed) && parsed;
bool displayErrors = bool.TryParse (req.Query["showDetails"].ToString (), out parsed) && parsed;

// string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
// dynamic data = JsonConvert.DeserializeObject(requestBody);

try
try
{
var connection = Environment.GetEnvironmentVariable("MongoDbConnection");
var databaseName = Environment.GetEnvironmentVariable("MongoDbDatabase");
var collectionName = Environment.GetEnvironmentVariable("MongoDbCollection");

MongoClientSettings settings = MongoClientSettings.FromUrl(
new MongoUrl(connection)
var collection = Shared.MongoDB<MyToDo>.GetDocumentCollection (
Environment.GetEnvironmentVariable ("MongoDbCollection")
);
var result = await collection.Find(FilterDefinition<MyToDo>.Empty)
.ToListAsync<MyToDo>();

settings.SslSettings = new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };

var mongoClient = new MongoClient(settings);
var client = new MongoClient(connection);
var database = client.GetDatabase(databaseName);

IMongoCollection<object> collection = database.GetCollection<object>(collectionName);

var result = await collection.Find(FilterDefinition<object>.Empty)
.ToListAsync<object>();

return new OkObjectResult(JsonConvert.SerializeObject(result));
}
catch (System.Exception ex)
return new OkObjectResult (JsonConvert.SerializeObject (result));
}
catch (System.Exception ex)
{
log.LogInformation("C# HTTP trigger function processed a request.");
log.LogInformation ("C# HTTP trigger function processed a request.");

if (displayErrors){
return new OkObjectResult(ex.Message);
if (displayErrors) {
return new OkObjectResult (ex.Message);
}
return new OkObjectResult("Failed to fetch data");
return new OkObjectResult ("Failed to fetch data");
}
}
}
Expand Down
68 changes: 68 additions & 0 deletions Serverless/SignalR/HttpPostTrigger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using Newtonsoft.Json;

// Document Storage
//using Microsoft.Azure.Documents;
//using System.Collections.Generic;

namespace Serverless
{
public static partial class Functions
{
// POST http://localhost:7071/api/HttpPostTrigger
/*
{
"_t": "MyToDo",
"Title": "Do something 3",
"IsCompleted": false
}
*/

[FunctionName(nameof(HttpPostTrigger))]
public static async Task<IActionResult> HttpPostTrigger(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]
HttpRequest req,
[SignalR(HubName = Shared.BROADCAST_HUB)]IAsyncCollector<SignalRMessage> signalRMessages,
ILogger log)
{
string requestBody = new StreamReader(req.Body).ReadToEnd();

if (string.IsNullOrEmpty(requestBody))
{
return new BadRequestObjectResult("Please pass a payload to broadcast in the request body.");
}

var data = JsonConvert.DeserializeObject<MyToDo>(requestBody);

var documentCollection = Shared.MongoDB<MyToDo>.GetDocumentCollection(
Environment.GetEnvironmentVariable("MongoDbCollection")
);
if (data.Id == Guid.Empty.ToString())
{
data.Id = Guid.NewGuid().ToString();
}
data._Id = MongoDB.Bson.ObjectId.GenerateNewId();
data.DateCreated = System.DateTime.UtcNow;

await documentCollection.InsertOneAsync(data);

await signalRMessages.AddAsync(new SignalRMessage()
{
Target = "notify",
//UserId = "Web",
Arguments = new object[] { data },
//GroupName = "ToDos"
});

return new CreatedResult($"/api/HttpGet/{data._Id}", data);
}
}
}
6 changes: 5 additions & 1 deletion Serverless/SignalR/Models/MyToDo.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using MongoDB.Bson.Serialization.Attributes;
using System;
using MongoDB.Bson.Serialization.Attributes;
using Newtonsoft.Json;

namespace Serverless
Expand All @@ -18,5 +19,8 @@ public class MyToDo

[BsonElement(nameof(IsCompleted))]
public bool IsCompleted { get; set; }

[BsonElement(nameof(DateCreated))]
public DateTime DateCreated { get; set; }
}
}
33 changes: 33 additions & 0 deletions Serverless/SignalR/Shared.MongoDb.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System;
using System.Security.Authentication;
using MongoDB.Driver;

namespace Serverless
{
public static partial class Shared
{
public static class MongoDB <T>
where T : class
{
public static IMongoCollection<T> GetDocumentCollection (string collectionName)
{
var connection = Environment.GetEnvironmentVariable ("MongoDbConnection");
var databaseName = Environment.GetEnvironmentVariable ("MongoDbDatabase");

MongoClientSettings settings = MongoClientSettings.FromUrl (
new MongoUrl (connection)
);

settings.SslSettings = new SslSettings () { EnabledSslProtocols = SslProtocols.Tls12 };

var mongoClient = new MongoClient (settings);
var client = new MongoClient (connection);
var database = client.GetDatabase (databaseName);

IMongoCollection<T> collection = database.GetCollection<T> (collectionName);

return collection;
}
}
}
}
7 changes: 7 additions & 0 deletions Serverless/SignalR/Shared.SignalR.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Serverless
{
public static partial class Shared
{
public const string BROADCAST_HUB = "broadcast";
}
}
1 change: 1 addition & 0 deletions Serverless/SignalR/SignalR-functions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.CosmosDB" Version="3.0.5" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SignalRService" Version="1.1.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.5" />
<PackageReference Include="MongoDB.Driver" Version="2.10.2" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
namespace SignalR
namespace Serverless
{
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;

public static class SignalRNegotiate
public static class SignalRHubs
{
// POST: http://localhost:7071/api/negotiate
// POST: https://my-signalr-functions.azurewebsites.net/api/hubs/broadcast/negotiate

[FunctionName("Negotiate")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "negotiate")] HttpRequest req,
[SignalRConnectionInfo(HubName = "broadcast")]SignalRConnectionInfo info,
[FunctionName(nameof(Broadcast))]
public static async Task<IActionResult> Broadcast(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "hubs/" + Shared.BROADCAST_HUB + "/negotiate")] HttpRequest req,
[SignalRConnectionInfo(HubName = Shared.BROADCAST_HUB)]SignalRConnectionInfo info,
ILogger log)
{
return await Task.FromResult(
Expand Down
46 changes: 0 additions & 46 deletions Serverless/SignalR/SignalRTrigger.cs

This file was deleted.

9 changes: 7 additions & 2 deletions Shared/Item.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,19 @@ namespace Shared
{
public class Item
{
public int Id { get; set; }
public string Id { get; set; }

[JsonProperty("Name")]
[JsonProperty("Title")]
public string Text { get; set; }

public string Description { get; set; } = "This is the description";

public bool IsCompleted { get; set; }

[JsonProperty("ListedPrice")]
public string Price { get; set; }

[JsonProperty(nameof(DateCreated))]
public DateTime DateCreated { get; set; }
}
}
10 changes: 4 additions & 6 deletions Utils/mongo-doc.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
{
"Id": "12c3g5b8-e1f8-4739-88c6-476f59adca1b",
"title": "test",
"isCompleted": true,
"Text": "test",
"Description": "this is a test"
}
"_t": "MyToDo",
"Title": "Do something 3",
"IsCompleted": false
}
20 changes: 20 additions & 0 deletions Utils/scrapbook.mongo
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//db.MyToDos.Todos.drop()

db.MyToDos.deleteMany({ "isCompleted" : true })

db.MyToDos.insert(
[{
"_id": {
"$oid": "5e7672116b395b002066d2a6"
},
"_t": "MyToDo",
"Id": "c1f5c787-5554-44a7-9736-640036e24fe0",
"Title": "Test",
"IsCompleted": false
}
]
)

db.MyToDos.find()//.pretty()

db.MyToDos.find({}, { name: 1, _id: 1 })
Loading