Get just the name from ldap in asp.net c# - c#

I want to diaplay all the names that match with the user provided name from a directory server using LDAP and bind it to grid view. Am able to achieve this task bt instead of just a name am getting other properties like LDAP://CN=Neha Shetty,OU=Users,OU=MUM,OU=Mumbai,OU=India,OU=APAC,OU=bunt,DC=xxx,DC=com. But i just want Neha Shetty. Here is my code
DirectoryEntry de = new DirectoryEntry("ADConnection");
DirectorySearcher deSearch = new DirectorySearcher(de);
//set the search filter
deSearch.SearchRoot = de;
String UserName = txt_To.Text;
// deSearch.Filter = "(&(objectCategory=user)(GivenName=*" + UserName + "*))";
deSearch = new DirectorySearcher("(&(objectCategory=user)(Name=*" + UserName + "*))");
//deSearch.SearchScope = SearchScope.Subtree;
string[] arrPropertiesToLoad = { "Surname" };
deSearch.PropertiesToLoad.AddRange(arrPropertiesToLoad);
// SearchResultCollection sResultColl = deSearch.FindAll();
SearchResultCollection sResultColl;
sResultColl = deSearch.FindAll();
Gridview1.DataSource = sResultColl;
Gridview1.DataBind();

LDAP://CN=Neha Shetty,OU=Users,OU=MUM,OU=Mumbai,OU=India,OU=APAC,OU=bunt,DC=xxx,DC=com
is the distinguished name of the entry, and is always returned in a search result that returns at least one entry. The distinguished name is used as the primary key for an entry in a directory.
Directories do not have properties, directories have attributes which are grouped according to objectClasses into entries; properties are single-valued attributes might be multi-valued. The LDAP client must specify which user attributes should be returned as one of the parameters of the search request.

Related

How to find Active Directory group email address using AD group name in C#

I have an Active Directory group with a name like Stack Over Flow IT. Need to find AD group email like stackoverflowit#stackoverflow.com. No need to find AD user list.
How to find AD group email address?
Or how to find AD group name using AD group email address?
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");
I'm unable to find Active Directory group email address using the above group instance code.
Mail of group
You can do the following:
PropertyValueCollection email = ((DirectoryEntry) group.GetUnderlyingObject()).Properties["mail"];
If you have RSAT available you can validate your code (in powershell) with:
get-adgroup -Identity "Stack Over Flow IT" -properties mail | select name,mail | sort mail
Find Group via mail
Here is the reverse way for completeness:
// replace stuff inside [] to match your environment
DirectoryEntry root = new DirectoryEntry("LDAP://dc=[YOUR DC]", [username], [password], AuthenticationTypes.Secure);
DirectorySearcher groupSearcher = new DirectorySearcher(root);
groupSearcher.Filter = "(mail=stackoverflowit#stackoverflow.com)";
groupSearcher.PropertiesToLoad.Add("name");
foreach (SearchResult groupSr in groupSearcher.FindAll())
{
ResultPropertyValueCollection groupName = groupSr.Properties["name"];
// do something with finding
}

Pasting a hyperlink value from C# to Access

I am uploading a file to \temp\ but I want to access it through a hyperlink in a given column inside Access. I can successfully paste the string to the hyperlink field, but there´s no link between the string and the file itself.
I tried to copy paste a website address from a browser to Access, surprisingly the hyperlink is pasted along with the "string"
//upload arquivo
string conexaoAccess2 = ConfigurationManager.ConnectionStrings["conexaoAccess"].ToString();
using (OleDbConnection conexaodb1 = new OleDbConnection(conexaoAccess2))
{
conexaodb1.Open();
Random r = new Random();
int n = r.Next();
// pega somente nome
string[] f = camArq.Split('\\');
string fn = f[(f.Length) - 1];
string fullDest = #"C:\temp\" + nomeArqnoExt + n + fileExtension0;
string q = "UPDATE tbl_reg SET Campo1 = #campo WHERE nome_user = #nome1";
//copia arquivo para a pasta destino
File.Copy(camArq, fullDest, true);
//to save to the database
OleDbCommand cmd = new OleDbCommand(q, conexaodb1);
var parCamp = cmd.CreateParameter();
parCamp.ParameterName = "campo";
parCamp.DbType = DbType.String;
parCamp.Value = fullDest;
cmd.Parameters.Add(parCamp);
var parNome1 = cmd.CreateParameter();
parNome1.ParameterName = "nome1";
parNome1.DbType = DbType.String;
parNome1.Value = mdl.nome;
cmd.Parameters.Add(parNome1);
cmd.ExecuteNonQuery();
}
I expect the string to be copied as an hyperlink, nevertheless, there´s no DbType that assumes this type of data, is there? The actual results are: I can successfully paste the file path to the field, but the field contains no hyperlink to anything whatsoever:
Access Hyperlink type field requires value that is composed of 3 parts separated by # character: displaytext#path#subreference. Options:
If using Hyperlink type field in Access table design, include # characters in string to save.
Just use a text field to save path string without # characters then use FollowHyperlink method in code or format string to hyperlink structure with concatenation expression: "#" & [fieldname] & "#" - calculate in query or textbox ControlSource and set textbox IsHyperlink property to yes.

Active Directory LDAP Search Filter or operator syntax

I am using LDAP Directory Services in C# to search users from LDAP with some filter criteria. I want to supply multiple OR filter criteria. For example firstName, lastName, telephone etc. It works fine when I supply all filter values but gives error when I just supply one or two filter values.
Here is the sample code I am using:
var LdapSearcher = new DirectorySearcher(RootDomain,
"(&(objectclass=user)(sn=" + lastName.Trim() + ")(givenName=" + firstName.Trim() + "))");
I get the result when I supply both sn and givenName values. However, it's an OR search and user will enter either lastName or FirstName.
How to apply OR Filter in LDAP DirectorySearcher.?
You need to use the | operator. From what you've provided, your conditions are :
objectclass must be equal "user"
sn OR givenName must be equal to the provided value
Let's say the user has provided the name "John Smith". Your filter should look like :
(&(objectClass=user)(|(sn=Smith)(givenName=John)))
var LdapSearcher = new DirectorySearcher(RootDomain,
"(&(objectclass=user)" +
(!(string.IsNullOrEmpty(lastName.Trim())) ? "(sn=" + lastName.Trim() + ")" : "") +
(!(string.IsNullOrEmpty(firstName.Trim())) ? "(givenName=" + firstName.Trim() + ")" : "")
+ ")");

Check if data exists in database

I am creating a login system using c#. I want to check if the username the user enters is already part of the database. This is the code that connects to a data adapter and then updates this once I have taken the data from the check boxes.
NorthwindDataSetTableAdapters.CustomersTableAdapter north = new NorthwindDataSetTableAdapters.CustomersTableAdapter();
NorthwindDataSet.CustomersDataTable northtable = north.GetData();
NorthwindDataSet northwindDataSet1 = new NorthwindDataSet();
NorthwindDataSet.CustomersRow newCustomersRow =
northwindDataSet1.Customers.NewCustomersRow();
newCustomersRow.Username = TextBox1.Text.ToString();
newCustomersRow.Password = TextBox2.Text.ToString() ;
newCustomersRow.FirstName = TextBox3.Text.ToString();
newCustomersRow.Surname = TextBox4.Text.ToString();
northwindDataSet1.Customers.Rows.Add(newCustomersRow);
north.Update(northwindDataSet1.Customers);
northwindDataSet1.Customers.AcceptChanges();
if (Page.IsValid)
Response.Redirect("thankyou.aspx");
What is the best way to check the Username field for duplicate data?
Call me crazy, but I'd just do something like (using "dapper")
string username = ...
int existingId = connection.Query<int?>(
#"select top 1 Id from Users where UserName = #username",
new { username }).FirstOrDefault();
if(existingId.HasValue) {
// not available - do something
}
Note that there is a race condition here so you should still have a unique constraint on the column itself. You might also want to thing about case sensitivity: is "Fred" the same username as "fred"?
Why not to mark the table Column as primary key or unique? Then you handle the exception inside a try{}catcht{} statement.
Have you tried using DataTable.Select? Something like:
var UserFound = NorthTable.Select("UserName = '" + TextBox1.Text + "'");
if(UserFound.Length != 0)
{
// do something...
}

DirectoryEntry Page Size limit

The code below works just fine, however what's happening is the code limits the results to 1500 users and we have more than 1500 users. What I'm trying to do is retrieve a list of all users that are a member of a specific group. I know DirectorySearcher has a PageSize setting however, I'm unable to find a way to set DirectoryEntry PageSize will still only pulling members of that group.
Does anybody know a way to change the page size? Or maybe how to pull members of a specific group in another fashion that will accommodate pagesize?
DirectoryEntry dEntryhighlevel = new DirectoryEntry("LDAP://CN=Users,OU=MyOu,OU=Clients,OU=Home,DC=bridgeTech,DC=net");
foreach (object dn in dEntryhighlevel.Properties["member"])
{
DirectoryEntry singleEntry = new DirectoryEntry("LDAP://" + dn);
DirectorySearcher dSearcher = new DirectorySearcher(singleEntry);
//filter just user objects
dSearcher.SearchScope = SearchScope.Base;
//dSearcher.Filter = "(&(objectClass=user)(dn=" + dn + "))";
//dSearcher.PageSize = 1000;
SearchResult singleResult = null;
singleResult = dSearcher.FindOne();
if (singleResult != null)
{
string Last_Name = singleResult.Properties["sn"][0].ToString();
string First_Name = singleResult.Properties["givenname"][0].ToString();
string userName = singleResult.Properties["samAccountName"][0].ToString();
string Email_Address = singleResult.Properties["mail"][0].ToString();
OriginalList.Add(Last_Name + "|" + First_Name + "|" + userName + "|" + Email_Address);
}
singleEntry.Close();
}
This came up in another thread recently: Always getting 1500 member of distribution list using PowerShell
In short, you want to use ranged retrieval to get the membership. This is the mechanism designed to help you fetch large attributes with >1500 values in them.
While we're on this topic, I'd like to predict your next thread. :) Reading the membership of the group will yield missing results depending upon the API you use. If you are "close to the metal" and using LDAP APIs, you'll find that users in the group due to primary group membership will be missing. I'd test this with whatever approach you use after resolving the ranged retrieval issue to ensure you don't miss anyone.
More info on this here: retrieving group members/membership from active directory when members attrib doesn't work
I'm working on something similar to this at the moment and noticed that your code differs to mine slightly. I haven't had any issues with limited results using the following code structure:
DirectoryEntry dEntryhighlevel = new DirectoryEntry("LDAP://CN=Users,OU=MyOu,OU=Clients,OU=Home,DC=bridgeTech,DC=net");
DirectorySearcher dSearcher = new DirectorySearcher();
//filter just user objects
dSearcher.Filter = "(objectClass=user)";
dSearcher.PageSize = 1000;
SearchResultCollection resultCollection = dirSearcher.FindAll();
foreach (SearchResult userResults in resultCollection )
{
string Last_Name = userResults .Properties["sn"][0].ToString();
string First_Name = userResults .Properties["givenname"][0].ToString();
string userName = userResults .Properties["samAccountName"][0].ToString();
string Email_Address = userResults .Properties["mail"][0].ToString();
OriginalList.Add(Last_Name + "|" + First_Name + "|" + userName + "|" + Email_Address);
}
That should return all your users. You'll need to use LDAP search patterns in your dSearcher.Filter in order to narrow users down to a specific group - see this link for some additional help with that.

Categories