How to create a new Mongo Database programatically? - c#

I'm trying to create a new database programatically, kind'a one database per client.
and using this:
public void CreateNewClientDatabase(Client client)
{
var connectionString = Util.GetClientDatabaseConnectionString(client.DatabaseName);
var mongoClient = new MongoDB.Driver.MongoClient(connectionString);
var server = mongoClient.GetServer();
var db = server.GetDatabase(client.DatabaseName);
db.CreateCollection("DatabaseCreated");
}
The Error I'm getting on CreateCollection is that I do not have the correct credentials, even though that in the connection string, my credentails are correct.
The Exception reads as:
Invalid credentials for database 'client_database_name'.
and the InnerException as:
{"Command 'authenticate' failed: auth fails (response: { \"errmsg\" : \"auth fails\", \"ok\" : 0.0 })"}
The connectionString ends up being this:
mongodb://admin_user:admin_pwd#linus.mongohq.com:10042/client_database_name
What am I missing?
P.S. Using version 1.7 of MongoDB Driver

Bruno ... to do this on a shared service like MongoHQ, you will need to use their API to create new databases programmatically. Docs for the API are located at: http://support.mongohq.com.

Related

C# Creation of DB on Firestore fails with no error message

I am following the docs on how to set up a backend with firestore:
https://firebase.google.com/docs/firestore/quickstart?authuser=0#c_1
I already set up a service account, genereted a key file and fed that into the code on my end. The connection works and I set the right permission (owner) to be able to read the bucket list.
But as soon as I try the first line of code from the tutorial:
FirestoreDb db = FirestoreDb.Create(project);
Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
The execution dies. It doesnt lead to an error message, it doesnt run into a catch block with an exception. It just doesnt continue after the Create(project) part.
I noticed however, that the created datebase on the firebase console and the service account dont seem to be connected yet. Also, I dont know what to put for "project". I tried the project Id from the service account (with which i can do listbuckets) but this doesnt seem to work.
In the docs it does not state anything about what else to do.
Can you guys give me a hint maybe?
Thank you
EDIT:
LONGER CODE EXCEPT:
var credential = GoogleCredential.FromFile("/Users/juliustolksdorf/Projects/Interior Circle/keys/interiorcircle-4f70f209e160.json");
var storage = StorageClient.Create(credential);
// Make an authenticated API request.
var buckets = storage.ListBuckets("interiorcircle");
foreach (var bucket in buckets)
{
Console.WriteLine(bucket.Name);
}
var db = FirestoreDb.Create("interiorcircle");
DocumentReference docRef = db.Collection("users").Document("alovelace");
Dictionary<string, object> user = new Dictionary<string, object>
{
{ "First", "Ada" },
{ "Last", "Lovelace" },
{ "Born", 1815 }
};
await docRef.SetAsync(user);
}
catch(Exception e)
{
DisplayAlert("hi", e.ToString(), "ok");
}
List buckets works, so the key is set correctly, but as soon as I try to do the create DB it fails.
You should refer to the Firestore .NET Client Documentation.
In order to connect, you should pass the projectId to FirestoreDb.Create and you should set and environment variable called GOOGLE_APPLICATION_CREDENTIALS which contains the path to your service account JSON file.
Edit:
You can also explicitly pass the credential to FirestoreDb, by using:
FirestoreDb db = new FirestoreDbBuilder { ProjectId = projectId, Credential = credential }.Build();

Connect to OrientDB using Gremlin.Net

Hi I'm trying to connect to Orient.DB (Community 3.0.18) with gremlin support from a easy console application and Gremlin.net.
I'm using the standard demodb. I can't get any gremlin query run, I get:
ResponseException: ServerSerializationError: Error during
serialization: Infinite recursion (StackOverflowError)
This is my code:
var gremlinServer = new GremlinServer("localhost", 8182, enableSsl:false, username: "root", password: "xxxx");
using (var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType))
{
var query = "g.V(\"33:5\")";
// Create async task to execute the Gremlin query.
var resultSet = gremlinClient.SubmitAsync<dynamic>(query).Result;
Console.WriteLine();
}
I also tried GraphSON3Reader and GraphSON3Writer having the same result.
I have two big doubt:
1) How to let this work
2) How can I specify the database? for example on CosmosDB you have to specify it in the user parameter, I tried also this solutino but again no luck.

Microsoft Graph .NET Client Library get verification record

I use Microsoft Graph .NET Client Library ( https://github.com/microsoftgraph/msgraph-sdk-dotnet ).
I want to call this API method:
https://learn.microsoft.com/en-us/graph/api/domain-list-verificationdnsrecords?view=graph-rest-1.0
GET https://graph.microsoft.com/v1.0/domains/{domain-name}/verificationDnsRecords
I try to do the following:
List<QueryOption> options = new List<QueryOption>
{
new QueryOption("domain-name", domain)
};
var r = await graphClient.Domains.Request(options).Select(p => p.VerificationDnsRecords).GetAsync();
But I get an error like "Unknown domain-name" parameter. I tried id instead of domain-name and get the same.
What is wrong and how to do?
Found solution how to set domain name. It should be:
await graphClient.Domains[domain].VerificationDnsRecords.Request().GetAsync();
without any QueryOption

Using Hangfire, connection string given in Startup.cs throws Cannot attach file as database error

I'm utilizing Hangfire in my ASP .Net MVC Web App, it had installed successfully. I'd like to use the same LocalDb to store queued jobs for Hangfire to dequeue and process as I've used to stored data. However I'm running into the below error when I provided its connectionString or name defined in Web.config in Startp.cs. I've had no trouble adding, deleting updating data in the same localDb before hangfire.
Cannot attach the file 'c:\users\jerry_dev\documents\visual studio 2013\Projects\Hangfire.Highlighter\Hangfire.Highlighter\App_Data\aspnet-Hangfire.Highlighter-20150113085546.mdf' as database 'aspnet-Hangfire.Highlighter-20150113085546'.
Startup.cs:
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.UseHangfire(config =>
{
string hangfireConnectionString = #"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Hangfire.Highlighter-20150113085546.mdf;Initial Catalog=aspnet-Hangfire.Highlighter-20150113085546;Integrated Security=True";
config.UseSqlServerStorage(hangfireConnectionString);
config.UseServer();
});
}
My project Solution is named "Hangfire.Highlighter"
Web.config:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Hangfire.Highlighter-20150113085546.mdf;Initial Catalog=aspnet-Hangfire.Highlighter-20150113085546;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
I know this is old - but its been 9 months and I pulled my hair out over this as well - and decided to do a write-up on it here.
My solution was to just create a quick and dirty DbContext, point it to the proper connection string, and call Database.CreateIfNotExists in the constructor:
public class HangfireContext : DbContext
{
public HangfireContext() : base("name=HangfireContext")
{
Database.SetInitializer<HangfireContext>(null);
Database.CreateIfNotExists();
}
}
In the HangfireBootstrapper.Start() method I do something like this:
public void Start()
{
lock (_lockObject)
{
if (_started) return;
_started = true;
HostingEnvironment.RegisterObject(this);
//This will create the DB if it doesn't exist
var db = new HangfireContext();
GlobalConfiguration.Configuration.UseSqlServerStorage("HangfireContext");
// See the next section on why we set the ServerName
var options = new BackgroundJobServerOptions()
{
ServerName = ConfigurationManager.AppSettings["HangfireServerName"]
};
_backgroundJobServer = new BackgroundJobServer(options);
var jobStarter = DependencyResolver.Current.GetService<JobBootstrapper>();
//See the Recurring Jobs + SimpleInjector section
jobStarter.Bootstrap();
}
}
Not sure why Hangfire has such a hard time with LocalDb - maybe it can only handle full-blown SQL instances? Either way this works for me, new team members, and new dev/staging/prod instances that get stood up.
I too know this is old, but ran into this recently. Here is my fix:
In Visual Studio, go to 'View -> SQL Server Object Explorer'
Connect to the Data Source if it isn't already connected. In the example above it was '(LocalDb)\v11.0'
Right click on 'Databases' -> 'Add New Database'
Fill Database name = Ex: 'aspnet-Hangfire.Highlighter-20150113085546' or whatever you've named the database in the connection string.
Fill Database location = This should be the Data Directory in your application, 'App_Data' for the MVC project.
This fixed the issue in my case.
Jack's answer didn't work for me, because I ran into this problem: No connection string named could be found in the application config file
I got it to work with the following modifications:
Remove "name=" from the string in the base initializer. Thanks to: https://stackoverflow.com/a/37697318/2279059
This moves the error to the call of UseSqlServerStorage. So instead of passing "HangfireContext" to it, I just copy the connection string from the dummy database context.
Complete setup code:
public class HangfireContext : DbContext
{
public HangfireContext() : base("HangfireContext") // Remove "name="
{
Database.SetInitializer<HangfireContext>(null);
Database.CreateIfNotExists();
}
}
public partial class Startup
{
public static void ConfigureHangfire(IAppBuilder app)
{
var db = new HangfireContext();
GlobalConfiguration.Configuration.UseSqlServerStorage(db.Database.Connection.ConnectionString); // Copy connection string
app.UseHangfireDashboard();
app.UseHangfireServer();
}
}
Is the DB already created? Can you try using a different conneciton string format?something like this,
"Server=.;Database=HangFire.Highlighter;Trusted_Connection=True;"
Answer as per AspNetCore 3.1 and Hangfire 1.7.17
Hangfire should create all the tables provided there is an existing database with the specified database name.
If you want to use LocalDb, you can use the following registrations (see below).
services
.AddHangfire(
(serviceProvider, config) =>
{
//read settings or hardcode connection string, but this is cleaner
var configuration = serviceProvider.GetService<IConfiguration>();
var connectionString = configuration.GetValue<string>("Hangfire:ConnectionString");
var sqlServerStorageOptions =
new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
};
config
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings();
.UseSqlServerStorage(connectionString, sqlServerStorageOptions);
});
The connection string is read, in my example, from the appsettings, so it'd look like this
"Hangfire": {
"ConnectionString": "Data Source=(localdb)\\MsSqlLocalDb; Database=Hangfire;"
}
Again, notice how the connection string has the name of the database (e.g: Hangfire) that MUST exist in localdb. If you remove the Database=xxx parameter altogether, it'll pick the master database by default and create all the tables there.

How to get the Mongo database specified in connection string in C#

I would like to connect to the database specified in the connection string, without specifying it again in GetDatabase.
For example, if I have a connection string like this;
mongodb://localhost/mydb
I would like to be able to db.GetCollection("mycollection") from mydb.
This would allow the database name to be configured easily in the app.config file.
Update:
MongoServer.Create is obsolete now (thanks to #aknuds1). Instead this use following code:
var _server = new MongoClient(connectionString).GetServer();
It's easy. You should first take database name from connection string and then get database by name. Complete example:
var connectionString = "mongodb://localhost:27020/mydb";
//take database name from connection string
var _databaseName = MongoUrl.Create(connectionString).DatabaseName;
var _server = MongoServer.Create(connectionString);
//and then get database by database name:
_server.GetDatabase(_databaseName);
Important: If your database and auth database are different, you can add a authSource= query parameter to specify a different auth database. (thank you to #chrisdrobison)
From docs:
NOTE If you are using the database segment as the initial database to
use, but the username and password specified are defined in a
different database, you can use the authSource option to specify the
database in which the credential is defined. For example,
mongodb://user:pass#hostname/db1?authSource=userDb would authenticate
the credential against the userDb database instead of db1.
In this moment with the last version of the C# driver (2.3.0) the only way I found to get the database name specified in connection string is this:
var connectionString = #"mongodb://usr:pwd#srv1.acme.net,srv2.acme.net,srv3.acme.net/dbName?replicaSet=rset";
var mongoUrl = new MongoUrl(connectionString);
var dbname = mongoUrl.DatabaseName;
var db = new MongoClient(mongoUrl).GetDatabase(dbname);
db.GetCollection<MyType>("myCollectionName");
With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:
const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");
The answer below is apparently obsolete now, but works with older drivers. See comments.
If you have the connection string you could also use MongoDatabase directly:
var db = MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");

Categories