salesforce SOQL : query to fetch all the fields on the entity - salesforce

I was going through the SOQL documentation , but couldn't find query to fetch all the field data of an entity say , Account , like
select * from Account [ SQL syntax ]
Is there a syntax like the above in SOQL to fetch all the data of account , or the only way is to list all the fields ( though there are lot of fields to be queried )

Create a map like this:
Map<String, Schema.SObjectField> fldObjMap = schema.SObjectType.Account.fields.getMap();
List<Schema.SObjectField> fldObjMapValues = fldObjMap.values();
Then you can iterate through fldObjMapValues to create a SOQL query string:
String theQuery = 'SELECT ';
for(Schema.SObjectField s : fldObjMapValues)
{
String theLabel = s.getDescribe().getLabel(); // Perhaps store this in another map
String theName = s.getDescribe().getName();
String theType = s.getDescribe().getType(); // Perhaps store this in another map
// Continue building your dynamic query string
theQuery += theName + ',';
}
// Trim last comma
theQuery = theQuery.subString(0, theQuery.length() - 1);
// Finalize query string
theQuery += ' FROM Account WHERE ... AND ... LIMIT ...';
// Make your dynamic call
Account[] accounts = Database.query(theQuery);
superfell is correct, there is no way to directly do a SELECT *. However, this little code recipe will work (well, I haven't tested it but I think it looks ok). Understandably Force.com wants a multi-tenant architecture where resources are only provisioned as explicitly needed - not easily by doing SELECT * when usually only a subset of fields are actually needed.

You have to specify the fields, if you want to build something dynamic the describeSObject call returns the metadata about all the fields for an object, so you can build the query from that.

I use the Force.com Explorer and within the schema filter you can click the checkbox next to the TableName and it will select all the fields and insert into your query window - I use this as a shortcut to typeing it all out - just copy and paste from the query window. Hope this helps.

In case anyone was looking for a C# approach, I was able to use reflection and come up with the following:
public IEnumerable<String> GetColumnsFor<T>()
{
return typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
.Where(x => !Attribute.IsDefined(x, typeof(System.Xml.Serialization.XmlIgnoreAttribute))) // Exclude the ignored properties
.Where(x => x.DeclaringType != typeof(sObject)) // & Exclude inherited sObject propert(y/ies)
.Where(x => x.PropertyType.Namespace != typeof(Account).Namespace) // & Exclude properties storing references to other objects
.Select(x => x.Name);
}
It appears to work for the objects I've tested (and matches the columns generated by the API test). From there, it's about creating the query:
/* assume: this.server = new sForceService(); */
public IEnumerable<T> QueryAll<T>(params String[] columns)
where T : sObject
{
String soql = String.Format("SELECT {0} FROM {1}",
String.Join(", ", GetColumnsFor<T>()),
typeof(T).Name
);
this.service.QueryOptionsValue = new QueryOptions
{
batchsize = 250,
batchSizeSpecified = true
};
ICollection<T> results = new HashSet<T>();
try
{
Boolean done = false;
QueryResult queryResult = this.service.queryAll(soql);
while (!finished)
{
sObject[] records = queryResult.records;
foreach (sObject record in records)
{
T entity = entity as T;
if (entity != null)
{
results.Add(entity);
}
}
done &= queryResult.done;
if (!done)
{
queryResult = this.service.queryMode(queryResult.queryLocator);
}
}
}
catch (Exception ex)
{
throw; // your exception handling
}
return results;
}

For me it was the first time with Salesforce today and I came up with this in Java:
/**
* #param o any class that extends {#link SObject}, f.ex. Opportunity.class
* #return a list of all the objects of this type
*/
#SuppressWarnings("unchecked")
public <O extends SObject> List<O> getAll(Class<O> o) throws Exception {
// get the objectName; for example "Opportunity"
String objectName= o.getSimpleName();
// this will give us all the possible fields of this type of object
DescribeSObjectResult describeSObject = connection.describeSObject(objectName);
// making the query
String query = "SELECT ";
for (Field field : describeSObject.getFields()) { // add all the fields in the SELECT
query += field.getName() + ',';
}
// trim last comma
query = query.substring(0, query.length() - 1);
query += " FROM " + objectName;
SObject[] records = connection.query(query).getRecords();
List<O> result = new ArrayList<O>();
for (SObject record : records) {
result.add((O) record);
}
return result;
}

I used following to get complete records-
query_all("Select Id, Name From User_Profile__c")
To get complete fields of record, we have to mention those fields as mentioned here-
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select.htm
Hope will help you !!!

Related

Dapper ORM not accepting multiple models

I am having a problem were Dapper won't accept multiple models, see my code example. I have the QueueItems and robots models in query but when I add the second (Robots) I get the folowing error "IDBconnection does not contain a definition for Query"
public void getdata()
{
using (IDbConnection connection = new SqlConnection(con))
{
string sql = "Select * from QueueItems";
var queryResult = connection.Query<QueueItems,Robots>(sql).ToList();
}
}
If your resultset contains columns for two pocos, you'll have to wrap them in an envelope (either a typed class or dynamic) object since you can only return one type.
The method signature for that is
var result = connection.Query<QueueItems,Robots,dynamic>(sql, (queueItem,robot) => {
dynamic d = new ExpandoObject();
d.QueueItem = queueItem
d.Robot = robot;
return d;
}, splitOn: "...insert split columns unless they're named Id...");
This will return a dynamic list where each record contains a QueueItem and Robot property.
Dapper by default splits on the "Id" column. If your query returns a recordset like this:
|Id|C1|C2|C3|Id|C4|C5
Id, C1, C2 and C3 will be mapped to queueItem, Id, C4 and C5 will be mapped to robot.

Finding data type information for certain objects in DacFx API

I'm writing a code generation tool against Sql Server Data Tools and I need to be able to get the data type for:
View Columns
Computed Columns on a table
Where is this information? For tables (with the exception of computed columns), it's here:
TSqlObject table; //retrieved elsewhere
TSqlObject column = table.GetReferenced(Table.Columns).First(); //first column
TSqlObject dataType = column.GetReferenced(Column.DataType).FirstOrDefault();
For computed columns, dataType above is null.
For views, I've tried:
TSqlObject view; //retrieved elsewhere
TSqlObject column = view.GetReferenced(View.Columns).First(); //first column
TSqlObject dataType = column.GetReferenced(Column.DataType).FirstOrDefault();//null
Is this information anywhere? Are there any other options for getting this information other than publishing the source .DACPAC to a database?
EDIT: in response to Ed Elliot below (regarding the use of the strongly-typed DacFx model)
The following code fails to bring back type information for the view:
TSqlTypedModel model = new TSqlTypedModel(#"path.dacpac");
var view = model.GetObjects<TSqlView>(Microsoft.SqlServer.Dac.Model.DacQueryScopes.UserDefined).FirstOrDefault();
var viewcolumns = view.Columns;
//false
bool viewHasTypeInformation = viewcolumns.Any(c => c.DataType.Count() > 0);
var table = model.GetObjects<TSqlTable>(Microsoft.SqlServer.Dac.Model.DacQueryScopes.UserDefined).FirstOrDefault();
var tablecolumns = table.Columns;
//true
bool tableHasTypeInformation = tablecolumns.Any(c => c.DataType.Count() > 0);
I'm starting to think this is a limitation of the DAC model itself.
oooh great topic :)
The easiest way to query using the DacFxStronglyTypedModel object which is available:
https://github.com/Microsoft/DACExtensions
It is a bit odd in that it is a sample which you build and then it gives you easy access to query the DacFx:
https://github.com/Microsoft/DACExtensions/tree/master/DacFxStronglyTypedModel
To get a strongly typed model do:
var model = new TSqlTypedModel("dacpacPath")Íž
Then when you query it for all the views (or whatever) you get a list of typed objects which are a lot "saner" than the DacFx.
The interface that you get back for views:
ISql120TSqlView (change the version number to your version number) has an IEnumerable of Columns:
IEnumerable<Microsoft.SqlServer.Dac.Extensions.Prototype.ISql120TSqlColumn> Columns
{
get;
}
The column interface then has an IEnumerable of DataTypes:
IEnumerable<Microsoft.SqlServer.Dac.Extensions.Prototype.ISqlDataType> DataType
{
get;
}
I haven't got a windows machine right now to get you a full demo but that should be enough, if you dont' get what you need put a comment and i'll get a sample tomorrow (if no one else does in the meantime).
To get the list of columns on a view do:
var views = model.GetObjects<TSqlView>(DacQueryScopes.UserDefined);
foreach (var v in views)
{
Console.WriteLine(v.Columns.Count());
}
This works for me with the 130 version of the Dac dll's.
To get to the details for computed columns you need to view the "ExpressionDependencies" on the column (see v.Columns) which is the same as for tables.
EDIT
So I have been having a play and there are some things that you just can't determine until runtime so the DacFx won't be able to figure out the type for those and they only way I know of it actually generating the record set and examining what you get back but there is some things we can do with computed columns, if we take this example:
create table [dbo].[the_table]
(
[Id] INT not null primary key,
[StringCol] varchar(234) not null,
[a] int,
[b] decimal,
[a_and_b] as [a] + [b]
)
for columns, Id, StringCol, a and b when we use the strongly typed dacfx we can get the column types by doing this:
var tables = model.GetObjects(DacQueryScopes.UserDefined);
foreach (var t in tables)
{
switch (c.ColumnType)
{
case ColumnType.Column:
ShowType(c.DataType);
break;
}
}
ShowType looks like this:
void ShowType(IEnumerable<ISqlDataType> types)
{
var builder = new StringBuilder();
foreach (var type in types)
{
var t = new TSqlDataType(type.Element);
builder.Append($"{t.SqlDataType.ToString()} ");
}
Console.Write(builder);
}
What we do is have a list of data types for each column, it might just be int or something like that but it is a list.
Now because we have a computed column, instead of just the data type(s) we have references to the underlying columns which we can get the data type(s) from:
void ShowDependencies(IEnumerable<ISqlModelElementReference> dependencies)
{
foreach (var dependency in dependencies)
{
if (dependency is TSqlColumnReference)
{
var column = new TSqlColumn(dependency.Element);
Console.Write(column.Name + " ");
ShowType(column.DataType);
}
}
}
to know when to call this version:
var tables = model.GetObjects<TSqlTable>(DacQueryScopes.UserDefined);
foreach (var t in tables)
{
Console.WriteLine($"table - {t.Name}");
foreach (var c in t.Columns)
{
Console.Write("\r\n" + c.Name.ToString() + " ");
switch (c.ColumnType)
{
case ColumnType.Column:
ShowType(c.DataType);
break;
case ColumnType.ComputedColumn:
Console.Write($"({c.Expression}) ");
ShowDependencies(c.ExpressionDependencies);
break;
for the sample table about we get this output:
table - [dbo].[the_table]
[dbo].[the_table].[Id] Int
[dbo].[the_table].[StringCol] VarChar
[dbo].[the_table].[a] Int
[dbo].[the_table].[b] Decimal
[dbo].[the_table].[a_and_b] ([a] + [b]) [dbo].[the_table].[a] Int [dbo].[the_table].[b] Decimal view - [dbo].[mutli_type]
we would then need to decide what the type is, as a guess sql will do an implicit cast as runtime to a decimal but at compile time I don't think it is known (happy to be corrected here!)
If we then take a view as an example:
create view the_view
as
select
*,
object_name(4) some_name,
123 as an_int
from
the_table
we have the columns from the base table which can be enumerated simply but the object_name and 123 are slightly harder, using the same code above but for views we get:
[dbo].[the_view].[Id] [dbo].[the_table].[Id] Int
[dbo].[the_view].[StringCol] [dbo].[the_table].[StringCol] VarChar
[dbo].[the_view].[a] [dbo].[the_table].[a] Int
[dbo].[the_view].[b] [dbo].[the_table].[b] Decimal
[dbo].[the_view].[a_and_b] [dbo].[the_table].[a_and_b]
[dbo].[the_view].[some_name] some_name = an_int =
[dbo].[the_view].[an_int] some_name = an_int =
So no type for the computed columns plus to get to the value for a_and_b we would need to further enumerate again to get the types we had above.
At this point what you have is a view with columns that point to functions / expressions and this is where is starts to get harder :) if you take the example above you could probably work out what object_name returned and determine that but when you get a view that is non-deterministic on either the data or data type what do you do?
If we take:
create view mutli_type
as
select case datepart(day, getdate())
when 1
then 100
when 2
then 'hello'
else
getdate()
end as multitype
depending on the day we get a different data type returned - double ouch.
If you really needed to know what the view returned you could get the select elements in the view and use the TSqlScript Dom to parse them into parts and try and infer each one, I have mocked up a sample that finds the getdate() function in this view to give you an idea of what you need to do but it isn't straightforward and I don't even want to consider stored procedures where you can pass in dynamic sql:
Full sample:
create table [dbo].[the_table]
(
[Id] INT not null primary key,
[StringCol] varchar(234) not null,
[a] int,
[b] decimal,
[a_and_b] as [a] + [b]
)
go
create view the_view
as
select *, object_name(4) some_name, 123 as an_int from the_table
go
create view mutli_type
as
select case datepart(day, getdate())
when 1
then 100
when 2
then 'hello'
else
getdate()
end as multitype
go
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SqlServer.Dac.Extensions.Prototype;
using Microsoft.SqlServer.Dac.Model;
using Microsoft.SqlServer.TransactSql.ScriptDom;
using ColumnType = Microsoft.SqlServer.Dac.Model.ColumnType;
namespace ConsoleApplication1
{
class Program
{
static void ShowType(IEnumerable<ISqlDataType> types)
{
var builder = new StringBuilder();
foreach (var type in types)
{
var t = new TSqlDataType(type.Element);
builder.Append($"{t.SqlDataType.ToString()} ");
}
Console.Write(builder);
}
static void ShowDependencies(IEnumerable<ISqlModelElementReference> dependencies)
{
foreach (var dependency in dependencies)
{
if (dependency is TSqlColumnReference)
{
var column = new TSqlColumn(dependency.Element);
Console.Write(column.Name + " ");
ShowType(column.DataType);
}
}
}
static void Main(string[] args)
{
var model = new TSqlTypedModel(#"path\Da.dacpac");
var views = model.GetObjects<TSqlView>(DacQueryScopes.UserDefined);
var tables = model.GetObjects<TSqlTable>(DacQueryScopes.UserDefined);
foreach (var t in tables)
{
Console.WriteLine($"table - {t.Name}");
foreach (var c in t.Columns)
{
Console.Write("\r\n" + c.Name.ToString() + " ");
switch (c.ColumnType)
{
case ColumnType.Column:
ShowType(c.DataType);
break;
case ColumnType.ComputedColumn:
Console.Write($"({c.Expression}) ");
ShowDependencies(c.ExpressionDependencies);
break;
case ColumnType.ColumnSet:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
foreach (var v in views)
{
Console.WriteLine($"view - {v.Name}");
foreach (var c in v.Columns)
{
Console.Write("\r\n" + c.Name.ToString() + " ");
var needDomParse = false;
switch (c.ColumnType)
{
case ColumnType.Column:
ShowType(c.DataType);
ShowDependencies(c.ExpressionDependencies);
break;
case ColumnType.ComputedColumn:
ShowType(c.DataType);
ShowDependencies(c.ExpressionDependencies);
if (!c.DataType.Any() && !c.ExpressionDependencies.Any())
{
needDomParse = true;
}
break;
case ColumnType.ColumnSet:
break;
default:
throw new ArgumentOutOfRangeException();
}
if (needDomParse)
{
//ouch
var create = new CreateViewStatement();
var parser = new TSql130Parser(false);
IList<ParseError> errors;
var fragment = parser.Parse(new StringReader(v.GetScript()), out errors);
var selectVisitor = new SelectVisitor();
fragment.Accept(selectVisitor);
foreach (var s in selectVisitor.Selects)
{
var spec = s.QueryExpression as QuerySpecification;
foreach (var element in spec.SelectElements)
{
var select = element as SelectScalarExpression;
if (select != null)
{
Console.Write(select.ColumnName.Value + " = ");
var caseExpression = select.Expression as SimpleCaseExpression;
if (caseExpression != null)
{
var func = caseExpression.ElseExpression as FunctionCall;
Console.WriteLine(func.FunctionName.Value);
}
}
}
}
}
}
}
}
}
internal class SelectVisitor : TSqlConcreteFragmentVisitor
{
public List<SelectStatement> Selects = new List<SelectStatement>();
public override void Visit(SelectStatement node)
{
Selects.Add(node);
base.Visit(node);
}
}
}
I hope it helps, I know it isn't a just do this but hopefully explains some of the challenges :)
Ed

Prevent SQL injection when building query

I know usually how to prevent it using preparedStatements, but now I have such a method for bulding queries. For example in Java:
private String buildQuery(String where) {
String query = "SELECT id, name FROM someTable";
if(where.length() > 0) {
query = query + " WHERE " + where;
}
return query;
}
'where' string is like this 'variable = value'. How can i prevent it here? I thought of passing variable and value separately, creating prepared statement using them and then returning that prepared statement as string somehow, but I'm not sure.
This is not specific to any one DB API.
TL;DR: Don't pass "SQL fragments" around.
Rather than passing complete clauses fro a select statement, or (sub-)expressions to add into a select clause, pass the components keeping the user data separate from the identifiers.
In this case do not pass name = value, pass them separately. Then validate name is a valid column for the table, and generate a parameter for the value part.
Thus, pseudo-code (my Java is rusty):
function BuildCommand(string column, object value) {
if !IsValidColumn("theTable", column)) throw InvalidOperation(...)
string sql = "Select column from theTable where " + column + " = #p0";
SqlCommand cmd = new SqlCommand(sql);
cmd.Parameters.Add("#p0", value);
return cmd;
}
You can use a map to pass your values and build a preparedStatement. Check the code below it should be something similar to that logic
public static PreparedStatement buildQuery(String where,Map<Integer, String> cond)
throws SQLException {
PreparedStatement stat = null;
String query = "SELECT id, name FROM someTable " + where;
try {
stat = con.prepareStatement(query);
for (Map.Entry<Integer, String> e : cond.entrySet()) {
stat.setString(e.getKey(), e.getValue());
}
} catch (SQLException e ) {
// Handle ex
} finally {
}
return stat;
}
public static void main(String[] a) throws SQLException {
Map<Integer,String> cond =new HashMap<Integer, String>();
cond.put(1,"val22");
cond.put(2,"val2");
buildQuery("col1 = ? and col2= ?", cond);
}
My suggestion is that if you have an array of where clauses in the parameter and rewrite the function as :
private String buildQuery(String[] where) {
String query = "SELECT id, name FROM someTable";
query = query + " WHERE "
for(int i = 0; i < where.length; i++) {
if(i > 0){
query = query + " AND "
}
query = query + w + " = ?";
}
return query;
}

Does dapper support .net dataset

in my opinion for dapper.query object there is a datareader, for dapper.Execute there is a ExectureNonQuery object. Correct me if i am wrong .
Can we use dapper for dataset which returns multiple tables?
No, there is not any built in support for DataSet, primarily because it seems largely redundant, but also because that isn't what dapper targets. But that doesn't mean it doesn't include an API for handling a query that selects multiple results; see QueryMultiple:
using (var multi = conn.QueryMultiple(sql, args))
{
var ids = multi.Read<int>().ToList();
var customers = multi.Read<Customer>().ToList();
dynamic someOtherRow = multi.Read().Single();
int qty = someOtherRow.Quantity, price = someOtherRow.Price;
}
Note that this API is forwards only (due to the nature of IDataReader etc) - basically, each Read / Read<T> etc maps to the next result grid in turn.
I might be late here but this is how I am doing the conversion of the IDataReader to a DataSet. Dapper returns a IDataReader when we use the ExecuteReaderAsync method. More information on this addition can be found here and here.
This is my attempt on this:
public async Task<DataSet> GetUserInformationOnUserId(int UserId)
{
var storedprocedure = "usp_getUserInformation";
var param = new DynamicParameters();
param.Add("#userId", UserId);
var list = await SqlMapper.ExecuteReaderAsync(_connectionFactory.GetEpaperDBConnection, storedprocedure, param, commandType: CommandType.StoredProcedure);
var dataset = ConvertDataReaderToDataSet(list);
return dataset;
}
And the ConvertDataReaderToDataSet will take in the IDataReader, you can use this method to convert the IReader to Dataset:
public DataSet ConvertDataReaderToDataSet(IDataReader data)
{
DataSet ds = new DataSet();
int i = 0;
while (!data.IsClosed)
{
ds.Tables.Add("Table" + (i + 1));
ds.EnforceConstraints = false;
ds.Tables[i].Load(data);
i++;
}
return ds;
}

Is my LDAP syntax wrong in search filter

This is my first attempt in trying to query our LDAP server for AD info. When I am trying to query the LDAP server here is what I'm trying to retrieve:
I am trying to retrieve all active employees with a countlimit of 500 records whose displayname starts with "sav", has an email address and has a userAccountControl attribute of 512. The problem I'm encountering is that I'm only getting back 8 records total. I should literally be getting back at least 10 records.
I did a separate search on the 2 records that were NOT retrieved in my search and each had an email address and a userAccountControl value of 512. So I'm not sure why those 2 records were missing.
I'm sure I've done something wrong in my syntax but I cannot find what it is. Any HELP/DIRECTION would be appreciated. Thank you.
After googling I've defined the SEARCH FILTER as:
String searchFilter = "(&(objectClass=user)(displayname="+displayname+"*"+")(mail=*)(userAccountControl=512))";
Please see my complete method below:
public List<String> getAutocompleteEmpRecordsList(String displayname, LdapContext ctx) {
List<String> activeEmpAttributes = new ArrayList<String>();
Attributes attrs = null;
int count = 0;
int empEmailAddrLen = 0;
try {
SearchControls constraints = new SearchControls();
constraints.setCountLimit(500);
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = {"displayname", "mail", "userAccountControl"};
constraints.setReturningAttributes(attrIDs);
String searchFilter = "(&(objectClass=user)(displayname="+displayname+"*"+")(mail=*)(userAccountControl=512))";
NamingEnumeration answer = ctx.search("OU=Standard,OU=Users,DC=xxx,DC=org", searchFilter, constraints);
if (answer != null) {
while (answer.hasMore()) {
attrs = ((SearchResult) answer.next()).getAttributes();
if (attrs.get("displayname") != null) {
int empNameLen = attrs.get("displayname").toString().length();
activeEmpAttributes.add(attrs.get("displayname").toString().substring(13, empNameLen));
}
count++;
ctx.close();
}
}
else {
throw new Exception("Invalid User");
}
System.out.println("activeEmpAttributes: " + activeEmpAttributes);
System.out.println("count: " + activeEmpAttributes.size());
} catch (Exception ex) {
ex.printStackTrace();
}
return activeEmpAttributes;
}
You may be confusing displayname attribute and cn attribute.
On Windows server you've got a command line tool called LDIDIFDE.EXE which can allow you to test your filter.
ldifde -f datas.ldf -d "OU=Standard,OU=THR Users,DC=txhealth,DC=org" -r "(&(objectClass=user)(displayname=sav*)(mail=*)(userAccountControl=512))"
ldifde -f datas.ldf -d "OU=Standard,OU=THR Users,DC=txhealth,DC=org" -r "(&(objectClass=user)(cn=sav*)(mail=*)(userAccountControl=512))"
In the User and computer MMC you can also test your filter.
Start User and computer Active-Directory :
Right buton on registered request :
Choose personalize search, you've got an helper tab for common attributes :
You can choose personalized tab for technical attributes
You can test en copy the resulting LDAP filter (you don't need the double (& one is enough):
Can you post your userAccountControl, displayName, and mail values for the two excluded users?
FWIW the medial search on displayName would run alot faster if you add a tuple index to it.
I downloaded a free AD tool to view all in AD that I needed and it showed me that the data was not the problem but I was just not hitting all the OU's that I needed because there is NOT just 1 OU where all our users are stored.
Consequently, after googling some more I found a page on the Oracle site regarding LDAP and I changed my LDAPContext to DirContext for my connection to do searches within the directory as well as using this context's REFERRAL and set the value to "follow" to avoid the PartialSearchException.
I thought I'd post my findings just in case some other newbie ran into the same issue.
If you see a downside to the changes I made please let me know. Regards.
Here is my corrected code:
public List<String> getAutocompleteEmpRecordsList(String displayname, DirContext ctx) {
List<String> activeEmpAttributes = new ArrayList<String>();
Attributes attrs = null;
int count = 0;
int empEmailAddrLen = 0;
try {
SearchControls constraints = new SearchControls();
constraints.setCountLimit(500);
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = {"displayname", "mail", "userAccountControl"};
constraints.setReturningAttributes(attrIDs);
String searchFilter = "(&(objectClass=user)(displayname="+displayname.trim()+"*"+")(mail=*)(userAccountControl=512))";
NamingEnumeration answer = ctx.search("DC=xxx,DC=org", searchFilter, constraints);
if (answer != null) {
while (answer.hasMore()) {
attrs = ((SearchResult) answer.next()).getAttributes();
if (attrs.get("displayname") != null) {
int empNameLen = attrs.get("displayname").toString().length();
activeEmpAttributes.add(attrs.get("displayname").toString().substring(13, empNameLen));
}
count++;
ctx.close();
}
}
else {
throw new Exception("Invalid User");
}
System.out.println("activeEmpAttributes: " + activeEmpAttributes);
System.out.println("count: " + activeEmpAttributes.size());
} catch (Exception ex) {
ex.printStackTrace();
}
return activeEmpAttributes;
}
Thanks anyway.

Resources