The following code works as it should do, if the server is running and if the usename and password are correct. However, if i give a wrong username or password, it does not give me feedback, but only runs into a timeout when calling the Count method.
MongoClientSettings setts = new MongoClientSettings()
{
Server = new MongoServerAddress("127.0.0.1", 27017),
Credentials = new MongoCredential[] { MongoCredential.CreateCredential("TestDatabase", "username", "password") }
};
this.client = new MongoClient(setts);
this.client.Cluster.DescriptionChanged += this.ClusterDescriptionChanged;
var database = this.client.GetDatabase("TestDatabase");
var collection = database.GetCollection<BsonDocument>("SimpleCollection");
var count = collection.Count(MongoDB.Driver.FilterDefinition<BsonDocument>.Empty);
How do i get error messages from the driver and how can i check if it's the connection, the user or the password that does not fit?
PS: The driver API has changed a lot since 2.0 in Jan.2016, which means that most webtutorials and posts on this site no longer work for the current version.
Once you get the client, you can check if the connection is successful
var server = client.GetServer();
server.Ping();
Also it is always a good idea to enclose your code in a try catch with timeout exception because that is expected.
for more info on this you can refer MongoDB C# Driver check Authentication status & Role
Related
I nee to connect to a mongo and run a commands.
I'm am connecting using the following piece of code. I want to test weather I am connecting by listing the databases.
MongoClient client = new MongoClient("mongodb://127.0.0.1:27017");
client.ListDatabases();
If I debug and click on the second line I cannot see the names of the databases. How can I print the names of the databases to screen to confirm I am connected to mongo.
You need to specify credentials in the Connection String. Couple ways you can do this:
var connectionString = "mongodb://user1:password1#127.0.0.1:27017";
Is the format expected, you will have to supply the username and password yourself, these are just placeholders.
Or you can create a MongoCredentials object and use that instead of a connection string (probably a bit cleaner this way, and allows more configuration if you look deeper into the object documentation)
var credential = MongoCredential.CreateMongoCRCredential("test", "user1", "password1");
var settings = new MongoClientSettings
{
Credentials = new[] { credential }
};
var mongoClient = new MongoClient(settings);
Both of these examples are found on MongoDB's documentation site
Try GetDatabaseNames() method and also assign the result to a variable. So that you can inspect it at breakpoint like
MongoClient client = new MongoClient("mongodb://127.0.0.1:27017/");
var databaseNames = client.GetDatabaseNames();
ListDatabases returns an IAsyncCursor so try the following:
var client = new MongoClient(<CONNECTION STRING>);
var cursor = client.ListDatabases();
cursor.ForEachAsync(db => Console.WriteLine(((BsonString)db["name"]).Value));
I'm looking to start an Azure runbook from a c# application which will be hosted on an Azure web app.
I'm using certificate authentication (in an attempt just to test that I can connect and retrieve some data)
Here's my code so far:
var cert = ConfigurationManager.AppSettings["mgmtCertificate"];
var creds = new Microsoft.Azure.CertificateCloudCredentials("<my-sub-id>",
new X509Certificate2(Convert.FromBase64String(cert)));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group-id>", "<automation-account-name>");
Every time I run this, no matter what certificate I use I get the same error:
An unhandled exception of type 'Hyak.Common.CloudException' occurred in Microsoft.Threading.Tasks.dll
Additional information: ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I've tried downloading the settings file which contains the automatically generated management certificate you get when you spin up the Azure account... nothing I do will let me talk to any of the Azure subscription
Am I missing something fundamental here?
Edit: some additional info...
So I decided to create an application and use the JWT authentication method.
I've added an application, given the application permissions to the Azure Service Management API and ensured the user is a co-administrator and I still get the same error, even with the token...
const string tenantId = "xx";
const string clientId = "xx";
var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));
var user = "<user>";
var pwd = "<pass>";
var userCred = new UserCredential(user, pwd);
var result = context.AcquireToken("https://management.core.windows.net/", clientId, userCred);
var token = result.CreateAuthorizationHeader().Substring("Bearer ".Length); // Token comes back fine and I can inspect and see that it's valid for 1 hour - all looks ok...
var sub = "<subscription-id>";
var creds = new TokenCloudCredentials(sub, token);
var client = new AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group>", "<automation-id>");
I've also tried using other Azure libs (like auth, datacentre etc) and I get the same error:
ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I'm sure it's just 1 tickbox I need to tick buried somewhere in that monolithic Management Portal but I've followed a few tutorials on how to do this and they all end up with this error...
public async Task StartAzureRunbook()
{
try
{
var subscriptionId = "azure subscription Id";
string base64cer = "****long string here****"; //taken from http://stackoverflow.com/questions/24999518/azure-api-the-server-failed-to-authenticate-the-request
var cert = new X509Certificate2(Convert.FromBase64String(base64cer));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(new CertificateCloudCredentials(subscriptionId, cert));
var ct = new CancellationToken();
var content = await client.Runbooks.ListByNameAsync("MyAutomationAccountName", "MyRunbookName", ct);
var firstOrDefault = content?.Runbooks.FirstOrDefault();
if (firstOrDefault != null)
{
var operation = client.Runbooks.Start("MyAutomationAccountName", new RunbookStartParameters(firstOrDefault.Id));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Also in portal:
1) Application is multitenant
2) Permissions to other applications section - Windows Azure Service Manager - Delegated permissions "Access Azure Service Management(preview)"
Ensure that your Management certificate has private key and was not made from the .CER file. The fact that you're not supplying a password when generating the X509Certificate object makes me think you're using public key only
Ensure that your Managemnet's certificate public key (.CER file) has been uploaded to the Azure management portal (legacy version, Management Certificate area)
Use CertificateCloudCredentials and not any other credential type of an object
Ok, stupid really but one of the tutorials I followed suggested installing the prerelease version of the libs.
Installing the preview (0.15.2-preview) has fixed the issue!
I am trying to insert elements into a MongoLab database (Sandbox plan) using C# (by parsing a xml file, but that is not the relevant part).
var connectionString = "mongodb://user:pass#ds011111.mongolab.com:11111/db";
var server = client.GetServer();
var database = server.GetDatabase("mydb");
var elementCollection = database.GetCollection<Entity>("entities");
XmlDocument doc = new XmlDocument();
doc.LoadXml(elementxml);
XmlNodeList elementList = doc.GetElementsByTagName("element");
foreach (XmlNode element in elementList)
{
var t = new Entity();
t.Name = element.FirstChild.InnerText;
elementCollection.Insert(t); // this causes the error below
}
This is the message I get:
WriteConcern detected an error 'not authorized for insert on mydb.entities'. (Response
was { "err" : "not authorized for insert on mydb.entities", "code" : 16544, "n" : 0,
"lastOp" : { "$timestamp" : NumberLong(0) }, "connectionId" : 33932414, "ok" : 1.0 }).
If I run the same code on localhost, everything works as intended
If I insert an element using mongo/shell I get Cannot use commands write mode, degrading to compatability mode, but it works
Does this mean I cannot populate my mongolab database with data (from C#) because I do not have the right permissions as a Sandbox user? If that is the case, what are my options?
The problem seems to be that you're authenticating to the "db" database but trying to use the "mydb" database. Except for specially-privileged/admin users, most users only have access to one database, hence the not authorized error. We run all our databases with authentication on, while the MongoDB defaults, which you're likely using locally, require no authentication; that's why you're not seeing the issue locally.
You should be grabbing the DB to be used from the URI. Here's an example from our Language Center.
// Standard URI format: mongodb://[dbuser:dbpassword#]host:port/dbname
String uri = "mongodb://user:pass#host:port/db";
MongoUrl url = new MongoUrl(uri);
MongoClient client = new MongoClient(url);
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase(url.DatabaseName);
If that doesn't sort you out, try our connectivity troubleshooting guide. In particular, the next thing I'd look at is whether you're using the right credentials (see the section entitled "Check your database credentials").
Finally, please don't hesitate to contact us as support#mongolab.com if you continue to have issues or have any other questions.
I am new to OpenStack, just a few hours experience. I want to create a new machine using OpenStack.NET and this is the code that I come up with.
var identityUrl = "http://server:5000/v2.0";
var imageUrl = "http://server:9292";
var username = "username";
var password = "password";
var cloudId = new CloudIdentity() { Username = username, Password = password };
var cloudIdProvider = new CloudIdentityProvider(new Uri(identityUrl));
cloudIdProvider.Authenticate(cloudId);
var cloudServersProvider = new CloudServersProvider(cloudId, cloudIdProvider);
var newServer = cloudServersProvider.CreateServer("cloudServerName", "Windows Server 2012", "m1.medium");
identityUrl is the url for identity service
imageUrl is the url for image service
I can authenticate on cloudIdProvider.Authenticate(cloudId); line so I think the identity service and username/password are correct.
When I debug on cloudServersProvider.CreateServer("cloudServerName", "Windows Server 2012", "m1.medium");, it throws No region was provided, the service does not provide a region-independent endpoint, and there is no default region set for the user's account. exception which I don't know how to fix it.
The Identity Service is likely failing to include information about the Compute Service endpoint, because you did not specify the tenantName and/or tenantId during authentication. The next release of the SDK will include support for specifying these as described in the preview build of the OpenStack Authentication documentation. However, since the described classes do not exist in the 1.3.1.0 release, you'll need to include a copy of them in your project until 1.3.2.0 is released.
CloudIdentityWithProject.cs
OpenStackIdentityProvider.cs
ProjectId.cs
I am attempting to download metric data from Google Analytics using C# and am performing user authentication with OAuth 2.0. I'm using the Installed Application authorisation flow, which requires logging into Google and copy-and-pasting a code into the application. I'm following the code taken from google-api-dotnet-client:
private void DownloadData()
{
Service = new AnalyticsService(new BaseClientService.Initializer() {
Authenticator = CreateAuthenticator(),
});
var request = service.Data.Ga.Get(AccountID, StartDate, EndDate, Metrics);
request.Dimensions = Dimensions;
request.StartIndex = 1;
request.MaxResults = 10000;
var response = request.Execute(); // throws Google.GoogleApiException
}
private IAuthenticator CreateAuthenticator()
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) {
ClientIdentifier = "123456789012.apps.googleusercontent.com",
ClientSecret = "xxxxxxxxxxxxxxxxxxxxxxxx",
};
return new OAuth2Authenticator<NativeApplicationClient>(provider, Login);
}
private static IAuthorizationState Login(NativeApplicationClient arg)
{
// Generate the authorization URL.
IAuthorizationState state = new AuthorizationState(new[] { AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user by opening a browser window.
Process.Start(authUri.ToString());
Console.Write("Google Authorization Code: ");
string authCode = Console.ReadLine();
// Retrieve the access token by using the authorization code.
state = arg.ProcessUserAuthorization(authCode, state);
return state;
}
The Google account xxxxxx#gmail.com registered the Client ID and secret. The same account has full administration rights in Google Analytics. When I try to pull data from Google Analytics, it goes through the authorisation process, which appears to work properly. Then it fails with:
Google.GoogleApiException
Google.Apis.Requests.RequestError
User does not have sufficient permissions for this profile. [403]
Errors [
Message[User does not have sufficient permissions for this profile.] Location[ - ] Reason [insufficientPermissions] Domain[global]
]
I've been struggling with this for a few hours. I've double checked that the correct user is being used, and is authorised on Google Analytics. I'm at a loss as to what is misconfigured. Any ideas as to what requires configuring or changing?
If auth seems to be working working then my suggestion is that you make sure you're providing the correct ID because based on your code snippet:
var request = service.Data.Ga.Get(AccountID, StartDate, EndDate, Metrics);
one can only assume that you're using the Account ID. If so, that is incorrect and you'd receive the error you've encountered. You need to query with the Profile ID.
If you login to Google Analytics using the web interface you'll see the following pattern in URL of the browser's address bar:
/a12345w654321p9876543/
The number following the p is the profile ID, so 9876543 in the example above. Make sure you're using that and actually you should be using the table id which would be ga:9876543.
If it isn't an ID issue then instead query the Management API to list accounts and see what you have access to and to verify auth is working correctly.
This can help : https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors, look error 403.
//Thanks for this post. The required profile id can be read from the account summaries.
Dictionary profiles = new Dictionary();
var accounts = service.Management.AccountSummaries.List().Execute();
foreach (var account in accounts.Items)
{
var profileId = account.WebProperties[0].Profiles[0].Id;
profiles.Add("ga:" + profileId, account.Name);
}