Add a new User for the database in mongodb - c#

I want to add a new user to newly created database and if this user exists then i will connect to that database.
My code is:
public CreateDatabaseOperationResult CreateDatabase(string databaseName,string username,string password, MongoServer server)
{
CreateDatabaseOperationResult createDatabaseOpResult = new CreateDatabaseOperationResult();
string message = null;
MongoCredentials credentials = new MongoCredentials(username, password);
MongoUser user = new MongoUser(credentials, false);
try
{
if (IsDatabaseNameValid(databaseName, out message))
{
if (server.DatabaseExists(databaseName, admincredentials) == true)
{
createDatabaseOpResult.Database = server.GetDatabase(databaseName, credentials);
MongoUser tempuser = createDatabaseOpResult.Database.FindUser(username);
if (tempuser.Equals(user))
{
//createDatabaseOpResult.DatabaseExists = true;
createDatabaseOpResult.IsOperationSuccessfull = false;
throw new ArgumentException("Database Already exist with different set of credentials ");
}
}
else
{
createDatabaseOpResult.Database = server.GetDatabase(databaseName, credentials);
createDatabaseOpResult.Database.AddUser(user);
//createDatabaseOpResult.DatabaseExists = false;
}
createDatabaseOpResult.IsOperationSuccessfull = true;
}
}
catch (MongoQueryException ex)
{
createDatabaseOpResult.Error = ex;
}
//catch (MongoAuthenticationException ex)
//{
// createDatabaseOpResult.Error = ex;
//}
catch (MongoException ex)
{
createDatabaseOpResult.Error = ex;
}
catch (ArgumentException ex)
{
createDatabaseOpResult.Error = ex;
}
return createDatabaseOpResult;
}
When i use the existing database it connects to that database but when i try to add new use Database.AddUser gives error 'invalid credentials for this database'
Please see the error and reply

Most people use the mongo shell to add and remove users, but if you really want to do it in C# the trick is to use the right credentials depending on what you are trying to do. Assume you have the following two sets of credentials, one for the admin database and one for regular databases:
var adminCredentials = new MongoCredentials("myadminusername", "myadminpassword", true);
var userCredentials = new MongoCredentials("myusername", "myuserpassword");
Note that when creating the adminCredentials you must pass true to the admin parameter.
To test if a database exists requires admin credentials:
if (server.DatabaseExists("mydatabase", adminCredentials))
{
// database exists
}
To add a user requires admin credentials:
var myDatabaseWithAdminCredentials = server.GetDatabase("mydatabase", adminCredentials);
if (myDatabaseWithAdminCredentials.FindUser("myusername") == null)
{
myDatabaseWithAdminCredentials.AddUser(userCredentials);
}
Normally you use regular user credentials to work with a database:
var myDatabaseWithUserCredentials = server.GetDatabase("mydatabase", userCredentials);
var count = myDatabaseWithUserCredentials.GetCollection("mycollection").Count();
Also, keep in mind that each database can have any number of users, so you don't really need to be checking whether the database already exists with a different set of credentials.

Related

Sign In - Cognito & .Net Framework

I'm trying to connect to AWS Cognito from a .net Framework project.
I can sign up succesfully but when I need to sign in, throws me an error: "User pool {userPool} client does not exist".
This is my code:
private async Task<bool> CheckPasswordAsync(string userName, string password)
{
try
{
var authReq = new AdminInitiateAuthRequest
{
UserPoolId = ConfigurationManager.AppSettings["USERPOOL_ID"],
ClientId = ConfigurationManager.AppSettings["CLIENT_ID"],
AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH,
};
authReq.AuthParameters.Add("USERNAME", userName);
authReq.AuthParameters.Add("PASSWORD", password);
AdminInitiateAuthResponse authResp = await _client.AdminInitiateAuthAsync(authReq);
var auts = authResp;
return true;
}
catch(Exception ex)
{
var exc = ex.Message;
return false;
}
}
I don't know if I need to ad more information to the method.
The user pool exists and is the same that I have in appSettings.
Any idea about what's wrong?
Thanks in advance.

a list of all users: Ldap referral error (LDAPReferralException)

I am using active directory and want a list of all users, basically in dotnet core. But I am receiving an exception:
Search result reference received, and referral following is off
Below is my code.
LdapSearchResults lsc = lc.Search("DC = xyz, DC = local", LdapConnection.SCOPE_ONE , "(|(objectClass = person)(objectClass = user))", null, false);
Necromancing - just in case the links go dark.
To fix it in your application, set ReferralFollowing to true.
if you get the message
Search result reference received, and referral following is off
, add
Novell.Directory.Ldap.LdapSearchConstraints cons = lc.SearchConstraints;
cons.ReferralFollowing = true;
lc.Constraints = cons;
to your code.
Example:
public static void GetUsers()
{
System.Collections.Generic.List<ARSoft.Tools.Net.Dns.SrvRecord> lsLdap = GetLdap();
ARSoft.Tools.Net.Dns.SrvRecord ldap = lsLdap[0];
string[] attrs = new string[] { "cn", "distinguishedName", "sAMAccountName", "userPrincipalName", "displayName", "givenName", "sn", "mail", "mailNickname", "memberOf", "homeDirectory", "msExchUserCulture" };
// CN = Common Name
// OU = Organizational Unit
// DC = Domain Component
string searchBase = "DC=cor,DC=local";
string searchFilter = "(&(objectClass=user)(objectCategory=person))";
string ldapHost = MySamples.TestSettings.ldapHost;
int ldapPort = MySamples.TestSettings.ldapPort;//System.Convert.ToInt32(args[1]);
string loginDN = MySamples.TestSettings.loginDN; // args[2];
string password = MySamples.TestSettings.password; // args[3];
Novell.Directory.Ldap.LdapConnection lc = new Novell.Directory.Ldap.LdapConnection();
int ldapVersion = Novell.Directory.Ldap.LdapConnection.Ldap_V3;
try
{
// connect to the server
lc.Connect(ldap.Target.ToString(), ldap.Port);
// bind to the server
lc.Bind(ldapVersion, loginDN, password);
Novell.Directory.Ldap.LdapSearchConstraints cons = lc.SearchConstraints;
cons.ReferralFollowing = true;
lc.Constraints = cons;
// To enable referral following, use LDAPConstraints.setReferralFollowing passing TRUE to enable referrals, or FALSE(default) to disable referrals.
Novell.Directory.Ldap.LdapSearchResults lsc = lc.Search(searchBase,
Novell.Directory.Ldap.LdapConnection.SCOPE_SUB,
searchFilter,
attrs,
false,
(Novell.Directory.Ldap.LdapSearchConstraints)null);
while (lsc.HasMore())
{
Novell.Directory.Ldap.LdapEntry nextEntry = null;
try
{
nextEntry = lsc.Next();
}
catch (Novell.Directory.Ldap.LdapReferralException eR)
{
// https://stackoverflow.com/questions/46052873/ldap-referal-error
// The response you received means that the directory you are requesting does not contain the data you look for,
// but they are in another directory, and in the response there is the information about the "referral" directory
// on which you need to rebind to "redo" the search.This principle in LDAP are the referral.
// https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/bp31k5d.html
// To enable referral following, use LDAPConstraints.setReferralFollowing passing TRUE to enable referrals, or FALSE (default) to disable referrals.
// are you sure your bind user meaning
// auth.impl.ldap.userid=CN=DotCMSUser,OU=Service Accounts,DC=mycompany,DC=intranet
// auth.impl.ldap.password = mypassword123
// has permissions to the user that is logging in and its groups?
System.Diagnostics.Debug.WriteLine(eR.LdapErrorMessage);
}
catch (Novell.Directory.Ldap.LdapException e)
{
// WARNING: Here catches only LDAP-Exception, no other types...
System.Console.WriteLine("Error: " + e.LdapErrorMessage);
// Exception is thrown, go for next entry
continue;
}
var atCN = nextEntry.getAttribute("cn");
var atUN = nextEntry.getAttribute("sAMAccountName");
var atDN = nextEntry.getAttribute("distinguishedName");
var atDIN = nextEntry.getAttribute("displayName");
if (atCN != null)
System.Console.WriteLine(atCN.StringValue);
if (atUN != null)
System.Console.WriteLine(atUN.StringValue);
if (atDN != null)
System.Console.WriteLine(atDN.StringValue);
if (atDIN != null)
System.Console.WriteLine(atDIN.StringValue);
System.Console.WriteLine("\n" + nextEntry.DN);
Novell.Directory.Ldap.LdapAttributeSet attributeSet = nextEntry.getAttributeSet();
System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
while (ienum.MoveNext())
{
Novell.Directory.Ldap.LdapAttribute attribute = (Novell.Directory.Ldap.LdapAttribute)ienum.Current;
string attributeName = attribute.Name;
string attributeVal = attribute.StringValue;
System.Console.WriteLine(attributeName + "value:" + attributeVal);
}
}
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
}
finally
{
// disconnect with the server
lc.Disconnect();
}
}
You have to activate the behaviour which will follow the referral returned by the directory.
The response you received means that the directory you are requesting does not contain the data you look for, but they are in another directory, and in the response there is the information about the "referral" directory on which you need to rebind to "redo" the search. This principle in LDAP are the referral.
I don't know how to do it in C#, but maybe have a look at :
https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/bp31k5d.html

Error when Inserting using SqlMapperExtension Dapper

Currently playing around with Dapper I'm trying to insert values into the db as follows
using (var sqlCon = new SqlConnection(Context.ReturnDatabaseConnection()))
{
sqlCon.Open();
try
{
var emailExists = sqlCon.Query<UserProfile>(#"SELECT UserId FROM User_Profile WHERE EmailAddress = #EmailAddress",
new { EmailAddress = userRegister.EmailAddress.Trim() }).FirstOrDefault();
if (emailExists == null) // No profile exists with the email passed in, so insert the new user.
{
userProfile.UniqueId = Guid.NewGuid();
userProfile.Firstname = userRegister.Firstname;
userProfile.Surname = userRegister.Surname;
userProfile.EmailAddress = userRegister.EmailAddress;
userProfile.Username = CreateUsername(userRegister.Firstname);
userProfile.Password = EncryptPassword(userRegister.Password);
userProfile.AcceptedTerms = true;
userProfile.AcceptedTermsDate = System.DateTime.Now;
userProfile.AccountActive = true;
userProfile.CurrentlyOnline = true;
userProfile.ClosedAccountDate = null;
userProfile.JoinedDate = System.DateTime.Now;
userProfile.UserId = SqlMapperExtensions.Insert(sqlCon, userProfile); // Error on this line
Registration.SendWelcomeEmail(userRegister.EmailAddress, userRegister.Firstname); // Send welcome email to new user.
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
sqlCon.Close();
}
}
The error I get is
ExecuteNonQuery requires the command to have a transaction when the connection
assigned to the command is in a pending local transaction. The Transaction
property of the command has not been initialized.
I have googled this error, but I misunderstood the answers provided.
From the error message I assume that you have started a transaction that was neither committed nor rolled back. The real cause for this error message is elsewhere.
I suggest you to log requests in Context.ReturnDatabaseConnection() and trace what requests precede this error.
Also I advice you to look in your code for all transactions and check if they are correctly completed (commit/rollback).

Can't Connect to SalesForce in C#

I am following this tutorial http://wiki.developerforce.com/page/Integrating_Force.com_with_Microsoft_.NET
However, I am getting this error:
LOGIN_MUST_USE_SECURITY_TOKEN: Invalid username, password, security
token; or user locked out. Are you at a new location? When accessing
Salesforce--either via a desktop client or the API--from outside of
your company’s trusted networks, you must add a security token to your
password to log in. To receive a new security token, log in to
salesforce.com at http://login.salesforce.com and click Setup | My
Personal Information | Reset Security Token.
This is my code in my Console App:
static void Main(string[] args)
{
string userName;
string password;
userName = "me#myWebsite.com";
password = "myPassword";
SforceService SfdcBinding = null;
LoginResult CurrentLoginResult = null;
SfdcBinding = new SforceService();
try
{
CurrentLoginResult = SfdcBinding.login(userName, password);
}
catch (System.Web.Services.Protocols.SoapException e)
{
// This is likley to be caused by bad username or password
SfdcBinding = null;
throw (e);
}
catch (Exception e)
{
// This is something else, probably comminication
SfdcBinding = null;
throw (e);
}
}
The error states I need a security token, but the documentation never seems to mention it and I'm not sure how to get one.
What I had to do (which was not in the documentation) is go to here:
https://na15.salesforce.com/_ui/system/security/ResetApiTokenConfirm?retURL=%2Fui%2Fsetup%2FSetup%3Fsetupid%3DPersonalInfo&setupid=ResetApiToken
And, reset my token. Then, append it to the end of my password like:
If your password = "mypassword"
And your security token = "XXXXXXXXXX"
You must enter "mypasswordXXXXXXXXXX" in place of your password
Ref. http://docs.servicerocket.com/pages/viewpage.action?pageId=83099770
With a SOAP API like this you need to authenticate to the service first by providing the username and password. Their response should return an authorization token that will be valid for a period of time. Then in your subsequent communications you pass this token to the API so that it knows who you are.
Get the authorization token:
SforceService SfdcBinding = null;
LoginResult CurrentLoginResult = null;
SfdcBinding = new SforceService();
try
{
CurrentLoginResult = SfdcBinding.login(userName, password);
}
catch (System.Web.Services.Protocols.SoapException e)
{
// This is likely to be caused by bad username or password
SfdcBinding = null;
throw (e);
}
catch (Exception e)
{
// This is something else, probably communication
SfdcBinding = null;
throw (e);
}
Setup the session:
//Change the binding to the new endpoint
SfdcBinding.Url = CurrentLoginResult.serverUrl;
//Create a new session header object and set the session id to that returned by the login
SfdcBinding.SessionHeaderValue = new SessionHeader();
SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;
Perform your query:
QueryResult queryResult = null;
String SOQL = "select FirstName, LastName, Phone from Lead where email = 'john.smith#salesforce.com'";
queryResult = SfdcBinding.query(SOQL);

Remove user account from administrators group on remote machine using C# and AccountManagment namespace

I have the code:
public bool RemoveUserFromAdministratorsGroup(UserPrincipal oUserPrincipal, string computer)
{
try
{
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine, computer, null, ContextOptions.Negotiate, _sServiceUser, _sServicePassword);
GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, "Administrators");
oGroupPrincipal.Members.Remove(oUserPrincipal);
oGroupPrincipal.Save();
return true;
}
catch
{
return false;
}
}
It is worked without any excaption. But when i run my app again i see this user in my listview. So, the user wasn't removed.
I have solved the issue without AccountManagment namespace.
public bool RemoveUserFromAdminGroup(string computerName, string user)
{
try
{
var de = new DirectoryEntry("WinNT://" + computerName);
var objGroup = de.Children.Find(Settings.AdministratorsGroup, "group");
foreach (object member in (IEnumerable)objGroup.Invoke("Members"))
{
using (var memberEntry = new DirectoryEntry(member))
if (memberEntry.Name == user)
objGroup.Invoke("Remove", new[] {memberEntry.Path});
}
objGroup.CommitChanges();
objGroup.Dispose();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}
The below solution is for deleting the user with the help of Directory Service ...
using System.DirectoryServices
private DeleteUserFromActiveDirectory(DataRow in_Gebruiker)
{
DirectoryEntry AD = new DirectoryEntry(strPathActiveDirectory ,
strUsername, strPassword)
DirectoryEntry NewUser =
AD.Children.Find("CN=TheUserName", "User");
AD.Children.Remove(NewUser);
AD.CommitChanges();
AD.Close();
}
I don't know what is exactly your problem but coding this way :
try
{
PrincipalContext context = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "passwd");
/* Retreive a user principal
*/
UserPrincipal user = UserPrincipal.FindByIdentity(context, "user1");
/* Retreive a group principal
*/
GroupPrincipal adminGroup = GroupPrincipal.FindByIdentity(context, #"dom\Administrateurs");
foreach (Principal p in adminGroup.Members)
{
Console.WriteLine(p.Name);
}
adminGroup.Members.Remove(user);
adminGroup.Save();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Give me the following exception :
Information about the domain could not be retrieved (1355)
Digging a bit arround that show me that I was running my code on a computer that was not on the target domain. When I run the same code from the server itself it works. It seems that the machine running this code must at least contact the DNS of the target domain.

Categories

Resources