MongoDB C# Driver failed to run database command authenticate - c#

I want to authenticate to MongoDB with C# not through passing the Connection String/Credentials on the MongoClient() instance. It's like we do it on MongoDB Shell, We call monog -> db.auth(<username>,<password>) it means Connect to database first and authenticate after that.
Write C# Code
This is my code:
var mongoClient = new MongoClient();
var testDB = mongoClient.GetDatabase("test");
string username = txtUserName.Text;
string password = txtPassword.Password;
// Check password
var cmd = new BsonDocument("authenticate", new BsonDocument
{
{"username",username },
{"password",password }
});
var queryResult = testDB.RunCommand<BsonDocument>(cmd);
My Code connect to MongoDB and call the authenticate Database Command (described Here. It's not the db.auth() Shell method)to login with it
Run MongoDB with --auth option.
Run my Code.
After step 3, I encountered this problem. My code say
Additional information: Command authenticate failed: field missing/wrong type in received authenticate command.
I have read MongoDB documents (Also the link I added above) I can't find What I was missing.

I think you can use a JsonCommand to call eval function to execute db.auth function like this - not tested -:
var command = new JsonCommand<BsonDocument>(#"{ eval: ""db.auth(\""username\"", \""password\"");"" }");
var result = db.RunCommand(command);

Related

Run Time error in making kusto connection in c# -- AADSTS50079:

"Run time exception AADSTS50079: Due to a configuration change made by your administrator, or because you moved to a new location, you must enroll in multi-factor authentication"
static void Main(string[] args)
{
var builder = new
KustoConnectionStringBuilder("help.kusto.windows.net/Samples")
{
FederatedSecurity = true,
UserID = "***#microsoft.com",
Password = "****",
EnforceMfa = true
};
var client =
Kusto.Data.Net.Client.KustoClientFactory.CreateCslQueryProvider(builder);
var reader = client.ExecuteQuery("StormEvents | count");
}
If you are microsoft FTE and try to query kusto on a dotNet Core Console Application, I suggest you to use a dotNet Framework Console Application.
use
var client = Kusto.Data.Net.Client.KustoClientFactory.CreateCslQueryProvider("https://help.kusto.windows.net/Samples;Fed=true");
var reader = client.ExecuteQuery("MyTable | count");
// Read the first row from reader -- it's 0'th column is the count of records in MyTable
// Don't forget to dispose of reader when done.
see https://learn.microsoft.com/en-us/azure/kusto/api/netfx/about-kusto-data
Then it will pop up a window to use VSTS as a multi-factor authentication.
It seems that VSTS authentication not support dotNet Core.

"Parameter does not exist or you do not have sufficient permissions" when running SSIS package in C#

I have a SSIS package with a bunch of variables, listed below:
I am trying to call the SSIS package from a C# Windows Form App using the code below:
// Create a connection to the server
string sqlConnectionString = "Data Source=BSQL_01;Initial Catalog=master;Integrated Security=SSPI;";
SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
// Create the Integration Services object
IntegrationServices integrationServices = new IntegrationServices(sqlConnection);
// Get the Integration Services catalog
Catalog catalog = integrationServices.Catalogs["SSISDB"];
// Get the folder
CatalogFolder folder = catalog.Folders["PORGPackages"];
// Get the project
ProjectInfo project = folder.Projects["PORGPackages"];
// Get the package
PackageInfo package = project.Packages["POHandler.dtsx"];
// Add project parameter
Collection<PackageInfo.ExecutionValueParameterSet> executionParameter = new Collection<PackageInfo.ExecutionValueParameterSet>();
executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 20, ParameterName = "SessionID", ParameterValue = "636943168325507712" });
// Run the package
long executionIdentifier = package.Execute(false, null, executionParameter);
ExecutionOperation executionOperation = integrationServices.Catalogs["SSISDB"].Executions[executionIdentifier];
while (!executionOperation.Completed) {
System.Threading.Thread.Sleep(5000);
executionOperation.Refresh();
MessageBox.Show("Running...");
}
if (executionOperation.Status == Operation.ServerOperationStatus.Success) {
Console.WriteLine("Success");
} else if (executionOperation.Status == Operation.ServerOperationStatus.Failed) {
Console.WriteLine("Failed");
} else {
Console.WriteLine("Something Went Really Wrong");
}
I am getting the following error:
The parameter 'SessionID' does not exist or you do not have sufficient
permissions.
Am I adding the parameter correctly? I don't know I can watch to see if it's being set, or if I have permission.
Am I adding the parameter correctly?
You have declared a variable called #SessionID not a parameter.
If you need to pass a variable value then you can refer to the following link:
How to pass variables to an SSIS package from a C# application
For more information about both objects (variables & parameters) you can refer to the following articles:
Getting Started with Parameters, Variables & Configurations in SSIS 2012
What's the difference between Variable and Parameters
SSIS Variables vs Parameters (SSIS Denali)

Cannot connect to Azure MySQL database from .NET Connector

I tried to connect to the Azure MySQL database using MySQL Workbench and MySQL Shell and it works fine. Now I am trying to connect using following C# code:
var connStringBuilder = new MySqlConnectionStringBuilder
{
Server = "creatur-db.mysql.database.azure.com",
Database = "test",
UserID = "creatur_db_main#creatur-db",
Password = "{my_password}",
SslMode = MySqlSslMode.Preferred,
};
using (MySqlConnection connection = new MySqlConnection(connStringBuilder.ToString()))
{
connection.Open();
connection.Close();
}
Here I replaced {my_password} with password to the database and it gives me an exception inside Open method:
MySql.Data.MySqlClient.MySqlException: 'Authentication to host
'creatur-db.mysql.database.azure.com' for user
'creatur_db_main#creatur-db' using method 'mysql_native_password'
failed with message: The connection string may not be right. Please
visit portal for references.
I also tried different connection strings:
Server=creatur-db.mysql.database.azure.com; Port=3306; Database=test; Uid=creatur_db_main#creatur-db; Pwd={my_password}; SslMode=Preferred
and
Database=test; Data Source=creatur-db.mysql.database.azure.com; User Id=creatur_db_main#creatur-db; Password={my_password}
But none of them worked.
The same exception occurs when I create new connection using Server Explorer in Visual Studio 2013. It seems the error has something to do with .NET Connector. I tried to use different versions of MySQL.Data.dll, .NET Framework and Visual Studio but no luck.
I just created a console application using VS2017 I used
Nuget package MySql.Data and .Net Framework 4.6.1
It works perfectly here What I did.
After Creating the MySQL server I used the CloudShell to connect to the SERVER (not a database).
Using this code:
mysql --host franktest.mysql.database.azure.com --user frank#franktest -p
I got an error
ERROR 9000 (HY000): Client with IP address '40.76.202.47' is not allowed to connect to this MySQL server.
So I add that IP and at the same time my IP from where I'm connected.
So once the IP were saved. I executed the previous command, and this time it worked perfectly. I created a database named: frankdemo using this command:
CREATE DATABASE frankdemo;
Then, back in VisualStudio used this code as my Main method, copied from the documentation.
static void Main(string[] args)
{
var builder = new MySqlConnectionStringBuilder
{
Server = "franktest.mysql.database.azure.com",
Database = "frankdemo",
UserID = "frank#franktest",
Password = "gr3enRay14!",
SslMode = MySqlSslMode.Required,
};
using (var conn = new MySqlConnection(builder.ConnectionString))
{
Console.WriteLine("Opening connection");
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText = "DROP TABLE IF EXISTS inventory;";
command.ExecuteNonQuery();
Console.WriteLine("Finished dropping table (if existed)");
command.CommandText = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);";
command.ExecuteNonQuery();
Console.WriteLine("Finished creating table");
command.CommandText = #"INSERT INTO inventory (name, quantity) VALUES (#name1, #quantity1),
(#name2, #quantity2), (#name3, #quantity3);";
command.Parameters.AddWithValue("#name1", "banana");
command.Parameters.AddWithValue("#quantity1", 150);
command.Parameters.AddWithValue("#name2", "orange");
command.Parameters.AddWithValue("#quantity2", 154);
command.Parameters.AddWithValue("#name3", "apple");
command.Parameters.AddWithValue("#quantity3", 100);
int rowCount = command.ExecuteNonQuery();
Console.WriteLine(String.Format("Number of rows inserted={0}", rowCount));
}
// connection will be closed by the 'using' block
Console.WriteLine("Closing connection");
}
Console.WriteLine("Press RETURN to exit");
Console.ReadLine();
}
Runed it and it works
The documentation I'm referring to is:
Create an Azure Database for MySQL server by using the Azure portal
Azure Database for MySQL: Use .NET (C#) to connect and query data

Create Exchange Mailboxes on Remote Exchange 2010 Server in C#

Title pretty much explains it all. I have a C# application that is not running on the Exchange Server. I need to be able to create mailboxes. I tried to use this tutorial, but it requires the PowerShell IIS Virutal directory to:
Not Require SSL
Allow Basic Authentication
Which are things that we cant do. This leads me to two possible solutions. Is there a way to modify the tutorial listed above to not require those two restrictions, or is there a way to do it without using power shell at all?
Here is the code, in case you dont feel like going to the link:
using System;
using System.Security;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace PowerShellTest
{
class Program
{
static void Main(string[] args)
{
// Prepare the credentials that will be used when connecting
// to the server. More info on the user to use on the notes
// below this code snippet.
string runasUsername = #"username";
string runasPassword = "password";
SecureString ssRunasPassword = new SecureString();
foreach (char x in runasPassword)
ssRunasPassword.AppendChar(x);
PSCredential credentials =
new PSCredential(runasUsername, ssRunasPassword);
// Prepare the connection
var connInfo = new WSManConnectionInfo(
new Uri("http://ServersIpAddress/PowerShell"),
"http://schemas.microsoft.com/powershell/Microsoft.Exchange",
credentials);
connInfo.AuthenticationMechanism =
AuthenticationMechanism.Basic;
// Create the runspace where the command will be executed
var runspace = RunspaceFactory.CreateRunspace(connInfo);
// generate the command parameters
var testNumber = 18;
var firstName = "Test";
var lastName = "User" + testNumber;
var username = "tuser" + testNumber;
var domainName = "pedro.test.local";
var password = "ActiveDirectoryPassword1234";
var ssPassword = new SecureString();
foreach (char c in password)
ssPassword.AppendChar(c);
// create the PowerShell command
var command = new Command("New-Mailbox");
command.Parameters.Add("Name", firstName + " " + lastName);
command.Parameters.Add("Alias", username);
command.Parameters.Add(
"UserPrincipalName", username + "#" + domainName);
command.Parameters.Add("SamAccountName", username);
command.Parameters.Add("FirstName", firstName);
command.Parameters.Add("LastName", lastName);
command.Parameters.Add("Password", ssPassword);
command.Parameters.Add("ResetPasswordOnNextLogon", false);
command.Parameters.Add(
"OrganizationalUnit", "NeumontStudents");
// Add the command to the runspace's pipeline
runspace.Open();
var pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(command);
// Execute the command
var results = pipeline.Invoke();
runspace.Dispose();
if (results.Count > 0)
Console.WriteLine("SUCCESS");
else
Console.WriteLine("FAIL");
}
}
}
You can set up a so-called runspace with many different AuthenticationMechanism's
Visit the MSDN site for code samples using:
Basic Authentication (which is used in your example)
Certificate Authentication
Kerberos Authentication
Negotiated Authentication
http://msdn.microsoft.com/en-us/library/ff326159(v=exchg.140).aspx
In any case, no need to give up on PowerShell just yet.
The code from that blog post is a little broken. The Pipeline class is an overly complex way to create a command, and the way that it's written involves creating a pair of runspaces (one local, one remote), instead of just the remote one.
Additionally, "Basic" and "http" in IIS do not mean "no security and no encryption in PowerShell". Everything sent over the WinRM layer is encrypted by default.
This Link from the Exchange Team covers the right way to do this in C# fairly well.
So:
You don't have to worry about the IIS "Basic", because there's another layer of security.
You can cut your code in half and make it faster if you use the C# from the Exchange team
Also to be 100% crystal clear:
You cannot manage Exchange 2010 remotely except thru PowerShell.
Hope This Helps

MongoDB with C#.net

I am Very new with MongoDB,I m using windows7 32bit,downloaded mongo exe files from http://www.mongodb.org/display/DOCS/Quickstart+Windows
And downloaded mongodb.dll also
Mongo mongo = new Mongo();
mongo.Connect();
gives me the error
Failed to connect to server localhost:27017
Is i m missing something,plz let me know
You should use
var connectionString = "mongodb://localhost/?safe=true";
var server = MongoServer.Create(connectionString);
var database = server.GetDatabase("test");

Categories