public DataBaseHandlingService()
        {
            try
            {
                conn = r.Connection().Hostname("127.0.0.1").Timeout(60).Connect();
            } catch (Exception e)
            {
                if (Convert.ToString(Environment.OSVersion.Platform) == "Unix")
                {
                    Console.WriteLine("\nAs this is a Unix machine, the bot cannot automatically open RethinkDB. Please enter rethinkdb into a console to start it.");
                    Environment.Exit(0);
                }

                Process rdb = new Process();
                rdb.StartInfo.UseShellExecute  = false;
                rdb.StartInfo.FileName         = Resources.RethinkDBExec + "rethinkdb.exe";
                rdb.StartInfo.CreateNoWindow   = true;
                rdb.StartInfo.WorkingDirectory = Resources.RethinkDBExec;
                bool work = rdb.Start();
                if (work)
                {
                    conn = r.Connection().Hostname("127.0.0.1").Timeout(60).Connect();
                }
                else
                {
                    throw new Exception();
                }
            }
        }
        public void can_connect()
        {
            var c = R.Connection()
                    .Hostname(AppSettings.TestHost)
                    .Port(AppSettings.TestPort)
                    .Timeout(60)
                    .Connect();

            int result = R.Random(1, 9).Add(R.Random(1, 9)).Run <int>(c);

            result.Should().BeGreaterOrEqualTo(2).And.BeLessThan(18);
        }
Exemple #3
0
        public void BeforeEachTest()
        {
            FixtureWaitHandle.WaitOne();

            conn = r.Connection()
                   .Hostname(AppSettings.TestHost)
                   .Port(AppSettings.TestPort)
                   .Connect();

            try
            {
                r.dbCreate(DbName).Run(conn);
                r.db(DbName).wait_().Run(conn);
            }
            catch
            {
            }

            foreach (var tableName in tableVars)
            {
                try
                {
                    r.db(DbName).tableCreate(tableName).Run(conn);
                    r.db(DbName).table(tableName).wait_().Run(conn);
                }
                catch
                {
                }
            }
        }
 void InitPool()
 {
     // DO NOT LOCK HERE
     if (Configuration.EnableRethinkSKS)
     {
         Logger.Log("DatabaseManager", $"Initializing RethinkDB Connection Pool for SKS at {Configuration.RethinkDBHost}:{Configuration.RethinkDBPort} with pool size {Configuration.RethinkDBPoolSize}");
         int tryCount = 0;
         while (connectionPool.Count < Configuration.RethinkDBPoolSize)
         {
             try {
                 // That library has a Connection pool but does not support hostname which is used by Rancher and other orchestrations in Load Balancer
                 var c = R.Connection()
                         .Hostname(Configuration.RethinkDBHost)
                         .Port(Configuration.RethinkDBPort)
                         .Timeout(60)
                         .Connect();
                 connectionPool.Add(c);
                 tryCount = 0;
             } catch (Exception e) {
                 tryCount++;
                 Logger.Error("DatabaseManager", $"Error connecting to database {e}");
             }
             if (tryCount > MAX_RETRY_COUNT)
             {
                 Logger.Error("DatabaseManager", $"Max Retries of {MAX_RETRY_COUNT} trying to connect to database.");
                 throw new ApplicationException($"Max Retries of {MAX_RETRY_COUNT} trying to connect to database.");
             }
         }
         InitData();
     }
 }
 private Connection NewConnection()
 {
     return R.Connection()
      .Hostname(ip)
      .Port(RethinkDBConstants.DefaultPort)
      .Timeout(60)
      .Connect();
 }
Exemple #6
0
 public Database()
 {
     c = R.Connection()
         .Hostname("localhost")
         .Port(RethinkDBConstants.DefaultPort)
         .Timeout(60)
         .Connect();
 }
Exemple #7
0
        public Connection CreateConnection()
        {
            var dbSettings = _config.GetSection("connection").Get <DatabaseSettings>();

            return(_dbDriver.Connection()
                   .Hostname(dbSettings.Hostname)
                   .Port(RethinkDBConstants.DefaultPort)
                   .Timeout(60).Connect());
        }
Exemple #8
0
 private void connectBtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
 {
     var c = R.Connection()
             .Hostname("127.0.0.1")
             .Port(RethinkDBConstants.DefaultPort)
             .Db("gerdb")
             .Timeout(60)
             .Connect();
 }
Exemple #9
0
 public static async Task Connect()
 {
     try
     {
         conn = r.Connection().Hostname("127.0.0.1").Timeout(60).Connect();
     } catch (Exception e)
     {
         Error.Throw("A connection to the database could not be established. This may be due to a bad internet connection, or the database may be down.");
     }
 }
        public static Connection connection()
        {
            var conn = R.Connection()
                       .Hostname("localhost")
                       .Port(RethinkDBConstants.DefaultPort)
                       .Timeout(60)
                       .Connect();

            return(conn);
        }
        private void Connect(Entitron.Entity.Nexus.ExtDB info)
        {
            dbName = info.DB_Name;

            c = r.Connection()
                .Hostname(info.DB_Server)
                .Port(Convert.ToInt32(info.DB_Port))
                .Timeout(60)
                .Connect();
        }
        public virtual dynamic getConnection()
        {
            RethinkDB R    = RethinkDB.R;
            var       conn = R.Connection()
                             .Hostname(this.hostname)
                             .Port(this.port)
                             .AuthKey(this.password)
                             .Timeout(60)
                             .Connect();


            return(conn);
        }
Exemple #13
0
 public RethinkDBState(string hostName = "127.0.0.1", int port = RethinkDBConstants.DefaultPort)
 {
     this._rethinkHostUrl  = hostName;
     this._rethinkHostPort = port;
     if (connection == null)
     {
         connection = rethinkDB
                      .Connection()
                      .Hostname(hostName)
                      .Port(port)
                      .Timeout(60)
                      .Connect();
     }
 }
Exemple #14
0
    { //shermaine calling restful api of ReThinkDB to connect to gamedatabase to update coins in real mmo game
        public bool Update(string GameUsername, int Gold)
        {
            try
            {
                RethinkDB  R    = new RethinkDB();
                Connection conn = R.Connection()
                                  .Hostname("localhost")
                                  .Port(28015)
                                  .Db("mmorpg")
                                  //.User("admin", "admin")
                                  .Timeout(60)
                                  .Connect();

                Console.WriteLine(R.Db("mmorpg").TableList().Run(conn));


                var results = R.Table("users").Filter(g => g["username"].Eq(GameUsername)).Run(conn);

                string id = "";
                foreach (var result in results)
                {
                    id = result["id"];
                }

                var results2 = R.Table("users").GetAll(id).G("stats").G("gold").Run(conn);

                string gold2 = "";
                foreach (var resultd in results2)
                {
                    gold2 = resultd.ToString();
                }


                Console.WriteLine(id);
                int gold3 = Convert.ToInt32(gold2);

                if (id == "")
                {
                    return(false);
                }
                R.Table("users").Get(id).Update(R.HashMap("stats", R.HashMap("gold", gold3 + Gold))).Run(conn);

                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Exemple #15
0
        // TODO: Connection pool somehow kty
        public Connection CreateConnection()
        {
            Connection conn = R.Connection()
                              .Hostname(_options.Host)
                              .Port(_options.Port)
                              .Timeout(_options.Timeout)
                              .User(_options.Username, _options.Password).Connect();

            if (!conn.Open)
            {
                conn.Reconnect();
            }

            return(conn);
        }
        public static void HandleUpdates()
        {
            var hub  = GlobalHost.ConnectionManager.GetHubContext <ChatHub>();
            var conn = R.Connection().Connect();
            var feed = R.Db("test").Table("chat")
                       .Changes().RunChanges <ChatMessage>(conn);

            foreach (var message in feed)
            {
                hub.Clients.All.onMessage(
                    message.NewValue.username,
                    message.NewValue.message,
                    message.NewValue.timestamp);
            }
        }
Exemple #17
0
        public Connection CreateConnection()
        {
            if (conn == null)
            {
                conn = R.Connection()
                       .Hostname(_options.Host)
                       .Port(_options.Port)
                       .Timeout(_options.Timeout)
                       .Connect();
            }

            if (!conn.Open)
            {
                conn.Reconnect();
            }

            return(conn);
        }
Exemple #18
0
 public RethinkService(string meetingId, InkCanvas inkCanv, InkCanvas guestInkCanv)
 {
     try
     {
         _meetingId      = meetingId;
         _boardInkCanvas = inkCanv;
         _guestInkCanvas = guestInkCanv;
         _rethinkCon     = _rethinkDb.Connection().Hostname(_rethinkServer).Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();
         if (_rethinkCon != null && _rethinkCon.Open)
         {
             CreateDatabase(_rethinkDatabase);
             //GetDefaultBoardData();
             GetDataChanges();
         }
     }
     catch (Exception ex)
     {
         App.InsertException(ex);
     }
 }
Exemple #19
0
        static void Main(string[] args)
        {
            HostConfiguration hostConfiguration = new HostConfiguration()
            {
                RewriteLocalhost = false
            };

            // run behind nginx proxy
            _host = new NancyHost(hostConfiguration, new Uri("http://localhost:8888"));

            try
            {
                Conn = R.Connection()
                       .Hostname("localhost")
                       .Port(RethinkDBConstants.DefaultPort)
                       .Timeout(RethinkDBConstants.DefaultTimeout)
                       .Connect();
            }catch (Exception e)
            {
                Console.WriteLine("Can't connect to RethinkDB database: " + e.Message);

                return;
            }

            _host.Start();

            Console.CancelKeyPress += (sender, e) =>
            {
                Console.WriteLine("^c pressed quiting..");

                _host.Dispose();
                Conn.Close();

                Environment.Exit(0);
            };

            while (true)
            {
                Thread.Sleep(1);
            }
        }
Exemple #20
0
 public static void dbinit()
 {
     Connection.Builder builder = r.Connection().Hostname("localhost").Port(28015);
     // connect
     Console.WriteLine("Floatzel is now loading EzioSoft RethinkDB Driver V2...");
     thonk = builder.Connect();
     // check if the database exists
     if (!(bool)r.DbList().Contains("FloatzelSharp").Run(thonk))
     {
         // it doesnt exist! make that database!
         Console.WriteLine("Database not detected! creating new database...");
         r.DbCreate("FloatzelSharp").Run(thonk);
         thonk.Use("FloatzelSharp");
         Console.WriteLine("Creating tables...");
         makeTables();
         Console.WriteLine("Database created!");
     }
     else
     {
         thonk.Use("FloatzelSharp");
         Console.WriteLine("Driver loaded!");
     }
     // check for legacy database stuff
     Console.WriteLine("Floatzel is now checking for 2.x database...");
     if ((bool)r.DbList().Contains("floatzel").Run(thonk))
     {
         oldthonk = builder.Connect();
         oldthonk.Use("floatzel");
         Console.WriteLine("Floatzel found 2.x database! Will convert data as its accessed");
         hasOld = true;
     }
     else
     {
         Console.WriteLine("Floatzel did not find 2.x databse!");
     }
 }
Exemple #21
0
        private void frmMain_Load(object sender, EventArgs e)
        {
            var assemblyInfo = Assembly.GetExecutingAssembly().GetName();

            Text = $"{assemblyInfo.Name} {assemblyInfo.Version.ToString(3)}";

            if (Config.Get() == null)
            {
                Application.Exit();
            }

            Task.Run(() =>
            {
                _connection = R.Connection()
                              .Hostname(Config.Get().Host)
                              .Port(Config.Get().Port)
                              .User(Config.Get().Username, Config.Get().Password)
                              .Connect();

                _rHelper = new RethinkHelper(_connection);

                FillTreeWithDatabases();
            });
        }
        public static int Main(string[] args)
        {
            const string rethinkHost = "localhost";
            const string redisHost   = "localhost";
            const string dbName      = "doc_stack_db";
            const string tableName   = "documents";

            //indexes
            const string name_client_user_index = "name_client_user";

            var ip = GetIp(rethinkHost);

            var c = R.Connection()
                    .Hostname(ip)
                    .Port(RethinkDBConstants.DefaultPort)
                    .Timeout(60)
                    .Connect();

            List <string> dbs = R.DbList().Run <List <string> >(c);

            if (!dbs.Contains(dbName))
            {
                R.DbCreate(dbName).Run(c);
            }
            var db = R.Db(dbName);

            List <string> tables = db.TableList().Run <List <string> >(c);

            if (!tables.Contains(tableName))
            {
                db.TableCreate(tableName).Run(c);
            }
            var documentTable = db.Table(tableName);

            List <string> indexes = documentTable.IndexList().Run(c);

            if (!indexes.Contains(name_client_user_index))
            {
                RethinkDb.Driver.Ast.ReqlFunction1 pathIx = row => { return(R.Array(row["name"], row["client"], row["user"])); };
                documentTable.IndexCreate("name_client_user", pathIx).Run(c);
                documentTable.IndexWait("name_client_user").Run(c);
            }

            try
            {
                var redis = OpenRedisConnection(redisHost).GetDatabase();

                var definition = new { id = "", name = "", size = 0, user = "", client = "", content = "" };

                while (true)
                {
                    string json = redis.ListLeftPopAsync("documents:process:0").Result;
                    if (json != null)
                    {
                        var document = JsonConvert.DeserializeAnonymousType(json, definition);
                        Console.WriteLine($"Document '{document.name}/{document.id}/{document.user}/{document.client}' will be persisted");
                        var now    = DateTime.UtcNow;
                        var toSave = new { id = document.id, user = document.user, client = document.client, name = document.name, document = document, inserted = now, updated = now, state = new[] { "persisted" } };

                        //first check if the document maybe already exists - right now we will just override
                        var x = new[] { "ocr-test2.png", "dummyClient", "dummyUser" };
                        //documentTable.GetAll(x).OptArg("index", "name_client_user");
                        //
                        documentTable.Insert(toSave).Run(c);
                    }
                    else
                    {
                        Thread.Sleep(500);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
                return(1);
            }
        }
Exemple #23
0
 public static Connection.Builder DefaultConnectionBuilder()
 {
     return(R.Connection()
            .Hostname(AppSettings.TestHost)
            .Port(AppSettings.TestPort));
 }
Exemple #24
0
    public override void OnInspectorGUI()
    {
        var galaxy = target as Galaxy;

        if (_currentLayer == null)
        {
            _currentLayer = galaxy.MapData.StarDensity;
        }

        if (Screen.width != _width)
        {
            _width   = Screen.width;
            _starTex = new Texture2D(_width, _width, TextureFormat.ARGB32, false);
            _linkTex = new Texture2D(_width, _width, TextureFormat.ARGB32, false);
            RenderStars();
            RenderLinks();
        }

        GUILayout.Label("Preview", EditorStyles.boldLabel);
        _galaxyMat.SetFloat("Arms", galaxy.MapData.GlobalData.Arms);
        _galaxyMat.SetFloat("Twist", galaxy.MapData.GlobalData.Twist);
        _galaxyMat.SetFloat("TwistPower", galaxy.MapData.GlobalData.TwistPower);
        _galaxyMat.SetFloat("SpokeOffset", _currentLayer.SpokeOffset);
        _galaxyMat.SetFloat("SpokeScale", _currentLayer.SpokeScale);
        _galaxyMat.SetFloat("CoreBoost", _currentLayer.CoreBoost);
        _galaxyMat.SetFloat("CoreBoostOffset", _currentLayer.CoreBoostOffset);
        _galaxyMat.SetFloat("CoreBoostPower", _currentLayer.CoreBoostPower);
        _galaxyMat.SetFloat("EdgeReduction", _currentLayer.EdgeReduction);
        _galaxyMat.SetFloat("NoisePosition", _currentLayer.NoisePosition);
        _galaxyMat.SetFloat("NoiseAmplitude", _currentLayer.NoiseAmplitude);
        _galaxyMat.SetFloat("NoiseOffset", _currentLayer.NoiseOffset);
        _galaxyMat.SetFloat("NoiseGain", _currentLayer.NoiseGain);
        _galaxyMat.SetFloat("NoiseLacunarity", _currentLayer.NoiseLacunarity);
        _galaxyMat.SetFloat("NoiseFrequency", _currentLayer.NoiseFrequency);
        var rect = GetControlRect(false, _width);

        EditorGUI.DrawPreviewTexture(rect, _white, _galaxyMat);
        if (_drawLinks)
        {
            EditorGUI.DrawPreviewTexture(rect, _linkTex, _transparent);
        }
        if (_drawStars)
        {
            EditorGUI.DrawPreviewTexture(rect, _starTex, _transparent);
        }

        _drawStars    = ToggleLeft($"Display {_stars.Count()} Stars", _drawStars);
        _drawResource = ToggleLeft("Display Resources", _drawResource);
        _drawLinks    = ToggleLeft($"Display {_starLinks.Count} Links", _drawLinks);

        GUILayout.Space(10);

        // Show default inspector property editor
        DrawDefaultInspector();

        BeginVertical("Box");
        EditorGUI.indentLevel++;
        GUILayout.Label(_currentLayerName);
        Inspect(_currentLayer);
        EditorGUI.indentLevel--;
        EndVertical();

        BeginVertical("Box");
        EditorGUI.indentLevel++;
        _showResourceMaps = Foldout(_showResourceMaps, "Resource Density Maps");
        if (_showResourceMaps)
        {
            EditorGUI.indentLevel++;
            foreach (var resourceDensity in galaxy.MapData.ResourceDensities)
            {
                BeginHorizontal();
                resourceDensity.Name = DelayedTextField(resourceDensity.Name);
                if (GUILayout.Button("Inspect"))
                {
                    _currentLayer = resourceDensity;
                }
                if (GUILayout.Button("Copy"))
                {
                    galaxy.MapData.ResourceDensities.Add(resourceDensity.Copy());
                }
                EndHorizontal();
            }
            EditorGUI.indentLevel--;
            if (GUILayout.Button("Add New Resource"))
            {
                galaxy.MapData.ResourceDensities.Add(new GalaxyMapLayerData()
                {
                    Name = "New Resource"
                });
            }
        }
        else if (_currentLayer != galaxy.MapData.StarDensity)
        {
            _currentLayerName = "Star Density";
            _currentLayer     = galaxy.MapData.StarDensity;
        }
        EditorGUI.indentLevel--;
        EndVertical();

        BeginVertical("Box");
        EditorGUI.indentLevel++;
        _showStarEditor = Foldout(_showStarEditor, "Star Tools");
        if (_showStarEditor)
        {
            _hilbertOrder = IntField("Hilbert Order", _hilbertOrder);
            _starCount    = IntField("Star Count", _starCount);
            //_hilbertIndex = (ulong) EditorGUILayout.IntField("Hilbert Index", (int) _hilbertIndex);
            if (GUILayout.Button("Evaluate Hilbert Curve"))
            {
                var points = EvaluateHilbert(_hilbertOrder, false);
                Debug.Log($"Hilbert curve has {points.Count()} points, resolution {Mathf.RoundToInt(points.Max(p=>p.x))+1}");
            }

            _minStarDistance = FloatField("Minimum Star Distance", _minStarDistance);

            if (GUILayout.Button("Generate Stars"))
            {
                var points = EvaluateHilbert(_hilbertOrder).ToArray();
                var stars  = new List <Vector2>();
                int bail   = 0;
                while (stars.Count < _starCount && bail < 10)
                {
                    var accum = 0f;
                    foreach (var hp in points.Select(p => p + Random.insideUnitCircle * ((points[0] - points[1]).magnitude / 2)))
                    {
                        var den = galaxy.MapData.StarDensity.Evaluate(hp, galaxy.MapData.GlobalData);
                        if (!float.IsNaN(den))
                        {
                            accum += saturate(den) * Random.value;
                        }
//						else
//							Debug.Log($"Density at ({hp.x},{hp.y}) is NaN");
                        if (accum > 1 && (!stars.Any() || stars.Min(s => (s - hp).magnitude) > _minStarDistance))
                        {
                            stars.Add(hp);
                            accum = 0;
                        }
                        //Debug.Log($"Accumulator: {accum}");
                    }
                    bail++;
                }
                Debug.Log($"Generated {stars.Count} stars.");
                _stars = stars;
                RenderStars();
            }
            if (_stars.Any())
            {
                _maxLinkLength = FloatField("Max Link Length", _maxLinkLength);
                if (GUILayout.Button("Generate Star Links"))
                {
                    _voronoiMesh = VoronoiMesh <Vertex2, Cell2, VoronoiEdge <Vertex2, Cell2> > .Create(_stars.Select(s => new Vertex2(s.x, s.y)).ToList());

                    _starLinks.Clear();
                    // Each cell in this collection represents one of the triangle faces of the Delaunay Triangulation
                    foreach (var cell in _voronoiMesh.Vertices)
                    {
                        var links = new[] { new VoronoiLink(cell.Vertices[0], cell.Vertices[1]),
                                            new VoronoiLink(cell.Vertices[0], cell.Vertices[2]),
                                            new VoronoiLink(cell.Vertices[2], cell.Vertices[1]) };

                        _starLinks.AddRange(links.Where(l => !_starLinks.ContainsLine(l) && l.Length < _maxLinkLength));
                        RenderLinks();
                    }
                }
                if (_starLinks.Any())
                {
                    _linkFilter = FloatField("Link Filter Percentage", _linkFilter);
                    if (GUILayout.Button("Filter Star Links"))
                    {
                        var bail      = 0;
                        var count     = _starLinks.Count * Mathf.Clamp01(_linkFilter);
                        var deadLinks = new List <VoronoiLink>();
                        for (int i = 0; i < count && bail < count * 10; bail++)
                        {
                            var link = _starLinks.ElementAt(Random.Range(0, _starLinks.Count));

                            if (deadLinks.Contains(link))
                            {
                                continue;
                            }

                            var mapMinusLink = _starLinks.Where(l => !l.Equals(link)).ToArray();
                            if (!mapMinusLink.ConnectedRegion(link.point1).Contains(link.point2))
                            {
                                deadLinks.Add(link);
                            }
                            else
                            {
                                _starLinks.Remove(link);
                                i++;
                            }
                            //if (_starLinks.Count(sl => sl.ContainsPoint(link.point1)) > 1 && _starLinks.Count(sl => sl.ContainsPoint(link.point2)) > 1)
                        }
                        RenderLinks();
                    }
                    if (GUILayout.Button("Save Star Data"))
                    {
                        galaxy.MapData.Stars = _stars.Select(s => new StarData {
                            Position = s
                        }).ToList();
                        foreach (var star in galaxy.MapData.Stars)
                        {
                            star.Links.Clear();
                            star.Links.AddRange(_starLinks.Where(sl => (sl.point1.ToVector2() - star.Position).sqrMagnitude < float.Epsilon)
                                                .Select(sl => galaxy.MapData.Stars.IndexOf(galaxy.MapData.Stars.First(s => (sl.point2.ToVector2() - s.Position).sqrMagnitude < float.Epsilon))));
                            star.Links.AddRange(_starLinks.Where(sl => (sl.point2.ToVector2() - star.Position).sqrMagnitude < float.Epsilon)
                                                .Select(sl => galaxy.MapData.Stars.IndexOf(galaxy.MapData.Stars.First(s => (sl.point1.ToVector2() - s.Position).sqrMagnitude < float.Epsilon))));
                        }
                    }

                    if (GUILayout.Button("Connect to RethinkDB"))
                    {
                        _connection = R.Connection().Hostname(EditorPrefs.GetString("RethinkDB.URL")).Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();
                    }
                    EditorGUI.BeginDisabledGroup(_connection == null);

                    if (GUILayout.Button("Drop Galaxy Table"))
                    {
                        R.Db("Aetheria").TableDrop("Galaxy").Run(_connection);
                    }

                    if (GUILayout.Button("Create Galaxy Table"))
                    {
                        R.Db("Aetheria").TableCreate("Galaxy").Run(_connection);
                    }

                    EditorGUI.BeginDisabledGroup(!galaxy.MapData.Stars.Any());

                    if (GUILayout.Button("Upload Star Data"))
                    {
                        Converter.Serializer.Converters.Add(new MathJsonConverter());
                        JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                        {
                            Converters = new List <JsonConverter>
                            {
                                new MathJsonConverter(),
                                Converter.DateTimeConverter,
                                Converter.BinaryConverter,
                                Converter.GroupingConverter,
                                Converter.PocoExprConverter
                            }
                        };
                        var starIDs = new Dictionary <StarData, Guid>();
                        foreach (var star in galaxy.MapData.Stars)
                        {
                            starIDs[star] = Guid.NewGuid();
                        }
                        foreach (var star in galaxy.MapData.Stars)
                        {
                            R.Db("Aetheria").Table("Galaxy").Insert(new ZoneData
                            {
                                ID        = starIDs[star],
                                Name      = starIDs[star].ToString().Substring(0, 8),
                                Wormholes = star.Links.Select(i => starIDs[galaxy.MapData.Stars[i]]).ToList(),
                                Position  = star.Position
                            }).Run(_connection);
                        }

                        //galaxy.MapData.GlobalData.MapLayers["StarDensity"] = galaxy.MapData.StarDensity.ID = Guid.NewGuid();
                        galaxy.MapData.StarDensity.Name = "StarDensity";
                        R.Db("Aetheria").Table("Galaxy").Insert(galaxy.MapData.StarDensity).Run(_connection);
                        foreach (var data in galaxy.MapData.ResourceDensities)
                        {
                            // galaxy.MapData.GlobalData.MapLayers[data.Name] = data.ID = Guid.NewGuid();
                            R.Db("Aetheria").Table("Galaxy").Insert(data).Run(_connection);
                        }

                        R.Db("Aetheria").Table("Galaxy").Insert(galaxy.MapData.GlobalData).Run(_connection);
                    }

                    EditorGUI.EndDisabledGroup();

                    EditorGUI.EndDisabledGroup();
                }
            }
        }
        EditorGUI.indentLevel--;
        EndVertical();


        EditorUtility.SetDirty(target);
    }
 private void OnEnable()
 {
     _connection = R.Connection().Hostname(EditorPrefs.GetString("RethinkDB.URL")).Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();
 }
 internal static void Init()
 {
     conn = R.Connection().Connect();
 }
        static async Task Main(string[] args)
        {
            var serilogger = new LoggerConfiguration()
                             .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
                             .CreateLogger();
            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder
                // .AddFilter("Microsoft", LogLevel.Warning)
                // .AddFilter("System", LogLevel.Warning)
                // .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
                .AddSerilog(serilogger)
                .AddConsole();
            });

            _logger = loggerFactory.CreateLogger <Program>();

            // Register extensions to Json.NET Serialization
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Converters = new List <JsonConverter>
                {
                    new MathJsonConverter(),
                    Converter.DateTimeConverter,
                    Converter.BinaryConverter,
                    Converter.GroupingConverter,
                    Converter.PocoExprConverter
                }
            };
            Converter.Serializer.Converters.Add(new MathJsonConverter());

            // Register extensions to MessagePack Serialization
            var resolver = CompositeResolver.Create(
                MathResolver.Instance,
                NativeGuidResolver.Instance,
                StandardResolver.Instance
                );
            var options = MessagePackSerializerOptions.Standard.WithResolver(resolver);

            MessagePackSerializer.DefaultOptions = options;

            var connection = R.Connection().Hostname("asgard.gamecult.games")
                             .Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();

            var cache = new DatabaseCache();

            // When entries are changed locally, push the changes to RethinkDB
            cache.OnDataUpdateLocal += async entry =>
            {
                var table  = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var result = await R.Db("Aetheria").Table(table).Update(entry).RunAsync(connection);

                _logger.Log(LogLevel.Information, $"Uploaded entry to RethinkDB: {entry.ID} result: {result}");
            };

            cache.OnDataInsertLocal += async entry =>
            {
                var table    = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var inserted = false;
                for (int i = 0; i < 5 && !inserted; i++)
                {
                    try
                    {
                        var result = await R.Db("Aetheria").Table(table).Insert(entry).RunAsync(connection);

                        _logger.Log(LogLevel.Information, $"Inserted entry to RethinkDB: {entry.ID} result: {result}");
                        inserted = true;
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e, e.Message);
                    }
                }
                if (!inserted)
                {
                    _logger.LogError("Failed to insert after 5 attempts!");
                }
            };

            cache.OnDataDeleteLocal += async entry =>
            {
                var table  = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var result = await R.Db("Aetheria").Table(table).Get(entry.ID).Delete().RunAsync(connection);

                _logger.Log(LogLevel.Information, $"Deleted entry from RethinkDB: {entry.ID} result: {result}");
            };

            // Get data from RethinkDB
            await GetTable("Items", connection, cache);
            await GetTable("Galaxy", connection, cache);
            await GetTable("Users", connection, cache);

            // Subscribe to changes from RethinkDB
            SubscribeTable("Items", connection, cache);
            SubscribeTable("Galaxy", connection, cache);
            SubscribeTable("Users", connection, cache);

            var server = new MasterServer(cache)
            {
                Logger = _logger
            };

            server.Start();

            var context = new GameContext(cache, s => _logger.Log(LogLevel.Information, s));

            context.MapLayers = cache.GetAll <GalaxyMapLayerData>().ToDictionary(m => m.Name);

            server.AddMessageListener <GalaxyRequestMessage>(galaxyRequest => galaxyRequest.Peer.Send(
                                                                 new GalaxyResponseMessage
            {
                Zones = cache.GetAll <ZoneData>().Select(zd =>
                                                         new GalaxyResponseZone
                {
                    Name     = zd.Name,
                    Position = zd.Position,
                    ZoneID   = zd.ID,
                    Links    = zd.Wormholes?.ToArray() ?? Array.Empty <Guid>()
                }).ToArray(),
                GlobalData  = context.GlobalData,
                StarDensity = context.MapLayers["StarDensity"]
            }));

            server.AddMessageListener <BlueprintsRequestMessage>(blueprintRequest => blueprintRequest.Peer.Send(
                                                                     new BlueprintsResponseMessage
            {
                Blueprints = cache.GetAll <BlueprintData>().ToArray()
            }));

            server.AddMessageListener <ZoneRequestMessage>(zoneRequest =>
            {
                var zone = cache.Get <ZoneData>(zoneRequest.ZoneID);

                // Zone has not been populated, generate the contents now!
                if (!zone.Visited)
                {
                    zone.Visited = true;
                    OrbitData[] orbits;
                    PlanetData[] planets;
                    ZoneGenerator.GenerateZone(
                        global: context.GlobalData,
                        zone: zone,
                        mapLayers: context.MapLayers.Values,
                        resources: cache.GetAll <SimpleCommodityData>().Where(i => i.ResourceDensity.Any()),
                        orbitData: out orbits,
                        planetsData: out planets);
                    cache.AddAll(orbits);
                    cache.AddAll(planets);
                    cache.Add(zone);
                }
                zoneRequest.Peer.Send(
                    new ZoneResponseMessage
                {
                    Zone     = zone,
                    Contents = zone.Orbits.Select(id => cache.Get(id))
                               .Concat(zone.Planets.Select(id => cache.Get(id)))
                               .Concat(zone.Stations.Select(id => cache.Get(id))).ToArray()
                });
            });

            Observable.Timer(DateTimeOffset.Now, TimeSpan.FromSeconds(60)).SubscribeOn(NewThreadScheduler.Default).Subscribe(_ =>
            {
                _logger.Log(LogLevel.Information, R.Now().Run <DateTime>(connection).ToString() as string);
            });

            while (true)
            {
                Thread.Sleep(100);
            }
        }
Exemple #28
0
        static async Task MainAsync(string[] args)
        {
            var types = Assembly.GetExecutingAssembly().GetTypes();

            foreach (var type in types)
            {
                // get all properties with the ConVar attribute
                var convars = type.GetProperties().Where(property => property.GetCustomAttributes(typeof(ConVarAttribute), false).Any());

                foreach (var property in convars)
                {
                    // get the convar attribute from the property
                    var convar = property.GetCustomAttribute <ConVarAttribute>(true);

                    // add the property to list of convars
                    // this will be used later to trace back which property belongs to which convar
                    ConVar.Convars.Add(convar.Name, new KeyValuePair <ConVarAttribute, PropertyInfo>(convar, property));
                }
            }

            if (args.Length == 0)
            {
                Console.WriteLine("No config file executed. Launch with 'dotnet Kurisu.dll bot.cfg'");
                return;
            }

            ReadConfig("build.cfg");

            // execute launch file
            ReadConfig(args[0]);

            // connect to database
            Connection = R.Connection()
                         .Hostname(DatabaseHostname)
                         .Port(RethinkDBConstants.DefaultPort)
                         .Timeout(RethinkDBConstants.DefaultTimeout)
                         .Connect();

            Connection.Use(Database);

            // initialize Discord bot
            Client = new DiscordClient(new DiscordConfiguration
            {
                Token                 = Token,
                TokenType             = TokenType.Bot,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            });

            Interactivity = Client.UseInteractivity(new InteractivityConfiguration());

            // setup modules
            Client.AddModule(new Scheduler());
            Client.AddModule(new Modules.Scan());

            // initialize CommandsNext
            Commands = Client.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefix = Prefix,
                EnableDms    = false
            });

            // register commands
            Commands.RegisterCommands <Administration>();
            Commands.RegisterCommands <Information>();
            Commands.RegisterCommands <Moderation>();
            Commands.RegisterCommands <Remind>();

            Commands.RegisterCommands <Commands.Welcome>();
            Commands.RegisterCommands <Commands.VirusScan>();
            Commands.RegisterCommands <Assistant>();

            Commands.CommandErrored += async e =>
            {
                if (e.Exception is CommandNotFoundException)
                {
                    return;
                }

                await e.Context.RespondAsync($"An error occured while executing the command:\n`{e.Exception.Message}`");
            };

            Client.Ready += async e =>
            {
                Client.DebugLogger.LogMessage(LogLevel.Info, "Kurisu", $"Logged in as {e.Client.CurrentUser.Username}", DateTime.Now);

                await Client.UpdateStatusAsync(new DiscordGame(Game));
            };

            Client.GuildMemberAdded += GuildMemberAdded;
            Client.GuildAvailable   += GuildAvailable;

            // start bot
            await Client.ConnectAsync();

            await Task.Delay(-1);
        }
Exemple #29
0
    public static RethinkQueryStatus RethinkConnect(DatabaseCache cache, string connectionString, bool syncLocalChanges = true, bool filterGalaxyData = true)
    {
        // Add Unity.Mathematics serialization support to RethinkDB Driver
        //Converter.Serializer.Converters.Add(new MathJsonConverter());
        JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        {
            Converters = new List <JsonConverter>
            {
                new MathJsonConverter(),
                Converter.DateTimeConverter,
                Converter.BinaryConverter,
                Converter.GroupingConverter,
                Converter.PocoExprConverter
            }
        };

        var connection = R.Connection().Hostname(connectionString).Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();

        Debug.Log("Connected to RethinkDB");

        if (syncLocalChanges)
        {
            // When entries are changed locally, push the changes to RethinkDB
            cache.OnDataUpdateLocal += async entry =>
            {
                var table  = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var result = await R
                             .Db("Aetheria")
                             .Table(table)
                             .Get(entry.ID)
                             .Replace(entry)
                             .RunAsync(connection);

                Debug.Log($"Uploaded entry to RethinkDB: {entry.ID} result: {result}");
            };

            cache.OnDataInsertLocal += async entry =>
            {
                var table  = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var result = await R
                             .Db("Aetheria")
                             .Table(table)
                             .Insert(entry)
                             .RunAsync(connection);

                Debug.Log($"Inserted entry to RethinkDB: {entry.ID} result: {result}");
            };

            cache.OnDataDeleteLocal += async entry =>
            {
                var table  = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var result = await R
                             .Db("Aetheria")
                             .Table(table)
                             .Get(entry.ID)
                             .Delete()
                             .RunAsync(connection);

                Debug.Log($"Deleted entry from RethinkDB: {entry.ID} result: {result}");
            };
        }

        var status = new RethinkQueryStatus();

        // Get all item data from RethinkDB
        Task.Run(async() =>
        {
            status.ItemsEntries = R
                                  .Db("Aetheria")
                                  .Table("Items")
                                  .Count().RunAtom <int>(connection);

            var result = await R
                         .Db("Aetheria")
                         .Table("Items")
                         .RunCursorAsync <DatabaseEntry>(connection);
            while (await result.MoveNextAsync())
            {
                var entry = result.Current;
                //Debug.Log($"Received Items entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
                cache.Add(entry, true);
                status.RetrievedItems++;
            }
        }).WrapErrors();

        // Get globaldata and all galaxy map layer data from RethinkDB
        Task.Run(async() =>
        {
            ReqlAst operation = R
                                .Db("Aetheria")
                                .Table("Galaxy");
            if (filterGalaxyData)
            {
                var filter = ((Table)operation).Filter(o =>
                                                       o["$type"] == typeof(GalaxyMapLayerData).Name ||
                                                       o["$type"] == typeof(GlobalData).Name ||
                                                       o["$type"] == typeof(MegaCorporation).Name);
                status.GalaxyEntries = filter.Count().RunAtom <int>(connection);
                operation            = filter;
            }
            else
            {
                status.GalaxyEntries = ((Table)operation).Count().RunAtom <int>(connection);
            }

            var result = await operation
                         .RunCursorAsync <DatabaseEntry>(connection);
            while (await result.MoveNextAsync())
            {
                var entry = result.Current;
                //Debug.Log($"Received Galaxy entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
                cache.Add(entry, true);
                status.RetrievedItems++;
            }
        }).WrapErrors();

        // Subscribe to changes from RethinkDB
        Task.Run(async() =>
        {
            var result = await R
                         .Db("Aetheria")
                         .Table("Items")
                         .Changes()
                         .RunChangesAsync <DatabaseEntry>(connection);
            while (await result.MoveNextAsync())
            {
                var change = result.Current;
                if (change.OldValue == null)
                {
                    Debug.Log($"Received change from RethinkDB (Entry Created): {change.NewValue.ID}");
                }
                else if (change.NewValue == null)
                {
                    Debug.Log($"Received change from RethinkDB (Entry Deleted): {change.OldValue.ID}");
                }
                else
                {
                    Debug.Log($"Received change from RethinkDB: {change.NewValue.ID}");
                }
                cache.Add(change.NewValue, true);
            }
        }).WrapErrors();

        Observable.Timer(DateTimeOffset.Now, TimeSpan.FromSeconds(60)).Subscribe(_ =>
        {
            Debug.Log(R.Now().Run <DateTime>(connection).ToString() as string);
        });

        return(status);
    }
Exemple #30
0
 internal static async Task Init()
 {
     conn = await R.Connection().ConnectAsync();
 }