Search For All Locations In Active Dirrectory Via LDAP - active-directory

I'm working in PL/SQL and searching LDAP ( with A.D defining the schema) for all locations. Right now I can apply a simple search and find all users. Each user has the address information via the following properties:
'physicalDeliveryOfficeName';
'streetAddress';
'l';--city
'st';--state
'postalCode';--zip code
However, I would like to search for all the locations separate from the search done for people. Is it possible to search Active directory to just find the locations(with out looking up each person) ? If so what would the search filter look like ? I tried objectClass=Physical-Location,DC=example,DC=com and didn't find any locations (beyond the schema) . I'm not sure if that's because there's a security issue, or its not possible to look up locations in that way.

What you have listed are attributes in AD. You can return attributes in searches and search for specific values but you'll always return the objects the attributes are attached to (in this case users). You're a little light on the details of how you're searching so I'll take a stab.
You can load just the location attributes you're looking for, be it State, City, etc.
var domain = "mydomain.com";
var dn = "CN=Users,DC=mydomain,DC=com";
var ldapSearchFilter = "(objectClass=user)";
var connection = new LdapConnection(domain);
var attributeList = new string[] { "physicalDeliveryOfficeName", "l", "st"};
try
{
var searchRequest =
new SearchRequest(dn, ldapSearchFilter,
SearchScope.OneLevel,
attributeList);
var searchResponse =
(SearchResponse)connection.SendRequest(searchRequest);
var locationList = (from SearchResultEntry entry in searchResponse.Entries
select entry.Attributes["physicalDeliveryOfficeName"][0].ToString())
.Distinct().ToList();
catch (Exception ex)
{
//Handle errors
}
One thing to keep in mind with this example. If the attributes aren't populated in AD, the WriteLine will throw an error when trying to read the attribute. If you are using some other search type (DirectorySearcher maybe) you should still be able to load just the attributes you want to get back.

Related

Using variables in azure search filter

I am creating a search for a website and using many filter options. I want to use filter on my many search results and for that i saw Filter property in SearchParameters for Azure Cognitive search.
What i want is to pass a variable in Filter when i try to pass those parameters in filter search.
Is there any possible way that i do not have to manually pass the Boulevard House from my data and use the variable houseName instead as i have provided options to choose and this is just plain-hardcode.
Any refernce will help as well, as i tried to read the documents but in vain.
{
Filter = String.Format("HouseName eq '{0}'", houseName)
} ;
var names = new List<Search>();
if (nameResult.Results.Count > 0)
{
foreach (SearchResult<Search> results in nameResult.Results)
{
names.Add(results.Document);
}
}
NameSearchViewModel nameSearchViewModel = new NameSearchViewModel();
nameSearchViewModel.Grants = names;
return View(namesSearchViewModel);
I'm assuming you are using the C# SDK. You could do something like this
parameters = new SearchParameters
{
Filter = String.Format("HouseName eq '{0}'", houseName)
}

Cakephp 3 - How to integrate external sources in table?

I working on an application that has its own database and gets user information from another serivce (an LDAP is this case, through an API package).
Say I have a tables called Articles, with a column user_id. There is no Users table, instead a user or set of users is retrieved through the external API:
$user = LDAPConnector::getUser($user_id);
$users = LDAPConnector::getUsers([1, 2, 5, 6]);
Of course I want retrieving data from inside a controller to be as simple as possible, ideally still with something like:
$articles = $this->Articles->find()->contain('Users');
foreach ($articles as $article) {
echo $article->user->getFullname();
}
I'm not sure how to approach this.
Where should I place the code in the table object to allow integration with the external API?
And as a bonus question: How to minimise the number of LDAP queries when filling the Entities?
i.e. it seems to be a lot faster by first retrieving the relevant users with a single ->getUsers() and placing them later, even though iterating over the articles and using multiple ->getUser() might be simpler.
The most simple solution would be to use a result formatter to fetch and inject the external data.
The more sophisticated solution would a custom association, and a custom association loader, but given how database-centric associations are, you'd probably also have to come up with a table and possibly a query implementation that handles your LDAP datasource. While it would be rather simple to move this into a custom association, containing the association will look up a matching table, cause the schema to be inspected, etc.
So I'll stick with providing an example for the first option. A result formatter would be pretty simple, something like this:
$this->Articles
->find()
->formatResults(function (\Cake\Collection\CollectionInterface $results) {
$userIds = array_unique($results->extract('user_id')->toArray());
$users = LDAPConnector::getUsers($userIds);
$usersMap = collection($users)->indexBy('id')->toArray();
return $results
->map(function ($article) use ($usersMap) {
if (isset($usersMap[$article['user_id']])) {
$article['user'] = $usersMap[$article['user_id']];
}
return $article;
});
});
The example makes the assumption that the data returned from LDAPConnector::getUsers() is a collection of associative arrays, with an id key that matches the user id. You'd have to adapt this accordingly, depending on what exactly LDAPConnector::getUsers() returns.
That aside, the example should be rather self-explanatory, first obtain a unique list of users IDs found in the queried articles, obtain the LDAP users using those IDs, then inject the users into the articles.
If you wanted to have entities in your results, then create entities from the user data, for example like this:
$userData = $usersMap[$article['user_id']];
$article['user'] = new \App\Model\Entity\User($userData);
For better reusability, put the formatter in a custom finder. In your ArticlesTable class:
public function findWithUsers(\Cake\ORM\Query $query, array $options)
{
return $query->formatResults(/* ... */);
}
Then you can just do $this->Articles->find('withUsers'), just as simple as containing.
See also
Cookbook > Database Access & ORM > Query Builder > Adding Calculated Fields
Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Custom Finder Methods

How to get users from Active Directory using Unboundid LDAP SDK?

I need to get users from Active Directory.
According to many places include MSDN
https://msdn.microsoft.com/en-us/library/ms677643%28v=vs.85%29.aspx
the correct query is this (&(objectClass=user)(objectCategory=person)).
Unfortunately, I was not able to create the query using Unboundid filters.
I have created the following filters:
Filter categoryFilter = Filter.createEqualityFilter("objectCategory","Person");
Filter objectFilter = Filter.createEqualityFilter("objectClass","user");
Filter searchFilter = Filter.createANDFilter(objectFilter, categoryFilter);
It does not return results.
When I looked into objectCategory of LDAP object I have found that it looks like the following:
CN=Person,CN=Schema,CN=Configuration,DC=…,DC=com
Therefore I have changed categoryFilter to the following:
Filter categoryFilter = Filter.createSubstringFilter("objectCategory", null, new String[]{"Person"}, null);
Unfortunately, I still do not get results.
Then I used the categoryFilter with the full objectCategory name:
Filter categoryFilter = Filter.createEqualityFilter("objectCategory","CN=Person,CN=Schema,CN=Configuration,DC=…,DC=com");
Only in the last case I get results.
How to make the filter more generic?
How to obtain the full objectCategory name from Active Directory?
I need to obtain CN=Person,CN=Schema,CN=Configuration,DC=…,DC=com for any Active Directory while I know that the objectCategory is Person.
Do you know other way to create filters for the query (&(objectClass=user)(objectCategory=person))?
Solution
(not mine therefore do not want to put in the answer)
I have created filter using the following string (sAMAccountType=805306368) and it works perfect:
Filter searchFilter = Filter.create("(sAMAccountType=805306368)");
Source: http://ldapwiki.com/wiki/Active%20Directory%20User%20Related%20Searches#section-Active+Directory+User+Related+Searches-AllUsers

Knockoutjs how to data-bind observable array members based on IDs

I'm not if the title explains what I need to achieve or not but I can change it later if some has a better suggestion.
I'm using KO to manage a whole bunch of data on the client side.
Here's the basic.
I have a list of training sessions
Each has a list of training session parts
Each training session parts are referencing items kept in other lists. For example, I have a list of activities (ex: biking, running, swimming, etc.)
Each activity is identified by an ID which is used in the training session parts to identify which activity was used for a particular session.
Now, all these list are stored as observable arrays, and each member of the lists are observables (I use KO.Mapping to map the JSON coming from the server)
When I display a training session in my UI, I want to display various information coming from various lists
Duration: 1h30
Activity: Biking
Process: Intervals
The only information I have in order to link the training session to its component is an ID which is fine. What I'm not sure is how to data-bind the name (text) of my activity to a <p> or <div> so that the name will change if I edit the activity (by using some functionality of the application).
The training session only has the ID to identify the activity, so I don’t know how to bind the name of the activity based on its ID.
Hopefully this makes senses and someone can help me figure it out. I found lots of info on how to bind to observable array but nothing addressing ID and linked information.
The easiest way would probably be to make your own constructors and link the data by hand. You can use mapping if you really want to, but you'll basically have to do the same manual linking, only in a more verbose format.
This is the fiddle with the example implementation: http://jsfiddle.net/aKpS9/3/
The most important part of the code is the linking, you have to take care to create the activity objects only once, and use the same objects everywhere, as opposed to creating new activity objects for the parts.
var TrainingSession = function(rawData, actualActivities){
var self = this;
self.name = ko.observable(rawData.name);
self.parts = ko.observableArray(ko.utils.arrayMap(rawData.parts, function(rawPart){
return ko.utils.arrayFirst(actualActivities(), function(ac){
return ac.ID() == rawPart.ID;
})
}));
}
var Activity = function(rawData){
var self = this;
self.ID = ko.observable(rawData.ID);
self.name = ko.observable(rawData.name);
}
var MainVM = function(rawData){
var self = this;
//first create an array of all activities
self.activities = ko.observableArray(ko.utils.arrayMap(rawData.activities, function(rawAc){
return new Activity(rawAc);
}));
self.trainingSessions = ko.observableArray(ko.utils.arrayMap(rawData.trainingSessions, function(session){
return new TrainingSession(session, self.activities);
}));
}

Salesforce Custom Object Relationship Creation

I want to create two objects and link them via a parent child relationship in C# using the Metadata API.
I can create objects and 'custom' fields for the objects via the metadata, but the service just ignores the field def for the relationship.
By snipet for the fields are as follows:
CustomField[] fields = new CustomField[] { new CustomField()
{
type = FieldType.Text,
label = "FirstName",
length = 50,
lengthSpecified = true,
fullName = "LJUTestObject__c.FirstName__c"
},
new CustomField()
{
type = FieldType.Text,
label = "LastName",
length = 50,
lengthSpecified = true,
fullName = "LJUTestObject__c.Lastname__c"
},
new CustomField()
{
type = FieldType.Text,
label = "Postcode",
length = 50,
lengthSpecified = true,
fullName = "LJUTestChildObject__c.Postcode__c"
},
new CustomField()
{
type = FieldType.MasterDetail,
relationshipLabel = "PostcodeLookup",
relationshipName = "LJUTestObject__c.LJUTestObject_Id__c",
relationshipOrder = 0,
relationshipOrderSpecified = true,
fullName = "LJUTestChildObject__c.Lookup__r"
}
};
The parent object looks like:
LJUTestObject
ID,
FirstName, Text(50)
LastName, Text(50)
The child objext looks like:
LJUTestChildObject
ID,
Postcode, Text(50)
I want to link the parent to the child so one "LJUTestObject", can have many "LJUTestChildObjects".
What values do I need for FieldType, RelationshipName, and RelationshipOrder to make this happen?
TL;DR:
Use this as a template for accomplishing what you want:
var cf = new CustomField();
cf.fullName = "ChildCustomObject__c.ParentCustomField__c";
cf.type = FieldType.MasterDetail;
cf.typeSpecified = true;
cf.label = "Parent Or Whatever You Want This To Be Called In The UI";
cf.referenceTo = "ParentCustomObject__c";
cf.relationshipName = "ParentOrWhateverYouWantThisToBeCalledInternally";
cf.relationshipLabel = "This is an optional label";
var aUpsertResponse = smc.upsertMetadata(metadataSession, null, null, new Metadata[] { cf });
The key difference:
The natural temptation is to put the CustomField instances into the fields array of a CustomObject, and pass that CustomObject to the Salesforce Metadata API. And this does work for most data fields, but it seems that it does not work for relationship fields.
Instead, pass the CustomField directly to the Salesforce Metadata API, not wrapped in a CustomObject.
Those muted errors:
Turns out that errors are occurring, and the Salesforce Metadata API knows about them, but doesn't bother telling you about them when they occur for CustomFields nested inside a CustomObject.
By passing the CustomField directly to the Metadata API (not wrapped in a CustomObject), the call to upsertMetadata will still return without an exception being thrown (as it was already doing for you), but this time, if something goes wrong, upsertResponse[0].success will be false instead of true, and upsertResponse[0].errors will give you more information.
Other gotchas
Must specify referenceTo, and if it doesn't match the name of an existing built-in or custom object, the error message will be the same as if you had not specified referenceTo at all.
fullName should end in __c not __r. __r is for relationship names, but remember that fullName is specifying the field name, not the relationship name.
relationshipName - I got it working by not including __r on the end, and not including the custom object name at the start. I haven't tested to be sure other ways don't work, but be aware that at the very least, you don't need to have those extra components in the relationshipName.
Remember generally that anything with label in its name is probably for display to users in the UI, and thus can have spaces in it to be nicely formatted the way users expect.
Salesforce... really???
(mini rant warning)
The Salesforce Metadata API is unintuitive and poorly documented. That's why you got stuck on such a simple thing. That's why no-one knew the answer to your question. That's why, four years later, I got stuck on the same thing. Creating relationships is one of the main things you would want to do with the Salesforce Metadata API, and yet it has been this difficult to figure out, for this long. C'mon Salesforce, we know you're a sales company more than a tech company, but you earn trazillions of dollars and are happy to show it off - invest a little more in a better API experience for the developers who invest in learning your platform.
I've not created these through the meta data API like this myself, but I'd suggest that:
relationshipName = "LJUTestObject__c.LJUTestObject_Id__c
Should be:
relationshipName = "LJUTestObject__c.Id
as Id is a standard field, the __c suffix is only used for custom fields (not standard fields on custom objects). Also, it may be that the relationship full name should end in __c not __r, but try the change above first and see how you go.
SELECT
Id,
OwnerId,
WhatId,
Reminder_Date_Time__c,
WhoId,
Record_Type_Name__c,
Task_Type__c,
Assigned_Date__c,
Task_Status__c,
ActivityDate,
Subject,
Attended_By__c,
Is_Assigned__c
FROM Task
WHERE
(NOT Task_Status__c LIKE 'Open') AND
ActivityDate >= 2017-12-13 AND
(NOT Service__r.Service_State__c LIKE 'Karnataka')

Resources