Beispiel #1
0
 private PsMongoContext BindToMongo(string server, string databasename)
 {
     try
     {
         var connectionString = string.Format("mongodb://{0}:27017/{1}", server, databasename);
         this.IMongoClient = new MongoClient(connectionString);
         var dbs = IMongoClient.ListDatabases().ToList();
         if (dbs != null)
         {
             this.MongoIsConnected = true;
             this.IMongoDatabase   = this.IMongoClient.GetDatabase(databasename);
             return(this);
         }
         else
         {
             this.MongoIsConnected = false;
             throw new Exception("Unable to query for databases on server '" + server + "'!");
         }
     }
     catch (Exception e)
     {
         this.MongoIsConnected = false;
         throw new Exception("Something went wrong Binding to Mongo! Full Error:\r\n\r\n" + e.Message);
     }
 }
 public IEnumerable <string> GetDatabases()
 {
     return(_client.ListDatabases()
            .ToList()
            .Select(d => d.GetValue(0).ToString())
            .ToList());
 }
Beispiel #3
0
        public OperationResult Execute(CancellationToken cancellationToken)
        {
            try
            {
                using var cursor = _session == null
                    ? _client.ListDatabases(cancellationToken)
                    : _client.ListDatabases(_session, cancellationToken);

                var result = cursor.ToList(cancellationToken);

                return(OperationResult.FromResult(new BsonArray(result)));
            }
            catch (Exception exception)
            {
                return(OperationResult.FromException(exception));
            }
        }
Beispiel #4
0
 static List<string> GetActiveDatabases(IMongoClient client)
 {
     List<string> dbs = new List<string>();
     using (var cursor = client.ListDatabases()) // await + Async() seem to exit the programm ... @@@ ask Piercesare why
     {
         cursor.ForEachAsync(d => dbs.Add(d.GetElement("name").Value.AsString)); //use await?
     }
     return dbs;
 }
Beispiel #5
0
        public Task <bool> Start()
        {
            _mongoClient = new MongoClient(_mongoUrl.ToString());
            _logger.LogInformation($"Connecting to {_mongoUrl.DatabaseName}");
            _mongoDatabase = _mongoClient.GetDatabase(_mongoUrl.DatabaseName);
            _mongoClient.ListDatabases().ToList();
            _logger.LogInformation($"Connected {_mongoUrl.DatabaseName}");

            return(Task.FromResult(true));
        }
 public Result <IList <BsonDocument> > GetDatabase()
 {
     try
     {
         return(_client.ListDatabases().ToList());
     }
     catch (Exception ex)
     {
         return(Result.Failure <IList <BsonDocument> >(ex.Message));
     }
 }
Beispiel #7
0
        public MongoDBService()
        {
            dbClient = new MongoClient("mongodb://127.0.0.1:27017");
            var dbList = dbClient.ListDatabases().ToList();

            Console.WriteLine("The list of databases are:");

            foreach (var item in dbList)
            {
                Console.WriteLine(item);
            }
        }
        /// <summary>
        /// Simple class used to check if connection with mongo is ok or if the
        /// cluster cannot be contacted.
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public static bool CheckConnection(IMongoClient client)
        {
            Task.Factory.StartNew(() => client.ListDatabases()); //forces a database connection
            Int32        spinCount = 0;
            ClusterState clusterState;

            while ((clusterState = client.Cluster.Description.State) != ClusterState.Connected &&
                   spinCount++ < 100)
            {
                Thread.Sleep(20);
            }
            return(clusterState == ClusterState.Connected);
        }
 public MongoDbContactOperations(string dbName)
 {
     Client = new MongoClient();
     //Check if MongoDb is running
     try
     {
         Client.ListDatabases();
     }
     catch
     {
         throw new Exception("MongoDb is not running");
     }
     Database = Client.GetDatabase(dbName);
 }
Beispiel #10
0
        public List <string> GetDatabasesNames()
        {
            List <string> dbNames = new List <string>();
            IAsyncCursor <BsonDocument> dbsCursor = _mongoClient.ListDatabases();

            while (dbsCursor.MoveNext())
            {
                foreach (var db in dbsCursor.Current)
                {
                    dbNames.Add(db["name"].AsString);
                }
            }

            return(dbNames);
        }
Beispiel #11
0
        public IAsyncCursor <BsonDocument> ListDatabases(
            CancellationToken cancellationToken = default)
        {
            if (TryGetSession(out IClientSessionHandle? session))
            {
                return(_client.ListDatabases(session, cancellationToken));
            }

            return(_client.ListDatabases(cancellationToken));
        }
Beispiel #12
0
 private void btnDbList_Click(object sender, EventArgs e)
 {
     client = new MongoClient(txtServer.Text.Trim());
     cboDB.Items.Clear();
     using (IAsyncCursor <BsonDocument> cursor = client.ListDatabases())
     {
         while (cursor.MoveNext())
         {
             IEnumerable <BsonDocument> batch = cursor.Current;
             foreach (BsonDocument doc in batch)
             {
                 cboDB.Items.Add(doc[0]);
             }
         }
     }
     cboDB.SelectedIndex = 0;
 }
Beispiel #13
0
        public List <string> GetDatabases()
        {
            List <string> databases = new List <string>();

            using (var cursor = client.ListDatabases())
            {
                while (cursor.MoveNext())
                {
                    var batch = cursor.Current;
                    foreach (var document in batch)
                    {
                        databases.Add(document.GetValue("name").AsString);
                    }
                }
            }

            return(databases);
        }
Beispiel #14
0
        public MongoDbService(IConfiguration configuration)
        {
            var dbUri = configuration.GetSection("AppSettings")
                        .GetSection("DbUri").Value;
            var databaseId = configuration.GetSection("AppSettings")
                             .GetSection("DatabaseId").Value;

            //string dbUri = "mongodb://localhost";
            _mClient = new MongoClient(dbUri);

            var dbList = _mClient.ListDatabases().ToList();

            if (dbList.Select(d => d.ToString()).Contains(databaseId))
            {
                Console.WriteLine($"Error: databse {databaseId} was not found on Uri {dbUri}");
            }

            _db = _mClient.GetDatabase(databaseId);
        }
        protected override bool CheckConnection()
        {
            _logger.LogInformation("CheckConnectionAsync() checking connection to the database.");

            if (_mongoClient == null)
            {
                return(false);
            }

            try
            {
                _mongoClient.ListDatabases();
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "CheckConnectionAsync() got exception: {Message}", ex.Message);
                return(false);
            }

            return(true);
        }
Beispiel #16
0
        public string FindUrl(string url)
        {
            _mongoDatabase = _mongoClient.GetDatabase("KittenUrlDb");
            _urlCollection = _mongoDatabase.GetCollection <KittenUrlDto>("KittenUrlDb");

            var dbList = _mongoClient.ListDatabases().ToList();

            var y = _urlCollection.Find(s => s.DateCreated < DateTime.Now).ToList();

            var path        = "https://localhost:44314/";
            var completeURl = path + url;

            var x = _urlCollection.Find(s => s.ShortUrl == url).ToList();

            if (x.Count > 0)
            {
                return(x.FirstOrDefault().LongUrl);
            }
            else
            {
                return(null); //translate to not found
            }
        }
Beispiel #17
0
        public bool DBExists()
        {
            bool found = false;


            IMongoClient client = this.MongoProvider.GetClient();

            using (var cursor = client.ListDatabases()) {
                while (cursor.MoveNext())
                {
                    foreach (BsonDocument i in cursor.Current)
                    {
                        string name = i["name"].ToString();

                        if (name.Equals(dbName.DB, StringComparison.OrdinalIgnoreCase))
                        {
                            found = true;
                        }
                    }
                }
            }

            return(found);
        }
Beispiel #18
0
 private PsMongoContext BindToMongo(string server)
 {
     try
     {
         var connectionString = string.Format("mongodb://{0}:27017", server);
         this.IMongoClient = new MongoClient(connectionString);
         var dbs = IMongoClient.ListDatabases().ToList();
         if (dbs != null)
         {
             this.MongoIsConnected = true;
             return(this);
         }
         else
         {
             this.MongoIsConnected = false;
             return(null);
         }
     }
     catch (Exception e)
     {
         this.MongoIsConnected = false;
         throw new Exception("Something went wrong Binding to Mongo! Full Error:\r\n\r\n" + e.Message);
     }
 }
 public static IEnumerable <string> GetDatabaseNames(this IMongoClient client)
 {
     return(client.ListDatabases()
            .ToList()
            .Select(db => db.GetValue("name").AsString));
 }
 public IList <BsonDocument> GetDatabase()
 {
     return(client.ListDatabases().ToList());
 }
Beispiel #21
0
        public static async Task Main(string[] args)
        {
            var baseDir   = AppDomain.CurrentDomain.BaseDirectory;
            var logConfig = new LoggerConfiguration()
                            .MinimumLevel.Debug()
                            .WriteTo.Console(theme: AnsiConsoleTheme.Code)
                            .WriteTo.File($"{baseDir}/log.txt", rollingInterval: RollingInterval.Day);

            ExceptionLogging.logger = logConfig.CreateLogger();
            await new LogMessage(LogSeverity.Info, "App", $"Starting with logging at {baseDir}").Log();

            await DataManipulator.MapTypes();

#if DEBUG
            BotInfo.debug = true;
#endif
            DotNetEnv.Env.Load($"{baseDir}/BotCatMaxy.env");
            dbClient = new MongoClient(Environment.GetEnvironmentVariable("DataToken"));

            var config = new DiscordSocketConfig
            {
                AlwaysDownloadUsers = true, //going to keep here for new guilds added, but seems to be broken for startup per https://github.com/discord-net/Discord.Net/issues/1646
                ConnectionTimeout   = 6000,
                MessageCacheSize    = 120,
                ExclusiveBulkDelete = false,
                DefaultRetryMode    = RetryMode.AlwaysRetry,
                GatewayIntents      = GatewayIntents.GuildBans | GatewayIntents.GuildMembers |
                                      GatewayIntents.GuildMessageReactions | GatewayIntents.GuildMessages | GatewayIntents.DirectMessages | GatewayIntents.Guilds
            };

            //Sets up the events
            _client        = new DiscordSocketClient(config);
            _client.Log   += ExceptionLogging.Log;
            _client.Ready += Ready;

            //Delete once https://github.com/discord-net/Discord.Net/issues/1646 is fixed
            _client.GuildAvailable += HandleGuildAvailable;

            await _client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("DiscordToken"));

            await _client.StartAsync();

            SettingsCache cacher = new SettingsCache(_client);

            //Gets build date
            const string BuildVersionMetadataPrefix = "+build";
            DateTime     buildDate = new DateTime();
            var          attribute = Assembly.GetExecutingAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>();
            if (attribute?.InformationalVersion != null)
            {
                var value = attribute.InformationalVersion;
                var index = value.IndexOf(BuildVersionMetadataPrefix);
                if (index > 0)
                {
                    value = value.Substring(index + BuildVersionMetadataPrefix.Length);
                    if (DateTime.TryParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var result))
                    {
                        buildDate = result.ToUniversalTime();
                    }
                }
            }

            string version = args.ElementAtOrDefault(0) ?? "unknown";
            await new LogMessage(LogSeverity.Info, "Main", $"Starting with version {version}, built {buildDate.ToShortDateString()}, {(DateTime.UtcNow - buildDate).LimitedHumanize()} ago").Log();
            StatusManager statusManager = new StatusManager(_client, version);

            await new LogMessage(LogSeverity.Info, "Mongo", $"Connected to cluster {dbClient.Cluster.ClusterId} with {dbClient.ListDatabases().ToList().Count} databases").Log();

            var serviceConfig = new CommandServiceConfig
            {
                DefaultRunMode  = RunMode.Async,
                IgnoreExtraArgs = true
            };

            CommandService service = new CommandService(serviceConfig);
            CommandHandler handler = new CommandHandler(_client, service);

            DynamicSlowmode dynamicSlowmode = new DynamicSlowmode(_client);
            LoggingHandler  logger          = new LoggingHandler(_client);
            TempActions     tempActions     = new TempActions(_client);
            FilterHandler   filter          = new FilterHandler(_client);

            //Debug info
            await new LogMessage(LogSeverity.Info, "Main", "Setup complete").Log();

            await Task.Delay(-1);
        }
Beispiel #22
0
 public IAsyncCursor <BsonDocument> ListDatabases(
     CancellationToken cancellationToken = default(CancellationToken))
 {
     return(wrapped.ListDatabases(cancellationToken));
 }
Beispiel #23
0
 public List <BsonDocument> HentDatabaseList()
 {
     return(client.ListDatabases().ToList());
 }
        public bool CheckForDatabase(string database)
        {
            var dbList = Enumerate(_client.ListDatabases()).Select(db => db.GetValue("name").AsString);

            return(dbList.Contains(database));
        }
Beispiel #25
0
        public bool DatabaseExists()
        {
            var dbList = client.ListDatabases().ToList().Select(db => db.GetValue("name").AsString);

            return(dbList.Contains(dbSettings.Database));
        }