예제 #1
0
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            this.Log  = providerRuntime.GetLogger(nameof(ArangoStorageProvider));
            this.Name = name;

            var databaseName = config.GetProperty("DatabaseName", "Orleans");
            var url          = config.GetProperty("Url", "http://localhost:8529");
            var username     = config.GetProperty("Username", "root");
            var password     = config.GetProperty("Password", "");
            var waitForSync  = config.GetBoolProperty("WaitForSync", true);

            collectionName = config.GetProperty("CollectionName", null);

            var serializationManager = providerRuntime.ServiceProvider.GetRequiredService <SerializationManager>();
            var grainRefConverter    = new GrainReferenceConverter(serializationManager, providerRuntime.GrainFactory);

            ArangoDatabase.ChangeSetting(s =>
            {
                s.Database              = databaseName;
                s.Url                   = url;
                s.Credential            = new NetworkCredential(username, password);
                s.DisableChangeTracking = true;
                s.WaitForSync           = waitForSync;
                s.Serialization.Converters.Add(grainRefConverter);
            });

            jsonSerializerSettings = new JsonSerializer();
            jsonSerializerSettings.Converters.Add(grainRefConverter);

            this.Database = new ArangoDatabase();

            return(Task.CompletedTask);
        }
예제 #2
0
        public ConfigDbContext(IOptions <ConfigDbSettings> options)
        {
            var configDbSettings = options.Value;

            ArangoDatabase.ChangeSetting(s =>
            {
                s.Database   = configDbSettings.DbName;
                s.Url        = configDbSettings.Url;
                s.Credential = new NetworkCredential(configDbSettings.UserName, configDbSettings.Password);
                s.SystemDatabaseCredential = new NetworkCredential(configDbSettings.UserName, configDbSettings.Password);
            });

            using (var db = ArangoDatabase.CreateWithSetting())
            {
                Versions = db.Document <DbVersions>(configDbSettings.BaseVersion);

                AppDefaults = db.Document <DbAppDefaults>(Versions.AppDefaults);

                UserDefaults = db.Document <DbUserDefaults>(Versions.UserDefaults);

                Cakes = db.Document <DbCakes>(Versions.Cakes);

                Avatars = db.Document <DbAvatars>(Versions.Avatars);

                Buildings = db.Document <DbBuildings>(Versions.Buildings);

                Store = db.Document <DbStore>(Versions.Store);
            }
        }
예제 #3
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);
            }
        }
예제 #4
0
 public ArangoConnection(ArangoOptions options)
 {
     ArangoDatabase.ChangeSetting(ArangoID, a =>
     {
         a.Url        = options.Url;
         a.Credential = options.Credential;
         a.SystemDatabaseCredential = options.SystemCredential;
         a.Database = options.Database;
     });
 }
예제 #5
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();
        }
예제 #6
0
        public void connect()
        {
            ArangoDatabase.ChangeSetting(s =>
            {
                s.Database = this.database;
                s.Url      = this.urlWithPort;

                // you can set other settings if you need
                s.Credential = new NetworkCredential(this.adminName, this.password);
                s.SystemDatabaseCredential = new NetworkCredential(this.adminName, this.password);
            });
        }
예제 #7
0
        static void Main(string[] args)
        {
            ArangoDatabase.ChangeSetting(s =>
            {
                s.Credential = new NetworkCredential(ConnectionConstants.ArangoUser, ConnectionConstants.ArangoPass);
            });

            ConnectionFactory factory = new ConnectionFactory
            {
                HostName    = ConnectionConstants.HostName,
                UserName    = ConnectionConstants.User,
                Password    = ConnectionConstants.Password,
                VirtualHost = ConnectionConstants.VHost
            };

            //factory2
            ConnectionFactory factory2 = new ConnectionFactory
            {
                HostName    = ConnectionConstants.HostName,
                UserName    = ConnectionConstants.User,
                Password    = ConnectionConstants.Password,
                VirtualHost = ConnectionConstants.VHost2
            };

            publicConnection = factory.CreateConnection();
            publicChannel    = publicConnection.CreateModel();
            publicChannel.BasicQos(0, 1, false); // Process only one message at a time
            string queueTaskPublisher = publicChannel.QueueDeclare().QueueName;

            publicChannel.QueueBind(queueTaskPublisher, "amq.topic", ConnectionConstants.QueuePublisher);

            //internal vhost
            connection = factory2.CreateConnection();
            channel    = connection.CreateModel();

            Console.WriteLine("Face Matching SERVICE Ready");
            Console.WriteLine("Consume to topic {0}", ConnectionConstants.QueuePublisher);
            EventingBasicConsumer eventingBasicConsumer = new EventingBasicConsumer(publicChannel);
            int counter = 0;

            eventingBasicConsumer.Received += (model, ea) =>
            {
                counter++;
                String  strMessage = System.Text.Encoding.UTF8.GetString(ea.Body);
                dynamic results    = JsonConvert.DeserializeObject <dynamic>(strMessage);
                Console.WriteLine("Service {1} : Received FB ID {0}", results.facebook_id, DateTime.Now);
                PublishTask(strMessage);
                // Acknowledge
                publicChannel.BasicAck(ea.DeliveryTag, false);
            };
            publicChannel.BasicConsume(queueTaskPublisher, false, eventingBasicConsumer);
        }
        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();
        }
예제 #9
0
        public ArangoConnection(ArangoOptions options)
        {
            // read arango setting from arango.json
            //string arangoSettingFilename = $"{AppContext.BaseDirectory}/arango.setting";

            //var arangoSetting = JsonConvert.DeserializeObject<ArangoOptions>(File.ReadAllText(arangoSettingFilename));

            ArangoDatabase.ChangeSetting(ArangoID, a =>
            {
                a.Url        = options.Url;
                a.Credential = options.Credential;
                a.SystemDatabaseCredential = options.SystemCredential;
                a.Database = options.Database;
            });
        }
예제 #10
0
        public ArangoPersistedGrantStore(ILogger <ArangoPersistedGrantStore> logger, IOptions <ArangoDBConfiguration> arangoDBConfig)
        {
            _logger         = logger;
            _arangoDBConfig = arangoDBConfig.Value;

            var creds = new NetworkCredential(
                _arangoDBConfig.Credentials.UserName,
                _arangoDBConfig.Credentials.Password
                );

            ArangoDatabase.ChangeSetting(s =>
            {
                s.Database   = arangoDBConfig.Value.Database;
                s.Url        = arangoDBConfig.Value.Url;
                s.Credential = creds;
                s.SystemDatabaseCredential = creds;
            });
        }
예제 #11
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);
                }
            }
        }
예제 #12
0
        public Task Init(CancellationToken ct)
        {
            var grainRefConverter = new GrainReferenceConverter(TypeResolver, GrainFactory);

            JsonSerializerSettings = new JsonSerializer();
            JsonSerializerSettings.Converters.Add(grainRefConverter);

            ArangoDatabase.ChangeSetting(s =>
            {
                s.Database              = Options.DatabaseName;
                s.Url                   = Options.Url;
                s.Credential            = new NetworkCredential(Options.Username, Options.Password);
                s.DisableChangeTracking = true;
                s.WaitForSync           = Options.WaitForSync;
                s.Serialization.Converters.Add(grainRefConverter);
            });

            this.Database = new ArangoDatabase();

            return(Task.CompletedTask);
        }
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            this.Log  = providerRuntime.GetLogger(nameof(ArangoStorageProvider));
            this.Name = name;

            var databaseName = config.GetProperty("DatabaseName", "Orleans");
            var url          = config.GetProperty("Url", "http://localhost:8529");
            var username     = config.GetProperty("Username", "root");
            var password     = config.GetProperty("Password", "password");

            waitForSync = config.GetBoolProperty("WaitForSync", true);

            var grainRefConverter = new GrainReferenceConverter();

            settings = new JsonSerializer();
            settings.DefaultValueHandling  = DefaultValueHandling.Include;
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            settings.ConstructorHandling   = ConstructorHandling.AllowNonPublicDefaultConstructor;
            settings.Converters.Add(grainRefConverter);

            if (!isInitialized)
            {
                ArangoDatabase.ChangeSetting(s =>
                {
                    s.Database              = databaseName;
                    s.Url                   = url;
                    s.Credential            = new NetworkCredential(username, password);
                    s.DisableChangeTracking = true;
                    s.WaitForSync           = waitForSync;
                    s.Serialization.Converters.Add(grainRefConverter);
                });
                isInitialized = true;
            }
            Database        = new ArangoDatabase();
            collectionsList = await Database.ListCollectionsAsync();
        }
예제 #14
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);
         }
     }
 }
예제 #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddMvc(options =>
            {
                options.ModelBinderProviders.Insert(0, new TupleModelBinderProvider());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Latest)
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            });

            var storage    = CloudStorageAccount.Parse(Configuration["AppSettings:AzureFiles:ConnectionString"]);
            var blobClient = storage.CreateCloudBlobClient();
            var container  = blobClient.GetContainerReference("maxorgconfig");

            services.AddDataProtection().PersistKeysToAzureBlobStorage(container.GetBlockBlobReference("maxorgkey"));
            services.AddScoped <IPasswordHasher <User>, ArgonPasswordHasher <User> >();

            services.AddAntiforgery(
                options =>
            {
                options.Cookie.Name         = "_af";
                options.Cookie.HttpOnly     = true;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.HeaderName          = "X-XSRF-TOKEN";
            }
                );

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser()
                               .Build());
                auth.DefaultPolicy = auth.GetPolicy(JwtBearerDefaults.AuthenticationScheme);
            });


            var key = Encoding.ASCII.GetBytes(Configuration["AppSettings:Secret"]);

            services.AddAuthentication(options =>
            {
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = "GitHub";
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidIssuer = Configuration["AppSettings:DefaultURL"],
                    ClockSkew   = TimeSpan.Zero
                };
                options.Audience = Configuration["AppSettings:Jwt:Audience"];
                options.Events   = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        if (accessToken.Count > 0)
                        {
                            context.Token = accessToken;
                        }

                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist/ClientApp"; });

            // Configure ArangoDB settings, to instantiate an object to communicate with Arango
            ArangoDatabase.ChangeSetting(settings =>
            {
                settings.Database = Configuration["AppSettings:Database:Name"];
                settings.Url      = Configuration["AppSettings:Database:Host"];

                var dbUsername = Configuration["AppSettings:Database:User"];
                var dbPassword = Configuration["AppSettings:Database:Password"];

                settings.Credential = new NetworkCredential(dbUsername, dbPassword);
                settings.SystemDatabaseCredential = new NetworkCredential(dbUsername, dbPassword);
                settings.WaitForSync = true;
                settings.ClusterMode = true;
                settings.Serialization.SerializeEnumAsInteger = false;
            });

            using (var db = ArangoDatabase.CreateWithSetting())
            {
                CreateCollection(db, "Group");
                CreateCollection(db, "RefreshToken");
                CreateCollection(db, "User");
                CreateCollection(db, "Subgroup", CollectionType.Edge);
                CreateCollection(db, "UsersInGroup", CollectionType.Edge);
            }
            services.AddOptions();
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));

            services.AddTransient(provider => ArangoDatabase.CreateWithSetting());
            services.AddTransient <IEmailSender, RegistrationSender>();
            services.AddSingleton(new HttpClient());

            services.AddSingleton <IScheduledTask, RemoveExpiredTokens>();
            services.AddSingleton <IScheduledTask, RemoveEmptyUsers>();
            services.AddSingleton <IScheduledTask, CheckCalendar>();
            services.AddScheduler((sender, args) => { args.SetObserved(); });
            services.AddSignalR();

            ConfigureAzure(services);

            services.Configure <GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Optimal;
            });

            services.Configure <BrotliCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Optimal;
            });

            services.AddResponseCompression(options =>
            {
                options.Providers.Add <BrotliCompressionProvider>();
                options.Providers.Add <GzipCompressionProvider>();
                options.EnableForHttps = true;
            });
            services.AddWebSockets(configure =>
            {
            });
        }