I want to access to ActiveDirectory using LINQ to LDAP and I want to Get List of All users in that
how can I do that?
You can try something like below.
using ActiveDs;
using BdsSoft.DirectoryServices.Linq;
using System.Linq.Expressions;
using System.DirectoryServices;
[DirectorySchema( "user", typeof( IADsUser ) )]
class User
{
public string Name { get; set; }
public string sAMAccountName { get; set; }
public string objectCategory { get; set; }
public string mail { get; set; }
public string Description { get; set; }
[DirectoryAttribute( "PasswordLastChanged", DirectoryAttributeType.ActiveDs )]
public DateTime PasswordLastSet { get; set; }
[DirectoryAttribute("distinguishedName")]
public string Dn { get; set; }
[DirectoryAttribute("memberOf")]
public string[] Groups { get; set; }
}
Use this code to access AD from a console app, placing your AD server in the below code:
static void Main( string[] args )
{
IEnumerable<User> users = GetADUsers();
Console.WriteLine( "Users: " + users.Count().ToString() );
}
static DirectoryEntry ROOT = new DirectoryEntry( "LDAP://MyADDomainLocation.com" );
private static IEnumerable<User> GetADUsers()
{
IEnumerable<User> users;
var usersDS = new DirectorySource<User>( ROOT, SearchScope.Subtree );
users = from usr in usersDS
where usr.Name == "A*" // FIlter A then any character(s)
select usr;
users = users.OrderBy( user => user.Name ).ToList(); // Sort them alphabetically by name.
return users;
}
For more information check Get All Users using C# with Linq To Active Directory
and LINQ to LDAP
For .NET Core or Standard, please see Chris D's answer, below.
For get comprehensive knowledge about this subject check (Almost) Everything In Active Directory via C#
I hope this will help to you.
Sorry to reply to such an old question, but I felt it needed an updated answer. I wrote a .NET Standard library for this:
Linq2Ldap.Core (NuGet, GitHub) The platform-independent core library that can translate from Expressions into LDAP filters, and parse them back out, again.
It has two wrapper libraries for Active Directory:
Linq2Ldap.Protocols (NuGet, GitHub) - A thin wrapper around Linq2Ldap.Core + System.DirectoryServices.Protocols.
Linq2Ldap (NuGet, GitHub) - A thin wrapper for System.DirectoryServices.
The heart of it can transpile between Expression<Func<T, bool>>s and LDAP filters. The models (T) referenced by the Expressions must implement an interface, IEntry, that basically defines a fancy indexer class that you'd use like this: m => m["cn"] == "someuser". You can also create special properties to alias your directory attributes, too. Please see the project wiki for more info.
Related
I am trying to implement logic using this library:
I have the verb write, and options by this scheme:
write (-md [-p|-s] [-t]) | (-txt [-v]) - where '|' - means or (only -p OR -s is accepted (but not necessary as shown by '[]') when using -md)
Is there easy way to implement this? or should I split this to separate verbs?
Sorry for answering own question but it would be helpful to someone else (source):
You can use use SetName argument while declaring OptionAttribute:
internal class Options
{
[Option("username", SetName = "auth")]
public string Username { get; set; }
[Option("password", SetName = "auth")]
public string Password { get; set; }
[Option("guestaccess", SetName = "guest")]
public bool GuestAccess { get; set; }
}
Now username and password can be used together, but guestaccess is alone within "guest" set, so it can not be used with options from other sets.
I'm trying to do what I thought would be a very simple think using Linq lambda, it probably is, but I can't find an example in any tutorial.
I have a simple class with a few properties. I want to get a list of one of the properties based on the value on another value in that class.
Below is an example of the code, using Linq to get the correct results:
public class Client
{
public int ClientId { get; set; }
public int ClientWorth { get; set; }
public strin ClientName { get; set; }
}
.
.
.
.
List<Client> allClients = this.GetAllClients();
List<string> richClients = (
from c in allClients
where c.ClientWorth > 500
select c.ClientId.ToString()).ToList();
Can someone tell me how to do this using a lambda
I can do the following:
List<Clients> richClients = allClients.Where(x => x.ClientWorth >500)
Which give me a list of all clients, but I would like to get a string list back with just the client ids.
After filtering by client worth value you should project results - i.e. select only client id value:
allClients.Where(c => c.ClientWorth > 500).Select(c => c.ClientId.ToString()).ToList()
Further reading: Enumerable.Select
I'm trying to convert from Entity Framework to Dapper to hopefully improve data access performance.
The queries I use are in the form of predicates like so Expression<Func<TModel, bool>>.
To give an example:
I have the following code which I need to convert to using Dapper.
What I currently do:
public async Task<List<TModel>> Get(Expression<Func<TModel, bool>> query)
{
// this.Context is of type DbContext
return await this.Context.Set<TModel>().Where(query).ToListAsync();
}
What I'd like to do:
public async Task<List<TModel>> Get(Expression<Func<TModel, bool>> query)
{
using (IDbConnection cn = this.GetConnection)
{
return await cn.QueryAsync<TModel>(query);
}
}
My google-fu is failing me, can someone please assist.
Edit:
Note that I did find:
https://github.com/ryanwatson/Dapper.Extensions.Linq
but I can't seem to figure out how to use it.
Firstly, one of the authors of Dapper said, when someone asked
Is there a plan to make Dapper.net compatible with IQueryable interfaces?
that
there are no plans to do this. It is far far outside what dapper tries to do. So far that I would say it is antithetical. Dapper core tries to be the friend to those who love their SQL.
(see https://stackoverflow.com/a/27588877/3813189).
In a way, that does suggest that the various extension packages to NuGet may help, as you have suggested.
I have tried DapperExtensions, which makes writing the query filters in a programmatic way a little easier - eg.
using System.Data.SqlClient;
using DapperExtensions;
namespace StackOverflowAnswer
{
class Program
{
static void Main(string[] args)
{
using (var cn = new SqlConnection("Server=.;Database=NORTHWND;Trusted_Connection=True;"))
{
var list = cn.GetList<Products>(
Predicates.Field<Products>(f => f.Discontinued, Operator.Eq, false)
);
}
}
class Products
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public bool Discontinued { get; set; }
}
}
}
I also tried Dapper.Extensions.Linq (the package you suggested), which promises to
builds on this providing advanced DB access through Linq queries. The fluid configuration makes setup simplistic and quick.
Unfortunately, I also couldn't get very far with it. There isn't much documentation and the tests don't seem to cover the QueryBuilder, which is what appears to be the class to use to translate Linq Expressions into the Dapper Extensions predicates (as suggested by the issue Parsing boolean expressions with the QueryBuilder). I tried the following, which required add the IEntity interface to my DTO -
using System;
using System.Data.SqlClient;
using System.Linq.Expressions;
using Dapper.Extensions.Linq.Builder;
using Dapper.Extensions.Linq.Core;
using DapperExtensions;
namespace StackOverflowAnswer
{
class Program
{
static void Main(string[] args)
{
using (var cn = new SqlConnection("Server=.;Database=NORTHWND;Trusted_Connection=True;"))
{
Expression<Func<Products, bool>> filter = p => !p.Discontinued;
var queryFilter = QueryBuilder<Products>.FromExpression(filter);
var list = cn.GetList<Products>(
queryFilter
);
}
}
class Products : IEntity
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public bool Discontinued { get; set; }
}
}
}
.. but it failed at runtime with the error
Operator was not found for StackOverflowAnswer.Program+Products
I'm not sure why generating the Predicate manually (the first example) works but the QueryBuilder doesn't..
I would say that it's increasingly looking like the comments left on your question are correct, that you will need to re-work your code away from the expressions that you used with Entity Framework. Since it's been so difficult to find any information about this QueryBuilder class, I would be concerned that (even if you did get it working) any issues that you encountered would be difficult to get help for (and bugs may go unfixed).
I wrote a utility to work EF with Dapper using attributes. I parsing predicate and translate to SQL.
"Users" POCO:
[Table("Users")]
public class User
{
[Key]
[Identity]
public int Id { get; set; }
public string Login { get; set;}
[Column("FName")]
public string FirstName { get; set; }
[Column("LName")]
public string LastName { get; set; }
public string Email { get; set; }
[NotMapped]
public string FullName
{
get
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
}
And simple query:
using (var cn = new SqlConnection("..."))
{
var usersRepository = new DapperRepository<User>(cn)
var allUsers = await userRepository.FindAllAsync(x => x.AccountId == 3 && x.Status != UserStatus.Deleted);
}
Maybe it will be useful to you?
MicroOrm.Dapper.Repositories
I have just started to explore Graph databases and Neo4jClient library for Neo4J. I am using Neo4JClient v1.1.0.11 downloaded from NuGet in Visual Studio. I want to create a Node in Neo4J and for that I am using this code (C#):
var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "user", "pass");
client.Connect();
client.Cypher.Create();
But on Cypher.Create Intellisense shows that it is deprecated. My question is what is the alternate way of creating a Node? An example would be appreciated.
In this particular case I have a User that I want to create in the database. The class looks like:
public class User
{
public Int32 ID { get; set; }
public String UserName { get; set; }
public String Name { get; set; }
public Boolean Active { get; set; }
public String Email { get; set; }
public String Password { get; set; }
}
Thanks
I believe only one overload on the Create method has been marked as obsolete - unless there is something I am not aware of. The following code should do what you need and does not show as being deprecated.
var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "user", "pass");
client.Connect();
var user = new User
{
// initialise properties
};
client.Cypher
.Create("(u:User {user})")
.WithParams(new { user = user })
.ExecuteWithoutResults();
There are a number of variations on this that will work but it should get you started.
As an aside, were you to use the first overload on the Create method you would indeed see it marked as deprecated. For example, this code
client.Cypher
.Create("(u:User {0})", user)
.ExecuteWithoutResults();
would give you the following warning in Visual Studio
'Neo4jClient.Cypher.ICypherFluentQuery.Create(string, params object[])' is obsolete: 'Use Create(string) with explicitly named params instead. For example, instead of Create("(c:Customer {0})", customer), use Create("(c:Customer {customer})").WithParams(new { customer }).'
I want to access to ActiveDirectory using LINQ to LDAP and I want to Get List of All users in that
how can I do that?
You can try something like below.
using ActiveDs;
using BdsSoft.DirectoryServices.Linq;
using System.Linq.Expressions;
using System.DirectoryServices;
[DirectorySchema( "user", typeof( IADsUser ) )]
class User
{
public string Name { get; set; }
public string sAMAccountName { get; set; }
public string objectCategory { get; set; }
public string mail { get; set; }
public string Description { get; set; }
[DirectoryAttribute( "PasswordLastChanged", DirectoryAttributeType.ActiveDs )]
public DateTime PasswordLastSet { get; set; }
[DirectoryAttribute("distinguishedName")]
public string Dn { get; set; }
[DirectoryAttribute("memberOf")]
public string[] Groups { get; set; }
}
Use this code to access AD from a console app, placing your AD server in the below code:
static void Main( string[] args )
{
IEnumerable<User> users = GetADUsers();
Console.WriteLine( "Users: " + users.Count().ToString() );
}
static DirectoryEntry ROOT = new DirectoryEntry( "LDAP://MyADDomainLocation.com" );
private static IEnumerable<User> GetADUsers()
{
IEnumerable<User> users;
var usersDS = new DirectorySource<User>( ROOT, SearchScope.Subtree );
users = from usr in usersDS
where usr.Name == "A*" // FIlter A then any character(s)
select usr;
users = users.OrderBy( user => user.Name ).ToList(); // Sort them alphabetically by name.
return users;
}
For more information check Get All Users using C# with Linq To Active Directory
and LINQ to LDAP
For .NET Core or Standard, please see Chris D's answer, below.
For get comprehensive knowledge about this subject check (Almost) Everything In Active Directory via C#
I hope this will help to you.
Sorry to reply to such an old question, but I felt it needed an updated answer. I wrote a .NET Standard library for this:
Linq2Ldap.Core (NuGet, GitHub) The platform-independent core library that can translate from Expressions into LDAP filters, and parse them back out, again.
It has two wrapper libraries for Active Directory:
Linq2Ldap.Protocols (NuGet, GitHub) - A thin wrapper around Linq2Ldap.Core + System.DirectoryServices.Protocols.
Linq2Ldap (NuGet, GitHub) - A thin wrapper for System.DirectoryServices.
The heart of it can transpile between Expression<Func<T, bool>>s and LDAP filters. The models (T) referenced by the Expressions must implement an interface, IEntry, that basically defines a fancy indexer class that you'd use like this: m => m["cn"] == "someuser". You can also create special properties to alias your directory attributes, too. Please see the project wiki for more info.