Exemplo n.º 1
0
        // Using async Task Main() requires adding <LangVersion>latest</LangVersion> to .csproj file
        static async Task Main(string[] args)
        {
            logger.Info("Main()");
            using (var embedIOContext = new Butterfly.Web.EmbedIO.EmbedIOContext("http://+:8000/")) {
                // Create a MemoryDatabase (no persistence, limited features)
                var database = new Butterfly.Db.Memory.MemoryDatabase();
                await database.CreateFromSqlAsync(@"CREATE TABLE todo (
	                id VARCHAR(50) NOT NULL,
	                name VARCHAR(40) NOT NULL,
	                PRIMARY KEY(id)
                );");

                database.SetDefaultValue("id", tableName => $"{tableName.Abbreviate()}_{Guid.NewGuid().ToString()}");

                // Listen for API requests
                embedIOContext.WebApi.OnPost("/api/todo/insert", async(req, res) => {
                    logger.Info("/api/todo/insert");
                    var todo = await req.ParseAsJsonAsync <Dict>();
                    await database.InsertAndCommitAsync <string>("todo", todo);
                });
                embedIOContext.WebApi.OnPost("/api/todo/delete", async(req, res) => {
                    logger.Info("/api/todo/delete");
                    var id = await req.ParseAsJsonAsync <string>();
                    await database.DeleteAndCommitAsync("todo", id);
                });

                // 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()
                embedIOContext.SubscriptionApi.OnSubscribe("todos", (vars, channel) => {
                    string clientName = vars?.GetAs("clientName", "");
                    logger.Info($"OnSubscribe():todos,clientName={clientName}");
                    return(database.CreateAndStartDynamicViewAsync("todo", dataEventTransaction => {
                        var eventTypes = string.Join(",", dataEventTransaction.dataEvents.Select(x => x.dataEventType.ToString()));
                        logger.Info($"clientName={clientName},eventTypes={eventTypes}");
                        channel.Queue(dataEventTransaction);
                    }));
                });

                embedIOContext.Start();

                Console.ReadLine();
            }
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            using (var ctx =
                       new Butterfly.Web.EmbedIO.EmbedIOContext("http://+:8000/")) {
                // Create database
                var database = new Butterfly.Db.Memory.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
                ctx.WebApi.OnPost("/api/contact/insert", async(req, res) => {
                    var record = await req.ParseAsJsonAsync <Dict>();
                    await database.InsertAndCommitAsync <string>("contact", record);
                });
                ctx.WebApi.OnPost("/api/contact/update", async(req, res) => {
                    var record = await req.ParseAsJsonAsync <Dict>();
                    await database.UpdateAndCommitAsync("contact", record);
                });
                ctx.WebApi.OnPost("/api/contact/delete", async(req, res) => {
                    var id = await req.ParseAsJsonAsync <string>();
                    await database.DeleteAndCommitAsync("contact", id);
                });

                // Define the Subscription API
                ctx.SubscriptionApi.OnSubscribe(
                    "all-contacts",
                    (vars, channel) => database.CreateAndStartDynamicViewAsync(
                        "SELECT * FROM contact",
                        dataEventTransaction => channel.Queue(dataEventTransaction)
                        )
                    );

                // Start the web server and wait
                ctx.Start();
                Console.ReadLine();
            }
        }
Exemplo n.º 3
0
        // 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 embedIOContext = new Butterfly.Web.EmbedIO.EmbedIOContext($"http://+:{port}/", wwwPath)) {
                // Create a MemoryDatabase (no persistence, limited features)
                var database = new Butterfly.Db.Memory.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
                embedIOContext.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()
                embedIOContext.SubscriptionApi.OnSubscribe("my-channel", (vars, channel) => {
                    return(database.CreateAndStartDynamicViewAsync("message", dataEventTransaction => channel.Queue(dataEventTransaction)));
                });

                embedIOContext.Start();

                Console.WriteLine($"Opening http://localhost:{port}/ in a browser...");
                ProcessX.OpenBrowser($"http://localhost:{port}/");
                Console.ReadLine();
            }
        }
Exemplo n.º 4
0
        public async Task RegistrationTests()
        {
            var database = new Butterfly.Db.Memory.MemoryDatabase();

            await database.CreateFromResourceFileAsync(Assembly.GetExecutingAssembly(), "Butterfly.Auth.Test.butterfly_auth_test.sql");

            database.SetDefaultValue("id", tableName => Guid.NewGuid().ToString());
            database.SetDefaultValue("created_at", tableName => DateTime.Now.ToUnixTimestamp());
            database.SetDefaultValue("updated_at", tableName => DateTime.Now.ToUnixTimestamp());
            database.AddInputPreprocessor(BaseDatabase.RemapTypeInputPreprocessor <DateTime>(dateTime => dateTime.ToUnixTimestamp()));

            // Create a single instance of AuthManager
            AuthManager authManager = new AuthManager(database);

            // Register a valid user
            UserRefToken registerAuthToken1 = await authManager.RegisterAsync(new {
                username   = "******",
                first_name = "John",
                last_name  = "Smith",
                email      = "*****@*****.**",
                phone      = "+13162105368",
                password   = "******"
            });

            // Verify the returned auth token can be authenticated
            var authToken1 = await authManager.AuthenticateAsync(UserRefTokenAuthenticator.AUTH_TYPE, registerAuthToken1.id);

            // Register an invalid email
            Exception exception2 = null;

            try {
                UserRefToken registerAuthToken2 = await authManager.RegisterAsync(new {
                    username   = "******",
                    first_name = "John",
                    last_name  = "Smith",
                    email      = "john",
                    phone      = "+13162105368",
                    password   = "******"
                });
            }
            catch (Exception e) {
                exception2 = e;
            }
            Assert.IsTrue(exception2.Message.Contains("Email address must contain"));

            // Register an invalid phone
            Exception exception3 = null;

            try {
                UserRefToken registerAuthToken2 = await authManager.RegisterAsync(new {
                    username   = "******",
                    first_name = "John",
                    last_name  = "Smith",
                    email      = "*****@*****.**",
                    phone      = "123",
                    password   = "******"
                });
            }
            catch (Exception e) {
                exception3 = e;
            }
            Assert.IsTrue(exception3.Message.Contains("Invalid phone number"));

            // Register a duplicate username
            Exception exception4 = null;

            try {
                UserRefToken registerAuthToken2 = await authManager.RegisterAsync(new {
                    username   = "******",
                    first_name = "John",
                    last_name  = "Smith",
                    email      = "*****@*****.**",
                    phone      = "+13162105368",
                    password   = "******"
                });
            }
            catch (Exception e) {
                exception4 = e;
            }
            Assert.IsTrue(exception4.Message.Contains("unavailable"));

            // Register without a password
            Exception exception5 = null;

            try {
                UserRefToken registerAuthToken2 = await authManager.RegisterAsync(new {
                    username   = "******",
                    first_name = "John",
                    last_name  = "Smith",
                    email      = "*****@*****.**",
                    phone      = "+13162105368"
                });
            }
            catch (Exception e) {
                exception5 = e;
            }
            Assert.IsTrue(exception5.Message.Contains("password cannot be null"));
        }