protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //allow viewing json in the browser by default GlobalConfiguration.Configuration.Formatters[0].SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); var data= new programs(); var connstr = @"mongodb://*****:*****@ds035607.mongolab.com:35607/revolentdata"; var client = new MongoDB.Driver.MongoClient(connstr); var server = client.GetServer(); var db = server.GetDatabase("revolentdata"); var coll = db.GetCollection<programsProgram>("movies"); var cursor = coll.FindAll(); data.program = cursor.ToList().ToArray(); Application["data"] = data; //factual api info Application["factkey"] = "UVz7N3cX8wHDYon4dHoVfmj8kzYL3sDVJ2SXn8Dl"; Application["factsec"] = "Ok2lXgEde7JazbsbZBMSJ5bYmH0wbTLycB13TUZW"; }
public void App010ImportJSON() { Console.WriteLine("mongoimport --host " + Program.MongoData.Host + " --port " + Program.MongoData.Port + " --db " + Program.MongoData.Database + " --collection zips --type json --file " + AppDomain.CurrentDomain.BaseDirectory + "\\resources\\zips.json" + Environment.NewLine); Console.WriteLine("Fire above command in a new command prompt and it will import zips to said database."); try { Console.WriteLine("Let me check if you have already done it..."); Double zipsCount = new MongoDB.Driver.MongoClient(new MongoDB.Driver.MongoClientSettings { Server = new MongoDB.Driver.MongoServerAddress(Program.MongoData.Host, Program.MongoData.Port) }).GetServer().GetDatabase(Program.MongoData.Database).GetCollection("zips").Count(); if (zipsCount > 20000) { Console.WriteLine("Great DB is saying " + zipsCount + " documents."); } else { Console.WriteLine("Result not satisfactory, please import and come back again to recheck status."); } } catch (Exception exc) { Console.WriteLine(exc.Message); Console.WriteLine("Check if MongoDB is running at " + Program.MongoData.Host + ":" + Program.MongoData.Port); } Console.WriteLine(); }
private void releaseMongoClient(MongoDB.Driver.MongoClient client) { lock (client_pool) { client_pool.Add(client); } }
public async Task <int> SaveGift(Gift gift) { var giftDocument = new BsonDocument { { "name", BsonValue.Create(gift.Name) } }; var settings = MongoDB.Driver.MongoClientSettings.FromUrl( new MongoDB.Driver.MongoUrl(ConnectionString) ); settings.SslSettings = new MongoDB.Driver.SslSettings() { EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12 }; var mongoClient = new MongoDB.Driver.MongoClient(settings); var mongoDb = mongoClient.GetDatabase(DatabaseName); var collection = mongoDb.GetCollection <BsonDocument>(CollectionName); return(await Task.Run(() => { var result = collection.InsertOneAsync(giftDocument); return result.Id; } )); }
public BulletNote(BulletRecords.NoteType requestedType = BulletRecords.NoteType.Default) { RecordId = Guid.NewGuid().ToString(); NoteType = requestedType; NoteBody = ""; var client = new MongoDB.Driver.MongoClient(); }
private static MongoDB.Driver.MongoDatabase ConnectToDatabase() { MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient(mongoUrl); var server = client.GetServer(); var db = server.GetDatabase(mongoDatabase); return db; }
public static ILoggerFactory AddMongodb(this ILoggerFactory factory, string connetionString = "mongodb://127.0.0.1:27017/logging") { var mongoUrl = new MongoDB.Driver.MongoUrl(connetionString); var client = new MongoDB.Driver.MongoClient(mongoUrl); factory.AddProvider(new MongodbProvider(client.GetDatabase(mongoUrl.DatabaseName))); return(factory); }
private async Task AddToMongoCollection() { var mongoClient = new MongoDB.Driver.MongoClient("mongodb://localhost:27017"); var db = mongoClient.GetDatabase("IntegrationTest"); var col = db.GetCollection <TestClass>("TestClass"); await col.InsertOneAsync(new TestClass { Test = 1 }); helper.WriteLine("Mongodb document inserted"); }
public IActionResult Index() { var connectionString = Startup.ConnectionString; var client = new MongoDB.Driver.MongoClient(connectionString); var db = client.GetDatabase("foo"); var collection = db.GetCollection <BsonDocument>("bar"); return(View()); }
public SharedController(IFilesService filesService, IConfiguration config) { this.config = config; this.filesService = filesService; var mongoClient = new MongoDB.Driver.MongoClient(config.GetConnectionString("MongoDbConnection")); var database = mongoClient.GetDatabase(nameof(WitDrive)); this.fsc = new FileSystemClient(database, chunkSize: 32768); }
public AccountController(IEmailSender emailSender, UserManager <User> userManager, IConfiguration config) { this.emailSender = emailSender; this.userManager = userManager; var mongoClient = new MongoDB.Driver.MongoClient(config.GetConnectionString("MongoDbConnection")); var database = mongoClient.GetDatabase(nameof(WitDrive)); this.space = long.Parse(config.GetSection("DiskSpace").GetSection("Space").Value); this.fsc = new FileSystemClient(database, chunkSize: 32768); }
public DirController(IDirService dirService, IConfiguration config) { this.config = config; this.dirService = dirService; var mongoClient = new MongoDB.Driver.MongoClient(config.GetConnectionString("MongoDbConnection")); var database = mongoClient.GetDatabase(nameof(WitDrive)); this.fsc = new FileSystemClient(database, chunkSize: 32768); this.space = long.Parse(config.GetSection("DiskSpace").GetSection("Space").Value); }
protected override void ConfigureEventStore() { var mongoDbConnectionString = Configuration.GetConnectionString("Merp-Accountancy-EventStore"); var mongoDbDatabaseName = MongoDB.Driver.MongoUrl.Create(mongoDbConnectionString).DatabaseName; var mongoClient = new MongoDB.Driver.MongoClient(mongoDbConnectionString); Services.AddSingleton(mongoClient.GetDatabase(mongoDbDatabaseName)); Services.AddTransient <IEventStore, MementoFX.Persistence.MongoDB.MongoDbEventStore>(); Services.AddTransient <IRepository, MementoFX.Persistence.Repository>(); }
public void ConfigureEventStore() { var mongoDbConnectionString = Configuration.GetConnectionString("OnTime-TaskManagement-EventStore"); var mongoDbDatabaseName = MongoDB.Driver.MongoUrl.Create(mongoDbConnectionString).DatabaseName; var mongoClient = new MongoDB.Driver.MongoClient(mongoDbConnectionString); Services.AddSingleton(mongoClient.GetDatabase(mongoDbDatabaseName)); Services.AddTransient <IEventStore, Memento.Persistence.MongoDB.MongoDbEventStore>(); Services.AddTransient <IRepository, Memento.Persistence.Repository>(); }
protected void Unnamed1_Click(object sender, System.EventArgs e) { string fileName = @"D:\stefan.steiger\Downloads\keywords.xlsx"; MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient("mongodb://localhost/27017/mydb"); MongoDB.Driver.MongoServer server = client.GetServer(); MongoDB.Driver.MongoDatabase database = server.GetDatabase("testdb"); MongoGridFs gridFs = new MongoGridFs(database); MongoDB.Bson.ObjectId id = MongoGridFsUsage.UploadFile(gridFs, fileName); // byte[] baFile = DownloadFile(gridFs, id); // DownloadFile(gridFs, id, @"d:\test.rar"); }
public AuthController(IConfiguration config, IMapper mapper, IAuthService service, UserManager <User> userManager, SignInManager <User> signInManager) { this.config = config; this.mapper = mapper; this.service = service; this.userManager = userManager; this.signInManager = signInManager; var mongoClient = new MongoDB.Driver.MongoClient(config.GetConnectionString("MongoDbConnection")); var database = mongoClient.GetDatabase(nameof(WitDrive)); this.fsc = new FileSystemClient(database, chunkSize: 32768); }
// http://odetocode.com/blogs/scott/archive/2013/04/16/using-gridfs-in-mongodb-from-c.aspx public static void Test() { string fileName = "clip_image071.jpg"; MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient(); MongoDB.Driver.MongoServer server = client.GetServer(); MongoDB.Driver.MongoDatabase database = server.GetDatabase("testdb"); MongoGridFs gridFs = new MongoGridFs(database); MongoDB.Bson.ObjectId id = UploadFile(gridFs, fileName); byte[] baFile = DownloadFile(gridFs, id); DownloadFile(gridFs, id, @"d:\test.rar"); }
// http://odetocode.com/blogs/scott/archive/2013/04/16/using-gridfs-in-mongodb-from-c.aspx public static void Test() { string fileName = "clip_image071.jpg"; MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient(); MongoDB.Driver.MongoServer server = client.GetServer(); MongoDB.Driver.MongoDatabase database = server.GetDatabase("testdb"); MongoGridFs gridFs = new MongoGridFs(database); MongoDB.Bson.ObjectId id = UploadFile(gridFs, fileName); byte[] baFile = DownloadFile(gridFs, id); DownloadFile(gridFs, id, @"d:\test.rar"); } // End Sub Test
public AlertingRepository(string connection) { if (string.IsNullOrWhiteSpace(connection)) { connection = "mongodb://localhost:27017"; } _client = new MongoDB.Driver.MongoClient(connection); _database = _client.GetDatabase("local", null); _alertTypes = _database.GetCollection<AlertType>("alerttypes"); var filter = new MongoDB.Bson.BsonDocument(); long count = _alertTypes.Count(filter); // AddTestData(); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson(); services.AddSingleton <IBotFrameworkHttpAdapter, ErrorLogginAdapter>(); // Create state store using the MongoDB storage component. var client = new MongoDB.Driver.MongoClient("mongodb://localhost/"); var storage = new MongoBotStateStore(new MongoStateStoreSettings(client)); services.AddSingleton(new UserState(storage)); services.AddSingleton(new ConversationState(storage)); services.AddTransient <IBot, StateManagementBot>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); #if ENABLE_MQTT_BROKER var mqttServerOptions = new MqttServerOptionsBuilder() .WithoutDefaultEndpoint() .Build(); services .AddHostedMqttServer(mqttServerOptions) .AddMqttConnectionHandler() .AddConnections(); #endif MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient(Configuration.GetConnectionString("mongodb")); var redisConfiguration = Configuration.GetSection("redis").Get <RedisConfiguration>(); var mqttOptions = Configuration.GetSection("MQTT").Get <MqttSubscribeConfig>(); services.AddSingleton(mqttOptions); services.AddSingleton(redisConfiguration); services.AddSingleton <IRedisConnectionFactory, RedisConnectionFactory>(); services.AddSingleton(client); queue_service = new MongoBackgroundTaskQueue(client); services.AddSingleton(queue_service); //IServiceCollection cols = services.AddSingleton<IBackgroundMongoTaskQueue, MongoBackgroundTaskQueue>(); //services.AddHostedService<MongoBackgroundHostService>(); //byte[] file_array = File.ReadAllBytes("output.txt"); //byte[] new_fileArray = new byte[file_array.Length + 8]; //Array.Copy(file_array, new_fileArray, file_array.Length); //DaegunPacket packet = PacketParser.ByteToStruct<DaegunPacket>(new_fileArray); //packet.timestamp = DateTime.Now; //queue_service.QueueBackgroundWorkItem(packet); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public void Test() { string connectionString = @"mongodb://*****:*****@pmisztalwedding.documents.azure.com:10255/?ssl=true&replicaSet=globaldb"; var settings = MongoDB.Driver.MongoClientSettings.FromUrl( new MongoDB.Driver.MongoUrl(connectionString) ); settings.SslSettings = new MongoDB.Driver.SslSettings() { EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12 }; var mongoClient = new MongoDB.Driver.MongoClient(settings); var client = new MongoDB.Driver.MongoClient(); }
public void Load_Pricing_List_NotQueryable() { string connectionString = ConfigurationManager.AppSettings["connectionString"].ToString(); string databaseName = "promo"; var client = new MongoDB.Driver.MongoClient(connectionString); var server = client.GetServer(); var database = server.GetDatabase(databaseName); var pricing = database.GetCollection <MOXE.PricingEveryday>("PricingAll_NoFilters"); var cursor = pricing.FindAll(); cursor.SetFields(MongoDB.Driver.Builders.Fields.Include("Identity", "Id")); var items = cursor.ToList(); //var p = PricingClient.LoadList(new ENTITY.Session<ENTITY.NullT>()); //Assert.IsNotNull(p); }
public void Mongo000DefaultConnect() { try { Console.WriteLine("Creating client..."); MongoDB.Driver.MongoClient _client = new MongoDB.Driver.MongoClient(); Console.WriteLine("Getting Server..."); MongoDB.Driver.MongoServer _server = _client.GetServer(); Console.WriteLine("Connecting..."); _server.Connect(); Console.WriteLine("Connection Successful."); } catch (Exception exc) { new frmException(exc, "You are not running MongoDB on localhost:27017." + Environment.NewLine + "So it is failing.").ShowDialog(); Console.WriteLine("Connection UnSuccessful."); } }
public void Mongo020ConnectClientSettings() { try { Console.WriteLine("Creating client..."); MongoDB.Driver.MongoClient _client = new MongoDB.Driver.MongoClient(new MongoDB.Driver.MongoClientSettings { Server = new MongoDB.Driver.MongoServerAddress(Program.MongoData.Host, Program.MongoData.Port) }); Console.WriteLine("Getting Server..."); MongoDB.Driver.MongoServer _server = _client.GetServer(); Console.WriteLine("Connecting..."); _server.Connect(); Console.WriteLine("Connection Successful."); } catch (Exception exc) { new frmException(exc, "You are not running MongoDB on " + Program.MongoData.Host + ":" + Program.MongoData.Port + "." + Environment.NewLine + "So it is failing.").ShowDialog(); Console.WriteLine("Connection UnSuccessful."); } }
public void Mongo020DB() { try { String connString = "mongodb://" + Program.MongoData.Host + ":" + Program.MongoData.Port; Console.WriteLine("Creating client..."); Console.WriteLine(connString); MongoDB.Driver.MongoClient _client = new MongoDB.Driver.MongoClient(connString); Console.WriteLine("Getting Server..."); MongoDB.Driver.MongoServer _server = _client.GetServer(); Console.WriteLine("Getting database " + Program.MongoData.Database + "..."); MongoDB.Driver.MongoDatabase _database = _server.GetDatabase(Program.MongoData.Database); Console.WriteLine(_database.Name); } catch (Exception exc) { new frmException(exc, "You are not running MongoDB on " + Program.MongoData.Host + ":" + Program.MongoData.Port + "." + Environment.NewLine + "Or you do not have rights to list databases.").ShowDialog(); Console.WriteLine("Connection UnSuccessful."); } }
private void CreateExpirationIndex(string dbName, string collectionName, TimeSpan timeToLive) { var mongoClient = new MongoDB.Driver.MongoClient(connectionString); var mongoDatabase = MongoDB.Driver.MongoClientExtensions.GetServer(mongoClient).GetDatabase(dbName); var collection = mongoDatabase.GetCollection <CacheItem>(collectionName); var keys = new MongoDB.Driver.Builders.IndexKeysBuilder(); keys.Ascending("ExpireAt"); var options = new MongoDB.Driver.Builders.IndexOptionsBuilder(); options.SetName("ExpirationIndex"); options.SetTimeToLive(timeToLive); options.SetSparse(false); options.SetUnique(false); options.SetBackground(true); collection.CreateIndex(keys, options); }
public void Mongo000ShowDbs() { try { String connString = "mongodb://" + Program.MongoData.Host + ":" + Program.MongoData.Port; Console.WriteLine("Creating client..."); Console.WriteLine(connString); MongoDB.Driver.MongoClient _client = new MongoDB.Driver.MongoClient(connString); Console.WriteLine("Getting Server..."); MongoDB.Driver.MongoServer _server = _client.GetServer(); Console.WriteLine("Connecting..."); String[] databases = _server.GetDatabaseNames().ToArray(); foreach (String db in databases) { Console.WriteLine("\t" + db); } Console.WriteLine(databases.Length + " databases listed."); } catch (Exception exc) { new frmException(exc, "You are not running MongoDB on " + Program.MongoData.Host + ":" + Program.MongoData.Port + "." + Environment.NewLine + "Or you do not have rights to list databases.").ShowDialog(); Console.WriteLine("Connection UnSuccessful."); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var rmqConfig = ConfigurationReader.ReadConfiguration <RabbitMqConfiguration>(); var fileConfig = ConfigurationReader.ReadConfiguration <FileConfiguration>(); var mysqlConfig = ConfigurationReader.ReadConfiguration <MySqlConfiguration>(); var mongoDbConfig = ConfigurationReader.ReadConfiguration <MongoDbConfiguration>(); var serviceConfig = ConfigurationReader.ReadConfiguration <ServiceConfiguration>(); if (string.IsNullOrWhiteSpace(serviceConfig?.Secret)) { throw new Exception($"Please set {nameof(ServiceConfiguration.Secret)} in the {nameof(ServiceConfiguration)}!"); } services.AddSingleton(serviceConfig); if (mongoDbConfig != null) { string connectionString; if (mongoDbConfig.UseDnsSrv) { connectionString = $"mongodb+srv://{mongoDbConfig.User}:{mongoDbConfig.Password}" + $"@{mongoDbConfig.Host}/{mongoDbConfig.Database}"; } else { connectionString = $"mongodb://{mongoDbConfig.User}:{mongoDbConfig.Password}" + $"@{mongoDbConfig.Host}:{mongoDbConfig.Port}/{mongoDbConfig.Database}"; } var client = new MongoDB.Driver.MongoClient(connectionString); var db = client.GetDatabase(mongoDbConfig.Database); services.AddSingleton(db); services.AddScoped <ISnippetRepository, MongoDbSnippetRepository>(); services.AddScoped <IUserRepository, MongoDbUserRepository>(); services.AddScoped <ISnippetQuery, MongoDbSnippetQuery>(); services.AddScoped <IUserQuery, MongoDbUserQuery>(); } else if (mysqlConfig != null) { services.AddSingleton(mysqlConfig); services.AddScoped <ISnippetRepository, MySqlSnippetRepository>(); services.AddScoped <IUserRepository, MySqlUserRepository>(); services.AddScoped <ISnippetQuery, MySqlSnippetQuery>(); services.AddScoped <IUserQuery, MySqlUserQuery>(); services.AddScoped <MySqlDbContext>(); } else { if (fileConfig == null) { fileConfig = new FileConfiguration(); } services.AddSingleton(fileConfig); services.AddScoped <ISnippetRepository, FileSnippetRepository>(); services.AddScoped <IUserRepository, FileUserRepository>(); services.AddScoped <ISnippetQuery, FileSnippetQuery>(); services.AddScoped <IUserQuery, FileUserQuery>(); } if (rmqConfig != null) { rmqConfig.QueueName = "SnippetStudio.Service"; services.AddCoseiRabbitMq(rmqConfig); } services.AddCosei(); services.AddScoped <SnippetService>(); services.AddScoped <UserService>(); services.AddScoped <TokenService>(); services.AddSignalR(); var validationParameters = TokenService.GetValidationParameters(serviceConfig.Secret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.TokenValidationParameters = validationParameters; }); services.AddControllers(); }
public static MongoDB.Driver.IMongoClient GeneratePoolMongodbClient(DataServerConfigSet configSet) { var settings = new MongoDB.Driver.MongoClientSettings() { MaxConnectionPoolSize = configSet.MaxPoolSize, MinConnectionPoolSize = configSet.MinPoolSize, Server = MongoDB.Driver.MongoServerAddress.Parse(configSet.Masters.First().serverUrl.Replace("mongodb://","")) }; var client = new MongoDB.Driver.MongoClient(settings); return client; }
public AboutController(MongoDB.Driver.MongoClient mongoDbClient) { _mongoDbClient = mongoDbClient; }
public MongoDbContext(string connectionString, string dbName) { var concreteType = this.GetType(); this.db = dbName; this.innerContext = new MongoDB.Driver.MongoClient(connectionString); var entitySets = new List <IEntitySet>(); var entitySetProperties = concreteType.GetProperties() .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(IEntitySet <,>)); foreach (var prop in entitySetProperties) { var keyType = prop.PropertyType.GetGenericArguments()[0]; var entityType = prop.PropertyType.GetGenericArguments()[1]; var createEntitySetMethod = typeof(EntitySet <,>).MakeGenericType(new[] { keyType, entityType }) .GetConstructor( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, null, new[] { typeof(MongoDbContext), typeof(string) }, null); var entitySet = createEntitySetMethod.Invoke(new object[] { this, this.db }); prop.SetValue(this, entitySet, new object[] { }); entitySets.Add(entitySet as IEntitySet); } this.entitySets = entitySets; var knownTypesResolverAttrs = concreteType.GetCustomAttributes(typeof(KnownDataTypesResolverAttribute)); foreach (KnownDataTypesResolverAttribute knownTypesResolverAttr in knownTypesResolverAttrs) { foreach (var type in knownTypesResolverAttr.TypesToUseForSearchingAssemblies) { var concreteEntityTypes = ContextUtils.FindInheritingTypes(type.Assembly, entitySets.Select(s => s.EntityType)); RegisterKnownTypes(concreteEntityTypes); } } var knownTypesAttrs = concreteType.GetCustomAttributes(typeof(KnownDataTypesAttribute)); foreach (KnownDataTypesAttribute knownTypesAttr in knownTypesAttrs) { RegisterKnownTypes(knownTypesAttr.Types); } var fileSetProperty = concreteType.GetProperties() .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(IFileSet <>)) .SingleOrDefault(); if (fileSetProperty != null) { var keyType = fileSetProperty.PropertyType.GetGenericArguments()[0]; var createFileSetMethod = typeof(FileSet <>).MakeGenericType(new[] { keyType }) .GetConstructor( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, null, new[] { typeof(MongoDbContext), typeof(string) }, null); var fileSet = createFileSetMethod.Invoke(new object[] { this, this.db }); fileSetProperty.SetValue(this, fileSet, new object[] { }); this.fileSet = fileSet as IFileSet; } }
public void InitializeDatabaseConnection(String connectionString, String dbname) { client = new MongoDB.Driver.MongoClient(connectionString); server = client.GetServer(); Database = server.GetDatabase(dbname); }
private static void WipeDatabase() { var client = new MongoDB.Driver.MongoClient(); client.DropDatabase("AutomatonNations"); }