using System;
using System.Collections.Generic;
using System.Configuration;
using System.Security.Cryptography;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Text;
using System.Web.Services;
namespace HostControl
{
public partial class OpenJob
{
protected global::AjaxControlToolkit.ToolkitScriptManager ScriptManager1;
protected global::System.Web.UI.WebControls.TextBox txtUserName;
protected global::AjaxControlToolkit.AutoCompleteExtender AutoCompleteExtender1;
protected global::System.Web.UI.WebControls.Button btnGetInfo;
protected global::System.Web.UI.WebControls.Label lblEmail;
protected global::System.Web.UI.WebControls.Label lblEmailResult;
protected global::System.Web.UI.WebControls.Label lblPhone;
protected global::System.Web.UI.WebControls.Label lblPhoneResult;
}
}
public partial class tickets_create : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
RetrieveListOfCompanies();
RetrieveListOfTicketOwners();
RetrieveListOfRequestTypes();
//RetrieveListOfUserRequestChange();
}
protected void RetrieveListOfCompanies()
{
ddlCompany.AppendDataBoundItems = true;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CMDB"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "RetrieveListOfCompanies";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
try
{
conn.Open();
ddlCompany.DataSource = cmd.ExecuteReader();
ddlCompany.DataValueField = "com_id";
ddlCompany.DataTextField = "com_name";
ddlCompany.DataBind();
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
}
protected void RetrieveListOfTicketOwners()
{
ddlTicketOwner.AppendDataBoundItems = true;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CMDB"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "RetrieveListOfTicketOwners";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
try
{
conn.Open();
ddlTicketOwner.DataSource = cmd.ExecuteReader();
ddlTicketOwner.DataValueField = "ownr_id";
ddlTicketOwner.DataTextField = "OwnerFullName";
ddlTicketOwner.DataBind();
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
}
protected void RetrieveListOfRequestTypes()
{
ddlRequestType.AppendDataBoundItems = true;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CMDB"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "RetrieveListOfRequestTypes";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
try
{
conn.Open();
ddlRequestType.DataSource = cmd.ExecuteReader();
ddlRequestType.DataValueField = "req_typ_id";
ddlRequestType.DataTextField = "req_typ_name";
ddlRequestType.DataBind();
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
}
protected void btnCreateNewTicket_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
if (fuAttachFile.HasFile)
{
string extension = Path.GetExtension(fuAttachFile.PostedFile.FileName).ToLower();
string MIMEType = null;
switch (extension)
{
case ".pdf":
MIMEType = "application/pdf";
break;
case ".doc":
MIMEType = "application/msword";
break;
case ".xls":
MIMEType = "application/vnd.ms-excel";
break;
case ".txt":
MIMEType = "text/plain";
break;
case ".png":
MIMEType = "image/png";
break;
case ".jpg":
MIMEType = "image/jpeg";
break;
case ".jpeg":
MIMEType = "image/jpeg";
break;
case ".vsd":
MIMEType = "application/vnd.visio";
break;
default:
lblFileTypeError.Visible = true;
lblFileTypeError.Text = "Please choose correct file format.";
return;
}
string filename = fuAttachFile.PostedFile.FileName.Split(new char[] { '\\' }).Last();
int fileSize = fuAttachFile.PostedFile.ContentLength;
if ((fileSize < 1048576))
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CMDB"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "InsertNewTicket";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
// Load InputStream into Byte array
byte[] imageBytes = new byte[fuAttachFile.PostedFile.InputStream.Length + 1];
fuAttachFile.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
//cmd.Parameters.AddWithValue("@usr_req_chg_id", SqlDbType.Int).Value = ddlUserRequestingChange.SelectedItem.Value;
cmd.Parameters.AddWithValue("@req_typ_id", SqlDbType.Int).Value = ddlRequestType.SelectedItem.Value;
cmd.Parameters.AddWithValue("@com_id", SqlDbType.Int).Value = ddlCompany.SelectedItem.Value;
cmd.Parameters.AddWithValue("@ownr_id", SqlDbType.Int).Value = ddlTicketOwner.SelectedItem.Value;
cmd.Parameters.AddWithValue("@tkt_desc", SqlDbType.VarChar).Value = txtTicketDesc.Text;
cmd.Parameters.AddWithValue("@tkt_file", SqlDbType.Image).Value = imageBytes;
cmd.Parameters.AddWithValue("@tkt_filename", SqlDbType.VarChar).Value = filename;
cmd.Parameters.AddWithValue("@tkt_mime", SqlDbType.VarChar).Value = MIMEType;
cmd.Parameters.AddWithValue("@tkt_size", SqlDbType.VarChar).Value = fileSize;
cmd.Parameters.AddWithValue("@sts_id", SqlDbType.Int).Value = 71;
string username = User.Identity.Name;
if (username.Contains('\\'))
{ username = username.Split('\\')[1]; }
cmd.Parameters.AddWithValue("@tkt_cre_user", SqlDbType.VarChar).Value = username;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
lblInsertError.Visible = true;
lblInsertError.Text = ("Error on insert: " + ex.Message.ToString());
}
finally
{
Response.Redirect("index.aspx");
conn.Close();
}
}
else
{
lblFileSize.Visible = true;
lblFileSize.Text = "File size must be 1MB or smaller.";
}
}
else // no file has been uploaded, we only need to update txtPhysicalDateCompleted
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CMDB"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "InsertNewTicket";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
byte[] imageBytes = new byte[1];
//cmd.Parameters.AddWithValue("@usr_req_chg_id", SqlDbType.Int).Value = ddlUserRequestingChange.SelectedItem.Value;
cmd.Parameters.AddWithValue("@req_typ_id", SqlDbType.Int).Value = ddlRequestType.SelectedItem.Value;
cmd.Parameters.AddWithValue("@com_id", SqlDbType.Int).Value = ddlCompany.SelectedItem.Value;
cmd.Parameters.AddWithValue("@ownr_id", SqlDbType.Int).Value = ddlTicketOwner.SelectedItem.Value;
cmd.Parameters.AddWithValue("@tkt_desc", SqlDbType.VarChar).Value = txtTicketDesc.Text;
cmd.Parameters.AddWithValue("@tkt_file", SqlDbType.Image).Value = imageBytes;
cmd.Parameters.AddWithValue("@tkt_filename", SqlDbType.VarChar).Value = "";
cmd.Parameters.AddWithValue("@tkt_mime", SqlDbType.VarChar).Value = "application/octet-stream";
cmd.Parameters.AddWithValue("@tkt_size", SqlDbType.VarChar).Value = 0;
cmd.Parameters.AddWithValue("@sts_id", SqlDbType.Int).Value = 71;
string username = User.Identity.Name;
if (username.Contains('\\'))
{ username = username.Split('\\')[1]; }
cmd.Parameters.AddWithValue("@tkt_cre_user", SqlDbType.VarChar).Value = username;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
lblInsertError.Visible = true;
lblInsertError.Text = ("Error on insert: " + ex.Message.ToString());
}
finally
{
Response.Redirect("index.aspx");
conn.Close();
}
}
}
}
}
Unhandled exception at line 3, column 412 in http://localhost:49426/CMDB/tickets/create.aspx?_TSM_HiddenField_=ToolkitScriptManager1_HiddenField&_TSM_CombinedScripts_=;;AjaxControlToolkit,+Version=4.1.60919.0,+Culture=neutral,+PublicKeyToken=28f01b0e84b6d53e:en-US:ee051b62-9cd6-49a5-87bb-93c07bc43d63:de1feab2:f2c8e708:720a52bf:f9cec9bc:589eaa30:698129cf:7a92f56c
0x800a139e - Microsoft JScript runtime error: AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of the scripts are referenced. If you are using an ASP.NET ScriptManager, switch to the ToolkitScriptManager in AjaxControlToolkit.dll.
Unhandled exception at line 205, column 5 in http://localhost:49426/CMDB/tickets/create.aspx
0x800a138f - Microsoft JScript runtime error: Unable to get value of the property 'UI': object is null or undefined
$create(Sys.Extended.UI.AutoCompleteBehavior, {"delimiterCharacters":"","id":"AutoCompleteExtender1","serviceMethod":"finduser","servicePath":"WebService.asmx"}, null, null, $get("txtUserName"));
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.DirectoryServices;
/// <summary>
/// Summary description for ADS
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class ADS : System.Web.Services.WebService {
[WebMethod]
public string[] findEmp(string prefixText, int count)
{
System.DirectoryServices.DirectoryEntry directory = new System.DirectoryServices.DirectoryEntry();
directory.Path = "LDAP://occo.local"; //CHANGE to your LDAP path
string filter = "(&(cn=" + prefixText + "*))";
string[] strCats = { "cn" };
List<string> items = new List<string>();
System.DirectoryServices.DirectorySearcher dirComp = new System.DirectoryServices.DirectorySearcher(directory, filter, strCats, System.DirectoryServices.SearchScope.Subtree);
System.DirectoryServices.SearchResultCollection results = dirComp.FindAll();
foreach (SearchResult result in results)
{
foreach (DictionaryEntry prop in result.Properties)
{
if (prop.Key.Equals("cn"))
{
System.Collections.IEnumerable propsEnum = prop.Value as System.Collections.IEnumerable;
foreach (object individualValue in propsEnum)
{
if (individualValue.ToString().IndexOf(prefixText) != 0)
{
items.Add(individualValue.ToString());
}
}
}
}
}
return items.ToArray();
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<div>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" ServiceMethod="findEmp"
MinimumPrefixLength="3"
CompletionInterval="100"
EnableCaching="true"
CompletionSetCount="10"
TargetControlID="txtUserName"
runat="server" FirstRowSelected="false" ServicePath="~/App_Code/ADS.cs"></asp:AutoCompleteExtender>
<br />
</div>
</form>
</body>
</html>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.DirectoryServices;
/// <summary>
/// Summary description for ADS
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class ADS : System.Web.Services.WebService {
[WebMethod]
public string[] findEmp(string prefixText, int count)
{
System.DirectoryServices.DirectoryEntry directory = new System.DirectoryServices.DirectoryEntry();
directory.Path = "LDAP://DC=yourdomain,DC=com"; //CHANGE to your LDAP path
string filter = "(&(cn=" + prefixText + "*))";
string[] strCats = { "cn" };
List<string> items = new List<string>();
System.DirectoryServices.DirectorySearcher dirComp = new System.DirectoryServices.DirectorySearcher(directory, filter, strCats, System.DirectoryServices.SearchScope.Subtree);
System.DirectoryServices.SearchResultCollection results = dirComp.FindAll();
foreach (SearchResult result in results)
{
foreach (DictionaryEntry prop in result.Properties)
{
if (prop.Key.Equals("cn"))
{
System.Collections.IEnumerable propsEnum = prop.Value as System.Collections.IEnumerable;
foreach (object individualValue in propsEnum)
{
if (individualValue.ToString().IndexOf(prefixText) != 0)
{
items.Add(individualValue.ToString());
}
}
}
}
}
return items.ToArray();
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="WebApplication3.index" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" ></ajax:ToolkitScriptManager>
<div>
<asp:TextBox ID="txtUserName" runat="server" AutoCompleteType="None"></asp:TextBox>
<ajax:AutoCompleteExtender ID="AutoCompleteExtender1" ServiceMethod="findEmp"
MinimumPrefixLength="2"
CompletionInterval="100"
EnableCaching="true"
CompletionSetCount="10"
TargetControlID="txtUserName"
runat="server" ></ajax:AutoCompleteExtender>
<br />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string[] findEmp(string prefixText, int count)
{
List<string> items = new List<string>();
return items.ToArray();
}
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<div>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" ServiceMethod="findEmp" MinimumPrefixLength="3" CompletionInterval="100" EnableCaching="true" CompletionSetCount="10"
TargetControlID="txtUserName" runat="server" FirstRowSelected="false"></asp:AutoCompleteExtender>
<br />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string[] findEmp(string prefixText, int count)
{
List<string> items = new List<string>();
return items.ToArray();
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
<%--<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>--%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="jquery-ui-1.9.2.custom.min.css" rel="stylesheet" />
<script src="Scripts/jquery-1.8.3.js"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.min.js"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.js"></script>
<script>
$(function () { var availableTags = ["ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme"]; $("#tags").autocomplete({ source: availableTags }); });
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="tags" />
<%-- <asp:ToolkitScriptManager ID="ToolkitScriptManager1" EnablePageMethods="True" runat="server"></asp:ToolkitScriptManager>
<asp:TextBox ID="txtADSearch" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1"
ServiceMethod="findit"
MinimumPrefixLength="3"
CompletionInterval="100"
EnableCaching="true"
CompletionSetCount="10"
TargetControlID="txtADSearch"
FirstRowSelected="false"
ServicePath="~/ADS.asmx"
runat="server">
</asp:AutoCompleteExtender>--%>
</form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="jquery-ui-1.9.2.custom.min.css" rel="stylesheet" />
<script src="Scripts/jquery-1.8.3.js"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.min.js"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.js"></script>
<script type="text/javascript">
$(function () {
$('#<%= txtName.ClientID %>').autocomplete({
source: "ADS.asmx"
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</form>
</body>
</html>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.DirectoryServices;
namespace HostControl
{
[WebService(Namespace = "http://localhost/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ads : System.Web.Services.WebService
{
[WebMethod]
public string[] findit(string prefixText, int count)
{
DirectoryEntry directory = new DirectoryEntry("LDAP://n-acdir:389");
string filter = "(&(cn=" + prefixText + "*))";
string[] strCats = { "cn" };
List<string> items = new List<string>();
DirectorySearcher dirComp = new DirectorySearcher(directory, filter, strCats, SearchScope.Subtree);
SearchResultCollection results = dirComp.FindAll();
foreach (SearchResult result in results)
{
foreach (DictionaryEntry prop in result.Properties)
{
if (prop.Key.Equals("cn"))
{
System.Collections.IEnumerable propsEnum = prop.Value as System.Collections.IEnumerable;
foreach (object individualValue in propsEnum)
{
if (individualValue.ToString().IndexOf(prefixText) != 0)
{
items.Add(individualValue.ToString());
}
}
}
}
}
return items.ToArray();
}
}
}
$('#<%= txtName.ClientID %>').autocomplete({
source: function(request, response) {
$.ajax({
url: "ADS.asmx/findit",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
public static string FriendlyDomainToLdapDomain(string friendlyDomainName)
{
string ldapPath = null;
try
{
DirectoryContext objContext = new DirectoryContext(
DirectoryContextType.Domain, friendlyDomainName);
Domain objDomain = Domain.GetDomain(objContext);
ldapPath = objDomain.Name;
}
catch (DirectoryServicesCOMException e)
{
ldapPath = e.Message.ToString();
}
return ldapPath;
}
public static string GetDomainDN(string domain)
{
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain);
Domain d = Domain.GetDomain(context);
DirectoryEntry de = d.GetDirectoryEntry();
return de.Properties["DistinguishedName"].Value.ToString();
}
public static List<string> GetADUsers2_0(string searchTerm)
{
List<string> res = new List<string>();
// define a directory searcher for your default context
string searchRootLDAPPath = GetDomainDN(Domain.GetCurrentDomain().Name);
using (DirectoryEntry defaultDE = new DirectoryEntry(String.Format("LDAP://{0}", searchRootLDAPPath)))
{
// define searcher - search through entire subtree, search for users
// (objectCategory=Person)
using (DirectorySearcher dsAllUsers = new DirectorySearcher(defaultDE))
{
dsAllUsers.SearchScope = SearchScope.Subtree;
dsAllUsers.Filter = String.Format("(&(objectCategory=person)(objectClass=user)(cn={0}*))", searchTerm);
// get the results
SearchResultCollection result = dsAllUsers.FindAll();
foreach (SearchResult searchResult in result)
{
res.Add(searchResult.GetDirectoryEntry().Name.Remove(0, 3)); //removing the CN=
}
}
}
return res;
}
private static List<string> GetADUsers(string searchTerm)
{
List<string> res = new List<string>();
using (var context = new PrincipalContext(ContextType.Domain, Domain.GetCurrentDomain().Name))
{
// create a principal object representation to describe
// what will be searched
UserPrincipal user = new UserPrincipal(context);
// define the properties of the search (this can use wildcards)
user.Enabled = true;
user.Name = String.Format("{0}*", searchTerm);
// create a principal searcher for running a search operation
using (PrincipalSearcher pS = new PrincipalSearcher())
{
// assign the query filter property for the principal object
// you created
// you can also pass the user principal in the
// PrincipalSearcher constructor
pS.QueryFilter = user;
// run the query
PrincipalSearchResult<Principal> results = pS.FindAll();
foreach (Principal result in results)
{
res.Add(result.Name);
}
}
}
return res;
}
In order for this to work you have to add reference to System.DirectoryServices.Apublic static string GetDomainDN(string domain)
{
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain);
Domain d = Domain.GetDomain(context);
DirectoryEntry de = d.GetDirectoryEntry();
return de.Properties["DistinguishedName"].Value.ToString();
}
[WebMethod]
public List<string> GetADUsers(string term)
{
List<string> res = new List<string>();
// define a directory searcher for your default context
string searchRootLDAPPath = GetDomainDN(Domain.GetCurrentDomain().Name);
using (DirectoryEntry defaultDE = new DirectoryEntry(String.Format("LDAP://{0}", searchRootLDAPPath)))
{
// define searcher - search through entire subtree, search for users
// (objectCategory=Person)
using (DirectorySearcher dsAllUsers = new DirectorySearcher(defaultDE))
{
dsAllUsers.SearchScope = SearchScope.Subtree;
dsAllUsers.Filter = String.Format("(&(objectCategory=person)(objectClass=user)(cn={0}*))", term);
// get the results
SearchResultCollection result = dsAllUsers.FindAll();
foreach (SearchResult searchResult in result)
{
res.Add(searchResult.GetDirectoryEntry().Name.Remove(0, 3)); //removing the CN=
}
}
}
return res;
}
<script type="text/javascript">
$(function() {
$("#<%= txtName.ClientID %>").autocomplete({
source: function(request, response) {
$.ajax({
url: "ADS.asmx/GetADUsers",
data: "{ 'term': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
[WebService(Namespace = "http://localhost")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ads : System.Web.Services.WebService
{
[WebMethod]
public static string GetDomainDN(string domain)
{
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain);
Domain d = Domain.GetDomain(context);
DirectoryEntry de = d.GetDirectoryEntry();
return de.Properties["DistinguishedName"].Value.ToString();
}
[WebMethod]
public List<string> GetADUsers(string term)
{
List<string> res = new List<string>();
// define a directory searcher for your default context
string searchRootLDAPPath = GetDomainDN(Domain.GetCurrentDomain().Name);
using (DirectoryEntry defaultDE = new DirectoryEntry(String.Format("LDAP://{0}", searchRootLDAPPath)))
{
// define searcher - search through entire subtree, search for users
// (objectCategory=Person)
using (DirectorySearcher dsAllUsers = new DirectorySearcher(defaultDE))
{
dsAllUsers.SearchScope = SearchScope.Subtree;
dsAllUsers.Filter = String.Format("(&(objectCategory=person)(objectClass=user)(cn={0}*))", term);
// get the results
SearchResultCollection result = dsAllUsers.FindAll();
foreach (SearchResult searchResult in result)
{
res.Add(searchResult.GetDirectoryEntry().Name.Remove(0, 3)); //removing the CN=
}
}
}
return res;
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="jquery-ui-1.9.2.custom.min.css" rel="stylesheet" />
<script src="Scripts/jquery-1.8.3.js"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.min.js"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.js"></script>
<script type="text/javascript">
$(function () {
$("#<%= txtName.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "ADS.asmx/GetADUsers",
data: "{ 'term': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</form>
</body>
</html>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
[WebService(Namespace = "http://www.nndsonline.org")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ads : System.Web.Services.WebService
{
[WebMethod]
public static string GetDomainDN(string domain)
{
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain);
Domain d = Domain.GetDomain(context);
DirectoryEntry de = d.GetDirectoryEntry();
return de.Properties["DistinguishedName"].Value.ToString();
}
[WebMethod]
public List<string> GetADUsers(string term)
{
List<string> res = new List<string>();
// define a directory searcher for your default context
string searchRootLDAPPath = GetDomainDN(Domain.GetCurrentDomain().Name);
using (DirectoryEntry defaultDE = new DirectoryEntry(String.Format("LDAP://{0}", searchRootLDAPPath)))
{
// define searcher - search through entire subtree, search for users
// (objectCategory=Person)
using (DirectorySearcher dsAllUsers = new DirectorySearcher(defaultDE))
{
dsAllUsers.SearchScope = SearchScope.Subtree;
dsAllUsers.Filter = String.Format("(&(objectCategory=person)(objectClass=user)(cn={0}*))", term);
// get the results
SearchResultCollection result = dsAllUsers.FindAll();
foreach (SearchResult searchResult in result)
{
res.Add(searchResult.GetDirectoryEntry().Name.Remove(0, 3)); //removing the CN=
}
}
}
return res;
}
}
[WebMethod]
public List<string> GetADUsers(string term)
{
List<string> res = new List<string>();
// define a directory searcher for your default context
try
{
string searchRootLDAPPath = GetDomainDN(Domain.GetCurrentDomain().Name);
using (DirectoryEntry defaultDE = new DirectoryEntry(String.Format("LDAP://{0}", searchRootLDAPPath)))
{
// define searcher - search through entire subtree, search for users
// (objectCategory=Person)
using (DirectorySearcher dsAllUsers = new DirectorySearcher(defaultDE))
{
dsAllUsers.SearchScope = SearchScope.Subtree;
dsAllUsers.Filter = String.Format("(&(objectCategory=person)(objectClass=user)(cn={0}*))", term);
// get the results
SearchResultCollection result = dsAllUsers.FindAll();
foreach (SearchResult searchResult in result)
{
res.Add(searchResult.GetDirectoryEntry().Name.Remove(0, 3)); //removing the CN=
}
}
}
}
catch (Exception ex)
{
res.Add(String.Format("Error: {0}", ex.Message));
}
return res;
}
The error message occurs when you are not in a domain. At least in my part. At work where I am in a domain works great.public static string GetDomainDN(string domain)
{
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain);
Domain d = Domain.GetDomain(context);
DirectoryEntry de = d.GetDirectoryEntry();
return de.Properties["DistinguishedName"].Value.ToString();
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$("#<%=tbAuto.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "ADS.asmx/GetADUsers",
data: "{ 'term': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="ui-widget">
<label for="tbAuto">Enter Email: </label>
<asp:TextBox ID="tbAuto" class="tb" runat="server">
</asp:TextBox>
</div>
</form>
</body>
</html>
using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using System.Web.Script.Services;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices;
using System;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ads : System.Web.Services.WebService
{
[WebMethod]
public static string GetDomainDN(string domain)
{
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain);
Domain d = Domain.GetDomain(context);
DirectoryEntry de = d.GetDirectoryEntry();
return de.Properties["DistinguishedName"].Value.ToString();
}
[WebMethod]
public List<string> GetADUsers(string term)
{
List<string> res = new List<string>();
// define a directory searcher for your default context
try
{
string searchRootLDAPPath = GetDomainDN(Domain.GetCurrentDomain().Name);
using (DirectoryEntry defaultDE = new DirectoryEntry(String.Format("LDAP://{0}", searchRootLDAPPath)))
{
// define searcher - search through entire subtree, search for users
// (objectCategory=Person)
using (DirectorySearcher dsAllUsers = new DirectorySearcher(defaultDE))
{
dsAllUsers.SearchScope = SearchScope.Subtree;
dsAllUsers.Filter = String.Format("(&(objectCategory=person)(objectClass=user)(cn={0}*))", term);
// get the results
SearchResultCollection result = dsAllUsers.FindAll();
foreach (SearchResult searchResult in result)
{
res.Add(searchResult.GetDirectoryEntry().Name.Remove(0, 3)); //removing the CN=
}
}
}
}
catch (Exception ex)
{
res.Add(String.Format("Error: {0}", ex.Message));
}
return res;
}
}
Here is a good starting point : article
Check solution at the end.
Regards,
Mishu