Пример #1
0
        async Task SetUpAsync()
        {
            Func <string, string, string> Env = (name, @default) =>
                                                Environment.GetEnvironmentVariable(name) ?? @default;

            var domain   = Env("FAUNA_DOMAIN", "localhost");
            var scheme   = Env("FAUNA_SCHEME", "http");
            var port     = Env("FAUNA_PORT", "8443");
            var secret   = Env("FAUNA_ROOT_KEY", "secret");
            var endpoint = $"{scheme}://{domain}:{port}";

            rootClient = new FaunaClient(secret: secret, endpoint: endpoint);

            const string dbName = "faunadb-csharp-test";

            DbRef = Database(dbName);

            try {
                await rootClient.Query(Delete(DbRef));
            } catch (BadRequest) {}

            await rootClient.Query(CreateDatabase(Obj("name", dbName)));

            clientKey = await rootClient.Query(CreateKey(Obj("database", DbRef, "role", "server")));

            adminKey = await rootClient.Query(CreateKey(Obj("database", DbRef, "role", "admin")));

            client      = rootClient.NewSessionClient(clientKey.Get(SECRET_FIELD));
            adminClient = rootClient.NewSessionClient(adminKey.Get(SECRET_FIELD));
        }
Пример #2
0
        private void Execute(
            string indexName,
            string collectionName,
            string fieldName,
            string serverKey)
        {
            var client = new FaunaClient(serverKey);

            try
            {
                var result = client
                             .Query(CreateIndex(Obj(
                                                    "name", indexName,
                                                    "source", Collection(collectionName),
                                                    "terms", Arr(Obj("field", Arr("data", fieldName)))
                                                    )))
                             .GetAwaiter()
                             .GetResult();

                Console.WriteLine(result);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
        }
Пример #3
0
        public void SetUp()
        {
            dummy = new DummyServer();
            dummy.Start();

            client = new FaunaClient("secret", "http://127.0.0.1:9999", timeout: TimeSpan.FromSeconds(10));
        }
Пример #4
0
        [Test] public async Task TestAuthenticateSession()
        {
            Value createdInstance = await client.Query(
                Create(await RandomClass(),
                       Obj("credentials",
                           Obj("password", "abcdefg")))
                );

            Value auth = await client.Query(
                Login(
                    createdInstance.Get(REF_FIELD),
                    Obj("password", "abcdefg"))
                );

            FaunaClient sessionClient = GetClient(secret: auth.Get(SECRET_FIELD));

            Value loggedOut = await sessionClient.Query(Logout(true));

            Assert.AreEqual(true, loggedOut.To <bool>().Value);

            Value identified = await client.Query(
                Identify(createdInstance.Get(REF_FIELD), "wrong-password")
                );

            Assert.AreEqual(false, identified.To <bool>().Value);
        }
Пример #5
0
        void AssertQueryException <TException>(FaunaClient client, Expr query, string code, string description, IReadOnlyList <string> position = null)
            where TException  : FaunaException
        {
            var exception = Assert.ThrowsAsync <TException>(async() => await client.Query(query));

            AssertException(exception, code, description, position);
        }
Пример #6
0
        static async Task <FaunaClient> CreateNewDatabase(FaunaClient client, string name)
        {
            await client.Query(CreateDatabase(Obj("name", name)));

            var key = await client.Query(CreateKey(Obj("database", Database(name), "role", "admin")));

            return(client.NewSessionClient(secret: key.Get(SECRET_FIELD)));
        }
Пример #7
0
        private async Task <bool> FillCategoryReference(string category, FaunaClient client)
        {
            var categoryReference = await client.Query(Get(Ref(
                                                               Collection("Categories"), category
                                                               )));

            InCategoryId = categoryReference.At("ref") as RefV;
            return(true);
        }
Пример #8
0
        public static async Task GetVectorPronunciation(FaunaClient client, string twitchdisplayname)
        {
            Value result = await client.Query(
                Get(
                    Match(Index("vectorprounciation_get_twitch_user"), twitchdisplayname)));

            TwitchUsers twitchusers = Decoder.Decode <TwitchUsers>(result.At("data"));

            Console.WriteLine("{0} : {1}", twitchusers.VectorProronunciation, twitchusers.TwitchDisplayName);
        }
Пример #9
0
        /// <summary>
        /// Creates a schema from the base class including indexes
        /// </summary>
        /// <param name="baseType"></param>
        /// <param name="onlyDecoratedChildren"></param>
        /// <param name="ignoreBaseClass"></param>
        /// <returns></returns>
        public static async Task CreateDatabaseSchema(FaunaClient client, Type baseType, bool onlyDecoratedChildren = true, bool ignoreBaseClass = true)
        {
            var types = new List <Type>(Assembly.GetAssembly(baseType).GetTypes().Where(t => t.BaseType == baseType));

            if (ignoreBaseClass == false)
            {
                types.Add(baseType);
            }

            await CreateDatabaseSchema(client, types, onlyDecoratedChildren);
        }
Пример #10
0
        public static async Task WriteLink(FaunaClient client, string capturedlink)
        {
            Links link = new Links(DateTime.UtcNow, capturedlink);

            await client.Query(
                Create(
                    Collection("links"),
                    Obj("data", Encoder.Encode(link))
                    )
                );
        }
Пример #11
0
 public FaunaProduct(ProductDto product, FaunaClient client)
 {
     Name      = product.Name;
     Price     = product.Price;
     Weight    = product.Weight;
     CreatedAt = DateTime.UtcNow;
     Quantity  = product.Quantity;
     if (!FillCategoryReference(product.CategoryId, client).ConfigureAwait(false).GetAwaiter().GetResult())
     {
         throw new ArgumentException("Can't find category");
     }
 }
Пример #12
0
        private async Task <List <Product> > GetProducts(Value[] values, FaunaClient client)
        {
            List <Product> products = new List <Product>();

            foreach (Value value in values)
            {
                var product = Decoder.Decode <Product>(value.At("data"));
                product.Id         = (value.At("ref") as RefV).Id;
                product.CategoryId = (value.At("data").At("category") as RefV).Id;
                var cat = await client.Query(Get(Ref(Collection(CATEGORY_COLLECTION_NAME), product.CategoryId)));

                product.CategoryName = cat.At("data").At("name").To <string>().Value;
                products.Add(product);
            }
            return(products);
        }
Пример #13
0
 public PageHelper(FaunaClient client,
                   Expr set,
                   Expr ts      = null,
                   Expr after   = null,
                   Expr before  = null,
                   Expr size    = null,
                   Expr events  = null,
                   Expr sources = null)
 {
     this.client         = client;
     this.set            = set;
     this.ts             = ts;
     this.after          = after;
     this.before         = before;
     this.size           = size;
     this.events         = events;
     this.sources        = sources;
     this.faunaFunctions = new List <Func <Expr, Expr> >();
 }
        private void Execute(string collectionName, string serverKey)
        {
            var client = new FaunaClient(serverKey);

            try
            {
                var result = client
                             .Query(
                    CreateCollection(Obj("name", collectionName)),
                    TimeSpan.FromSeconds(30))
                             .GetAwaiter()
                             .GetResult();

                Console.WriteLine(result);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
        }
Пример #15
0
        public async Task Create(Type collectionType, FaunaClient client)
        {
            FaunaCollection collection = collectionType.GetCustomAttribute <FaunaCollection>();

            var options = new Dictionary <string, Expr>();

            if (!string.IsNullOrEmpty(this.Name))
            {
                options.Add("name", this.Name);
            }
            else
            {
                options.Add("name", GenerateIndexName(collectionType));
            }
            options.Add("source", Collection(collection?.Name ?? collectionType.Name));

            if (Terms != null && Terms.Length > 0)
            {
                options.Add("terms", GenerateTermsObj(collectionType));
            }

            if (Values != null && Values.Length > 0)
            {
                options.Add("values", GenerateValuesObj(collectionType));
            }

            if (this.Data != null)
            {
                options.Add("data", Obj(JsonConvert.DeserializeObject <Dictionary <string, Expr> >(Data)));
            }
            if (this.Permissions != null)
            {
                options.Add("permissions", Obj(JsonConvert.DeserializeObject <Dictionary <string, Expr> >(Permissions)));
            }
            options.Add("unique", this.Unique);
            options.Add("serialized", this.Serialized);

            await client.Query(CreateIndex(options));
        }
Пример #16
0
        public static async Task GetVectorPronunciationAll(FaunaClient client)
        {
            Value value = await client.Query(Paginate(Match(Index("vpronunciation"))));


            TwitchUsers twitchUsers = value.At("data").To <TwitchUsers>().Value;

            Console.WriteLine(" loaded: {0}", twitchUsers.VectorProronunciation);

            //Value result = await client.Query(
            //            Get(
            //            Match(Index("vpronunciation"))));

            //IResult<Value> data = result.At("data").To<Value>();

            //data.Match(
            //    Success: value => ProcessData(value),
            //    Failure: reason => Console.WriteLine($"Something went wrong: {reason}")
            //);

            //TwitchUsers twitchusers = (TwitchUsers)result.At("data").To<TwitchUsers>();
            //Console.WriteLine(twitchusers.TwitchDisplayName);
        }
Пример #17
0
        public static async Task CreateDatabaseSchema(FaunaClient client, List <Type> types, bool onlyDecoratedChildren = true)
        {
            foreach (Type type in types)
            {
                System.Diagnostics.Debug.WriteLine("Creating fauna collection for " + type.Name + "...");
                await client.Query(CreateCollection(type));

                System.Diagnostics.Debug.WriteLine("created");

                var indexAttributes = type.GetCustomAttributes <FaunaIndex>();
                if (indexAttributes != null)
                {
                    foreach (FaunaIndex index in indexAttributes)
                    {
                        System.Diagnostics.Debug.WriteLine("Creating fauna index for " + type.Name + "...");
                        if (index != null)
                        {
                            await index.Create(type, client);
                        }
                    }
                }
            }
        }
Пример #18
0
        private void OnMessageReceived(object sender, OnMessageReceivedArgs e)
        {
            var fclient = new FaunaClient(endpoint: ENDPOINT, secret: Settings.Fauna_Secret);

            if (coders.Contains(e.ChatMessage.DisplayName))
            {
                //string name = await GetVectorPronunciation(fclient, e.ChatMessage.DisplayName);
                _ = ("!so " + e.ChatMessage.DisplayName);
                new CommandAnnounce(client).Execute($"A live coder is in the chat, check out {e.ChatMessage.DisplayName}, stream at twitch dot tv/{e.ChatMessage.DisplayName}", e);
                coders.Remove(e.ChatMessage.DisplayName);
            }

            foreach (Match link in Regex.Matches(e.ChatMessage.Message,
                                                 @"(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})"))
            {
                var protocollink = new UriBuilder(link.Value.ToString()).Uri.ToString();

                if (!e.ChatMessage.DisplayName.StartsWith("StreamElements"))
                {
                    Log.Information($"link : {DateTime.UtcNow.ToString()}, {protocollink}", "info");
                    Data.WriteLink(fclient, protocollink).Wait();
                    DiscordBot.PostMessage(e.ChatMessage.DisplayName, 729021058568421386, protocollink).Wait();
                }
            }

            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:53425/chathub")
                             .Build();

            connection.StartAsync().Wait();
            connection.InvokeCoreAsync("SendMessage", args: new[] { e.ChatMessage.Message, e.ChatMessage.Username });


            //Data.GetVectorPronunciation(fclient, e.ChatMessage.Username).Wait();
            // Data.GetVectorPronunciationAll(fclient).Wait();
        }
Пример #19
0
        public async Task TestStreamHandlesLossOfAuthorization()
        {
            await adminClient.Query(
                CreateCollection(Obj("name", "streamed-things-auth"))
                );

            Value createdInstance = await adminClient.Query(
                Create(Collection("streamed-things-auth"),
                       Obj("credentials",
                           Obj("password", "abcdefg"))));

            var docRef = createdInstance.At("ref");

            // new key + client
            Value newKey = await adminClient.Query(CreateKey(Obj("role", "server-readonly")));

            FaunaClient streamingClient = adminClient.NewSessionClient(newKey.At("secret").To <string>().Value);

            var provider = await streamingClient.Stream(docRef);

            var done = new TaskCompletionSource <object>();

            List <Value> events = new List <Value>();

            var monitor = new StreamingEventMonitor(
                async value =>
            {
                if (events.Count == 0)
                {
                    try
                    {
                        // update doc on `start` event
                        await adminClient.Query(Update(docRef, Obj("data", Obj("testField", "afterStart"))));

                        // delete key
                        await adminClient.Query(Delete(newKey.At("ref").To <RefV>().Value));

                        // push an update to force auth revalidation.
                        await adminClient.Query(Update(docRef, Obj("data", Obj("testField", "afterKeyDelete"))));
                    }
                    catch (Exception ex)
                    {
                        done.SetException(ex);
                    }
                }

                // capture element
                events.Add(value);

                // ask for more elements
                provider.RequestData();
            },
                ex => { done.SetException(ex); },
                () => { done.SetResult(null); }
                );

            // subscribe to data provider
            monitor.Subscribe(provider);

            // wrapping an asynchronous call
            AsyncTestDelegate res = async() => await done.Task;

            // blocking until we get an exception
            var exception = Assert.ThrowsAsync <StreamingException>(res);

            // clear the subscription
            monitor.Unsubscribe();

            // validating exception message
            Assert.AreEqual("permission denied: Authorization lost during stream evaluation.", exception.Message);
            AssertErrors(exception, code: "permission denied", description: "Authorization lost during stream evaluation.");
        }
Пример #20
0
 public static IQueryable <T> Query <T>(this FaunaClient client, Expression <Func <T, bool> > selector) => Query(new FaunaClientProxy(client), selector);
Пример #21
0
 public static Task Delete(this FaunaClient client, IReferenceType obj) => Delete(new FaunaClientProxy(client), obj);
 public FaunaDbUserRepository(FaunaClient client)
 {
     _client = client;
 }
 public FaunaClientProxy(FaunaClient client)
 {
     _client = client;
 }
Пример #24
0
        public HatDescriptionRepository(IConfiguration configuration)
        {
            var secret = configuration["FaunaDb:Secret"];

            _Client = new FaunaClient(secret);
        }
Пример #25
0
 public static Task Delete(this FaunaClient client, string id) => Delete(new FaunaClientProxy(client), id);
 public ArtistRepository(FaunaClient faunaClient, IMapper mapper)
 {
     _faunaClient = faunaClient;
     _mapper      = mapper;
 }
Пример #27
0
 public static Task <T> Get <T>(this FaunaClient client, string @ref) => Get <T>(new FaunaClientProxy(client), @ref);
Пример #28
0
 public FaunaHealthCheckDal()
 {
     _client = new FaunaClient(endpoint: Endpoint, secret: Secret);
 }
Пример #29
0
 public static IQueryable <T> Query <T>(this FaunaClient client, Expression <Func <T, object> > index, params Expr[] args) => Query(new FaunaClientProxy(client), index, args);
Пример #30
0
        async Task SetUpAsync()
        {
            adminKey = await rootClient.Query(CreateKey(Obj("database", DbRef, "role", "admin")));

            adminClient = rootClient.NewSessionClient(adminKey.Get(SECRET_FIELD));

            await client.Query(CreateClass(Obj("name", "spells")));

            await client.Query(CreateClass(Obj("name", "characters")));

            await client.Query(CreateClass(Obj("name", "spellbooks")));

            await client.Query(CreateIndex(Obj(
                                               "name", "all_spells",
                                               "source", Class("spells")
                                               )));

            await client.Query(CreateIndex(Obj(
                                               "name", "spells_by_element",
                                               "source", Class("spells"),
                                               "terms", Arr(Obj("field", Arr("data", "element")))
                                               )));

            await client.Query(CreateIndex(Obj(
                                               "name", "elements_of_spells",
                                               "source", Class("spells"),
                                               "values", Arr(Obj("field", Arr("data", "element")))
                                               )));

            await client.Query(CreateIndex(Obj(
                                               "name", "spellbooks_by_owner",
                                               "source", Class("spellbooks"),
                                               "terms", Arr(Obj("field", Arr("data", "owner")))
                                               )));

            await client.Query(CreateIndex(Obj(
                                               "name", "spells_by_spellbook",
                                               "source", Class("spells"),
                                               "terms", Arr(Obj("field", Arr("data", "spellbook")))
                                               )));

            magicMissile = GetRef(await client.Query(
                                      Create(Class("spells"),
                                             Obj("data",
                                                 Obj(
                                                     "name", "Magic Missile",
                                                     "element", "arcane",
                                                     "cost", 10)))
                                      ));

            fireball = GetRef(await client.Query(
                                  Create(Class("spells"),
                                         Obj("data",
                                             Obj(
                                                 "name", "Fireball",
                                                 "element", "fire",
                                                 "cost", 10)))
                                  ));

            faerieFire = GetRef(await client.Query(
                                    Create(Class("spells"),
                                           Obj("data",
                                               Obj(
                                                   "name", "Faerie Fire",
                                                   "cost", 10,
                                                   "element", Arr(
                                                       "arcane",
                                                       "nature"
                                                       ))))
                                    ));

            summon = GetRef(await client.Query(
                                Create(Class("spells"),
                                       Obj("data",
                                           Obj(
                                               "name", "Summon Animal Companion",
                                               "element", "nature",
                                               "cost", 10)))
                                ));

            thor = GetRef(await client.Query(
                              Create(Class("characters"),
                                     Obj("data", Obj("name", "Thor")))
                              ));

            var thorsSpellbook = GetRef(await client.Query(
                                            Create(Class("spellbooks"),
                                                   Obj("data",
                                                       Obj("owner", thor)))
                                            ));

            thorSpell1 = GetRef(await client.Query(
                                    Create(Class("spells"),
                                           Obj("data",
                                               Obj("spellbook", thorsSpellbook)))
                                    ));

            thorSpell2 = GetRef(await client.Query(
                                    Create(Class("spells"),
                                           Obj("data",
                                               Obj("spellbook", thorsSpellbook)))
                                    ));
        }