I m using the following code to invoke SOAP method dynamically. It works when the input for the service is ONE(1). When I increase the input to Two it returns error.
Out of idea why this happens.
I referred to this link to built this..
http://www.codeproject.com/Articles/18950/Dynamic-Discovery-and-Invocation-of-Web-Services
My SOAP Service:
[WebMethod]
public string UpdateMapString(string status, string astationid)
{
return string.Format("Update Completed");
}
This is my C# Code Calling the SOAP service.
The main Function:
private MethodInfo[] methodInfo;
private ParameterInfo[] param;
private Type service;
private Type[] paramTypes;
public List<Type> myproperty = new List<Type>();
private string MethodName = "";
public List<string> treews = new List<string>();
public List<string> treeParameters = new List<string>();
public static void Main(string[] args)
{
Program a = new Program();
a.DynamicInvocation();
a.selectMethod();
a.invoke();
Console.ReadLine();
}
To Call Service:
public void DynamicInvocation()
{
try
{
Uri uri = new Uri("http://localhost:50167/Service.asmx?WSDL");
WebRequest webRequest = WebRequest.Create(uri);
System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
// Get a WSDL file describing a service
ServiceDescription sd = ServiceDescription.Read(requestStream);
string sdName = sd.Services[0].Name;
// Add in tree view
// treeWsdl.Nodes.Add(sdName);
treews.Add(sdName);
Console.WriteLine("Service Name: " + sdName);
// messageTextBox.Text += "Generating Proxy \r\n";
// progressBar1.PerformStep();
// Initialize a service description servImport
ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
servImport.AddServiceDescription(sd, String.Empty, String.Empty);
servImport.ProtocolName = "Soap";
servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;
// messageTextBox.Text += "Generating assembly \r\n";
// progressBar1.PerformStep();
CodeNamespace nameSpace = new CodeNamespace();
CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
codeCompileUnit.Namespaces.Add(nameSpace);
// Set Warnings
ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);
if (warnings == 0)
{
StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());
// messageTextBox.Text += "Compiling assembly \r\n";
// progressBar1.PerformStep();
// Compile the assembly with the appropriate references
string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
CompilerParameters param = new CompilerParameters(assemblyReferences);
param.GenerateExecutable = false;
param.GenerateInMemory = true;
param.TreatWarningsAsErrors = false;
param.WarningLevel = 4;
CompilerResults results = new CompilerResults(new TempFileCollection());
results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
Assembly assembly = results.CompiledAssembly;
service = assembly.GetType(sdName);
methodInfo = service.GetMethods();
foreach (MethodInfo t in methodInfo)
{
if (t.Name == "Discover")
break;
Console.WriteLine(t.Name);
}
}
// messageTextBox.Text += warnings;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
// messageTextBox.Text += "\r\n" + ex.Message + "\r\n\r\n" + ex.ToString(); ;
// progressBar1.Value = 70;
}
}
To get the Method:
public void selectMethod()
{
treeParameters.Add(treews[0]);
MethodName = methodInfo[0].Name;
param = methodInfo[0].GetParameters();
/// myProperty.add = param[e.Node.Index].ParameterType;
myproperty.Add(param[0].ParameterType);
// Console.WriteLine("This is param: " + param[0].ToString());
// myProperty = new properties(param.Length);
// Get the Parameters Type
paramTypes = new Type[param.Length];
for (int i = 0; i < paramTypes.Length; i++)
{
paramTypes[i] = param[i].ParameterType;
}
foreach (ParameterInfo temp in param)
{
treeParameters.Add(temp.ParameterType.Name + " " + temp.Name);
}
}
To Invoke Service (error in this function)
public void invoke()
{
Console.WriteLine("Invoke:");
object[] param1 = new object[param.Length];
try
{
for (int i = 0; i < param.Length; i++)
{
//param1[i] = Convert.ChangeType(myProperty.MyValue[i], myProperty.TypeParameter[i]);
// Console.WriteLine(myproperty[i].ToString());
param1[i] = Convert.ChangeType("10", typeof(string));
}
foreach (MethodInfo t in methodInfo)
{
//Console.WriteLine("Tname: " + t.Name.ToString());
if (t.Name == MethodName)
{
//Invoke Method
Object obj = Activator.CreateInstance(service);
//*****************error at this line
Object response = t.Invoke(obj, param1);
//*****************error at this line
// Console.WriteLine(t.Name);
Console.WriteLine(response.ToString());
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
//MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Related
I am using ThreadPool.QueueUserWorkItem for threading in C# WinForms, but it makes the main UI hangs don't know why, is there any other good way for threading rather than ThreadPool which make the UI goes smooth!
ThreadPool.QueueUserWorkItem(new WaitCallback(KeywordSearch), cts);
private void KeywordSearch(object r)
{
string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] alphas = (alphabet + alphabet.ToLower()).ToCharArray();
if (this.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
this.Cursor = Cursors.WaitCursor;
});
}
else
{
this.Cursor = Cursors.WaitCursor;
}
foreach (char a in alphas)
{
MessageBox.Show(a.ToString());
string correctkeywordforQuery = KeywordTxt.Text + " " + a;
var webRequest = WebRequest.Create(#"https://clients1.google.com/complete/search?client=youtube&hl=en&gl=us&sugexp=ytfdc%2Ccfro%3D1%2Cfp.dquf%3D1&gs_rn=64&gs_ri=youtube&ds=yt&cp=2&gs_id=6l&q=" + correctkeywordforQuery + "&callback=google.sbox.p50&gs_gbg=7dNuEZN941O5Tlh1iM");
string result;
using (var response = webRequest.GetResponse())
using (var content = response.GetResponseStream())
using (var reader = new StreamReader(content))
{
var strContent = reader.ReadToEnd();
result = strContent.Replace("google.sbox.p50 && google.sbox.p50(", ""); ;
//text.Remove(text.ToString().LastIndexOf(character), character.Length);
result = result.Remove(result.Length - 1);
}
var jsonser = new JavaScriptSerializer();
var obj = jsonser.Deserialize<dynamic>(result);
foreach (var x in obj[1])
{
//CancellationToken token = (CancellationToken)r;
//if (token.IsCancellationRequested)
//{
// cts.Cancel();
// return;
//}
var value1 = x[0]; // bd felek
// MessageBox.Show(value1);
string thecorrectlinktogetallthedata = "https://www.youtube.com/results?search_query=" + value1+ "&hl=en";
// Process.Start(thecorrectlinktogetallthedata);
if (richTextBox1.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
richTextBox1.Text += "\r\n"+thecorrectlinktogetallthedata;
});
}
else
{
richTextBox1.Text += "\r\n" + thecorrectlinktogetallthedata;
}
// Process.Start(thecorrectlinktogetallthedata);
// create the constructor with post type and few data
//show the response string on the console screen.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(thecorrectlinktogetallthedata);
string htmlcontent = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
htmlcontent = reader.ReadToEnd();
}
HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(htmlcontent);
if (richTextBox1.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
richTextBox1.Text += "\r\n" + htmlcontent;
});
}
else
{
richTextBox1.Text += "\r\n" + htmlcontent;
}
//watch?v
HtmlAgilityPack.HtmlNodeCollection Nodes = document.DocumentNode.SelectNodes("//a");
//MessageBox.Show(Nodes.Count.ToString());
foreach (HtmlAgilityPack.HtmlNode node in Nodes)
{
string ahref = node.Attributes["href"].Value;
string classname = node.GetAttributeValue("classname", string.Empty);
//MessageBox.Show(ahref);
if (ahref.Contains("watch?v"))
{
string title = node.GetAttributeValue("title",string.Empty);
if(title.Trim().ToString()!= string.Empty)
{
//newRows[0] = title;
//newRows[1] = ahref; ;
if (ResultGrid.InvokeRequired)
{
ResultGrid.BeginInvoke((MethodInvoker)delegate ()
{
object[] newRows = { title, "https://www.youtube.com" + ahref };
//MessageBox.Show(title);
ResultGrid.Rows.Add(newRows);
ResultGrid.Update();
//ResultCountLabel.Text = ResultGrid.Rows.Count.ToString();
});
}
else
{
object[] newRows = { title, "https://www.youtube.com" + ahref };
//
ResultGrid.Rows.Add(newRows);
ResultGrid.Update();
//ResultCountLabel.Text = ResultGrid.Rows.Count.ToString();
}
}
}
}
break;
}
}
if (this.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
this.Cursor = Cursors.Default;
});
}
else
{
this.Cursor = Cursors.Default;
}
}
This is my code which is returning the expected output on my friend's PC, but not on mine.
We are both working with Visual Studio 2017 Community:
enter image description here
This is the code that will return latitude and longitude of the entered address:
[enter image description here][2]
The first time it works fine but after that its throwing (403 forbidden error !!! / mainly problem is on the request.getResponse())
private static String[] x = new String[3];
public static String[] GetFirstLastName(string address)
{
try {
string url = "http://maps.google.com/maps/api/geocode/xml?address=" + address + "&sensor=false";
WebRequest request = WebRequest.Create(url);
// request.UseDefaultCredentials = true;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
using (WebResponse response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
var ds = new DataSet("Employee");
ds.ReadXml(reader);
DataRow dr = null;
var dt = new DataTable("Employee");
dt.Columns.AddRange(new DataColumn[2]
{
new DataColumn("Latitude", typeof (string)),
new DataColumn("Longitude", typeof (string))
});
int i = 0;
try
{
foreach (DataRow row in ds.Tables["result"].Rows)
{
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return x;
}
foreach (DataRow row in ds.Tables["result"].Rows)
{
if (i == 0)
{
string geometry_id = ds.Tables["geometry"].Select("result_id = " + row["result_id"])[0]["geometry_id"].ToString();
dr = ds.Tables["location"].Select("geometry_id = " + geometry_id)[0];
dt.Rows.Add(dr["lat"], dr["lng"]);
// Console.WriteLine(dr["lat"].ToString() + " " + dr["lng"].ToString());
i = 1;
break;
}
}
x[0] = dr["lat"].ToString();
x[1] = dr["lng"].ToString();
reader.Close();
}
// request.Timeout = 0;
// request.Abort();
response.Close();
return x;
}
}
catch(Exception e)
{
Console.WriteLine(e);
x[0] = "";
x[1] = "";
return x;
}
}
public static String[] GetFirstLastName1(string address)
{
try
{
string url = "http://maps.google.com/maps/api/geocode/xml?address=" + address + "&sensor=false";
WebRequest request = WebRequest.Create(url);
// request.UseDefaultCredentials = true;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
using (WebResponse response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
var ds = new DataSet("Employee");
ds.ReadXml(reader);
DataRow dr = null;
var dt = new DataTable("Employee");
dt.Columns.AddRange(new DataColumn[2]
{
new DataColumn("Latitude", typeof (string)),
new DataColumn("Longitude", typeof (string))
});
int i = 0;
try
{
foreach (DataRow row in ds.Tables["result"].Rows)
{
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return x;
}
foreach (DataRow row in ds.Tables["result"].Rows)
{
if (i == 0)
{
string geometry_id = ds.Tables["geometry"].Select("result_id = " + row["result_id"])[0]["geometry_id"].ToString();
dr = ds.Tables["location"].Select("geometry_id = " + geometry_id)[0];
dt.Rows.Add(dr["lat"], dr["lng"]);
// Console.WriteLine(dr["lat"].ToString() + " " + dr["lng"].ToString());
i = 1;
break;
}
}
x[0] = dr["lat"].ToString();
x[1] = dr["lng"].ToString();
reader.Close();
}
//// request.Timeout = 0;
/// request.Abort();
response.Close();
return x;
}
}
catch (Exception e)
{
Console.WriteLine(e);
x[0] = "";
x[1] = "";
return x;
}
}
static void Main(string[] args)
{
int i = 0;
for (;;)
{
String x = Console.ReadLine();
if (i == 0)
{
String[] y = GetFirstLastName(x);
Console.WriteLine(y[0] + " " + y[1]);
}
else
{
String[] y = GetFirstLastName1(x);
Console.WriteLine(y[0] + " " + y[1]);
}
i++;
}
//Console.ReadKey();
}
}
}
/*(Same Code above)
enter code here
///My Friends Output
/// My Output
[2]: https://i.stack.imgur.com/qeDcz.png */
Glad to see you've joined StackOverflow!
Now a 403 error occurs usually not in relation to a syntax error in your code but in relation to the response received from Google's servers.
Now Google in particular is very restrictive on how many API calls you can make a day (Google makes a lot of money off developers who pay for lots of API calls). This page contains the limits. If you've made more than the numbers in here, that's why you're getting the error and you'll have to wait until tomorrow. Do keep in mind not to send too many http requests and accidentally DOS them, as they'll blacklist you for this.
Make sure you are not caching their page or storing the js script locally as this will also cause a blacklist.
Make sure you use https: and not http: here.
I read this article , I want to get sent bytes and receive bytes for all process, but sent bytes and receive bytes of all process always return 0;
Here is my code:
namespace Network
{
public class NetworkTraffic
{
private List<PerformanceCounter> listBytesSentPerformanceCounter;
private List<PerformanceCounter> listBytesReceivedPerformanceCounter;
//private PerformanceCounter bytesSentPerformanceCounter;
//private PerformanceCounter bytesReceivedPerformanceCounter;
public NetworkTraffic()
{
listBytesSentPerformanceCounter = new List<PerformanceCounter>();
listBytesReceivedPerformanceCounter = new List<PerformanceCounter>();
List<string> listInstanceName = GetInstanceName();
foreach (string str in listInstanceName)
{
PerformanceCounter bytesSentPerformanceCounter = new PerformanceCounter();
PerformanceCounter bytesReceivedPerformanceCounter = new PerformanceCounter();
bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
bytesSentPerformanceCounter.CounterName = "Bytes Sent";
bytesSentPerformanceCounter.InstanceName = str;
bytesSentPerformanceCounter.ReadOnly = false;
listBytesSentPerformanceCounter.Add(bytesSentPerformanceCounter);
bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
bytesReceivedPerformanceCounter.CounterName = "Bytes Received";
bytesReceivedPerformanceCounter.InstanceName = str;
bytesReceivedPerformanceCounter.ReadOnly = false;
listBytesReceivedPerformanceCounter.Add(bytesReceivedPerformanceCounter);
}
}
//public float GetBytesSent()
//{
// float bytesSent = bytesSentPerformanceCounter.RawValue;
// return bytesSent;
//}
//public float GetBytesReceived()
//{
// float bytesReceived = bytesReceivedPerformanceCounter.RawValue;
// return bytesReceived;
//}
private static List<string> GetInstanceName()
{
// Used Reflector to find the correct formatting:
string assemblyName = GetAssemblyName();
if ((assemblyName == null) || (assemblyName.Length == 0))
{
assemblyName = AppDomain.CurrentDomain.FriendlyName;
}
StringBuilder builder = new StringBuilder(assemblyName);
for (int i = 0; i < builder.Length; i++)
{
switch (builder[i])
{
case '/':
case '\\':
case '#':
builder[i] = '_';
break;
case '(':
builder[i] = '[';
break;
case ')':
builder[i] = ']';
break;
}
}
List<string> listInstanceName = new List<string>();
Process[] listProcess = Process.GetProcesses();
string InstanceName;
foreach (Process pro in listProcess)
{
InstanceName = string.Format(CultureInfo.CurrentCulture,
"{0}[{1}]",
builder.ToString(),
pro.Id);
listInstanceName.Add(InstanceName);
}
return listInstanceName;
}
private static string GetAssemblyName()
{
string str = null;
Assembly entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
{
AssemblyName name = entryAssembly.GetName();
if (name != null)
{
str = name.Name;
}
}
return str;
}
public static void Main()
{
NetworkTraffic networkTraffic = new NetworkTraffic();
try
{
while (true)
{
WebRequest webRequest = WebRequest.Create("http://www.google.com");
webRequest.Method = "GET";
using (WebResponse response = webRequest.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
}
//Console.WriteLine("Bytes sent: {0}", networkTraffic.GetBytesSent());
//Console.WriteLine("Bytes received: {0}", networkTraffic.GetBytesReceived());
foreach (PerformanceCounter send in networkTraffic.listBytesSentPerformanceCounter)
{
Console.WriteLine("Instance name: " + send.InstanceName + " Sent: " + send.RawValue);
}
Thread.Sleep(1000);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}
Anyone can help me resolve this.
I have a WCF Service and i want to invoke this at run time ...
if i do the same code and instead of WCF(.svc) if i call (.asmx) i can able to get through and getting results... but here WCF gets failed
private void button1_Click(object sender, EventArgs e)
{
string WebserviceUrl = "http://localhost:90/service1/service1.svc";
string serviceName = Service1;
string methodName = GetData;
string[] arArguments = new string[2];
arArguments[0] = 2 ;
string sData =CallWebService(WebserviceUrl, serviceName, methodName, arArguments);
if (!string.IsNullOrEmpty(sData))
MessageBox.Show(sData + "\tData Available");
else
MessageBox.Show(sData + "\tData not Available");
}
[SecurityPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
private string CallWebService(string WebserviceUrl, string serviceName, string methodName, string[] arArguments)
{
System.Net.WebClient client = new System.Net.WebClient();
System.IO.Stream stream = client.OpenRead(WebserviceUrl + "?wsdl");
ServiceDescription description = ServiceDescription.Read(stream);
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12";
importer.AddServiceDescription(description, null, null);
importer.Style = ServiceDescriptionImportStyle.Client;
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
CodeNamespace nmspace = new CodeNamespace();
CodeCompileUnit unit1 = new CodeCompileUnit();
unit1.Namespaces.Add(nmspace);
ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
if (warning == 0) // If Successfull
{
CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };
CompilerParameters parms = new CompilerParameters(assemblyReferences);
CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
if (results.Errors.Count > 0) // Error Part
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window.");
}
object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Name;
}
else
{
return null;
}
}
how to achieve this .....
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"});