jQuery Bootgrid sorting, pagination and search functionality not working - asp.net

I have a jQuery bootgrid implemented into my ASP.Net application which is filled using a Generic Handler.
I fill the bootgrid using the Generic Handler as follows:
$(function () {
var grid = $("#grid").bootgrid({
ajax: true,
ajaxSettings: {
method: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false
},
url: "/MyHandler.ashx",
rowCount: [10, 50, 75, 100, 200, -1]
});
}
Here's MyHandler.ashx code:
public class RolesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
context.Response.Write(GetData());
}
public bool IsReusable
{
get
{
return false;
}
}
public string GetData()
{
var result = string.Empty;
var con = new SqlConnection();
var cmd = new SqlCommand();
var dt = new DataTable();
string sSQL = #"SELECT Id, Name
FROM dbo.AspNetRoles;";
try
{
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
}
}
var sNumRows = dt.Rows.Count.ToString();
var sDT = JsonConvert.SerializeObject(dt);
result = "{ \"current\": 1, \"rowCount\": 10, \"rows\": " + sDT + ", \"total\": " + sNumRows + " }";
}
catch (Exception ex)
{
}
finally
{
cmd.Dispose();
THF.Models.SQLConnectionManager.CloseConn(con);
}
return result;
}
}
Basically all the important functionality of my bootgrid that worked before I implemented it the ajax way doesn't work anymore. Specifically the ordering, searching and pagination functionality aren't working at all without any errors.
As far as I know from a bit of research. This is because every time a search phrase is made, or a header is clicked (for ordering) etc. The bootgrid performs an ajax call.
Any idea on how to fix the functionality here?

After much work I ended up getting it working and this is the final code result:
public class RolesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
var current = context.Request.Params["current"];
var rowCount = context.Request.Params["rowCount"];
var orderById = context.Request.Params["sort[Id]"];
var orderByName = context.Request.Params["sort[Name]"];
var searchPhrase = context.Request.Params["searchPhrase"];
var orderBy = "Id";
var orderFrom = "ASC";
if (orderById != null)
{
orderBy = "Id";
orderFrom = orderById;
}
else if (orderByName != null)
{
orderBy = "Name";
orderFrom = orderByName;
}
context.Response.Write(GetData(current, rowCount, orderBy, orderFrom, searchPhrase));
}
public bool IsReusable
{
get
{
return false;
}
}
public string GetData(string current, string rowCount, string orderBy, string orderFrom, string searchPhrase)
{
var result = string.Empty;
var currentNum = Convert.ToInt32(current) - 1;
var temp = 0;
if (!"Id".Equals(orderBy, StringComparison.OrdinalIgnoreCase)
&& !"Name".Equals(orderBy, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderBy is not a valid value");
if (!"desc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase) && !"asc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderFrom is not a valid value");
if (!int.TryParse(rowCount, out temp))
throw new ArgumentException("Rowcount is not a valid number");
var dt = new DataTable();
string sSQL = #"SELECT Id, Name
FROM dbo.AspNetRoles
WHERE Id LIKE #searchPhrase
OR Name LIKE #searchPhrase
ORDER BY " + orderBy + " " + orderFrom + #"
OFFSET ((" + currentNum.ToString() + ") * " + rowCount + #") ROWS
FETCH NEXT " + rowCount + " ROWS ONLY;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
command.Parameters.Add(new SqlParameter("#searchPhrase", "%" + searchPhrase + "%"));
command.Parameters.Add(new SqlParameter("#orderBy", orderBy));
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
connection.Close();
}
}
var total = string.Empty;
string sSQLTotal = #"SELECT COUNT(*)
FROM dbo.Log
WHERE Id LIKE #searchPhrase
OR Name LIKE #searchPhrase;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQLTotal, connection))
{
command.Parameters.Add(new SqlParameter("searchPhrase", "%" + searchPhrase + "%"));
connection.Open();
command.CommandTimeout = 0;
total = command.ExecuteScalar().ToString();
connection.Close();
}
}
var rows = JsonConvert.SerializeObject(dt);
return result = "{ \"current\": " + current + ", \"rowCount\": " + rowCount + ", \"rows\": " + rows + ", \"total\": " + total + " }";
}
}

Related

Increase data insert performance

We have created a code that loops in to CosmosDb records and inserts values to Sql db. But in the process, the data insertion perfomance is very slow. please help with suggestions, here is the code. This process is taking more than 4 hours for inserting a data of 4000 rows.
namespace PushNotificationUserInsert
{
class Program
{
static void Main(string[] args)
{
Task.Run(async () =>
{
#region Variables
var endpoint = ConfigurationManager.AppSettings["DocDbEndpoint"];
var masterKey = ConfigurationManager.AppSettings["DocDbMasterKey"];
var connetionString = ConfigurationManager.AppSettings["SQL_connetionString"].ToString();
// var useremail = "\"\"";
string path = #"xxxx.txt";
string[] useremails = File.ReadAllLines(path);
List<string> It = useremails.ToList();
var newIt = It.Distinct().ToList();
var channel = "\"msteam\"";
var cnn = new SqlConnection(connetionString);
var cnnInsert = new SqlConnection(connetionString);
string query = null;
cnn.Open();
foreach (var email in newIt)
{
query = "SELECT * FROM c where c.document.bot_js.mail = \"" + email + "\" AND CONTAINS(c.id," + channel + ", true)";
dynamic responses = "";
JSONModel.Rootobject records = null;
string conversationId = "";
//string email = "";
#endregion
#region Reading data from SQL
// cnn.Open();
SqlDataReader dataReader;
String Output = "";
SqlCommand command = new SqlCommand(#"SELECT [ConversatonReferenceJson] FROM [dbo].[ConversationReferences] where emailid like ''", cnn);
//command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = dataReader.GetValue(0).ToString();
records = JsonConvert.DeserializeObject<JSONModel.Rootobject>(Output);
}
dataReader.Close();
dataReader.Dispose();
#endregion
string[] readText = File.ReadAllLines(path);
//List<string> It = readText.ToList();
//var newIt = It.Distinct().ToList();
//foreach (string email in newIt)
//{
Console.WriteLine(email);
try
{
#region reading data from Consmos DB
using (var client = new DocumentClient(new Uri(endpoint), masterKey))
{
responses = client.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri("Cosmosdbname", "cosmosdbtablebame"), query).ToList();
}
#endregion
#region Looping throught each cosmos DB records and insert value in SQL
foreach (var response in responses)
{
conversationId = response.id.Remove(0, 26);
records.conversation.id = conversationId;
cnnInsert.Open();
SqlCommand commInsert = new SqlCommand("INSERT INTO [ConversationReferences] VALUES " +
"(#ChannelId, #UserId, #ConverJson, #ID, #EmailID)", cnnInsert);
commInsert.Parameters.AddWithValue("#ChannelId", "xxxx");
commInsert.Parameters.AddWithValue("#UserId", "tobedeleted");
commInsert.Parameters.AddWithValue("#ConverJson", JsonConvert.SerializeObject(records));
commInsert.Parameters.AddWithValue("#ID", "tobedeleted");
commInsert.Parameters.AddWithValue("#EmailID", email);
commInsert.ExecuteNonQuery();
cnnInsert.Close();
Console.WriteLine("records updated for " + email);
}
#endregion
}
catch (Exception ex)
{
cnnInsert.Close();
throw;
}
finally
{ cnnInsert.Close(); }
Console.ReadKey();
}
}).Wait();
}
}

The type or namespace GlobalVar could not be found

Please dear this is my code and everything is fine but the GlobalVar is not being declared any suggestions.
[WebMethod(MessageName = "OpenAccount", Description = "This method is to add new account")]
[System.Xml.Serialization.XmlInclude(typeof(ContactResult))]
public ContactResult openaccount(String FullName, String Phone)
{
ContactResult cr = new ContactResult();
**GlobalVar var = new GlobalVar();**
try
{
using (SqlConnection openconn = new SqlConnection(var.connectionstring))
{
string save = "INSERT into AndroidContact (AndroidContactName,AndroidContactPhone) VALUES ('" + FullName + "' ,'" + Phone + "')";
using (SqlCommand query = new SqlCommand(save))
{
query.Connection = openconn;
query.Parameters.Add("#AndroidContactName", SqlDbType.NVarChar, 50).Value = FullName;
query.Parameters.Add("#AndroidContactPhone", SqlDbType.NVarChar, 50).Value = Phone;
openconn.Open();
query.ExecuteNonQuery();
openconn.Close();
}
}
cr.ErrorID = 0;
cr.ErrorMessage = "Contact Added";
return cr;
}
catch (Exception ex){
cr.ErrorID = 1;
cr.ErrorMessage = ex.Message;
return cr;
}
}
}
}
Thanks, but i fixed mine like that :
public class WebService1 : System.Web.Services.WebService
{
[WebMethod(MessageName = "OpenAccount", Description = "This method is to add new account")]
[System.Xml.Serialization.XmlInclude(typeof(ContactResult))]
public ContactResult openaccount(String FullName, String Phone)
{
ContactResult cr = new ContactResult();
SqlConnection Connection = new SqlConnection();
try
{
Connection.ConnectionString = ConfigurationManager.ConnectionStrings["webConnectionString"].ToString();
Connection.Open();
SqlCommand save = new SqlCommand ("INSERT into AndroidContact (AndroidContactName,AndroidContactPhone) VALUES ('" + FullName + "' ,'" + Phone + "')",Connection);
save.ExecuteNonQuery();
cr.ErrorID = 0;
cr.ErrorMessage = "Contact Added";
return cr;
}
catch (Exception ex)
{
cr.ErrorID = 1;
cr.ErrorMessage = ex.Message;
return cr;
}
}
}

How to Create and Delete edge properties (Titan 1.0) using c# in .net mvc?

I was using Titan 1.0 with gremlin server to create and delete vertex. I want to implement this logic in my .net project. I wonder if there is any pre build plugin for titan and gremlin server in asp.net?
Currently i'm directly using command prompt to create and delete the required vertices and edges. how can I implement it in my .net MVC project?
I've created one class in my project for interacting with Gremlin server using REST API. you can make small changes to make it work for you.
Source: https://askgif.com/blog/145/how-to-create-and-delete-edge-properties-titan-1-0-using-c-in-net-mvc/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using RestSharp;
using urNotice.Common.Infrastructure.Common.Config;
using urNotice.Common.Infrastructure.Common.Constants;
using urNotice.Common.Infrastructure.Common.Enum;
using urNotice.Common.Infrastructure.commonMethods;
using urNotice.Common.Infrastructure.Model.urNoticeModel.DynamoDb;
using urNotice.Services.NoSqlDb.DynamoDb;
namespace urNotice.Services.GraphDb
{
public class GremlinServerGraphEdgeDb : IGraphEdgeDb
{
private delegate Dictionary<string, string> AddEdgeAsyncDelegate(string userName, string graphName, Dictionary<string, string> properties);
public Dictionary<string, string> AddEdge(string userName, string graphName, Dictionary<string, string> properties)
{
string url = TitanGraphConfig.Server;
var response = CreateEdge(graphName, properties, url);
// add edge to dynamodb.
var edgeDetail = new OrbitPageEdgeDetail
{
url = url,
edgeId = response[TitanGraphConstants.Id],
graphName = graphName,
properties = properties
};
IDynamoDb dynamoDbModel = new DynamoDb();
dynamoDbModel.UpsertOrbitPageEdgeDetail(edgeDetail, userName, properties[EdgePropertyEnum._inV.ToString()], properties[EdgePropertyEnum._outV.ToString()]);
//Adding edgeDetail for faster query.
//dynamoDbModel.UpsertOrbitPageEdgeForQueryDetail(edgeDetail, userName, properties[EdgePropertyEnum._inV.ToString()], properties[EdgePropertyEnum._outV.ToString()]);
return response;
}
public Dictionary<string, string> DeleteEdge(string inV, string outV, string label)
{
string url = TitanGraphConfig.Server;
IDynamoDb dynamoDbModel = new DynamoDb();
string uniqueKey = OrbitPageUtil.GenerateUniqueKeyForEdgeQuery(inV, label, outV);
var edgeInfo = dynamoDbModel.GetOrbitPageCompanyUserWorkgraphyTable(
DynamoDbHashKeyDataType.EdgeDetail.ToString(),
uniqueKey,
null);
if (edgeInfo == null)
return null;
var response = DeleteEdgeNative(TitanGraphConfig.Graph, edgeInfo.CompareId, url);
dynamoDbModel.DeleteOrbitPageCompanyUserWorkgraphyTable(edgeInfo);
//Deleting Edge detail creating for only query purpose.
//string uniqueKey = OrbitPageUtil.GenerateUniqueKeyForEdgeQuery(inV, label, outV);
//edgeInfo = dynamoDbModel.GetOrbitPageCompanyUserWorkgraphyTable(
// DynamoDbHashKeyDataType.EdgeDetail.ToString(),
// uniqueKey,
// null);
//if(edgeInfo!=null)
// dynamoDbModel.DeleteOrbitPageCompanyUserWorkgraphyTable(edgeInfo);
return response;
}
public Dictionary<string, string> AddEdgeAsync(string userName, string graphName, Dictionary<string, string> properties)
{
var addEdgeAsyncDelegate = new GremlinServerGraphEdgeDb.AddEdgeAsyncDelegate(AddEdge);
addEdgeAsyncDelegate.BeginInvoke(userName, graphName, properties, null, null);
return null;
}
private Dictionary<String, String> CreateEdge(string graphName, Dictionary<string, string> properties, string url)
{
var uri = new StringBuilder(url + "/?gremlin=");
//http://localhost:8182/?gremlin=g.V(8320).next().addEdge("Using",g.V(12416).next(),"Desc","Item used by Person","time",12345)
string graphProperties = string.Empty;
//_outV must be the first parameter
graphProperties += "'" + properties[EdgePropertyEnum._label.ToString()] + "', g.V(" + properties[EdgePropertyEnum._inV.ToString()] + ").next() ,";
foreach (KeyValuePair<string, string> property in properties)
{
if (property.Key == EdgePropertyEnum._inV.ToString() || property.Key == EdgePropertyEnum._outV.ToString() || property.Key == EdgePropertyEnum._label.ToString())
{
//do nothing.. May be in future we will write logic here.
}
else
{
if (property.Key == EdgePropertyEnum.PostedDateLong.ToString() || property.Key == EdgePropertyEnum.SalaryAmount.ToString())
graphProperties += "'" + property.Key + "', " + property.Value + " ,";
else
graphProperties += "'" + property.Key + "', '" + property.Value + "' ,";
}
}
if (!string.IsNullOrEmpty(graphProperties))
{
graphProperties = graphProperties.Substring(0, graphProperties.Length - 2);
}
uri.Append("g.V(" + properties[EdgePropertyEnum._outV.ToString()] + ").next().addEdge(" + graphProperties + ");");
var client = new RestClient(uri.ToString());
var request = new RestRequest();
request.Method = Method.GET;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", "", ParameterType.RequestBody);
var res = client.Execute(request);
var content = res.Content; // raw content as string
dynamic jsonResponse = JsonConvert.DeserializeObject(content);
var response = new Dictionary<String, String>();
response["status"] = "200";
response["CreateEdgeStatus"] = "200";
response[TitanGraphConstants.Id] = jsonResponse.result.data[0].id;
response[TitanGraphConstants.RexsterUri] = url;
return response;
}
private Dictionary<String, String> DeleteEdgeNative(string graphName, string edgeId, string url)
{
var uri = new StringBuilder(url + "/?gremlin=");
//var uri = new StringBuilder(url + "/graphs/" + graphName + "/edges/" + edgeId);
//http://localhost:8182/?gremlin=g.E('odxqo-6f4-2hat-9kw').drop()
uri.Append("g.E('" + edgeId + "').drop();");
var client = new RestClient(uri.ToString());
var request = new RestRequest();
request.Method = Method.GET;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", "", ParameterType.RequestBody);
var res = client.Execute(request);
var content = res.Content; // raw content as string
dynamic jsonResponse = JsonConvert.DeserializeObject(content);
var response = new Dictionary<String, String>();
response["status"] = "200";
response["DeleteEdgeStatus"] = "200";
//response[TitanGraphConstants.Id] = jsonResponse.result.data[0].id;
//response[TitanGraphConstants.RexsterUri] = url;
return response;
}
}
}
comment if you face any issue in the class.

Changing the parameter in sql query of ASP.NET page - with button_click event, sql query in every button click

I have a ASP.NET page which have details in below manner.
Date OfficerID DutyID
25-NOV-13 2 666
26-NOV-13 2 666
27-NOV-13 2 666
28-NOV-13 2 666
29-NOV-13 2 666
30-NOV-13 2 666
01-DEC-13 2 666
02-DEC-13 2 523
The above is being populated in gridview through below code snippet
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate and sysdate+18";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
GridView1.DataSource = table;
GridView1.DataBind();
Now I also have a previous button which should output the same page but with sql query slightly changed
select * from duty_rota where duty_date between sysdate-18 and sysdate;
and with every button click the date parameters should be decreased by 18, i.e with 1st previous button click query will be
sysdate-18 and sysdate
with 2nd click
sysdate-36 and sysdate-18
with 3rd click
sysdate-54 and sysdate-36
and so on...
Please help me how could I acheieve it , I was trying to implement it with a variable associated with Previous buttons button click event which would change with every subsequent click. But I am not really able to accomplish it. Can anybody please guide me on this.
Write below code to handle dynamic query on previous and next button click event :
protected void PrevioseButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(false);
this.BindGrid(sqlQuery);
}
protected void NextButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(true);
this.BindGrid(sqlQuery);
}
private string GenerateQuery(bool isNext)
{
if (ViewState["fromDate"] == null && ViewState["toDate"] == null)
{
ViewState["fromDate"] = isNext ? "sysdate+18" : "sysdate-18";
ViewState["toDate"] = isNext ? "sysdate+36" : "sysdate";
}
else
{
var from = ViewState["fromDate"].ToString().Replace("sysdate", string.Empty);
var to = ViewState["toDate"].ToString().Replace("sysdate", string.Empty);
int fromDay = 0;
int toDay = 0;
if (from != string.Empty)
{
fromDay = Convert.ToInt32(from);
}
if (to != string.Empty)
{
toDay = Convert.ToInt32(to);
}
if (!isNext)
{
fromDay = fromDay - 18;
toDay = toDay - 18;
}
else
{
fromDay = fromDay + 18;
toDay = toDay + 18;
}
from = "sysdate";
to = "sysdate";
if (fromDay > 0)
{
from += "+" + fromDay;
}
else if (fromDay < 0)
{
from += fromDay.ToString();
}
if (toDay > 0)
{
to += "+" + toDay;
}
else if (toDay < 0)
{
to += toDay.ToString();
}
ViewState["fromDate"] = from;
ViewState["toDate"] = to;
}
var sqlQuery = "select * from duty_rota where duty_date between " + ViewState["fromDate"] + " and "
+ ViewState["toDate"];
return sqlQuery;
}
private void BindGrid(string sqlQuery)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
On the button click event, try this:
DataTable table = new DataTable();
string connectionString = GetConnectionString();
if (Session["sysdate"] == null || string.IsNullOrEmpty(Session["sysdate"].ToString()))
Session["sysdate"] = "-18";
else
Session["sysdate"] = "+ " + (Convert.ToInt32(Session["sysdate"]) - 18).ToString();
string sysdate = Session["sysdate"].ToString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate " + sysdate + " and sysdate+18 " + sysdate;
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
Me thoughts an ObjectDataSource control would perfectly provide you with a solution...however then I realized that your pagesize varies!
In such a case you need to have your pagination to be disassociated with the gridview. Meaning pagination should be separate and your data which needs to be displayed in the grid view need to be separate. They may have something like a master-child relationship. It means you'd need separate db calls for fetching "each".
You pagination part could be rendered by a gridview or a data list view.
However, if the pagesize on the gridview is always constant you need read this: http://www.codeproject.com/Articles/13963/Implement-Paging-using-ObjectDataSource-with-GridV

I need to fetch all users email of a particular group using AD in .net 2.0

I know there are lots of methods already given in stackoverflow but in my case all of them taking too long time. I post a method which takes less time but still it is too long to implement. Please help me so that it takes less execution time. Also take consideration that i am using .net 2.0 framework.
try
{
List<string> lstEmails = new List<string>();
string filter1 = string.Format("(anr={0})", "groupname");
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = filter1;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("mail");
IEnumerable res = (IEnumerable)searcher.FindOne().GetDirectoryEntry().Invoke("members");
//IEnumerable<string> rest = (IEnumerable<string>)res;
if (res != null)
{
try
{
int index = 0;
foreach (IEnumerable resl in res)
{
DateTime start = DateTime.Now;
DirectoryEntry dr = new DirectoryEntry(resl);
string strEmail = null;
if (dr.Properties["mail"].Value != null)
{
strEmail = dr.Properties["mail"].Value.ToString();
Console.WriteLine(strEmail);
DateTime stop = DateTime.Now;
Console.WriteLine((stop - start).TotalMinutes.ToString());
index++;
Console.WriteLine(index.ToString());
}
if (!string.IsNullOrEmpty(strEmail))
{
// groupMemebers.Add("sam",strEmail);
}
}
}
catch { }
}
}
catch { }
This is your suggested method Daro..
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain, "domainname" + strLDAPUserName, strLDAPPassword);
DomainController controller = DomainController.FindOne(context);
DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}",controller.Domain), strLDAPUserName, strLDAPPassword, AuthenticationTypes.Secure);
List<string> userList = new List<string>();
DateTime StartTime = DateTime.Now;
using (DirectorySearcher ds = new DirectorySearcher(entry))
{
ds.PropertiesToLoad.Add("mail");
ds.PageSize = 10000;
string DistingushiedName = "CN=" + groupName + ",OU=Users,dc=CompanyName,dc=com";
ds.Filter = "(&(objectClass=user)(memberof:1.2.840.113556.1.4.1941:="+DistingushiedName+"))";
ds.SearchScope = SearchScope.Subtree;
try
{
foreach (SearchResult user in ds.FindAll())
{
try
{
userList.Add(user.Path);//.Properties["mail"][0].ToString());
}
catch (Exception E)
{
throw new Exception(E.Message);
}
}
}
catch(Exception E)
{
throw new Exception(E.Message);
}
DateTime EndTime = DateTime.Now;
TimeSpan Dif = EndTime.Subtract(StartTime);
}
Here is your solution:-
string[] email = new string[0];
DirectoryEntry entry = new DirectoryEntry("LDAP://OU=Users,dc=me,dc=com", username, password);
string groupName = "GroupName";//Group NAme
DirectorySearcher groupSearch = new DirectorySearcher(entry);
groupSearch.Filter = "(SAMAccountName=" + groupName + ")";
groupSearch.PropertiesToLoad.Add("member");
SearchResult groupResult = groupSearch.FindOne(); // getting the members who belongs to the concern groupname
if (groupResult != null)
{
email = new string[groupResult.Properties["member"].Count]; //creatign an array to store all the email address
for (int iSearchLoop = 0; iSearchLoop < groupResult.Properties["member"].Count; iSearchLoop++)
{
string userName = groupResult.Properties["member"][iSearchLoop].ToString();
int index = userName.IndexOf(',');
userName = userName.Substring(0, index).Replace("CN=", "").ToString(); // the name of the user will be fetched.
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(name=" + userName + ")";
search.PropertiesToLoad.Add("mail");
SearchResult result = search.FindOne(); //finding the mail id
if (result != null)
{
email[iSearchLoop] = result.Properties["mail"][0].ToString(); //assigning the mail id to an array....
}
}
}
Hope this helps you
Easy enough (if your AD is 2003 R2 or higher):
List<string> userList = new List<string>();
DateTime StartTime = DateTime.Now;
using (DirectorySearcher ds = new DirectorySearcher(new DirectoryEntry ("GC://DC=YourDomain,DC=com")))
{
ds.PropertiesToLoad.Add("mail");
ds.PageSize = 10000;
ds.Filter = "(&(objectClass=user)(memberof:1.2.840.113556.1.4.1941:=YOUR_GROUP'S DN))";
ds.SearchScope = SearchScope.Subtree;
try
{
foreach (SearchResult user in ds.FindAll())
{
try
{
userList.Add(user.Path);//.Properties["mail"][0].ToString());
}
catch (Exception E)
{
throw new Exception(E.Message);
}
}
}
catch(Exception E)
{
throw new Exception(E.Message);
}
DateTime EndTime = DateTime.Now;
TimeSpan Dif = EndTime.Subtract(StartTime);
}
Replace YOUR_GROUP'S DN with the distiguished name of your group...
memberof:1.2.840.113556.1.4.1941:= is the "new" LDAP_MATCHING_RULE_IN_CHAIN operator, and retrieves all group members. Look here to see if your AD is ready and get more information.
Edit:
I gave you an answer, but an explanation might help further.
In general you should avoid ANR searches because they expand to large wildcard OR queries. Use them only if you have no idea which property contains the name you are searching for. They are much slower than explicit AND searches.
Secondly if you have more than one domain, you should turn off referral chasing unless you want to search through all domains until you get a hit. In this case it would be better to do a GC:// than a LDAP:// search to find the object you’re looking for, than do an LDAP search on that object. Depending on what you are looking for the GC query could well be enough
Edit 2:
Modified the code to give more error information and get the user path instead of E-Mail.
Hey this is the correct way...
try
{
List<string> ReturnArray = new List<string>();
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domainName, domainName + "\\" + UserName, Password);
DomainController controller = DomainController.FindOne(context);
string LDAPAddress = string.Format("LDAP://{0}", controller.Domain);
DirectoryEntry deDirEntry = new DirectoryEntry(LDAPAddress, UserName, Password);
deDirEntry.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher mySearcher = new DirectorySearcher(deDirEntry);
mySearcher.PropertiesToLoad.Add("distinguishedName");
string sFilter = String.Format("(&(objectcategory=group)(cn=" + GroupName + "))");
mySearcher.Filter = sFilter;
mySearcher.Sort.Direction = SortDirection.Ascending;
mySearcher.Sort.PropertyName = "cn";
SearchResult result;
DirectoryEntry ResultEntry;
result = mySearcher.FindOne();
ResultEntry = result.GetDirectoryEntry();
GroupName = ResultEntry.Properties["distinguishedName"].Value.ToString();
mySearcher = new DirectorySearcher(deDirEntry);
mySearcher.PropertiesToLoad.Add("cn");
mySearcher.PropertiesToLoad.Add("mail");
sFilter = String.Format("(&(objectClass=person)(memberOf={0}))", GroupName);
mySearcher.Filter = sFilter;
mySearcher.Sort.Direction = SortDirection.Ascending;
mySearcher.Sort.PropertyName = "cn";
SearchResultCollection results;
results = mySearcher.FindAll();
foreach (SearchResult resEnt in results)
{
ResultPropertyCollection propcoll = resEnt.Properties;
foreach (string key in propcoll.PropertyNames)
{
if (key == "mail")
{
foreach (object values in propcoll[key])
{
if (!String.IsNullOrEmpty(values.ToString()))
{
ReturnArray.Add(values.ToString());
Console.WriteLine(values.ToString());
}
}
}
}
}
return ReturnArray;
}
catch
{
return null;
}
Thanks everyone for your valuable suggesstion

Resources