Which of these is the better architecture/design approach? - c#

Objective
To write a effecient Active Directory library to ease the work of technicals who are responsible to create access models into the domain controller's Active Directory. This library must allow the following:
Basic operations: Add, Modify, Delete, List entries;
An entry may either be an organizational unit, group or user (no further need required as of now);
I thought about having a class which would represent the domain with which we want to work with.
public class Domain {
public Domain(string root) {
Root = root;
Entries = new Dictionary<string, IDirectoryEntry>();
}
public string Root { get; private set; }
public Dictionary<string, IDirectoryEntry> Entries { get; private set; }
}
Then, I have used dependency injection to enforce the belonging constraint to a domain of an entry. For example:
public abstract class DirectoryEntry : IDirectoryEntry {
public DirectoryEntry(Domain domain, string name) {
Domain = domain;
Name = name;
Domain.Entries.Add(name, this);
}
public Domain { get; private set; }
public Name { get; set; }
}
public class OrganizationalUnit : DirectoryEntry {
public OrganizationalUnit(Domain domain, string name)
: base(domain, name) {
}
}
public class Group : DirectoryEntry {
public Group(Domain domain, string name)
: base(domain, name) {
}
}
Now, notice that I add the entry using Domain.Entries.Add() to the given domain upon instantiation of an IDirectoryEntry interface.
Questions
Is this a good practice, if I don't want the user to change the Domain property of any IDirectoryEntry instances?
Would it be preferable to simply let this Domain.Entries.Add() line go away, and have a method within my Domain class that would add an entry to the domain?
Code Sample for question #2
public class Domain {
//See above for other members.
public void AddEntry<T>(T entry) {
Entries.Add(entry.Name, entry);
}
}
What is, according to you, the best architecture in this situation?Both seem to be good enough to be considered, so I'm a bit confused about it wanting the easiest possible way for the library end-users.

Have you looked at .NET 3.5/4's System.DirectoryServices.AccountManagement namespace? It provides much of the functionality you require in a more unified and .NET friendly interface. I personally have written a library with similar requirements to yours, using a combination of both.
Overall, I think your design looks good, but I don't know enough about your problem domain to know if you'll be painting yourself into a corner so to speak.
Specifically, to Question 1, I think that will work; however, anyone with a reference to an instance of Domain could remove any given Entry.
To Question 2, that is very likely how I would implement it myself, unless I had a compelling reason not to.

Related

Add and remove for ObservableCollection from another class

I created the ObservableCollection, which works with bindings, etc. Now I have a problem, I can't access it from other classes. Tried most things but probably missing some obvious things.
public MyFavorites()
{
ObservableServers = new ObservableCollection<Server>();
}
private ObservableCollection<Server> _myListOfServersObjects;
public ObservableCollection<Server> ObservableServers
{
get => _myListOfServersObjects;
set
{
if (_myListOfServersObjects != value)
{
_myListOfServersObjects = value;
OnPropertyChanged("ObservableServers");
}
}
}
full code: https://pastebin.com/KLFHwhKg
so i`m trying to add: https://pastebin.com/p7dBDcXq
This may get flagged because it's a very broad topic and not related to a specific issue. The general way you solve this is to create an interface such as the following:
public interface IServerCollection
{
IList<Server> ObservableServers { get; }
}
Notice that I've changed ObservableServers from an ObservableCollection<> to an IList<>. From the perspective of the other parts of your application the actual implementation doesn't matter, so choose the most basic interface object that will fulfill their needs. The actual implementation class fills in the details:
public class ServerCollection : IServerCollection
{
private IList<Server> _myListOfServersObjects = new ObservableCollection<Server>();
public IList<Server> ObservableServers {get => _myListOfServersObjects;}
}
So somewhere in your application something creates an instance of type ServerCollection, and it then gets passed in as an IList to whatever needs it e.g.:
public IServerCollection ServerCollection {get; private set;}
public MyFavorites(IServerCollection serverCollection)
{
ServerCollection = serverCollection;
}
This is known broadly as "Inversion of Control", and the actual passing of the interface instance into your class is known as "Dependency Injection". There are heaps of resources about both of these around the net, they're well worth reading up on. They solve a lot of problems but they also create a new one: you find yourself passing lots of these interface references around and storing them at multiple levels of your application. Thus, in a real application you typically use a dependency injection framework to largely automate the work for you, and in the case of .NET the package of choice 9 times out of 10 is Ninject.

Where to inject a dependent component which has already a constructor

I have a few business objects that have to be used together to get a specific outcome. Take a look at the following very simplyfied example for reference.
My question is: how do I get a reference to the agent using DI in the Station class ? I mostly prefer constructor injection, but that is not possible the Station class already has a stationCode as a required item.
Any ideas ?
Usage:
var station1 = new Station("xx");
var station2 = new Station("yy");
var route = new Route(station1, station2);
var length = route.GetLength();
public class Location
{
public int Position {get; set;}
}
public interface IAgent
{
Location GetLocation(string stationCode);
}
public class Station
{
private string _stationCode;
public Station(string stationCode)
{
_stationCode = stationCode;
}
public Location GetLocation()
{
// issue here: how to get a reference to the agent instance using DI
_agent.GetLocation(_stationCode);
}
}
public class Route
{
private Station _station1;
private Station _station2;
public Route(Station station1, Station station2)
{
_station1 = station1;
_station2 = station2;
}
public int GetLength()
{
var location1 = _station1.GetLocation();
var location2 = _station2.GetLocation();
result = location2.Position - location1.Position;
return result;
}
}
Your classes seem to be having an identity crisis. When using DI, you should have just 2 types of classes to deal with - injectables and newables. Your Station class seems like a kludge because it both provides a service (has dependencies) and has state. To make your classes DI-friendly, you should design classes that only provide state to classes that only do something with the state (services).
Route
This class is injectable - that is, it should be wired from the DI container.
public interface IRoute
{
int GetLength(Station station1, Station station2);
}
public class Route : IRoute
{
private readonly IAgent _agent;
public Route(IAgent agent)
{
if (agent == null) throw new ArgumentNullException("agent");
_agent = agent;
}
public int GetLength(Station station1, Station station2)
{
var location1 = _agent.GetLocation(station1.StationCode);
var location2 = _agent.GetLocation(station2.StationCode);
result = location2.Position - location1.Position;
return result;
}
}
Station
This class is newable - that is, you should always use the new keyword to instantiate it.
public class Station
{
private string _stationCode;
public Station(string stationCode)
{
_stationCode = stationCode;
}
public string StationCode
{
get { return _stationCode; }
// Optional: provide setter here
}
}
Usage
var station1 = new Station("xx");
var station2 = new Station("yy");
// IRoute is injected where you need to make the calculation
var length = _route.GetLength(station1, station2);
Perhaps it would be better to rename Route to something more appropriate, since it does not provide a route, it calculates the route length.
Frankly, if your Station class doesn't have any other state than a single string variable, it would probably make more sense to eliminate the class and just use strings for station1 and station2. But this is mostly just a matter of personal taste.
The concept of two types of classes to deal with, injectables and newables, is a good idea. But when newables should contain only limited business logic, you are drifting away from pure object-oriented concepts. When you write code for a complex domain model, your newable business classes contain both business logic and data. That´s also the intention of the question, I assume. The Station and Route classes are simple examples that contain much more logic and data in reality.
So I would suggest to have better separation of concerns, by separating code for storage from you business logic. I see two common solutions for this.
When data is loaded in memory, a separate StationStore class is an injectable that loads stations and stores them in the context of the business domain, eg. in a static property:
public IEnumarable<Station> Station.Store { get; internal set; }
All DI code can be hidden in a business base class. It´s less disturbing to put DI dependencies there. So an agent can be resolved in the generic base class based on the template types provided.
public class Station : BusinessClass<Station, StationAgent>
{
public string StationCode { get; internal set; }
public Location Location { get; internal set; }
public Station(string stationCode)
{
base.Load(stationCode, this);
}
}

C# Loose coupling

I can't explain my problem in English. so let me show my situation.
// in Main Project
public class User
{
public int version
{
get;
set;
}
}
// in Common Project
public class Service : BaseService
{
User _user;
public void SetVersion(int versionID)
{
_user.version = versionID;
}
public bool HasMessage()
{
return GetMessage(user.version);
}
}
And now I have another sub project. and I need use Service class in there.
so I wish make Service class independent from User class.
how do I do that?
I have only below solution. Is there any brilliant way?
public class Service : BaseService
{
Action<int> _getCallBack;
Func<int> _setCallBack;
public Service(Action<int> getCallback, Func<int> setCallBack)
{
_getCallback = getCallback;
_setCallback = setCallback;
}
public void SetVersion(int versionID)
{
setCallback(versionID);
}
public bool HasMessage()
{
return GetMessage(getCallback())
}
}
It depends on your use of 'User' in service.
You can add an interface IUser in Common project, and have User implement it.
Then in the other SubProject, write UserSub : IUser that also implements the interface IUser.
That way Service is independent, but you'll still have to implement something in each project that uses Service. (Which you need to do anyway, because Service currently uses it as an inner variable.
Yes there are several best practices which allow decoupling components, they are called design patterns. I would recommend to take a look at all of them to decide which one fits your context best. All of them have advantages and disadvantages, application scope and impact. There is no one brilliant solution for decoupling.
I think the command pattern can be the right one for your problem.
See: http://www.dofactory.com/net/design-patterns
and https://csharpdesignpatterns.codeplex.com

How to ensure the sequence of methods in fluent API?

I want to create fluent interface for some of my classes that I am building as part of a framework. I have created the methods and I am able to successfully chain methods. Now I want to ensure that I can handle the improper sequence of method calls.
The thing I am doing is something like CreateWorkflow -> OpenConfiguration -> ChangeUserName
In the above scenario it wouldn't make sense if ChangeUserName was called first because it is dependent on OpenConfiguration.
I am confused whether I am correct in creating a Fluent chain of methods for this scenario or not and how to make the sequence work. To me this scenario seems to be very suitable for creating a fluent API.
Here is the sample code that enforces method chain in specific order. I've used the example from here and fixed a minor issue in the original code. Here is the running code in dotnet fiddler
public interface IName
{
IAge WithName(string name);
}
public interface IAge
{
IPersist WithAge(int age);
}
public interface IPersist
{
void Save();
}
public class Person : IName, IAge, IPersist
{
public string Name { get; private set; }
public int Age { get; private set; }
public IAge WithName(string name)
{
Name = name;
return this;
}
public IPersist WithAge(int age)
{
Age = age;
return this;
}
public void Save()
{
// save changes here
}
}
The real key is if you require a specific sequence for a fluent API to work you API needs improvement. Maybe you should consider something a little different. If ChangeUserName needs OpenConfiguration the consumer of the API shouldn't care. Either internalize the dependency so the API becomes:
CreateWorkflow -> ChangeUserName
or if the consumer already has the Configuration Object you could use a Dependency Injection approach and make the API something like:
CreateWorkflow(IConfigurationManager) -> ChangeUserName
or
CreateWorkflow -> ChangeUserName(IConfigurationManager)
I show 2 approaches here as I am not sure what the scope of dependency is on your configuration class. By either internalizing the need or adding a required parameter onto the signature of one of the methods you should be able to eliminate the fixed sequence issue. Other than a clear "Start" and "Finish" to your API.
Hope this helps.

From anemic domain to domain driven

I was trying to find a clear and simple example of what an anemic domain really means. There is a lot of theory around, and also many well answered questions. Still, I could not get a clear picture about to what extent "anemic domain" meaning really goes. Therefore, I believe it would be simpler to see a dummy practical example of an anemic domain design and than ask you how could this be evolved to a domain driven one...
So, let's say we have a data entity of type TaskData:
public class TaskData
{
public Guid InternalId { get; set; }
public string Title { get; set; }
public string Details { get; set; }
public TaskState ExplicitState { get; set; }
public IEnumerable<TaskData> InnerTasks { get; set; }
}
And there is the need of an additional property called "ActualState", which is a computed state: if the Task has inner sub-tasks, the value strictly depends of the children, otherwise, the "ActualState" is equal to "ExplicitState"
If I write this logic in a separate service class (I call them "engines") we have:
internal class TaskStateCalculator
{
public TaskState GetState(TaskData taskData)
{
if (taskData.InnerTasks.Any())
{
if (taskData.InnerTasks.All(x => this.GetState(x) == TaskState.Done))
{
return TaskState.Done;
}
if (taskData.InnerTasks.Any(x => this.GetState(x) == TaskState.InProgress))
{
return TaskState.InProgress;
}
return TaskState.Default;
}
return taskData.ExplicitState;
}
}
The first question is:
Does the code above reflect an anemic domain design, even if the TaskStateCalculator service/engine is part of my Domain Layer?
If yes, in order to avoid it, we'll need to move the logic inside the TaskData class (and rename TaskData to Task). Am I right?
The second question is (actually a chain of them):
What if we have a more difficult situation? Let's say there is the need for a property called ComputeSomething inside Task entity, and the logic of this property needs to access the entire Task's repository. In this case, the Task class would have a dependency on TaskRepository. Would this be ok? How would EF construct an instance of such class? What is the alternative?
I was trying to find a clear and simple example of what an anemic domain really means
It's in fact really easy to go from an anemic domain model to a rich one.
Set all property setters to private and then add methods if you want to change state of a model.
Evaluate all Law of Demeter violations and add methods where suitable.
Eventually you will have a correct model.
In your case I would encapsulate that logic inside TaskData as your TaskStateCalculator violate Law of Demeter
public class TaskData
{
public Guid InternalId { get; private set; }
public string Title { get; private set; }
public string Details { get; private set; }
public TaskState ExplicitState { get; private set; }
public IEnumerable<TaskData> InnerTasks { get; private set; }
public TaskState GetState()
{
if (!InnerTasks.Any())
return ExplicitState;
if (InnerTasks.All(x => this.GetState(x) == TaskState.Done))
{
return TaskState.Done;
}
if (InnerTasks.Any(x => this.GetState(x) == TaskState.InProgress))
{
return TaskState.InProgress;
}
return TaskState.Default;
}
}
another thing is that I would probably not expose InnerTasks collection at all to the outside world (just have it as a member field). But it's hard to say as I do not know how the class is used in other scenarios.
Why private setters
Every time you have to change more than one property it's often better to describe the behavior with a method, as it's then impossible to forget to change all required properties. A method also describes better what you are trying to do than changing a set of properties.
Even if you just change a single property, that property can set the class in an invalid state as the change may not be compatible with the rest of the information in the class. Don't forget that encapsulation is one of the core principles in OOP

Categories