// Using async Task Main() requires adding <LangVersion>latest</LangVersion> to .csproj file static async Task Main(string[] args) { const int port = 8000; var wwwPath = args.Length > 0 ? args[0] : "../../../www"; using var context = new EmbedIOContext($"http://+:{port}/", wwwPath); // Create a MemoryDatabase (no persistence, limited features) var database = new MemoryDatabase(); await database.CreateFromSqlAsync(@"CREATE TABLE message ( id INT NOT NULL AUTO_INCREMENT, text VARCHAR(40) NOT NULL, PRIMARY KEY (id) );"); // Listen for API requests context.WebApi.OnPost("/api/message/insert", async(req, res) => { var text = await req.ParseAsJsonAsync <dynamic>(); await database.InsertAndCommitAsync <long>("message", new { text }); }); // Listen for subscribe requests... // - The handler must return an IDisposable object (gets disposed when the channel is unsubscribed) // - The handler can push data to the client by calling channel.Queue() context.SubscriptionApi.OnSubscribe("messages", (vars, channel) => { return(database.CreateAndStartDynamicViewAsync("message", dataEventTransaction => channel.Queue(dataEventTransaction))); }); context.Start(); Console.ReadLine(); }
static void Main(string[] args) { using var context = new EmbedIOContext("http://+:8000/"); // Create database var database = new MemoryDatabase(); database.CreateFromSqlAsync(@"CREATE TABLE contact ( id VARCHAR(50) NOT NULL, first_name VARCHAR(40) NOT NULL, last_name VARCHAR(40) NOT NULL, PRIMARY KEY(id) );").Wait(); database.SetDefaultValue("id", table => $"{table.Abbreviate()}_{Guid.NewGuid().ToString()}"); // Define the Web API context.WebApi.OnPost("/api/contact/insert", async(req, res) => { var record = await req.ParseAsJsonAsync <Dict>(); await database.InsertAndCommitAsync <string>("contact", record); }); context.WebApi.OnPost("/api/contact/update", async(req, res) => { var record = await req.ParseAsJsonAsync <Dict>(); await database.UpdateAndCommitAsync("contact", record); }); context.WebApi.OnPost("/api/contact/delete", async(req, res) => { var id = await req.ParseAsJsonAsync <string>(); await database.DeleteAndCommitAsync("contact", id); }); // Define the Subscription API context.SubscriptionApi.OnSubscribe( "all-contacts", (vars, channel) => database.CreateAndStartDynamicViewAsync( "SELECT * FROM contact", dataEventTransaction => channel.Queue(dataEventTransaction) ) ); // Start the web server and wait context.Start(); Console.ReadLine(); }