Connecting to Sun One Directory Server through VS.NET

I am trying to connect to Sun One Directory Server through VB.NET or C# as per our project's requirement. I have tried a code that is given below:

protected void Button1_Click(object sender, EventArgs e)

{

DirectoryEntry oDE;

oDE = new DirectoryEntry("LDAP://Schawda.calance.com:25243/uid=admin,ou=administrators,ou=topologymanagement,o=netscaperoot,dc=calance,dc=com", "admin", "1", AuthenticationTypes.Secure);

DirectorySearcher deSearch = new DirectorySearcher();

deSearch.SearchRoot = oDE;

try

{

deSearch.Filter = "(&(objectClass=user)(uid=*)";

deSearch.SearchScope = SearchScope.Subtree;

SearchResult results = deSearch.FindOne();

if (!(results == null))

{

oDE = new DirectoryEntry(results.Path, "admin", "1", AuthenticationTypes.Secure);

if (oDE.Properties["cn"] != null && oDE.Properties["cn"].Value != null)

{

TextBox1.Text = oDE.Properties["cn"].Value.ToString();

}

}

}

catch (Exception ex)

{

Response.Write("Error occured: " + ex.Message);

}

}

But this code gives me an error "The Server is Not Operational"

I have also tried one more code with different classes available in .NET

That is:

protected void Button1_Click(object sender, EventArgs e)

{

string server = "LDAP://Schawda.calance.com:25242/dc=calance,dc=com";

string dn = "ou=people,dc=calance,dc=com";

//string objclass = "organizationalPerson";

try

{

LdapConnection connect = new LdapConnection(server);

NetworkCredential creds = new NetworkCredential(

"uid=SChawda",

"1", dn);

connect.Credential = creds;

connect.Bind(creds);

TextBox1.Text = "The Server Response was successful";

connect.SessionOptions.ProtocolVersion = 3;

}

catch (Exception ex)

{

Console.WriteLine("\nUnexpected exception occured: {0}",

ex.Message);

}

}

And this code gives me an error "The LDAP Server is unavailable"

Can Anyone Please help me to resolve this issue as soon as possible.

And please help me to connect the sun one directory server with .NET. I'll appreciate your genuine helps. Thank you.

Message was edited by:

.NETPROF

[2330 byte] By [.NETPROFa] at [2007-11-27 2:49:20]
# 1

My job is nearly done :-) A question on .NET programming on the Sun Java forum !

The server is not operational message indicates that either the server name or port number are incorrect.

Verify that your Sun One Directory Server name is really schwada.calance.com. For example can you successfully ping it or resolve its name with nslookup ?

Verify that the port number is correct. In your two code samples you have two different port numbers, 25243 and 25242. The default LDAP port number is 389.

Finally, are you sure you have correctly specified the parameters to the DirectoryEntry constructor ?

The constructor takes four parameters;New (path as String, username as String, password as String, authenticationType as System.DirectoryServices.AuthenticationTypes)

Do you really mean to connect to the directory object "LDAP://Schawda.calance.com:25243/uid=admin,ou=administrators,ou=topologymanagement,o=netscaperoot,dc=calance,dc=com"

with user name of "admin"

and a password of "1"

or did you mean to connect as the following:String LDAPURL = "("LDAP://Schawda.calance.com:25243";

String username = "uid=admin,ou=administrators,ou=topologymanagement,o=netscaperoot,dc=calance,dc=com";

String password = "admin";

oDE = new DirectoryEntry(LDAPURL, username,password,AuthenticationTypes.Secure);

BTW, AuthenticationTypes.Secure means to use either NTLM or Kerberos to authenticate the user, or if username & password are null, to use the credentials of the currently logged in user. Perhaps you meant to use LDAP Simple Bind in which case you should probably be using something like:oDE = new DirectoryEntry(LDAPURL, username,password, AuthenticationTypes.None);

adler_stevena at 2007-7-12 3:20:32 > top of Java-index,Core,Core APIs...
# 2

Hii! thank you very much for your genuine reply. I have tried to implement the way u adviced me to pass the urls, username and password. This time wat i have done is:

String LDAPURL = "LDAP://Schawda.calance.com:25243";

String username ="uid=admin,ou=administrators,ou=topologymanagement,o=netscaperoot,dc=calance,dc=com";

String password = "1";

DirectoryEntry oDE;

oDE = new DirectoryEntry(LDAPURL, username, password, AuthenticationTypes.None);

DirectorySearcher deSearch = new DirectorySearcher();

deSearch.SearchRoot = oDE;

try

{

deSearch.Filter = "(&(objectClass=user)(uid=*)";

deSearch.SearchScope = SearchScope.Subtree;

int results = deSearch.FindOne();

if (!(results == null))

{

//oDE = new DirectoryEntry(results.Path, "admin", "1", AuthenticationTypes.Secure);

if (oDE.Properties["givenname"] != null && oDE.Properties["givenname"].Value != null)

{

TextBox1.Text = oDE.Properties["cn"].Value.ToString();

}

}

}

catch (Exception ex)

{

Response.Write("Error occured: " + ex.Message);

}

This is the code that i tried this time but again it gives an error and this time the error is "This operation returned because the timeout period expired."

Hence, I am still not clear how to connect to Sun One Directory Server 5.2 using C#.

What is the better way to connect: using DirectoryEntry() or Using LDAPConnection Class. I have used both the types for creating connection as i have shown in my previous post. but Both didn't work. Kindly help me to send the exact code to make a connection with Sun Directory server and authenticating user into that directory server with the help of his user name and password.

Thanking you. Waiting for a good reply as soon as possible.

.NETPROFa at 2007-7-12 3:20:32 > top of Java-index,Core,Core APIs...
# 3

Having a quiet chuckle to myself as I post some C# and Visual Basic code on a Sun Java forum !

Now all I have to do is convince you to use Active Directory ;-)

Here is a very basic C# console application.using System;

using System.Text;

using System.DirectoryServices;

using System.Collections.Generic;

namespace csharpsun

{

class Program

{

static void Main(string[] args)

{

String strLDAP = "LDAP://steveadsunone.antipodes.com:25941/dc=antipodes,dc=com";

String strAdmin = "uid=Administrator,ou=Administrators,ou=TopologyManagement,o=netscaperoot";

String strPassword = "XXXXXX";

String strFilter = "(&(objectClass=inetorgperson)(mail=*))";

String[] strAttribs = {"cn", "givenName","sn","mail"};

DirectoryEntry objDE;

try

{

objDE = new DirectoryEntry(strLDAP, strAdmin, strPassword, AuthenticationTypes.None);

DirectorySearcher objDS = new DirectorySearcher();

objDS.SearchRoot = objDE;

objDS.SearchScope = SearchScope.Subtree;

objDS.Filter = strFilter;

objDS.PropertiesToLoad.AddRange(strAttribs);

SearchResultCollection results = objDS.FindAll();

if (!results.Equals(null))

{

foreach (SearchResult result in results)

{

Console.WriteLine(result.Path);

ResultPropertyCollection propColl = result.Properties;

foreach (String strKey in propColl.PropertyNames)

{

foreach (Object objProp in propColl[strKey])

{

Console.WriteLine(String.Concat(strKey, ": ", result.Properties[strKey][0]));

}

}

}

}

}

catch (Exception ex)

{

Console.WriteLine(String.Concat("exception: ",ex.Message));

}

}

}

}

and for completeness, an example in Visual BasicImports System.DirectoryServices

Module Module1

Sub Main()

Dim strLDAP As String = "LDAP://steveadsunone.antipodes.com:25941/dc=antipodes,dc=com"

Dim strAdmin As String = "uid=Administrator,ou=Administrators,ou=TopologyManagement,o=netscaperoot"

Dim strPassword As String = "XXXXX"

Dim strFilter As String = "(&(objectClass=inetorgperson)(mail=*))"

Dim strAttribs As String() = {"cn", "givenName","sn","mail"}

Dim objDE As DirectoryEntry

Try

objDE = New DirectoryEntry(strLDAP, strAdmin, strPassword, AuthenticationTypes.None)

Dim objDS As DirectorySearcher = New DirectorySearcher

objDS.SearchRoot = objDE

objDS.SearchScope = SearchScope.Subtree

objDS.Filter = strFilter

objDS.PropertiesToLoad.AddRange(strAttribs)

Dim results As SearchResultCollection = objDS.FindAll

If Not (results.Equals(vbNull)) Then

Dim result As SearchResult

For Each result In results

Console.WriteLine(result.Path)

Dim propColl As ResultPropertyCollection = result.Properties

Dim strKey As String

Dim objProp As Object

For Each strKey In propColl.PropertyNames

For Each objProp In propColl(strKey)

Console.WriteLine(String.Concat(strKey, ": ", result.Properties(strKey)(0)))

Next

Next

Next

End If

Catch ex As ActiveDirectory.ActiveDirectoryObjectNotFoundException

Console.WriteLine(String.Concat("object not found",vbCRLF,ex.Message))

Catch ex As ActiveDirectory.ActiveDirectoryOperationException

Console.WriteLine(String.Concat("Operation Exception",vbCrLf,ex.Message))

Catch ex As ActiveDirectory.ActiveDirectoryServerDownException

Console.WriteLine(String.Concat("Server Down",vbCrLf,ex.Message))

Catch ex As Exception

Console.WriteLine(String.Concat("Some other exception" ,vbCrLf ,ex.Message))

End Try

End Sub

End Module

In your last sample, I can see three obvious errors.

1. The LDAP URL doesn't have a naming component. It should be something likeString LDAPURL = "LDAP://Schawda.calance.com:25243/dc=calance,dc=com";

2. Your username may be incorrect. Verify using theSun Java System Directory Server console. On my installation the default configuration administrator is:"uid=Administrator,ou=Administrators,ou=TopologyManagement,o=netscaperoot"

3. Incorrect LDAP query filter, you're missing a trailing bracket.deSearch.Filter = "(&(objectClass=user)(uid=*))";

Although this should have raised an exception for an invalid filter.

adler_stevena at 2007-7-12 3:20:33 > top of Java-index,Core,Core APIs...
# 4

Hi Mr. Steven,

I appreciate your advice but i m sorry i won't be able to do that. Bcoz this is a project that has been given to me by my project manager in my company. And It is our company's client's wish to use Sun One Directory Server 5.2. Hence, we can't use Active Directory for this. We have to get the solution anyhow. One More Time i would like to post the code after implementing your suggestions. Here is the code :

String LDAPURL = "LDAP://Schawda.calance.com:25243/dc=calance,dc=com";

String username = "uid=admin,ou=administrators,ou=topologymanagement,o=netscaperoot";

String password = "1";

DirectoryEntry oDE;

oDE = new DirectoryEntry(LDAPURL, username, password, AuthenticationTypes.None);

DirectorySearcher deSearch = new DirectorySearcher();

deSearch.SearchRoot = oDE;

try

{

deSearch.Filter = "(&(objectClass=user)(uid=*))";

deSearch.SearchScope = SearchScope.Subtree;

int results = deSearch.PropertiesToLoad.Add("givenname");

if ((results == 0))

{

//oDE = new DirectoryEntry(results.Path, "admin", "1", AuthenticationTypes.Secure);

if (oDE.Properties["givenname"] != null && oDE.Properties["givenname"].Value != null)

{

TextBox1.Text = oDE.Properties["cn"].Value.ToString();

}

}

}

catch (Exception ex)

{

Response.Write("Error occured: " + ex.Message);

}

But Still I m getting an error : "This operation returned because the timeout period expired." Kindly please show me the way to resolve this issue. Thanks for your all types of helps

.NETPROFa at 2007-7-12 3:20:33 > top of Java-index,Core,Core APIs...
# 5

[nobr]Huh !

I have given you a perfectly good, working piece of sample code that demonstrates how to use both C# and Visual Basic and System.Directory Services to query a Sun One Directory Server.

Have you tested my code sample in your environment ?

One of the reasons why a LDAP Server may timeout whilst performing a query is that either there are lots of entries in the directory (perhaps in the order of tens or hundreds of thousands, even millions), or that your query string is complex and not taking advantage of indexed attributes. The only way to fix that is to ensure that your query is efficient and uses the appropriate indexes.

And BTW, there are still bugs in your code. int results = deSearch.PropertiesToLoad.Add("givenname");

PropertiesToLoad gets a value indicating the list of properties to retrieve during the search. It doesn't perform the search, you need to use execute either FindOne or FindAll methods. Have a read of the DirectorySearcher class at http://msdn2.microsoft.com/en-us/library/system.directoryservices.directorysearcher_members.aspx

And just for good measure, seeing as though you are doing this with a web server, here's the same sample code running within ASP.NET.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

Enter in the users first name: (Eg. John)<br />

<input id="Text1" runat="server" style="width: 231px" type="text" /><br />

<br />

?lt;input id="Submit1" runat="server" onserverclick="Submit1_ServerClick" type="submit"

value="submit" />

<br />

<br />

<textarea id="TextArea1" runat="server" style="width: 528px; height: 133px"></textarea></div>

</form>

</body>

</html>

and the code behind the ASP.NET web pageusing System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.DirectoryServices;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Submit1_ServerClick(object sender, EventArgs e)

{

String strLDAP = "LDAP://steveadsunone.antipodes.com:25941/dc=antipodes,dc=com";

String strAdmin = "uid=Administrator,ou=Administrators,ou=TopologyManagement,o=netscaperoot";

String strPassword = "XXXXXX";

String[] strAttribs = { "cn", "givenName", "sn", "mail" };

DirectoryEntry objDE;

try

{

objDE = new DirectoryEntry(strLDAP, strAdmin, strPassword, AuthenticationTypes.None);

DirectorySearcher objDS = new DirectorySearcher();

objDS.SearchRoot = objDE;

objDS.SearchScope = SearchScope.Subtree;

objDS.Filter = String.Concat("(givenName=", Text1.Value, ")");

objDS.PropertiesToLoad.AddRange(strAttribs);

SearchResultCollection results = objDS.FindAll();

if (!results.Equals(null))

{

foreach (SearchResult result in results)

{

ResultPropertyCollection propColl = result.Properties;

foreach (String strKey in propColl.PropertyNames)

{

foreach (Object objProp in propColl[strKey])

{

TextArea1.Value += (String.Concat("\r\n",strKey, ": ", result.Properties[strKey][0]));

}

}

}

}

}

catch (Exception ex)

{

Response.Write(String.Concat("Exception", "\r\n", ex.Message));

}

}

}

As I've stated before, I'm not a developer, so this code may not be the most elegant, nor am I a web designer, but I can guarantee that these samples definitely work against a SunOne Directory Server.[/nobr]

adler_stevena at 2007-7-12 3:20:33 > top of Java-index,Core,Core APIs...
# 6

Thank you very much for your help Mr. Steven Finally my code has started executing Thank you so much. I know I have become an irritating element for you. But this i have a different issue however that may be a very small thing for you but not for me. hence i would kindly request you to help me I am almost nearabout my solution. I have tried the following code to authenticate the user to enter into the directory server and display the user attributes on the webpage. The code i have written is:

DirectoryEntry de = new DirectoryEntry(strDomain, strUser, strPass, authtype);

DirectorySearcher desrch = new DirectorySearcher(de);

SearchResultCollection results;

desrch.Filter = "uid=SChawda,ou=people";

try

{

results = desrch.FindAll();

if (results.Count > 0)

{

foreach (SearchResult resent in results)

{

ResultPropertyCollection respropcoll = resent.Properties;

foreach (string keys in respropcoll.PropertyNames)

{

foreach (object values in respropcoll[keys])

{

Label4.Text += "Your Attributes are: " + values.ToString();

}

}

}

}

}

catch (Exception ex)

{

Label4.Text = ex.Message;

}

and The entries that i m entering into text boxes are :

Domain : LDAP://Schawda.calance.com:25242/dc=calance,dc=com

UserName : SChawda

Password : 1

But when i press LogOn Button it gives me error "An invalid dn syntax has been specified" at the line : results = desrch.FindAll();

i have also tried Username as "uid=SChawda,ou=people", "uid=SChawda,ou=People","SChawda,ou=people" and "uid=SChawda,ou=people,dc=calance,dc=com" as my user is under organizationalUnit=People,dc=calance,dc=com

Hence kindly please send me the solution for that I would be grateful to you. Thankyou so much for ur great support.

.NETPROFa at 2007-7-12 3:20:33 > top of Java-index,Core,Core APIs...
# 7

Please read either the JNDI Tutorial http://java.sun.com/products/jndi/tutorial/ or search for some information about LDAP http://www.google.ie/search?hl=en&q=ldap+for+dummies&meta=

Without knowing your directory structure and what objectClasses you have instantiated, how can I know what your user names are ?

I suggest that you either run the sample code and list out the full distinguished names of your users , or use the Sun Java System Directory Server console to view your user objects.

Depending on what objectClass you are using and from the limited information you have provided, I would hazard a guess and suggest that a valid user name could beuid=SChawda,ou=people,dc=calance,dc=com

cn=SChawda,ou=people,dc=calance,dc=com

cn=Sam Chawda,ou=people,dc=calance,dc=com

adler_stevena at 2007-7-12 3:20:33 > top of Java-index,Core,Core APIs...