how to use IronPython to debug the Script step by step? - c#

I'm working on a project in which I am creating a IronPython compiler depend on IronPython ,
But I have some problem on debugging the Script and can use breakpoint ? could you please give me some help ? thanks. all my code is there: [https://github.com/heyxEvget/IronPython-Debugger]
public ScriptEngine GetEngine()
{
if (_engine != null)
return _engine;
_engine = Python.CreateEngine();
_engine.Runtime.IO.SetOutput(_stream, Encoding.UTF8);
_engine.Runtime.IO.SetErrorOutput(_stream, Encoding.UTF8);
string path = Environment.CurrentDirectory;
string ironPythonLibPath = string.Format(#"{0}\IronPythonLib.zip", path);
var paths = _engine.GetSearchPaths() as List<string> ?? new List<string>();
paths.Add(path);
paths.Add(ironPythonLibPath);
path = Environment.GetEnvironmentVariable("IRONPYTHONPATH");
if (!string.IsNullOrEmpty(path))
{
var pathStrings = path.Split(';');
paths.AddRange(pathStrings.Where(p => p.Length > 0));
}
_engine.SetSearchPaths(paths.ToArray());
return _engine;
}
private void GetPythonVarsInfo(ScriptScope scope)
{
_varList.Clear();
var items = scope.GetItems();
foreach (var item in items)
{
_varList.Add(new VarValue
{
VarName = item.Key,
Value = item.Value
});
}
valueListView.ItemsSource = _varList;
}
private void OnExecuteButtonClick(object sender, ItemClickEventArgs e)
{
string outPutString = string.Empty;
outPutString = "*************************************" +
"Excute Date: " + DateTime.Now.ToLocalTime().ToString(CultureInfo.InvariantCulture);
ExeceutePython(document, outPutString);
TabControl.SelectedIndex = 2;
}
private void ExeceutePython(EditorDocument document, string outPutString)
{
ScriptEngine engine = GetEngine();
string script = document.Text;
ScriptSource source = engine.CreateScriptSourceFromString(script);
ScriptScope scope = _engine.CreateScope();
try
{
source.Compile();
OutputTextBox.AppendText(outPutString + Environment.NewLine);
var result = source.Execute(scope);
if (result != null)
{
OutputTextBox.AppendText(engine.Operations.Format(result));
}
OutputTextBox.AppendText(Environment.NewLine);
GetPythonVarsInfo(scope);
}
catch (Exception ex)
{
var eo = engine.GetService<ExceptionOperations>();
var eoString = eo.FormatException(ex);
OutputTextBox.AppendText(eoString);
return;
}
}

Given this setup code to create the IronPython script engine
var engine = IronPython.Hosting.Python.CreateEngine(new Dictionary<string, object> { { "Debug", ScriptingRuntimeHelpers.True }});
Debug.Assert(engine.Runtime.Setup.DebugMode);
var source = engine.CreateScriptSourceFromFile("script.py");
dynamic result = source.Execute();
You can then use
System.Diagnostics.Debugger.Break()
inside your scripts to get the debugger to break.

You can use visual studio isolated shell for that
Visual Studio Isolated Shell

Related

C# Roslyn CompletionService where to get method overload information

I've got a method that returning back from CompletionService.GetDescriptionAsync(Document, CompletionItem) gives me the following description:
void SQL.GetSQLiteDB(string url) (+ 1 overload)
This is a method I made on a Xamarin project, here are both method signatures:
public static void GetSQLiteDB(string url);
public static string GetSQLiteDB(string url, string name);
What's the Roslyn way to get information on both?
Here's how I'm setting up completions:
async Task InitCodeCompletion()
{
host = MefHostServices.Create(MefHostServices.DefaultAssemblies);
workspace = new AdhocWorkspace(host);
Type[] types =
{
typeof(object),
typeof(System.Linq.Enumerable),
typeof(System.Collections.IEnumerable),
typeof(Console),
typeof(System.Reflection.Assembly),
typeof(List<>),
typeof(Type),
typeof(SQL)
};
imports = types.Select(x => x.Namespace).Distinct().ToImmutableArray();
assemblies = types.Select(x => x.Assembly).Distinct().ToImmutableArray();
references = assemblies.Select(t => MetadataReference.CreateFromFile(t.Location) as MetadataReference).ToImmutableArray();
compilationOptions = new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
usings: imports);
projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Script", "Script", LanguageNames.CSharp, isSubmission: true)
.WithMetadataReferences(references).WithCompilationOptions(compilationOptions);
project = workspace.AddProject(projectInfo);
documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Script", sourceCodeKind: SourceCodeKind.Script,
loader: TextLoader.From(TextAndVersion.Create(SourceText.From(""), VersionStamp.Create())));
document = workspace.AddDocument(documentInfo);
var services = workspace.Services;
completionService = CompletionService.GetService(document);
}
async Task<CodeCompletionResults> GetCompletions(string code)
{
string codeModified = "using SQL = XamTestNET5.Services.SQLiteGeneratorService; " + Environment.NewLine;
codeModified += "using HtmlSvc = XamTestNET5.Services.HtmlRetrievalService;" + Environment.NewLine;
// ^^^ The above two lines set up some simple namespace aliases in my project, if you know how to put this in a separate project document and use it in code completion please let me know in comments as otherwise doing so gives me an exception that you can't have multiple syntax trees
codeModified += code;
var source = SourceText.From(codeModified);
document = document.WithText(source);
// cursor position is at the end
var position = source.Length;
var completions = await completionService.GetCompletionsAsync(document, position);
return new CodeCompletionResults() { InputCode = code, ModifiedCode = codeModified, Completions = completions };
}
Here's how I'm getting them now and putting them in a browser control:
private async void CSharpShellEnvironment_EntryCodeCompletionEntry(object sender, CSharpShellEnvironment.EntryEventArgs e)
{
if (e.Value != "")
{
CodeCompletionResults results = await GetCompletions(e.Value);
CompletionList list = results.Completions;
if (list != null)
{
if (list.Items != null)
{
StringBuilder sb = new StringBuilder();
foreach (var item in list.Items)
{
string spanText = (item.Span.Start != item.Span.End) ? results.ModifiedCode.Substring(item.Span.Start, item.Span.Length) : "";
bool recommended = spanText == "" ? true : item.DisplayText.StartsWith(spanText);
if (recommended)
{
string fText = item.DisplayText.Substring(spanText.Length);
string props = "";
foreach(var p in item.Properties)
{
props += $"<span data-key=\"{p.Key}\" data-value=\"{p.Value}\"></span>";
}
string tags = "";
foreach(var t in item.Tags)
{
tags += $"<span data-tag=\"{t}\"></span>";
}
string descStr = "";
if (item.Tags != null)
{
if (item.Tags.Where(x => x.ToLower() == "method").FirstOrDefault() != null && item.Tags.Where(x => x.ToLower() == "public").FirstOrDefault() != null)
{
var desc = await completionService.GetDescriptionAsync(document, item);
descStr += $"<span data-desc=\"{desc.Text}\">";
foreach(var part in desc.TaggedParts)
{
descStr += $"<span data-desc-part-tag=\"{part.Tag}\" data-desc-part-text=\"{part.Text}\"></span>";
}
descStr += "</span>";
}
}
sb.AppendLine($"<div class=\"codecompleteentry\" data-display-text=\"{item.DisplayText}\" data-span-text=\"{spanText}\" data-final-text=\"{fText}\">{props}{tags}{descStr}{fText}</div>");
}
}
string scriptInputClick = "Array.prototype.forEach.call(document.getElementsByClassName('codecompleteentry'), function(el) { el.addEventListener('click', function(elem) { var text = { MessageType: 'CodeCompletion', Parameters: JSON.stringify({ DataDisplayText: el.getAttribute('data-display-text'), DataSpanText: el.getAttribute('data-span-text'), DataFinalText: el.getAttribute('data-final-text') }), Message: el.innerText }; window.chrome.webview.postMessage(text); } ); });";
sb.AppendLine($"<script type=\"text/javascript\">{scriptInputClick}</script>");
env.EnterCodeCompletionResponse(sb.ToString());
}
else
{
env.EnterCodeCompletionResponse(strNoSuggestions);
}
}
else
{
env.EnterCodeCompletionResponse(strNoSuggestions);
}
}
else
{
env.EnterCodeCompletionResponse(strNoSuggestions);
}
}
It seems on the surface that CompletionSurface has everything you need, but it doesn't, you need to reference the Document's SemanticModel in order to get all of the signature overloads of a method when the user types ( on a method during code completion.
It wasn't very obvious to me until I started looking through the RoslynPad source, which I recommend doing for a practical example: https://github.com/aelij/RoslynPad
List<IEnumerable<ReferencedSymbol>> allMethodRefs = new List<IEnumerable<ReferencedSymbol>>();
async Task<CodeCompletionResults> GetCompletions(string code)
{
string codeModified = "using SQL = XamTestNET5.Services.SQLiteGeneratorService; " + Environment.NewLine;
codeModified += "using HtmlSvc = XamTestNET5.Services.HtmlRetrievalService;" + Environment.NewLine;
// ^^^ I put my namespace aliases in the same SyntaxTree for now,
// I'd like a better solution though.
codeModified += code;
var source = SourceText.From(codeModified);
document = document.WithText(source);
// cursor position is at the end
var position = source.Length;
var completions = await completionService.GetCompletionsAsync(document, position);
syntaxRoot = await document.GetSyntaxRootAsync();
semanticModel = await document.GetSemanticModelAsync();
var methods = syntaxRoot.DescendantNodes().OfType<InvocationExpressionSyntax>();
allMethodRefs = new List<IEnumerable<ReferencedSymbol>>();
if (methods != null)
{
if (methods.Count() > 0)
{
foreach(var m in methods)
{
var info = semanticModel.GetSymbolInfo(m);
if (info.Symbol != null)
{
allMethodRefs.Add(await SymbolFinder.FindReferencesAsync(info.Symbol, solution));
}
else
{
foreach(var symbol in info.CandidateSymbols)
{
allMethodRefs.Add(await SymbolFinder.FindReferencesAsync(symbol, solution));
}
}
}
}
}
return new CodeCompletionResults() { InputCode = code, ModifiedCode = codeModified, Completions = completions };
}

AppConfig from design environment

Trying to get the appconfig path from the debug environment for a component but I keep getting nulls errors from this when I build the solution is vs2017. any help appreciated.
public string GetAppConfigPath()
{
var devenv = (DTE)_c.Site.GetService(typeof(DTE));
var projects = (Array)devenv.ActiveSolutionProjects;
var activeProject = (Project)projects.GetValue(0);
foreach (ProjectItem item in activeProject.ProjectItems)
{
if (!item.Name.Equals("app.config")) continue;
var info = new System.IO.FileInfo(activeProject.FullName);
if (info.Directory != null)
return info.Directory.FullName + "\\" + item.Name;
}
return null;
}

How to change Tick icon of ELCImagepicker in Xamarin.forms?

I am using ELCImagepicker.dll to create gallery with multi image selection. Everything is working fine.
1- I want to change icon of Tick whenever user select. It's very old style
2- Change validation message of maximum selection. I want to use the word "select" instead of "send".
Here is the MediaService file. maxImage set validation of maximum images
public class MediaService : IMediaService
{
public async Task OpenGallery(int maxImage)
{
var picker = ELCImagePickerViewController.Create(maxImage);
picker.MaximumImagesCount = maxImage;
var topController = UIApplication.SharedApplication.KeyWindow.RootViewController;
while (topController.PresentedViewController != null)
{
topController = topController.PresentedViewController;
}
topController.PresentViewController(picker, true, null);
List<string> images = new List<string>();
await picker.Completion.ContinueWith(t =>
{
picker.BeginInvokeOnMainThread(() =>
{
//dismiss the picker
picker.DismissViewController(true, null);
if (t.IsCanceled || t.Exception != null)
{
}
else
{
//List<string> images = new List<string>();
var items = t.Result as List<AssetResult>;
foreach (var item in items)
{
var path = Save(item.Image, item.Name);
images.Add(path);
//CleanPath(path);
}
}
});
});
MessagingCenter.Send<App, List<string>>((App)Xamarin.Forms.Application.Current, "ImagesSelected", images);
}
string Save(UIImage image, string name)
{
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, name); // hardcoded filename, overwritten each time
NSData imgData = image.AsJPEG();
NSError err = null;
if (imgData.Save(jpgFilename, false, out err))
{
return jpgFilename;
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
return null;
}
}
void IMediaService.ClearFiles(List<string> filePaths)
{
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
if (Directory.Exists(documentsDirectory))
{
foreach (var p in filePaths)
{
File.Delete(p);
}
}
}
}
Please guide
Since the author hasn't expose the api that can change icon or text,so you have to change them inside the source code, and then create dll for using.
Alert text :here
Icon : here

accept multi line string in Process.Start

i am parsing a path from a directory location:
assuming that InitialPath = #"C:\Users\username\Documents\Visual Studio 2015\Projects"
and i have a loop of:
var list = new List<string>();
foreach(var folder in Directory.GetDirectories(InitialPath) {
var folder = Path.GetFileName(folder);
var file = Path.GetFileName(Directory.GetFiles(folder, "*.sln").Single());
list.Add(InitialPath + "\\" + folder + "\\" + file); //would then result something like "C:\Users\username\Documents\Visual Studio 2015\Projects\Folder1\Project1inFolder1.sln"
}
if i try a path from the list and assign it to a richbox as its .text value, it returns a single line text.
but when i'm displaying it on a MessageBox, the string is being broken into two lines as below:
i need to force it not to be broken into several lines. i mean, i need it to be a single line string only no matter the length of the string because Process.Start() wont accept the string because it gets cut into lines. see below for reference:
PS: sorry for not being able to explain my question eligibly, english is not my natural language
just in case, here is my code snippet:
using MaterialSkin;
using MaterialSkin.Controls;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Principal;
namespace The_Projects {
public partial class MainForm : MaterialForm {
public MainForm() {
InitializeComponent();
var materialSkinManager = MaterialSkinManager.Instance;
materialSkinManager.AddFormToManage(this);
materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;
materialSkinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
public class DirectoryInformation {
private string _FolderName;
private string _Solution;
private DateTime _Created;
private DateTime _Accessed;
private DateTime _Modified;
private string _SecIdentity;
private string _NTAccount;
private double _FileSize;
private int _FileCount;
public string FolderName {
get { return _FolderName; }
set { _FolderName = value; }
}
public string Solution {
get { return _Solution; }
set { _Solution = value; }
}
public DateTime Created {
get { return _Created; }
set { _Created = value; }
}
public DateTime Accessed {
get { return _Accessed; }
set { _Accessed = value; }
}
public DateTime Modified {
get { return _Modified; }
set { _Modified = value; }
}
public string SecIdentity {
get { return _SecIdentity; }
set { _SecIdentity = value; }
}
public string NTAccount {
get { return _NTAccount; }
set { _NTAccount = value; }
}
public double FileSize {
get { return _FileSize; }
set { _FileSize = value; }
}
public int FileCount {
get { return _FileCount; }
set { _FileCount = value; }
}
}
public string InitialPath = #"X:\_\Document\Visual Studio 2015\Projects\";
public string FolderPath = string.Empty;
public string Solution = string.Empty;
private void MainForm_Load(object sender, EventArgs e) {
var projectList = new List<DirectoryInformation>();
foreach(var dirs in Directory.GetDirectories(InitialPath)) {
var ac = File.GetAccessControl(dirs);
var di = new DirectoryInfo(dirs);
var dirInf = new DirectoryInformation() {
FolderName = Path.GetFileName(dirs),
Solution = Path.GetFileName(Directory.GetFiles(dirs, "*.sln").Single()),
Created = Directory.GetCreationTime(dirs),
Accessed = Directory.GetLastAccessTime(dirs),
Modified = Directory.GetLastWriteTime(dirs),
SecIdentity = ac.GetOwner(typeof(SecurityIdentifier)).ToString(),
NTAccount = ac.GetOwner(typeof(SecurityIdentifier)).Translate(typeof(NTAccount)).ToString(),
FileSize = (double) di.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(x => x.Length) / 1024000,
FileCount = Directory.GetFiles(dirs, "*.*", SearchOption.AllDirectories).Count()
};
projectList.Add(dirInf);
}
lstProjectList.DataSource = projectList;
lstProjectList.DisplayMember = "FolderName";
}
private void lstProjectList_SelectedIndexChanged(object sender, EventArgs e) {
var project = lstProjectList.SelectedValue as DirectoryInformation;
lblFolder.Text = project.FolderName;
lblCreated.Text = project.Created.ToString();
lblAccess.Text = project.Accessed.ToString();
lblModified.Text = project.Modified.ToString();
lblIdentifier.Text = project.SecIdentity;
lblOwner.Text = project.NTAccount;
lblSize.Text = project.FileSize.ToString("F2") + " MB";
lblCount.Text = project.FileCount.ToString();
FolderPath = InitialPath + project.FolderName;
Solution = FolderPath + "\\" + project.Solution;
}
private void btnOpenProject_Click(object sender, EventArgs e) {
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", Solution);
//Clipboard.SetText(Solution);
}
private void btnOpenFolder_Click(object sender, EventArgs e) {
Process.Start("explorer.exe", FolderPath);
}
}
}
It's just the way your MessageBox is wrapping text. You've got two options here:
Create a custom Forms class
Create a form dialog just for showing messages
EDIT:
Change this:
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", Solution);
to
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", "\"" + Solution + "\"");
What's happening here is the second parameter to the Process.Start method is treated as argument(s) for the executable given by the first parameter. So what process.start does is the equivalent (but not quite the same) of opening the command prompt and typing out:
"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe" X:\_\Document\Visual Studio 2015\.....
and the command prompt treats (space) as a parameter separator, so it treats X:\_\Document\Visual as one parameter, Studio as the next and so on. When you use "\"" around the string you're telling Process.Start that the whole thing (including spaces) is a single parameter.
Your sample had some bugs in it, for me this worked and I got all *.sln files
//this is just to show that you can get short file name if you need FileInfo
var list = new Dictionary<string, string>();
var files = Directory.GetFiles(InitialPath, "*.sln", SearchOption.AllDirectories);
foreach (var file in files)
{
FileInfo fileInfo = new FileInfo(file);
list.Add(fileInfo.Name, file);
}
Process.Start(list.FirstOrDefault().Value);
On my computer starts with no problems.
But if you want a devenv.exe start with a solution open you do it like so
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", #"devenv/""" + fullFilePath + #"""");
you need the command in arguments devenv/ and you must you must enclose paths in double quotation marks ("fullFilePath").

Retrieving user attributes from Active Directory using LDAP - JAVA

EDIT: I've posted the solution below.
I know you don't like these type of questions, but i've been struggling with this issue for half a day now.
I've written a C# code that fetches user attributes from our Active Directory using LDAP, the code works well.
The code is as follows:
DirectoryEntry dirEnt = new DirectoryEntry("LDAP://dc=dom,dc=int");
DirectorySearcher adSearch = new DirectorySearcher(dirEnt);
adSearch.SearchScope = SearchScope.Subtree;
adSearch.PageSize = 10000;
adSearch.Filter = "(&(objectClass=user))";
SearchResultCollection sColl = adSearch.FindAll();
foreach (SearchResult sResult in sColl)
{
string sConn = sResult.Properties["distinguishedName"][0].ToString();
DirectoryEntry dirEnt2 = new DirectoryEntry("LDAP://" + sConn);
...
// dirEnt2 contains ALL attributes for the user
}
I'm trying to port this code to Java, but it seems like that the technique I used in C# does not work too well in Java.
Using the following code
DirContext context;
ArrayList<String> nList = new ArrayList<String>();
Hashtable env = new Hashtable();
String username = ...;
String password = ...;
try {
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUri);
try {
context = new InitialDirContext(env);
} catch (NamingException e) {
throw new RuntimeException(e);
}
SearchControls ctrl = new SearchControls();
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration enumeration = context.search("", "(objectClass=user)",
ctrl);
while (enumeration.hasMore()) {
SearchResult result = (SearchResult) enumeration.next();
Attributes attribs = result.getAttributes();
NamingEnumeration values = ((BasicAttribute)
attribs.get("distinguishedName")).getAll();
while (values.hasMore()) {
nList.add(values.next().toString());
}
}
} catch (NamingException e) {
e.printStackTrace();
}
for (String sVar : nList ){
Hashtable env2 = new Hashtable();
env2.put(Context.SECURITY_PRINCIPAL, username);
env2.put(Context.SECURITY_CREDENTIALS, password);
env2.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env2.put(Context.PROVIDER_URL, "ldap://DOM/" + sVar);
Attributes attrs = null;
try {
context = new InitialDirContext(env2);
attrs = context.getAttributes(sVar);
} catch (NamingException e) {
System.out.println(e.toString());
continue;
}
System.out.println(attrs.toString());
}
Yields that attrs only contains BASIC attributes regarding the user (such as samaccountname, displayname, etc)
and no 'email', 'telephone' or any other similar attributes.
Any help on the issue is blessed!
Here's the solution, sorry for the messy code/formatting
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.*;
public class UserFetch {
public static void main(String[] args) {
try{
// Activate paged results
byte[] cookie = null;
int count=0;
int total;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.REFERRAL, "follow");
env.put(Context.SECURITY_AUTHENTICATION, "Simple");
env.put(Context.SECURITY_PRINCIPAL, "USERNAME#DOM.COM");
env.put(Context.SECURITY_CREDENTIALS, "PASSWORD");
env.put(Context.PROVIDER_URL, "ldap://DOM.COM:389");
LdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(new Control[]{
new PagedResultsControl(10000, Control.CRITICAL) });
do {
// Perform the search
NamingEnumeration results =
ctx.search("dc=DOM,dc=COM", "(&(objectclass=user)(employeeNumber=*))", getSimpleSearchControls());
// Iterate over a batch of search results
while (results != null && results.hasMore()) {
// Display an entry
SearchResult entry = (SearchResult)results.next();
Attributes attrs = entry.getAttributes ();
System.out.println(attrs.get("SAMAccountName")); // Username
System.out.println("Firstname: " +
attrs.get("givenname")); // firstname
System.out.println("Lastname: " + attrs.get("sn")); // lastname
System.out.println("EmployeeID " + attrs.get("employeeID"));
System.out.println("EmployeeNumber: " +
attrs.get("employeeNumber"));
// Handle the entry's response controls (if any)
}
// Examine the paged results control response
Control[] controls = ctx.getResponseControls();
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc =
(PagedResultsResponseControl)controls[i];
total = prrc.getResultSize();
cookie = prrc.getCookie();
} else {
// Handle other response controls (if any)
}
}
}
// Re-activate paged results
ctx.setRequestControls(new Control[]{
new PagedResultsControl(10000, cookie, Control.CRITICAL) });
} while (cookie != null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SearchControls getSimpleSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(30000);
String[] attrIDs =
{ "SAMAccountName", "sn", "givenname", "employeeID",
"employeeNumber" };
searchControls.setReturningAttributes(attrIDs);
return searchControls;
}
}
Try setting the returned attributes on your SearchControls
ctrl.setReturningAttributes(new String[] {"email", "telephone"});

Categories