How to filter result to get groups based on users from AZure AD using Microsoft Graph Api - azure-active-directory

I am getting groups from AZ AD based on users. In one scnaior I need to get all but in other scenario I want to filter and only get groups based on the filter. I used the below code but I am not getting data.
The groups that I need. Technician, Research, ADMIN. I want to just get these groups based on the useridenfiticaiton /email.
Below is the code:
GraphServiceClient graphClient = GetGraphicClient(accessToken);
List<Option> options = new List<Option>();
options.Add(new HeaderOption("ConsistencyLevel", "eventual"));
options.Add(new QueryOption("$filter", $"DisplayName eq 'Technician'"));
// options.Add(new QueryOption("$filter", $"DisplayName eq 'Research'"));
options.Add(new QueryOption("$count", "true"));
var groups = graphClient.Users[uniqueIdentification]
.MemberOf
.Request(options)
.GetAsync().Result;
Note that I need to filter based on all 3 criteria. And be able to store the Group in a List object

Please check if below is the cause as it may be possible.
Try by avoiding result in .GetAsync().Result; which may lead to deadlock condition which may probably lead to no result which looks like your case.
For example: filtered for jobTitle in query options:
List<Option> requestOptions = new List<Option>();
//var requestOptions= new List<Option>();
requestOptions.Add(new QueryOption("$count", "true"));
requestOptions.add(new QueryOption("$filter", " jobTitle eq 'Retail Manager’ "));
requestOptions.add(new QueryOption("$filter", " jobTitle eq 'Marketing Assistant'"));
var request = await graphClient.Users["UPN"].MemberOf
.Request(requestOptions).Header("ConsistencyLevel", "eventual")
// .Filter("(jobTitle eq 'Retail Manager' ) or (jobTitle eq 'Marketing Assistant')") // try this if query options doesn't work
.GetAsync();
In graph explorer tried this :
But not sure later again it gives error as group doesn't have jobTitle as property.
Please check below References:
Graph API .net SDK - Filter Me.MemberOf based on displayName of groups - Stack Overflow
c# - Filtering the transitive group memberships of a user using
Graph SDK - Stack Overflow

Related

How to get the maximum number of members based on users from Azure AD using Graph Api

I am getting the the groups based on users from Microsoft Graph Api. Although I am getting the groups but they are coming to total count of 100.
I tried to use paging technique but it is keep failing. Can someone help me out?
var page = graphClient
.Users[uniqueIdentification]
.MemberOf
.Request()
.GetAsync().Result;
var names = new List<string>();
names.AddRange(page
.OfType<Group>()
.Select(x => x.DisplayName)
.Where(name => !string.IsNullOrEmpty(name)));
The above code only return top 100.
When I tried below code for paging it got cast error .
Error:
Unable to cast object of type 'System.Collections.Generic.List`1[Microsoft.Graph.DirectoryObject]' to type 'System.Collections.Generic.IEnumerable`1[Microsoft.Graph.Group]'.
Code:
var group2 = new List<Group>();
var groupsPage = graphClient.Users[uniqueIdentification].MemberOf.Request().Top(300).GetAsync().Result;
group2.AddRange((IEnumerable<Group>)groupsPage.CurrentPage);
while (groupsPage.NextPageRequest != null)
{
groupsPage = groupsPage.NextPageRequest.GetAsync().Result;
group2.AddRange((IEnumerable<Group>)groupsPage.CurrentPage);
}
The maximum sizes of pages are 100 and 999 user objects respectively
and are default .
Some queries are supported only when you use the
ConsistencyLevel header set to eventual and $count to true
For the error:
Unable to cast object of type 'System.Collections.Generic.List`1[Microsoft.Graph.DirectoryObject]' to type 'System.Collections.Generic.IEnumerable`1[Microsoft.Graph.Group]'.
It looks like here group2 is of type list but trying to add/append the page of type Ienumerable to it which is leading to cast error.(note:list implements Ienumerable (parent) but ienumerable doesn't inherit from list as Ienumerable can be list, queue ,stack )
using System.Linq;
While using var group2 = new List<Group>();
try to add .ToList(); or .Cast<group>().ToList(); depending on latest or old type of versions before adding or appending to the group2 of type list
Please check the References to know further details :
List users - Microsoft Graph v1.0 | Microsoft Docs
How to append enumerable collection to an existing list in C# -
Stack Overflow

Hi all, I'm getting an Error Campaigns Filed is Mandatory in new Leads from 2021. when i am trying to create a new lead

QueryResult result1 = connection.query("select id, Name from Campaign where id='" + campaignId +
"'");
LeadDetails lead = new LeadDetails();
lead.setFirstName(leadDeatils.getFirstName());
lead.setLastName(leadDeatils.getLastName());
lead.setSalutation("Mrs.");
lead.setIndus("sasadd");
Campaign campaign = (Campaign)result1.getRecords()[0];
lead.setCampaign(campaign);
SaveResult[] sr = connection.create(new SObject[] { lead });
I am new bee here. please help me out. thank you.
What is it, integration that sends Leads to SF using SOAP API?
You will have to contact Administrators / Developers in charge of that Salesforce org. There's no standard lookup from Lead to Campaign so there's nothing to be made mandatory from 2021. Here's list of standard fields.. And here's the entity relationship diagram showing that Leads (and Contacts) are linked to Campaign via many-to-many helper table called CampaignMember. (bottom left).
Whatever error you're getting - it's probably new custom field/validation rule/some other thing the SF admins in your organisation did without notifying integration team.
P.S. If you have campaign id and there's custom Campaign__c field on lead or something -you don't have to query it? You probably could just call lead.setCampaign(campaignId ); or something like that?
Added Campaign Member to get fixed
CampaignMember campaignMember = new CampaignMember();
campaignMember.setCampaignId(campaignId);
campaignMember.setLeadId(leadId);
SaveResult[] result = connection.create(new SObject[] { campaignMember });
if (result.length == 1 && result[0].isSuccess()) {
System.out.println("LeadAssignment.setCampaignMember() : " + result);
// lead.setAttachments(attachResult.getClass());;
} else {
System.out.println("LeadAssignment.setCampaignMember() : Campaign member added on lead " + leadId);
}

The collection property 'identifierUris' cannot be used in a 'where' query expression

Using Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient api I am trying to find an existing Application in AAD which has the same as my desired IdentifierUrl. This is so i can decide on creating one or leaving the existing one alone.
I'm using the following calls. However I get this error:
The collection property 'identifierUris' cannot be used in a 'where' query expression. Collection properties are only supported as the source of 'any' or 'all' methods in a 'where' query option
What is the recommended way of doing this? thanks
public static async Task<IApplication> FindApplicationByUrlAsync(string accessToken, string tenantId, string identifierUrl)
{
var graphClient = NewActiveDirectoryClient(accessToken, tenantId);
var matches = await graphClient.Applications.Where(app => app.IdentifierUris.Contains(identifierUrl)).ExecuteAsync();
return matches.CurrentPage.ToList().FirstOrDefault();
}
Use the Any function:
var result = await client.Applications.Where(a => a.IdentifierUris.Any(i => i == identifierUri)).ExecuteAsync();
That'll get translated into a request as follows:
https://graph.microsoft.com/beta/applications?$filter=identifierUris/any(c:c eq 'yourIdentifierUri')
More info on filters for the Azure AD Graph here:
https://msdn.microsoft.com/en-us/library/azure/ad/graph/howto/azure-ad-graph-api-supported-queries-filters-and-paging-options

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

How to perform an 'OR' query with S4S connector?

I'm trying figure out how to query Salesforce with multiple filters where either filter can be true (similar to a traditional WHERE x='' OR y='' SQL statement).
The following appears works, but produces an 'AND' query where both filters must be true:
var dataSource = new GenericSalesforceEntityDataSource("Download__c", GetSalesforceSession);
dataSource.AddDataSourceFilter("Contact__c", new Operator(ComparisonOperator.Equals), profile.ContactId);
dataSource.AddDataSourceFilter("Lead__c", new Operator(ComparisonOperator.Equals), profile.LeadId);
var downloads = dataSource.GetQueryResultsAsEntities();
I would like to avoid hard-coding SOQL queries into my .NET application, if possible. Does the S4S API support these sorts of queries, or should I be using SOQL for this?
The Sitecore for Salesforce Connector (S4S) has composite filters that allow you to programmatically create a DataSource that is converted into a SOQL query with OR operators in the where clause.
var dataSource = new GenericSalesforceEntityDataSource("Download__c", GetSalesforceSession);
var orFilter = new LogicalDisjunctionFilter();
orFilter.AddDataSourceFilter("Contact__c", ComparisonOperator.Equals, profile.ContactId);
orFilter.AddDataSourceFilter(ApexLog.Fields.Location, ComparisonOperator.Equals, "SystemLog");
// The two filters above will be combined with a logical OR
dataSource.AddDataSourceFilter(orFilter);
var downloads = dataSource.GetQueryResultsAsEntities();
You can use combinations of the LogicalDisjunctionFilter with the LogicalConjunctionFilter to build up AND and OR logic as required.
Alternatively, you could directly add the SOQL where clause to the datasource.
var dataSource = new GenericSalesforceEntityDataSource("Download__c", GetSalesforceSession);
dataSource.SoqlFilter = string.Format("Contact__c = '{0}' OR Location = 'SystemLog'", profile.ContactId);
var downloads = dataSource.GetQueryResultsAsEntities();
Or, as Matt suggests, you could build up your own SOQL string and run that directly.
var dataSource = new GenericSalesforceEntityDataSource("Download__c", GetSalesforceSession);
var queryResult = dataSource.RunSoqlQuery(new SoqlQuery(string.Format("Select Id from Download__c where Contact__c = '{0}' OR Location = 'SystemLog'", profile.ContactId)));
var downloads = dataSource.EntitysFromQueryResult<GenericSalesforceEntity>(queryResult);
SOQL would make this much easier so that should be the route you choose if available to you, especially since it offers the easiest way to perform logical operations with your filters.

Resources