C# architecture - design patterns - c#

Not sure how to implement this scenario:
I have a base class let's say
public abstract class ConfigurationBase
{
public int Id {get; set;}
public string Name {get; set;}
}
and several derived classes
public class Config1 : ConfigurationBase
{
public string Url {get;set;}
public string ReferrerUrl {get; set;}
}
public string Config2 : ConfigurationBase
{
public string Domain {get; set;}
public bool AllowCookie {get; set;}
}
and a ConfigurationService which gets called with different parameters.
The idea would be that according to the parameters range to construct an instance of Config1 or Config2 or etc.
So the question is how can this be implemented in code?
Depending on same condition, instantiate a certain type.
One idea or how we had it so far, was to store the full qualified type to be instantiated in the database and construct it through reflection.
I am kind of reluctant to use this approach and I am asking if there are some other answers.

I think the proper way would be to create a factory class that handles creation of your configuration objects :
public class ConfigurationFactory {
public ConfigurationBase GetConfig(object[] parameters)
// Build your objects here according to your params... do stuff...
if (parameters[0] ...)
return new Config2(...);
elseif ...
return new Config1(...);
}
}
And then call that method with your parameters
ConfigurationFactory factory = new ConfigurationFactory();
ConfigurationBase config = factory.GetConfig(parameters);
Even though this method requires knowledge of how to create your different objets, it is only centralized in one place, so it can easily be changed.
Additionnaly, you might want to define an more generic interface defining how to get your configuration data, so that your objects will be easier to handle without knowing their concrete type.
Hope that helps

How about a Factory Pattern?
Edit: realized that you don't want to keep separate methods, in that case you will need an enum (at least) + an (ugly) method accepting all possible parameters ( that is the columns in your table)
public class ConfigurationService {
private ConfigurationBase CreateConfig1(string id, string name, string url, string referenceUrl){...}
private ConfigurationBase CreateConfig2(string id, string name, string domain, bool allowCookie){...}
public ConfigudationBase CreateConfig( string id, string name, string domain, bool allowCookie, string url, string referenceUrl, ConfigType configTypeEnum){
//call the expected factory method based on enum type.
}
}

If you have knowledge of all the subclasses of ConfigurationBase and the rules by which you instantiate them are the same, then you should be looking at a Factory pattern.
If you do not have knowledge of all the subclasses, then you need to pull the type in dynamically from a data store (not necessarily a database) and instantiate it at runtime.
If you do not know all the rules by which you instantiate the objects, you need to pull the rules from a data store and execute them.
Obviously, the more dynamic you make it the more complexity you are going to have to deal with.

A rather weird idea :) So don't blame me, is to build a hashvalue of the different parameters types and store an internal dictionary of hashvalue and specific Config type. So the factory method could be params, then build the hashvalue, retrieve the config type from the dictionary create and pass the params using reflection and return that.
I have to say, all my ideas resolve around reflection :)

Related

C# DDD - Domain Object Creation

I have started learning and creating CQRS with event sourcing using C#. I checked a lot of samples and in each sample, while constructing domain object all required domain fields are either passed using the constructor or a through a static method to create the domain object.
Should I pass the complete DTO to to the domain object to construct it instead of passing a long list of individual fields which I am getting from my top layer?
public class Student : AggregateRoot
{
public int ID { get; set; }
public string Name { get; set; }
// Without ID and Name a domain object should not be created
//Can I write like this?
public Student(StudentDto studentDto)
{
ID = studentDto.ID;
Name = studentDto.Name;
}
//Can I write like this?
public Student(int id,string name)
{
ID = id;
Name = name;
}
}
DTO is the wrong thing to use here. You are introducing an undesirable linkage between DTO's and domain objects and they evolve differently. You can imagine that domain objects may evolve to take more arguments or DTO's will need more properties.
In general, you should pass the explicit fields domain object needs in its constructor. If you end up having a long list of constructor arguments, either the domain object may be having too many resonsibilities, or you can use the Builder pattern to reduce number of explicit arguments needed.
I think this is one way to approach DDD persistence problem.
See https://vaughnvernon.co/?p=879, V. Vernon does the same thing.

Factory pattern with a class that can has different class sub types

I have data from multiple organisations (police, fire, office) that need output in different formats.
To achieve this, I defined the following (this is a little simplified):
Transaction class -
"Success" indicator - Boolean.
"Type of department"- String or Enum.
A class which can be of any type - Police, Fire or Office (My question is on this as you will see).
A GenerateOutput() method - to handle generation of file formats.
Police class
Age - String
VehicleNumber - Integer
Supervisor - String
Fire class
Name - String
FireEngineNumber - Integer
County - Enum
WorkTimings - Enum
Office Class
Age - String
DeskNumber - Integer
Department - String
PayScale - Enum
IsManagement - Bool
As you can see, the Police, Fire and Office classes dont share anything in common and are primarily intended as data carrying entities. I intend to use a Factory to return an appropriate generic (not a C# generic) Transaction object with the data (Transaction object with Police, Fire or Office data within it) and then pass the returned object to a Strategy pattern which determines the file format (CSV, Excel, or XML; specified in a configuration file) each one needs.
My problem is in the definition of the Transaction object.
What type does the class in "3." of the Transaction class need to be? The data for each org differs, there are no common members, I am unable to define a common class for all.
Is the overall design appropriate? What other designs should I consider?
Based on Peter's comments below:
I think using generics might work, I ran into a problem though. I would like to use a factory to return the object requested, using GetTransactionObject, as below. What should be the return type of GetTransactionObject to accomodate this.
class TransactionFactory
{
Dictionary<string, Type> typeClassLookup;
public TransactionFactory()
{
typeClassLookup = new Dictionary<string, Type>();
typeClassLookup.Add("Police", typeof(PoliceData));
typeClassLookup.Add("Fire", typeof(FireData));
}
Transaction<????> GetTransactionObject(string org)
{
if( typeClassLookup.TryGetValue(org, out typeValue))
{
switch (typeValue.ToString())
{
case "policeData":
transactionObject = new Transaction<PoliceData>() { Data = new PoliceData(), params = null};
case "FireData":
transactionObject = new Transaction<FireData>() {Data = new FireData(), params = null};
}
}
return transactionObject;
If the types really have nothing in common, then you need no explicit base class. System.Object suffices, just as with many other generic types (i.e. any generic type lacking a constraint).
In other words, you could declare as:
class Transaction<T>
{
public bool Success { get; private set; }
public T Entity { get; private set; }
public Transaction(bool success, T entity)
{
Success = success;
Entity = entity;
}
public void GenerateOutput() { /* something goes here */ }
}
Personally, I would avoid adding a "department type" member. After all, that's implicit from the type parameter T. But you could add that easily to the above if you want.
If and when you find that the types do have something in common, such that your Transaction<T> type needs to do more than simply hold onto an instance of one of those types (which is about all it can do without a constraint), then you will be able to put that commonality into an interface or base class (depending on the specific need), and specify that in a constraint for the Transaction<T> class.
Note that it's not clear what you mean for the GenerateOutput() to do, or how it should work. But assuming that you want output that is specific for each Entity value, it seems to me that that is your "something in common". I.e., it's not the Transaction<T> class at all that needs to implement that method, but rather each entity type. In that case, you have something like this:
interface IDepartmentEntity
{
void GenerateOutput();
}
class Office : IDepartmentEntity
{
public void GenerateOutput() { /* department-specific logic here */ }
}
// etc.
Then you can declare:
class Transaction<T> where T : IDepartmentEntity
{
public bool Success { get; private set; }
public T Entity { get; private set; }
public Transaction(bool success, T entity)
{
Success = success;
Entity = entity;
}
public void GenerateOutput() { Entity.GenerateOutput(); }
}
EDIT:
Per Prasant's follow-up edit, with a request for advice on the GetTransactionObject()…
The right way to do this depends on the caller and the context, a detail not provided in the question. IMHO, the best scenario is where the caller is aware of the type. This allows the full power of generics to be used.
For example:
class TransactionFactory
{
public Transaction<T> GetTransactionObject<T>()
where T : IDepartmentEntity, new()
{
return new Transaction<T>()
{
Data = new T(),
params = null
}
}
}
Then you call like this:
Transaction<FireData> transaction = factory.GetTransactionObject<FireData>();
The caller, of course already knowing the type it is creating, then can fill in the appropriate properties of the transaction.Data object.
If that approach is not possible, then you will need for Transaction<T> itself to have a base class, or implement an interface. Note that in my original example, the IDepartmentEntity interface has only one method, and it's the same as the GenerateOutput() method in the Transaction class.
So maybe, that interface is really about generating output instead of being a data entity. Call it, instead of IDepartmentEntity, something like IOutputGenerator.
In that case, you might have something like this:
class Transaction<T> : IOutputGenerator
{
// all as before
}
class TransactionFactory
{
public IOutputGenerator GetTransactionObject(string org)
{
if( typeClassLookup.TryGetValue(org, out typeValue))
{
switch (typeValue.ToString())
{
case "policeData":
transactionObject = new Transaction<PoliceData>() { Data = new PoliceData(), params = null};
case "FireData":
transactionObject = new Transaction<FireData>() {Data = new FireData(), params = null};
}
}
return transactionObject;
}
}
This is an inferior solution, as it means the caller can only directly access the IOutputGenerator functionality. Anything else requires doing some type-checking and special-case code, something that really ought to be avoided whenever possible.
Note: if the Transaction type has other members which, like the GenerateOutput() method, are independent of the contained type T here, and which would be useful to callers who don't know T, then a possible variation of the above is to not reuse the interface used for the department-specific data types, but instead declare a base class for Transaction<T>, named of course Transaction, containing all those members not related to T. Then the return value can be Transaction.
What type does the class in "3." of the Transaction class need to be?
To decouple your department classes from the various export types, I recommend you make the department classes implement a common interface. Something like this:
public interface Exportable {
// return a list of attribute names, values, and types to export
IList<Tuple<String, String, Type>> GetAttributes();
}
For example:
public class Police : Exportable {
public IList<Tuple<String, String, Type>> GetAttributes() {
// return list size 3 - attribute info for Age, VehicleNumber, Supervisor
}
}
Is the overall design appropriate? What other designs should I consider?
The Transaction class design doesn't seem well suited for this problem.
Consider an Export class with a method for each export type, each method which receives the attributes returned from the Exportable interface method. Basic outline:
public static class Export {
public static boolean CSV(IList<Tuple<String, String, Type>> attributes) {
// export attributes to CSV, return whether succeeded
}
public static boolean Excel(IList<Tuple<String, String, Type>> attributes) {
// export attributes to Excel, return whether succeeded
}
// same thing for XML
}

C# Primitive Types or Complex Types as Method Signatures?

What are the pros and cons of using Primitve Types or Complex Types?
When should you use primitive types over complex types and vice versa?
i.e.:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public int IQ { get; set; }
}
public void FooPrimitiveTypes (string firstName, string lastName, int age, int IQ)
{
}
public void FooComplexTypes(Person person)
{
}
To pass each property separately are generally used when you are dealing with disjoint values. Also, sometimes used on constructors. Bad practice.
This way is preferred when the values are related.
Why #1 is a bad practice - suppose you needed to add height. I'd much rather update one class by adding another property, instead of 50 methods.
Does Foo conceptually deal with a Person? Does all (or at least most) of Person get used by Foo, or is it just using a few bits of information that happen to be in Person? Is Foo likely to ever deal with something that's not a Person? If Foo is InsertPersonIntoDB(), then it's probably best to deal with Person.
If Foo is PrintName(), then maybe PrintName(string FirstName, string LastName) is more appropriate (or alternatively, you might define a Name class instead and say that a person has a Name).
If you find yourself creating half initialized temporary Person objects just to pass to Foo, then you probably want to break down the parameters.
Something to note is that when you use primitives they are being passed by value... the object reference is also being passed by value but since all the underlying references to the values are references it is effectively pass by reference. So depending on what you are doing this pass by value or pass by reference could be of importance. Also in the first case modifications to the primitives will not affect the values of the variables in the calling scope however modifying the object passed in will affect the object in the calling scope.

C# plugin architecture question

I'm working on a system monitoring application similar to Nagios in C#. I have a plugin interface defined as:
public interface IPlugin
{
PluginResult Execute();
}
Each plugin, depending on its functionality, will have a variable number of arguments. As an example, a ping plugin might take a hostname, # of packets, timeout value, etc. I want the user to be able to define these arguments per service in my user interface, but obviously these arguments won't be known until the application discovers which plugins are available. I'm curious as to how others might design a plugin such that these variable arguments would be discoverable by the application.
Right now, as an example, I've got a ping plugin:
public class PingPlugin : IPlugin
{
private const string RESULT_MESSAGE = "Average ms: {0}; Packet loss: {1}";
private string _hostname;
private int _packets;
private int _timeout;
private int _warningTimeThreshold;
private int _warningLossThreshold;
private int _errorTimeThreshold;
private int _errorLossThreshold;
public PingPlugin(
string hostname,
int packets,
int timeout,
int warningTimeThreshold,
int warningLossThreshold,
int errorTimeThreshold,
int errorLossThreshold)
{
_hostname = hostname;
_packets = packets;
_timeout = timeout;
_warningTimeThreshold = warningTimeThreshold;
_warningLossThreshold = warningLossThreshold;
_errorTimeThreshold = errorTimeThreshold;
_errorLossThreshold = errorLossThreshold;
}
public PluginResult Execute()
{
// execute the plugin
}
}
I thought I might be able to discover the constructor parameters using reflection and present the user with a property grid to allow the configuration of the plugin, but I'm not sure the best way to provide a set of default values with this design. What might some alternatives be?
Have you considered looking at the Managed Extensibility Framework?
Rather than have a Plugin constructor determine the parameters, you might consider something like this:
public interface IPlugin
{
PluginResult Execute(Object parameters);
}
public class PingParameters
{
//Various parameters here, including [Description] and [DisplayName] attributes if you wish
}
public class ParametersTypeAttribute : Attribute
{
public Type Type { get; private set; }
public ParametersTypeAttribute(Type type)
{
Type = type;
}
}
[ParametersType(typeof(PingParameters))]
public class PingPlugin : IPlugin
{
public PluginResult Execute(Object parameters)
{
return Execute((PingParameters) parameters);
}
private PluginResult Execute(PingParameters parameters)
{
//Your execution code here
}
}
This gives you more flexibility for the parameters, as you can add attributes, provide setter validation and even specify designer/converter integration for the property grid. The property grid hooks up directly to the parameters object.
You can apply the [DefaultValue] attribute to the parameters.
In C# for, you can use new syntax for this: int warningLossThreshold = 30,
I voted +1 for the MEF answer too, it will solve many of your problems.
However, if you want to do it without MEF, it seems to me that you are missing some way to have the plugins tell your application via metadata, about the parameters it require.
One possible design could be this: Have an IPluginProvider interface, which your application can discover. This should have a parameterless constructor, so you can easily new up an instance. It should then have methods that return whatever metadata is needed (such as "pretty names" for the parameters, which are required, what are some sensible defaults, and so on). It should then include CreateInstance method, which takes the actual parameters as IDictionary<string,object> and returns the actual IPlugin instance.
I haven't looked at the MEF (will do now).
I had a problem almost identical to yours, I solved it with Attributes.
I have a UI which (calls BL which) uses reflection to show all the available "services" (nothing more than appropriately decorated classes).
When the user selects a "service" further attributes drive the UI. The attribute "schema" is fairly straight forward, and allows for any number of parameters with any name. By introducing constants (with the attribute definition) you can standardise common things like "name" so that your services are consistent.
All the data is then stored in a Key-Value pair table.
The great thing about this is that you can just dump new / modified "service" assemblies in teh bin dir - no extra work required. The only dependency is the attribute definitions assembly - so keep this lean.
Source code is at CodePlex if you want to "steal" some :)

Constraining string length in domain classes

I have a persistence ignorant domain model that uses abstract repositories to load domain objects.
The concrete implementation of my repositories (the data access layer (DAL)) uses entity framework to fetch data from a sql server database.
The database has length constraints on a lot of its varchar columns.
Now imagine that I have the following domain class:
public class Case
{
public Case(int id, string text)
{
this.Id = id;
this.Text = text;
}
public int Id { get; private set; }
public string Text { get; set; }
}
And an abstract repository defined as follows:
public abstract class CaseRepository
{
public abstract void CreateCase(Case item);
public abstract Case GetCaseById(int id);
}
The [text] column of the table in sqlserver is defined as nvarchar(100)
Now I know that I mentioned that my domain class (Case) was persistence ignorant, nevertheless I feel that it is wrong that it allows
for values of the text parameter that cannot ultimately be saved by my concrete repository implementation because the entity framework
will throw an exception when assigning the text property to the entity framework generated class when it is longer than 100 characters.
So I have decided that I wish to check this constraint in the domain model, because this allows me to check data validity before attempting to
pass it on to the DAL, and thus making error reporting more centric to the domain object. I guess you could argue that I could just check the
constraint in my constructor and in the property setter, but since I have hundreds of classes that all have similar constraints I wanted a
more generic way to solve the problem
Now, the thing that I've come up with is a class called ConstrainedString, defined as follows:
public abstract class ConstrainedString
{
private string textValue;
public ConstrainedString(uint maxLength, string textValue)
{
if (textValue == null) throw new ArgumentNullException("textValue");
if (textValue.Length > maxLength)
throw new ArgumentException("textValue may not be longer than maxLength", "textValue");
this.textValue = textValue;
this.MaxLength = maxLength;
}
public uint MaxLength { get; private set; }
public string Value
{
get
{
return this.textValue;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
if (value.Length > this.MaxLength) throw new ArgumentException("value cannot be longer than MaxLength", "value");
this.textValue = value;
}
}
}
Furthermore I have an implementation of ConstrainedString called String100 :
public class String100 : ConstrainedString
{
public String100(string textValue) : base(100, textValue) { }
}
Thus leading to a different implementation of Case that would look like this:
public class Case
{
public Case(int id, String100 text)
{
this.Id = id;
this.Text = text;
}
public int Id { get; private set; }
public String100 Text { get; set; }
}
Now, my question is; Am I overlooking some built-in classes or some other approach that I could use instead? Or is this a reasonable approach?
Any comments and suggestions are most welcome.
Thank you in advance
I believe your validation should reside in your domain model. The constraints on your fields directly represent some business logic. Ultimately you have to validate before you persist anyway.
I think this depends on many factors (as well as some personal preferences). Sometimes the constraint should form part of the domain object - for example with social security numbers/passport numbers... - these normally have a fixed length and cannot vary as a domain rule - not a data persistence rule (although you might constrain the db as well).
Some prefer to not have these sort of checks in their domain model and instead have something like a validation attribute on the property that can be inspected and executed external from the domain object by a seperate validator.
The issue you might have with your method (although not difficult to get around) is getting any ORM/Mapper - if you're using one - to know how to map a string to/from the db to your ConstrainedString.
The ConstrainedString might not get around the issue of the domain object having extra info about the constraint as it might need to construct the ConstrainedString
If you change the constraints of a Case, it makes sense that you'd have to make a new one - you've changed the contract, and old code will no longer know if it's meeting the requirements or not.
Instead of worrying about what your repository will or will not allow, define what you will allow in your class, and make sure that you find a way to work with any repository that you change to in the future. You own your API - your dependencies do not.

Categories