예제 #1
0
        public async Task <Terminal> Get(Guid guid, Graph.Common.NeuronQuery neuronQuery, CancellationToken cancellationToken = default(CancellationToken))
        {
            Terminal result = null;

            NeuronRepository.FillWithDefaults(neuronQuery, this.settingsService);

            using (var db = ArangoDatabase.CreateWithSetting(this.settingsService.DatabaseName))
            {
                AssertionConcern.AssertStateTrue(await Helper.GraphExists(db), Constants.Messages.Error.GraphNotInitialized);
                var t = await db.DocumentAsync <Terminal>(guid.ToString());

                if (
                    t != null && (
                        neuronQuery.TerminalActiveValues.Value.HasFlag(Graph.Common.ActiveValues.All) ||
                        (
                            Helper.TryConvert(neuronQuery.TerminalActiveValues.Value, out bool activeValue) &&
                            t.Active == activeValue
                        )
                        )
                    )
                {
                    result = t.CloneExcludeSynapticPrefix();
                }
            }

            return(result);
        }
예제 #2
0
 public async Task Clear()
 {
     using (var db = ArangoDatabase.CreateWithSetting(this.settingsService.DatabaseName))
     {
         await Helper.Clear(db, nameof(Settings));
     }
 }
예제 #3
0
 private async Task UpdateUser(User userToUpdate)
 {
     using (var db = ArangoDatabase.CreateWithSetting())
     {
         await db.UpdateByIdAsync <User>(userToUpdate.Id, userToUpdate);
     }
 }
예제 #4
0
 public async Task Clear()
 {
     using (var db = ArangoDatabase.CreateWithSetting(this.settingsService.DatabaseName))
     {
         await Helper.Clear(db, nameof(Terminal), CollectionType.Edge);
     }
 }
예제 #5
0
        public async Task Save(Settings dto, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (dto.Id != Guid.Empty.ToString())
            {
                throw new ArgumentException("Invalid 'Settings' document id.");
            }

            using (var db = ArangoDatabase.CreateWithSetting(this.settingsService.DatabaseName))
            {
                if (!db.ListCollections().Any(c => c.Name == nameof(Settings)))
                {
                    throw new InvalidOperationException(
                              $"Collection '{nameof(Settings)}' not initialized."
                              );
                }

                if (await db.DocumentAsync <Settings>(dto.Id) == null)
                {
                    await db.InsertAsync <Settings>(dto);
                }
                else
                {
                    await db.ReplaceByIdAsync <Settings>(dto.Id, dto);
                }
            }
        }
예제 #6
0
        static void Main(string[] args)
        {
            var creds = new NetworkCredential("root", "123456");

            ArangoDatabase.ChangeSetting(s =>
            {
                s.Database   = "IdentityTest";
                s.Url        = "http://localhost:8529/";
                s.Credential = creds;
                s.SystemDatabaseCredential = creds;
            });

            // Keys must be saved without encoding but
            // retrieved with UrlEncoding.
            //
            using (var database = ArangoDatabase.CreateWithSetting())
            {
                database.Collection("Hello").Insert(new Hello {
                    Key = ToBase64UrlFromString("hello/world"), Text = "Hello world"
                });
                var data = database.Collection("Hello").Document <Hello>(ToBase64UrlFromString("hello/world"));

                //var grant = database.Collection("PersistedGrants").Document<PersistedGrants>(WebUtility.UrlEncode("gmzAS+Gw3zjqPNU0sFvRBC9AGkZqXyNxRx+HQhPiUvs="));
                //Console.WriteLine(grant.Key);
            }
        }
예제 #7
0
        public async Task <ActionResult> GetUserInfo(string userId)
        {
            using (var db = ArangoDatabase.CreateWithSetting())
            {
                var user = await(from u in db.Query <User>()
                                 where u.Key == userId
                                 select new
                {
                    u.Username,
                    u.RealName,
                    u.Email,
                    u.Description,
                    u.Birthday,
                    u.Occupation,
                    u.Key
                })
                           .FirstOrDefaultAsync();
                if (user == null)
                {
                    return(NotFound());
                }

                return(Ok(new
                {
                    user.Username,
                    user.RealName,
                    user.Email,
                    user.Description,
                    user.Birthday,
                    user.Occupation,
                    user.Key,
                    ProfilePicture = $"{Configuration["AppSettings:DefaultURL"]}/api/users/{user.Key}/profile.jpeg"
                }));
            }
        }
예제 #8
0
        public async Task StoreAsync(PersistedGrant grant)
        {
            using (var database = ArangoDatabase.CreateWithSetting())
            {
                var collection = database.Collection(_arangoDBConfig.Collections.PersistedGrants);
                var encodedKey = ToBase64UrlFromString(grant.Key);

                if (await collection.ExistsAsync(encodedKey))
                {
                    return;
                }

                await collection
                .InsertAsync(
                    new ArangoDBPersistedGrant {
                    Key          = encodedKey,
                    GrantKey     = grant.Key,
                    ClientId     = grant.ClientId,
                    CreationTime = grant.CreationTime,
                    Data         = grant.Data,
                    Expiration   = grant.Expiration,
                    SubjectId    = grant.SubjectId,
                    Type         = grant.Type
                }
                    );
            }
        }
예제 #9
0
 public void deleteDB(string name)
 {
     this.connect();
     using (var db = ArangoDatabase.CreateWithSetting())
     {
         db.DropDatabase(name);
     }
 }
예제 #10
0
 public dataBaseManager(string urlWithPort, string database, string adminName, string password)
 {
     this.urlWithPort = urlWithPort;
     this.database    = database;
     this.adminName   = adminName;
     this.password    = password;
     this.connect();
     this.db = ArangoDatabase.CreateWithSetting();
 }
예제 #11
0
 public async Task RemoveAsync(string key)
 {
     using (var database = ArangoDatabase.CreateWithSetting())
     {
         var encodedKey = WebUtility.UrlEncode(key);
         await database.Collection(_arangoDBConfig.Collections.PersistedGrants)
         .RemoveByIdAsync(encodedKey);
     }
 }
예제 #12
0
 private async Task <User> GetUserWithId(string userId)
 {
     using (var db = ArangoDatabase.CreateWithSetting())
     {
         var selectedUser = await(from u in db.Query <Models.Users.User>()
                                  where u.Key == userId
                                  select u).FirstOrDefaultAsync();
         return(selectedUser);
     }
 }
예제 #13
0
 public void createDB(string name)
 {
     this.connect();
     using (var db = ArangoDatabase.CreateWithSetting())
     {
         db.CreateDatabase(name);
         //var currentDatabaseInfo = db.CurrentDatabaseInformation();
         //Console.WriteLine(currentDatabaseInfo.Path);
     }
 }
예제 #14
0
 public async Task RemoveAllAsync(string subjectId, string clientId, string type)
 {
     using (var database = ArangoDatabase.CreateWithSetting())
     {
         await database.Query <ArangoDBPersistedGrant>()
         .Where(pg => pg.SubjectId == subjectId && pg.ClientId == clientId && pg.Type == type)
         .Remove()
         .ToListAsync();
     }
 }
예제 #15
0
        public IActionResult GetAllUsers([FromQuery] UsersQueryOptions options)
        {
            using (var db = ArangoDatabase.CreateWithSetting())
            {
                var query = from u in db.Query <User>()
                            select new
                {
                    u.Key,
                    u.Username,
                    u.RealName,
                    u.Email,
                    u.Description,
                    u.Occupation,
                    birthday = AQL.DateFormat(u.Birthday, "%dd/%mm/%yyyy")
                };
                if (options.Name != null)
                {
                    query = query.Where(u => AQL.Contains(AQL.Lower(u.Username), AQL.Lower(options.Name)));
                }

                if (options.Email != null)
                {
                    query = from u in query
                            where AQL.Lower(u.Email) == AQL.Lower(options.Email)
                            select u;
                }

                if (options.Limit.HasValue)
                {
                    query = query.Take(options.Limit.Value);
                }

                if (options.Sorted.HasValue && options.Sorted.Value == true)
                {
                    query = query.OrderBy(user => user.Username);
                }

                var defaultValue = query.FirstOrDefault();
                var queryCount   = query.Count();
                if (query.Count() >= 250 || options.Page.HasValue)
                {
                    var skipValue = (options.Page ?? 0) * 250;
                    query = query.Skip(skipValue).Take(250).Select(u => u);
                }

                if (options.MaxElements.HasValue && options.MaxElements.Value > 0)
                {
                    query = query.Take(options.MaxElements.Value);
                }

                return(Ok(query));
            }
        }
예제 #16
0
        public ArrangoDbWriter(string url, string Database, string UserName, string Password)
        {
            ArangoDatabase.ChangeSetting(s =>
            {
                s.Database   = Database;
                s.Url        = url;
                s.Credential = new NetworkCredential(UserName, Password);
                s.SystemDatabaseCredential = new NetworkCredential(UserName, Password);
            });

            db = ArangoDatabase.CreateWithSetting();
        }
예제 #17
0
        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var task = new Task(() =>
            {
                using (var db = ArangoDatabase.CreateWithSetting())
                {
                    db.Query <User>().Where(u => u.Username == null).Remove().Execute();
                }
            });

            task.Start();
            return(task);
        }
예제 #18
0
        public async Task <IActionResult> AddUserToChat(string chatId, AddUserToChatRequest request)
        {
            using (var db = ArangoDatabase.CreateWithSetting())
            {
                var usersInChatGraph = db.Graph("ChatsUserGraph");
                var edge             = new ChatMembers {
                    Chat = chatId, User = request.UserId
                };
                await usersInChatGraph.InsertEdgeAsync <ChatMembers>(edge);

                return(Ok());
            }
        }
        public static void Connect(string collectionName)
        {
            if (Collection != null)
            {
                throw new TraceStateException("Connection already established.");
            }

            ArangoDatabase.ChangeSetting(s =>
            {
                s.Database = "test";
                s.Url      = "http://localhost:8529";

                // you can set other settings if you need
                s.Credential = new NetworkCredential("root", "");
                s.SystemDatabaseCredential = new NetworkCredential("root", "");
            });

            client = ArangoDatabase.CreateWithSetting();

            //client.CreateDatabase(Dns.GetHostName());


            //just to update the description state
            var databases = client.ListDatabases();

            if (client.Connection == null)
            {
                throw new TraceStateException("Local db is unreachable.");
            }

            //client.CreateCollection("logggs");

            Collection = client.Collection(collectionName);

            Buffers = new LogBuffer[NumberOfBuffers];
            for (int i = 0; i < NumberOfBuffers; i++)
            {
                Buffers[i] = new LogBuffer();
            }

            Arbiter = new Arbiter2(Buffers);
            //I create a new delegate in order to call a method with a Conditional Attribute
            Arbiter.OnAllBuffersFilled += delegate { Flush(); };

            timer           = new Timer(2000);
            timer.AutoReset = true;
            timer.Elapsed  += delegate { Timer_Elapsed(null, null); };
            timer.Start();
        }
예제 #20
0
        public async Task <IActionResult> GetUserNotificationPreferences()
        {
            using (var db = ArangoDatabase.CreateWithSetting())
            {
                var user = await(from u in db.Query <User>()
                                 where u.Key == HttpContext.User.Identity.Name
                                 select u).FirstOrDefaultAsync();

                if (user == null)
                {
                    return(NotFound());
                }

                return(Ok(new { Preferences = user.NotificationPreference }));
            }
        }
예제 #21
0
        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            Task task = new Task(() =>
            {
                using (var db = ArangoDatabase.CreateWithSetting())
                {
                    var dateTimeNow = DateTime.UtcNow;
                    db.Query <RefreshToken>()
                    .Where(t => t.Expires <= dateTimeNow)
                    .Remove()
                    .Execute();
                }
            });

            task.Start();
            return(task);
        }
예제 #22
0
        public async Task <IActionResult> SetUserNotificationPreferences([FromBody] NotificationPreference newPreference)
        {
            using (var db = ArangoDatabase.CreateWithSetting())
            {
                var user = await(from u in db.Query <User>()
                                 where u.Key == HttpContext.User.Identity.Name
                                 select u).FirstOrDefaultAsync();
                if (user == null)
                {
                    return(NotFound());
                }

                user.NotificationPreference = newPreference;
                await db.UpdateByIdAsync <User>(user.Key, user);

                return(Ok());
            }
        }
예제 #23
0
        public async Task <IActionResult> GetChatById(string chatId)
        {
            using (var db = ArangoDatabase.CreateWithSetting())
            {
                var chat = await db.Query <Chat>()
                           .Where(c => c.Key == chatId)
                           .Select(c => c)
                           .FirstOrDefaultAsync();

                if (chat == null)
                {
                    return(NotFound());
                }

                var filteredChat = (await db.CreateStatement <Chat>(@"    FOR c in Chat
                    FILTER c._key == " + $"'{chatId}'" + @"
                            LET messages = (
                                FOR m in c.messages
                                FOR u in User
                                FILTER m.sender == u._key
                                return MERGE(m, {sender: u.username, senderId: m.sender})
                            )
                    return MERGE(c, {messages: messages})"
                                                                    ).ToListAsync()).Select(c => new { c.Key, c.Name, c.Messages, c.IsGroup, c.ProjectId });

                var traversalResult = await db.TraverseAsync <User, Chat>(new TraversalConfig
                {
                    StartVertex = chat.Id,
                    GraphName   = "ChatsUsersGraph",
                    Direction   = EdgeDirection.Outbound,
                    MinDepth    = 1,
                    MaxDepth    = 1
                });

                var chats = traversalResult.Visited.Vertices;
                // si el usuario no esta en ese chat entonces lo descartamos
                if (chats.Find(u => u.Key == HttpContext.User.Identity.Name) == null)
                {
                    return(NotFound());
                }

                return(Ok(filteredChat.FirstOrDefault()));
            }
        }
예제 #24
0
 public async Task <IEnumerable <PersistedGrant> > GetAllAsync(string subjectId)
 {
     using (var database = ArangoDatabase.CreateWithSetting())
     {
         return(await database.Query <ArangoDBPersistedGrant>()
                .Where(pg => pg.SubjectId == subjectId)
                .Select(grant => new PersistedGrant
         {
             Key = grant.GrantKey,
             ClientId = grant.ClientId,
             CreationTime = grant.CreationTime,
             Data = grant.Data,
             Expiration = grant.Expiration,
             SubjectId = grant.SubjectId,
             Type = grant.Type
         })
                .ToListAsync());
     }
 }
예제 #25
0
        public async Task <Settings> Get(Guid dtoGuid, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (dtoGuid != Guid.Empty)
            {
                throw new ArgumentException("Invalid 'Settings' document id.");
            }

            Settings result = null;

            using (var db = ArangoDatabase.CreateWithSetting(this.settingsService.DatabaseName))
            {
                if ((await db.ListCollectionsAsync()).Any(c => c.Name == nameof(Settings)))
                {
                    result = await db.DocumentAsync <Settings>(dtoGuid.ToString());
                }
            }

            return(result);
        }
예제 #26
0
        private static Domain.Model.QueryResult GetNeuronResults(Guid?centralGuid, Guid?relativeGuid, string settingName, NeuronQuery neuronQuery, CancellationToken token = default(CancellationToken))
        {
            Domain.Model.QueryResult result = null;

            using (var db = ArangoDatabase.CreateWithSetting(settingName))
            {
                var queryResult = db.CreateStatement <Domain.Model.NeuronResult>(
                    NeuronRepository.CreateQuery(centralGuid, relativeGuid, neuronQuery, out List <QueryParameter> queryParameters),
                    queryParameters,
                    options: new QueryOption()
                {
                    FullCount = true
                }
                    );
                var neurons = queryResult.AsEnumerable().ToArray();

                if (centralGuid.HasValue)
                {
                    neurons.ToList().ForEach(nr => nr.Terminal = nr.Terminal.CloneExcludeSynapticPrefix());
                }

                var fullCount = (int)queryResult.Statistics.Extra.Stats.FullCount;

                if (
                    neuronQuery.Page.Value != 1 &&
                    fullCount == NeuronRepository.CalculateOffset(neuronQuery.Page.Value, neuronQuery.PageSize.Value) &&
                    neurons.Length == 0
                    )
                {
                    throw new ArgumentOutOfRangeException("Specified/Default Page is invalid.");
                }

                result = new Domain.Model.QueryResult()
                {
                    Count   = fullCount,
                    Neurons = neurons
                };
            }

            return(result);
        }
예제 #27
0
        public override async Task InsertTest()
        {
            ArangoDatabase.ChangeSetting(s =>
            {
                s.Database = "benchmark";
                s.Url      = "http://localhost:8529";

                // you can set other settings if you need
                s.Credential = new NetworkCredential("root", "pass.123");
                s.SystemDatabaseCredential = new NetworkCredential("root", "pass.123");
            });
            var fakesUsers = UserUtility.GetFakeUsers(Times);

            using (var db = ArangoDatabase.CreateWithSetting())
            {
                foreach (var userList in UserUtility.SpiltBySize(fakesUsers, 10000))
                {
                    db.Collection("Users").InsertMultiple(userList);
                }
            }
        }
예제 #28
0
        public async Task <PersistedGrant> GetAsync(string key)
        {
            using (var database = ArangoDatabase.CreateWithSetting())
            {
                var encodedKey = ToBase64UrlFromString(key);

                var grant = await database.Collection(_arangoDBConfig.Collections.PersistedGrants)
                            .DocumentAsync <ArangoDBPersistedGrant>(encodedKey);

                return(new PersistedGrant
                {
                    Key = grant.GrantKey,
                    ClientId = grant.ClientId,
                    CreationTime = grant.CreationTime,
                    Data = grant.Data,
                    Expiration = grant.Expiration,
                    SubjectId = grant.SubjectId,
                    Type = grant.Type
                });
            }
        }
예제 #29
0
파일: Helper.cs 프로젝트: ei8/cortex-graph
        internal static async Task Save(object value, string collectionName, string databaseName)
        {
            using (var db = ArangoDatabase.CreateWithSetting(databaseName))
            {
                AssertionConcern.AssertStateTrue(await Helper.GraphExists(db), Constants.Messages.Error.GraphNotInitialized);

                var txnParams = new List <object> {
                    value
                };

                string[] collections = new string[] { collectionName };

                // https://docs.arangodb.com/3.1/Manual/Appendix/JavaScriptModules/ArangoDB.html
                // This 'ArangoDB' module should not be confused with the arangojs JavaScript driver.
                var r = await db.ExecuteTransactionAsync <object>(
                    new TransactionData()
                {
                    Collections = new TransactionCollection()
                    {
                        Read  = collections,
                        Write = collections
                    },
                    Action = $@"
    function (params) {{ 
        const db = require('@arangodb').db;
        if (db.{collectionName}.exists(params[0]))
        {{
            db.{collectionName}.remove(params[0]);
        }}

        db.{collectionName}.save(params[0]);
    }}",
                    Params = txnParams
                }
                    );
            }
        }
예제 #30
0
파일: Helper.cs 프로젝트: ei8/cortex-graph
 internal async static Task CreateDatabase(ISettingsService settingsService)
 {
     ArangoDatabase.ChangeSetting(
         settingsService.DatabaseName,
         s =>
     {
         s.Database   = settingsService.DatabaseName;
         s.Url        = settingsService.DbUrl;
         s.Credential = new System.Net.NetworkCredential(settingsService.DbUsername, settingsService.DbPassword);
         s.SystemDatabaseCredential = s.Credential;
         // this ensures that dates are not parsed during jsonserialization
         // src/ArangoDB.Client/Serialization/DocumentSerializer.cs - DeserializeSingleResult does not use created serializer
         // src/ArangoDB.Client/Http/HttpCommand.cs - (line 141) setting EnabledChangeTracking to false ensures that Deserialize is called instead of DeserializeSingleResult
         s.DisableChangeTracking = true;
     }
         );
     using (var db = ArangoDatabase.CreateWithSetting(settingsService.DatabaseName))
     {
         if (!(await db.ListDatabasesAsync()).Any(s => s == settingsService.DatabaseName))
         {
             await db.CreateDatabaseAsync(settingsService.DatabaseName);
         }
     }
 }