GetDatabaseName: - mongodb

I have a problem when retrieving the names of existing databases:
<code>
var connectionString = "mongodb://user:pw#localhost/admin";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var lst = server.GetDatabaseNames();
lst.Dump(); -- this is in Linqpad
</code>
Linqpad reports:
<code>
Command 'listDatabases' failed: need to login (response: { "errmsg" : "need to login", "ok" : 0.0 })
The same error happens when omitting the database name in the connection string.
The same error happens when using in my c# application.
Could you please explain how to get that list?
Well, in the meantime a had a look at the documentation (which I should have done before, sorry) and found out that I had to use this function with a parameter providing the admin credentials.
OK. BUT the error message is confusing and should be something like: You must provide the admin credentials..............

You can try,
const string legalConnectionString = "mongodb://localhost/?safe=true";
var productionMongoDatabase = MongoServer.Create(legalConnectionString ).GetDatabase(productionDb, new MongoCredentials("admin", "1111111", true));

Related

Power BI REST API ExportToFileInGroup Not Working

I am able to programmatically log in to the PowerBI Client, gather my Workspaces as well as get a specific Report from a specific Workspace. I need to programmatically render that report to a .pdf or .xlsx file. Allegedly this is possible with the ExportToFileInGroup/ExportToFileInGroupAsync methods. I even created a very simple report without any parameters. I can embed this using the sample app from here. So that at least tells me that I have what I need setup in the backend. But it fails when I try to run the ExportToFileInGroupAsync method (errors below code.)
My Code is:
var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(new string[] {
PowerBiScopes.ReadReport,
PowerBiScopes.ReadDataset,
});
var userInfo = await graphServiceClient.Me.Request().GetAsync();
var userName = userInfo.Mail;
AuthDetails authDetails = new AuthDetails {
UserName = userName,
AccessToken = accessToken,
};
var credentials = new TokenCredentials($"{accessToken}", "Bearer");
PowerBIClient powerBIClient = new PowerBIClient(credentials);
var groups = await powerBIClient.Groups.GetGroupsAsync();
var theGroup = groups.Value
.Where(x => x.Name == "SWIFT Application Development")
.FirstOrDefault();
var groupReports = await powerBIClient.Reports.GetReportsAsync(theGroup.Id);
var theReport = groupReports.Value
.Where(x => x.Name == "No Param Test")
.FirstOrDefault();
var exportRequest = new ExportReportRequest {
Format = FileFormat.PDF,
};
string result = "";
try {
var response = await powerBIClient.Reports.ExportToFileInGroupAsync(theGroup.Id, theReport.Id, exportRequest);
result = response.ReportId.ToString();
} catch (Exception e) {
result = e.Message;
}
return result;
It gets to the line in the try block and then throws the following errors:
An error occurred while sending the request.
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
UPDATE
Relating to #AndreyNikolov question, here is our Embedded capacity:
After this was implemented, no change. Same exact error.
Turns out the issue was on our side, more specifically, security/firewall settings. Here is the exact quote from our networking guru.
"After some more investigation we determined that our firewall was causing this issue when it was terminating the SSL connection. We were able to add a bypass for the URL and it is now working as expected."

"Not authorized on ___ to execute command" with mLab + MongoDB ^3.0

Connects without a hitch, but on insert() throws me this error.
var MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
var url = 'mongodb://____:____#ds125565.mlab.com:25565/heroku_w268n9pj';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
db = client.db('temp');
console.log("connected!");
const collection = db.collection('temp');
collection.insert([{
something: please
}
});
I saw some other answers regarding mLab accounts and credentials, but I just created a new admin account for this. Frustrating because it was working previously with v2.3.
When attempting to connect to an mlab database, you have to correctly specify the client. It's located at the end of your connection string, just after the final forward slash.
mlab_url = "mongodb://db_user_name:db_password#ds139725.mlab.com:39725/heroku_sd1fp182?retryWrites=false"
client = MongoClient(url)
db = client["heroku_sd1fp182"]
collection = db["coinHack"]
You may also get the error:
This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.
Just add "?retryWrites=false" to your connection string, as shown above.

Calling XSJS file in SAPUI5 for writng data on HANA

I'm trying to create a service to write data from a SAPUI5 frontend to HANA tables.
As far as I checked, I believe this is not possible via OData Services. So I've found another way, sing an XSJS file with a SQL INSERT statement.
Now, my problem is using this in UI5. As with OData, I would use something like oModel.create but now I think this doesn't work like that.
Those anyone has a clue?
Thanks!
Eva
UPDATE:
After using the first answer, I tried to create an entry in a HANA Table, but I'm getting a 500 error. Here's the code of the xsjs file:
var data = '', conn = $.db.getConnection(), pstmt;
if($.request.body){
data = $.request.parameters.get("firstName");
}
var conn = $.db.getConnection();
var pstmt = conn.prepareStatement( 'INSERT INTO "Z003HB1N"."T_TEST" (FIRSTNAME) VALUES(?)' );
pstmt.setString(1,data);
pstmt.execute();
pstmt.close();
conn.commit();
conn.close();
doResponse(200,'');
$.response.contentType = 'text/plain';
$.response.setBody('Upload ok');
$.response.status = 200;
Any clue what might be wrong?
You can simply use .ajax calls to call your new oData service on HANA and use parameters to hand over the desired values to your .xsjs service.
Example:
var query = "firstName=Sherlock&lastName=Holmes"
jQuery.ajax({
url : "url/to/your/Service.xsjs?" + query,
success : function(response) {
// will be called once the xsjs file sends a response
console.log(response);
},
error : function(e) {
// will be called in case of any errors:
console.log(e);
}
});
On HANA you can access the provided parameters in your service like this:
var firstName = $.request.parameters.get("firstName");
var lastName = $.request.parameters.get("lastName");

Meteor: Unique MongoDB URL for different users

I'm very keen to utilize Meteor as the framework for my next project. However, there is a requirement to keep customer data separated into different MongoDB instances for users from different customers.
I have read on this thread that it could be as simple as using this:
var d = new MongoInternals.RemoteCollectionDriver("<mongo url>");
C = new Mongo.Collection("<collection name>", { _driver: d });
However, I was dished this error on my server/server.js. I'm using meteor 0.9.2.2
with meteor-platform 1.1.0.
Exception from sub Ep9DL57K7F2H2hTBz Error: A method named '/documents/insert' is already defined
at packages/ddp/livedata_server.js:1439
at Function._.each._.forEach (packages/underscore/underscore.js:113)
at _.extend.methods (packages/ddp/livedata_server.js:1437)
at Mongo.Collection._defineMutationMethods (packages/mongo/collection.js:888)
at new Mongo.Collection (packages/mongo/collection.js:208)
at Function.Documents.getCollectionByMongoUrl (app/server/models/documents.js:9:30)
at null._handler (app/server/server.js:12:20)
at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1594)
at _.extend._runHandler (packages/ddp/livedata_server.js:943)
at packages/ddp/livedata_server.js:737
Can anyone be so kind as to enlighten me whether or not I have made a mistake somewhere?
Thanks.
Br,
Ethan
Edit: This is my server.js
Meteor.publish('userDocuments', function () {
// Get company data store's mongo URL here. Simulate by matching domain of user's email.
var user = Meteor.users.findOne({ _id: this.userId });
if (!user || !user.emails) return;
var email = user.emails[0].address;
var mongoUrl = (email.indexOf('#gmail.com') >= 0) ?
'mongodb://localhost:3001/company-a-db' :
'mongodb://localhost:3001/company-b-db';
// Return documents
return Documents.getCollectionByMongoUrl(mongoUrl).find();
});
and this is the server side model.js
Documents = function () { };
var documentCollections = { };
Documents.getCollectionByMongoUrl = function (url) {
if (!(url in documentCollections)) {
var driver = new MongoInternals.RemoteCollectionDriver(url);
documentCollections[url] = new Meteor.Collection("documents", { _driver: driver });
}
return documentCollections[url];
};
Observation: The first attempt to new a Meteor.Collection works fine. I can continue to use that collection multiple times. But when I log out and login as another user from another company (in this example by using an email that is not from #gmail.com), the error above is thrown.
Downloaded meteor's source codes and peeked into mongo package. There is a way to hack around having to declare different collection names on the mongodb server based on Hubert's suggestion.
In the server side model.js, I've made these adaptation:
Documents.getCollectionByMongoUrl = function (userId, url) {
if (!(userId in documentCollections)) {
var driver = new MongoInternals.RemoteCollectionDriver(url);
documentCollections[userId] = new Meteor.Collection("documents" + userId, { _driver: driver });
documentCollections[userId]._connection = driver.open("documents", documentCollections[userId]._connection);
}
return documentCollections[userId];
};
Super hack job here. Be careful when using this!!!!
I believe Meteor distinguish its collections internally by the name you pass to them as the first argument, so when you create the "documents" collection the second time, it tries to override the structure. Hence the error when trying to create the /documents/insert method the second time.
To work around this, you could apply a suffix to your collection name. So instead of:
new Meteor.Collection('documents', { _driver: driver });
you should try:
new Meteor.Collection('documents_' + userId, { _driver: driver })

Copy a database using mongo driver

I have the following code:
mongoServer.CopyDatabase(mongoDatabaseName, partitionName.Replace("__", string.Empty));
mongoServer.DropDatabase(mongoDatabaseName);
I obtain the following exception "NotImplementedException - The method or operation is not implemented."
How is it possible? I've wronged something? How can I copy my database?
The exception is correct as the CopyDatabase method isn't implemented. See the JIRA ticket for the history of the issue.
Instead, you need to directly invoke the 'copydb' command via a call to RunCommand on the admin database like is described in this answer. So something like:
var adminDB = Server.GetDatabase("admin");
var command = new CommandDocument(new List<BsonElement> {
new BsonElement("copydb", 1),
new BsonElement("fromhost", "localhost"),
new BsonElement("fromdb", mongoDatabaseName),
new BsonElement("todb", partitionName.Replace("__", string.Empty))
});
var result = adminDB.RunCommand(command);