DistinguishedName attribute of Active Directory - c#

This is my code :
public bool ActiveDirectoryAuthenticate(string username, string password)
{
var result = false;
using (var entry = new DirectoryEntry("LDAP://*****/DC=******,DC=biz",username,password,AuthenticationTypes.Secure))
{
var searcher = new DirectorySearcher(entry){Filter = "objectClass=user"};
try
{
var sr = searcher.FindOne();
var PathDic = sr.Properties["distinguishedName"][0].ToString();
result = true;
}
catch (Exception exception)
{
}
}
return result;
}
The problem is
sr.Properties["distinguishedName"][0].ToString();
does not return correct value.
Please help me

Just an idea but don't you need to put value like this :
var PathDic = sr.Properties["distinguishedName"][0].Value.ToString();

My problem resolve:
public bool ActiveDirectoryAuthenticate(string username, string password)
{
var result = false;
using (
var entry = new DirectoryEntry("LDAP://PT/DC=pt,DC=biz", username, password,
AuthenticationTypes.Secure))
{
var searcher = new DirectorySearcher(entry) {Filter = "sAMAccountName=Bank.Members"};
searcher.PropertiesToLoad.Add("distinguishedName");
try
{
var sr = searcher.FindOne();
var name = sr.Properties["distinguishedName"][0].ToString();
result = true;
}
catch (Exception exception)
{
}
}
return result;
}

Related

SQLite table doesn't get updated

I have a problem. I created a SwitchButton and want to store the state in a database table. So I created this code to debug:
SettingSwitch.CheckedChange += (s, b) =>
{
SettingDb testsetting = new SettingDb
{
Name = mItems[position].Name,
};
SettingDb test = MainActivity.db.SelectRowFromTableSettings(testsetting);
if (test != null)
{
bool SwitchValueBool = Convert.ToBoolean(test.Value);
}
bool isChecked = ValueDictionary[position];
if(isChecked == true)
{
isChecked = false;
}
else if(isChecked == false)
{
isChecked = true;
}
SettingDb setting = new SettingDb()
{
Name = SettingName.Text,
Type = "Switch",
Value = isChecked.ToString()
};
MainActivity.db.UpdateTableSettings(setting);
ValueDictionary[position] = isChecked;
SettingDb test2 = MainActivity.db.SelectRowFromTableSettings(testsetting);
if (test2 != null)
{
bool SwitchValueBool = Convert.ToBoolean(test2.Value);
}
};
The expected outcome should be:
test.Value = False
test2.Value = Opposite of test.Value, so True
But now the value I get from the table is always False. Here is the update function:
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
public bool UpdateTableSettings(SettingDb setting)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
connection.BeginTransaction();
connection.Query<SettingDb>("UPDATE SettingDb SET Value=? WHERE Name=?", setting.Value, setting.Name);
//connection.Update(setting);
connection.Commit();
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public SettingDb SelectRowFromTableSettings(SettingDb setting)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
return connection.Query<SettingDb>("SELECT * FROM SettingDb WHERE Name=?", setting.Name).FirstOrDefault();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return null;
}
}
The table value doesn't get updated!!!
Can someone tell me what I am doing wrong?
Please let me know!
According to your description, you want to update sqlite database table, please take a look the following code and modify the update function.
static void UpdateDatabase(int primaryKey, string newText, int newValue)
{
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "mydatabase.db");
var db = new SQLiteConnection(path, false);
string sql = "UPDATE MyTable SET MyTextColumn = ?, MyValueColumn = ? WHERE MyPrimaryKey= ?";
string[] parms = new String[] { newText, newValue.ToString(), primaryKey.ToString() };
var cmd = db.CreateCommand(sql, parms);
cmd.ExecuteNonQuery();
}

IFtpHomeDirectoryProvider did not rise

I've realized curom authentication for ftp site basing on https://blogs.msdn.microsoft.com/robert_mcmurray/2011/06/30/how-to-create-an-authentication-provider-for-ftp-7-5-using-blogengine-nets-xml-membership-files/, but IFtpHomeDirectoryProvider.GetUserHomeDirectoryData did not rise
public class FtpEngineNetAuthentication : BaseProvider,
IFtpAuthenticationProvider
, IFtpRoleProvider
, IFtpHomeDirectoryProvider
, IFtpPostprocessProvider
, IFtpLogProvider
{
private readonly string _logfile = Path.Combine(#"c:\test", "logs", "FtpExtension.log");
private string _dbConnectionString;
private string _ftpHomeDirectory;
protected override void Initialize(StringDictionary config)
{
// Retrieve the paths from the configuration dictionary.
_dbConnectionString = config["RextorConnectionString"];
_ftpHomeDirectory = config["ftpHomeDirectory"];
}
bool TryGetUser(string login, out User user)
{
user = null;
try
{
using (var conn = new SqlConnection(_dbConnectionString))
{
var command = new SqlCommand("SELECT UserName, Password, HashAlgorithm, PasswordSalt FROM Orchard_Users_UserPartRecord WHERE UserName = #login", conn);
command.Parameters.AddWithValue("#login", login);
conn.Open();
using (var reader = command.ExecuteReader())
{
if (reader.Read()) // Don't assume we have any rows.
{
user = new User()
{
Login = reader.GetString(0),
Password = reader.GetString(1),
HashAlgorithm = reader.GetString(2),
PasswordSalt = reader.GetString(3)
};
}
}
conn.Close();
}
}
catch (Exception)
{
return false;
}
return true;
}
// Define the GetUserHomeDirectoryData method.
string IFtpHomeDirectoryProvider.GetUserHomeDirectoryData(string sessionId, string siteName, string userName)
{
// Test if the path to the home directory is empty.
if (string.IsNullOrEmpty(_ftpHomeDirectory))
{
// Throw an exception if the path is missing or empty.
throw new ArgumentException(#"Missing ftpHomeDirectory value in configuration.");
}
LogMessage($"directory: {userName}");
var result = $#"{_ftpHomeDirectory}\{userName}";
LogMessage(result);
// Return the path to the home directory.
return result;
}
// Define the AuthenticateUser method.
bool IFtpAuthenticationProvider.AuthenticateUser(string sessionId, string siteName, string userName, string userPassword, out string canonicalUserName)
{
// Define the canonical user name.
canonicalUserName = userName.Replace("#", "").Replace(".", "");
// Validate that the user name and password are not empty.
if (String.IsNullOrEmpty(userName) || String.IsNullOrEmpty(userPassword))
{
// Return false (authentication failed) if either are empty.
return false;
}
try
{
// Create a user object.
User user = null;
// Test if the user name is in the dictionary of users.
if (TryGetUser(userName, out user))
{
var saltBytes = Convert.FromBase64String(user.PasswordSalt);
// Retrieve a sequence of bytes for the password.
bool isValid;
if (user.HashAlgorithm == "PBKDF2")
{
LogMessage($"user password: {user.Password}");
LogMessage($"user salt: {user.PasswordSalt}");
LogMessage($"user salt&pwd: {Encoding.Unicode.GetString(CombineSaltAndPassword(saltBytes, userPassword))}");
// We can't reuse ComputeHashBase64 as the internally generated salt repeated calls to Crypto.HashPassword() return different results.
isValid = true;
//Crypto.VerifyHashedPassword(user.Password, Encoding.Unicode.GetString(CombineSaltAndPassword(saltBytes, userPassword)));
//PasswordHash.ValidatePassword(user.Password, Encoding.Unicode.GetString(CombineSaltAndPassword(saltBytes, userPassword)));
//BCryptHelper.CheckPassword(user.Password, Encoding.Unicode.GetString(CombineSaltAndPassword(saltBytes, userPassword)));
}
else
{
isValid = SecureStringEquality(user.Password, ComputeHashBase64(user.HashAlgorithm, saltBytes, userPassword));
}
//if (isValid && user.HashAlgorithm != DefaultHashAlgorithm)
//{
// var keepOldConfiguration = _appConfigurationAccessor.GetConfiguration("Orchard.Users.KeepOldPasswordHash");
// if (String.IsNullOrEmpty(keepOldConfiguration) || keepOldConfiguration.Equals("false", StringComparison.OrdinalIgnoreCase))
// {
// user.HashAlgorithm = DefaultHashAlgorithm;
// user.Password = ComputeHashBase64(user.HashAlgorithm, saltBytes, userPassword);
// }
//}
return isValid;
}
}
catch (Exception ex)
{
LogMessage(ex.Message);
// Raise an exception if an error occurs.
throw new ProviderException(ex.Message, ex.InnerException);
}
// Return false (authentication failed) if authentication fails to this point.
return false;
}
bool IFtpRoleProvider.IsUserInRole(string sessionId, string siteName,string userName, string userRole)
{
LogMessage($"check role: {userName} - {userRole}");
return true;
}
public FtpProcessStatus HandlePostprocess(FtpPostprocessParameters postProcessParameters)
{
LogMessage("Running Post Process"); //this message never appears
return FtpProcessStatus.FtpProcessContinue;
}
public void Log(FtpLogEntry logEntry)
{
//LogMessage(logEntry.);
}
private void LogMessage(string logEntry)
{
using (var sw = new StreamWriter(_logfile, true))
{
// Retrieve the current date and time for the log entry.
var dt = DateTime.Now;
sw.WriteLine("{0}\t{1}\tMESSAGE:{2}",
dt.ToShortDateString(),
dt.ToLongTimeString(),
logEntry);
sw.Flush();
}
}

Getting users from active directory using openldap c#

I'm a newbie using c# and i need to create an extension that goes to a directory and retrieves info about the users like username, name and email.
This is the login validation method that i created and it's working.
public void MssValidateUserLDAP(string ssHostname, string ssBaseDN, string ssUsername, string ssPassword, out bool ssOk, out string ssErrorMessage) {
ssOk = false;
ssErrorMessage = string.Empty;
String ssBaseRDN = string.Empty; // stores user RDN for authentication
LdapConnection connection = new LdapConnection(ssHostname);
connection.AuthType = AuthType.Basic;
try
{
SearchRequest searchRequest = new SearchRequest();
// Search parameters
searchRequest.Scope = System.DirectoryServices.Protocols.SearchScope.OneLevel;
searchRequest.DistinguishedName = ssBaseDN;
searchRequest.Filter = ssUsername;
// cast the returned directory response as a SearchResponse object
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
// enumerate the entries in the search response
foreach (SearchResultEntry entry in searchResponse.Entries)
{
ssBaseRDN = entry.DistinguishedName;
ssOk = true;
}
if (ssBaseRDN != "")
{
connection.Bind(new NetworkCredential(ssBaseRDN, ssPassword));
}
else { ssOk = false; ssErrorMessage = "User not found"; }
}
catch (Exception e)
{
ssErrorMessage = e.GetType().Name + " " + e.Message;
ssOk = false;
}
}
This is what i was able to do, but it's not working and i can't find the reason behind that. Any help would be appreciated!
public void MssSearch(string ssUsername, string ssPassword, string ssPath, out RLUserRecordList ssUsers, out string ssErrorMessage) {
ssErrorMessage = "";
ssUsers = new RLUserRecordList(null);
try
{
RLUserRecordList aux = new RLUserRecordList();
DirectoryEntry rootEntry = new DirectoryEntry(ssPath,ssUsername,ssPassword);
DirectorySearcher searcher = new DirectorySearcher(rootEntry);
foreach(SearchResult result in searcher.FindAll())
{
RCUserRecord u = new RCUserRecord(Convert.ToString(result.Properties["cn"][0]));
aux.Append(u);
}
ssUsers = aux;
}
catch (Exception e){
ssErrorMessage = e.GetType().Name + " " + e.Message;
}
} // MssSearch

Is creating an EPT (MS PS Enteprise Project Type) via PSI/CSOM possible?

The following code does not throw any exception but it also doesn't create a new EPT:
public void CreateEnterpriseProjectType(Guid eptGuid, string eptName, string eptDescription)
{
ProjectContext pwaContext = new ProjectContext("http://serverName/pwaName");
pwaContext.Credentials = new NetworkCredential("adminUsername", "adminPassword", "domainName");
EnterpriseProjectTypeCreationInformation eptData = new EnterpriseProjectTypeCreationInformation();
eptData.Id = eptGuid;
eptData.Name = eptName;
eptData.Description = eptDescription;
eptData.IsDefault = false;
eptData.IsManaged = true;
eptData.WorkspaceTemplateName = "PROJECTSITE#0";
eptData.ProjectPlanTemplateId = Guid.Empty;
eptData.WorkflowAssociationId = Guid.Empty;
// Get the maximum order of the existing EPTs and increment by 1 in order to use an order that does not already exist
eptData.Order = Convert.ToInt32(Database.GetValue("SELECT MAX(ENTERPRISE_PROJECT_TYPE_ORDER) FROM [ProjectWebApp].[pub].[MSP_ENTERPRISE_PROJECT_TYPES]")) + 1;
pwaContext.Load(pwaContext.ProjectDetailPages);
pwaContext.ExecuteQuery();
List<ProjectDetailPageCreationInformation> projectDetailPages = new List<ProjectDetailPageCreationInformation>() {new ProjectDetailPageCreationInformation() { Id = pwaContext.ProjectDetailPages[1].Id, IsCreate = false }};
eptData.ProjectDetailPages = projectDetailPages;
EnterpriseProjectType newEpt = pwaContext.EnterpriseProjectTypes.Add(eptData);
pwaContext.EnterpriseProjectTypes.Update();
}
Any ideas on what I'm doing wrong or what I'm missing? Is it possible to create an EPT programmatically?
Yes, it is possible to create an EPT programmatically. Turns out three things were missing:
A second PDP having IsCreate = true (at least one with IsCreate = true and one with IsCreate = false are required for successfully creating an EPT)
A query for iterating through the existing EPTs before adding a new one:
pwaContext.Load(pwaContext.EnterpriseProjectTypes);
pwaContext.ExecuteQuery();
A pwaContext.ExecuteQuery(); after the pwaContext.EnterpriseProjectTypes.Update(); command.
The following code works fine for me:
public class PSI
{
private ProjectContext _context;
private string basicEpt = "Enterprise Project"; // Basic enterprise project type.
private static readonly PSI psi = new PSI();
private int timeoutSeconds = 60;
SvcProject.ProjectClient _prClient;
private PSI ()
{
_context = new ProjectContext(System.Configuration.ConfigurationManager.AppSettings["PwaUrl"]);
//credentials of currently running acount or enable line below
//_context.Credentials = new System.Net.NetworkCredential("user", "pass", "domain");
timeoutSeconds = int.Parse(System.Configuration.ConfigurationManager.AppSettings["DefaultTimeoutPwa"]);
_prClient = new SvcProject.ProjectClient("basicHttp_Project");
}
public static PSI Instance
{
get{ return psi; }
}
public Guid GetEptUid(string eptName)
{
Guid eptUid = Guid.Empty;
try
{
var eptList = _context.LoadQuery( _context.EnterpriseProjectTypes.Where(ept => ept.Name == eptName));
_context.ExecuteQuery();
eptUid = eptList.First().Id;
}
catch (Exception ex)
{
string msg = string.Format("GetEptUid: eptName = \"{0}\"\n\n{1}", eptName, ex.GetBaseException().ToString());
throw new ArgumentException(msg);
}
return eptUid;
}
public PublishedProject CreateProject(string prName, string description, DateTime startDate)
{
try
{
System.Console.Write("\nCreating project: {0} ...", prName);
ProjectCreationInformation newProj = new ProjectCreationInformation();
newProj.Id = Guid.NewGuid();
newProj.Name = prName;
newProj.Description = description;
newProj.Start = startDate;
newProj.EnterpriseProjectTypeId = GetEptUid(basicEpt);
PublishedProject newPublishedProj = _context.Projects.Add(newProj);
QueueJob qJob = _context.Projects.Update();
JobState jobState = _context.WaitForQueue(qJob, timeoutSeconds);
if (jobState == JobState.Success)
return newPublishedProj;
else
return null;
}
catch (Exception ex)
{
System.Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine("\nError: {0}", ex.Message);
System.Console.ResetColor();
return null;
}
}
}

You don't have permission to post in a group

I've finished a program in C# which integrates with Facebook and posts to more than one group in a click
but I am facing a problem right now when there is a group that you don't have a permission to post to I can't complete posting to the rest
here's the post function
I put it in other Class
public static bool PostImage(Frm form,string AccessToken, string Status, string ImagePath)
{
try
{
if (form.listBox2 .SelectedItems .Count > 0)
{
string item;
foreach (int i in form. listBox2.SelectedIndices)
{
item = form.listBox2.Items[i].ToString();
groupid = item;
FacebookClient fbpost = new FacebookClient(AccessToken);
var imgstream = File.OpenRead(ImagePath);
dynamic res = fbpost.Post("/" + groupid + "/photos", new
{
message = Status,
File = new FacebookMediaStream
{
ContentType = "image/jpg",
FileName = Path.GetFileName(ImagePath)
}.SetValue(imgstream)
});
result = true;
}
}
return result;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return false;
}
}
You need to put a try catch block inside the loop. Then, in the catch block you log the error (or do whatever you want with it) then continue the loop:
foreach (int i in form. listBox2.SelectedIndices)
{
try
{
item = form.listBox2.Items[i].ToString();
groupid = item;
FacebookClient fbpost = new FacebookClient(AccessToken);
var imgstream = File.OpenRead(ImagePath);
dynamic res = fbpost.Post("/" + groupid + "/photos", new
{
message = Status,
File = new FacebookMediaStream
{
ContentType = "image/jpg",
FileName = Path.GetFileName(ImagePath)
}.SetValue(imgstream)
});
result = true;
}
catch(exception excp)
{
//Do something with the exception
}
}
Now I don't know exactly how your code works, but this should give you a rough idea.

Categories