How/where to create a void method in CQRS pattern - c#

I am trying to implement the CQRS pattern in clean architecture.
I know If a commads/query then i need to add a folder named as commads/query in applictionLayer.
Now I want to create a void method. not a command or query it is just a void method. and I want to use this again into my queries and commands.
public void FormatSomethingHtml(Something something)
{
something.FinePrint = _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
// removed rest
}
I don't know where should create this method.
If I create this method inside commandHandler, I could not reuse it.
i.e:
public class UpdateSomethingCommandHandler : IRequestHandler<UpdateSomethingCommand, Something>
{
// removed rest
public void FormatSomethingHtml(Something something)
{
something.FinePrint = _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
// removed rest
}
}
In above method I can use inside UpdateSomethingCommandHandler.
But I could not reuse it in another handler.
ie. When I call like this
new UpdateSomethingCommandHandler.FormatSomethingHtml(something); I got error.
Where can create a common method?

This should be a utility service and inject it in any query/handler you need.
Ex:
public interface IFormatService
{
void FormatSomethingHtml(Something something)
}
public class HtmlFormatService: IFormatService
{
public void FormatSomethingHtml(Something something)
{
something.FinePrint = _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
// removed rest
}
}
In your handler, you would inject it and use it just like any other service
Also, I would consider changing the return type to either Something so you can update the object and return ot or simply accept a string and return the formatted string like this:
public string FormatSomethingHtml(string something)
{
return _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
}
In your handler/query
var something = new Something();
something.Fingerprint = _formatter.FormatSomethingHtml(...)

Related

c# access to central data

my Situation:
I've got a lot of Data which i need in every corner of my program. Something like Data Paths and so on. I need those informations in various classes.
What is the best way to implement that?
Sample:
class A
{
public string GetPath()
{
return "C:\\";
}
}
class B
{
private void sample()
{
A ab = new A();
string path = ab.GetPath();
}
}
class C
{
private void sample()
{
A ab = new A();
string path = ab.GetPath();
}
}
So in my case i always need to initiate A and A always need to work inside the function "GetPath".
I want to prevent that the "GetPath"-Function always will be processed.
Sounds like dependency injection may be a relevant concept to look into. There are lots of tools and frameworks to help you with advanced versions of this, but the core principle is as follows:
Simplified example:
An interface do declare what you need, without specifying how it will be provided:
interface IDataProvider {
string GetPath();
}
An implementing class to provide it (could be completely different, so long as it implements the interface correctly):
public class DataProvider : IDataProvider(){
private string _path = "";
public GetPath()
{
// Load only first time
if (string.IsNullOrEmpty(_path))
{
// You could return a hard-coded value, like this, or fetch
// data in a more flexible way (config? DB? Web-service? ...?)
_path = #"C:\...";
}
return _path;
}
}
Now pass the implementation in as an instance of the interface wherever you need it:
class C {
IDataProvider _dataProvider;
public C(IDataProvider provider)
{
// This has no knowledge about DataProvider, it only cares
// about this being an instance of an object that implements
// the signature "GetPath()":
_dataProvider = provider;
}
private void Sample()
{
string path = _dataProvider.GetPath();
}
}
Now, from wherever you start up your project:
public class StartApp
{
IDataprovider prov = new DataProvider();
C myC = new C(prov);
myC.Sample();
// ..and similarly for other components,
// use the same Provider-instance:
D yourD = new D(prov);
ED yourE = new E(prov);
}
You could also read config-values from files or a database, or whatever you like in DataProvider. The point here is to fetch the data once, and then use it everywhere via a shared instance.
As BWA says in comments, you should be using a static class for A. In example:
static class A
{
public static string GetPath()
{
return "C:\\";
}
}
A static class, function or variable is one where there is only one within the program, so can be accessed from anywhere. You cannot, however, declare instances of a static class. To access this function, use the following:
string path = A.GetPath();
If you need to declare instances of this class, use a static function or variable to store the path variable instead.
What About encapsulate it before for more secure against sof exception.
not tested code
private string getPath;
public string GetPath
{
get => getPath; set => getPath=value;
}

c# Method redirect or overload (possibly with arguments)

I'm not sure if this is possible, but I'm essentially looking for a class constructor redirect.
An example of what I'm attempting:
public class Test
{
public Test() : TestFromOther();
//public Test() => TestFromOther();
public TestFromOther() { return 'this' with some stuff done here }
//another case might be => TestFromOther(defaultparam)
}
I'm trying to do this so that even if the base constructor is called, it redirects to my method.
(I don't want to just put a call to TestFromOther() inside the body of the constructor.. I'm specifically looking for the :TestFromOther() or => operator.. I've seen it before but for the life of me cannot remember how it's done)
EDIT: It's mostly for cleanliness and readability, thus having the Logger.GetCurrentClassLogger();
public class Logger {
private string _callerClass;
// obviously this doesn't function, but is the ideal end product
//public Logger() => GetCurrentClassLogger();
// Ideally I want the constructor to be this function and if a user, for
// whatever reason does call the empty constructor, it goes to this func
public Logger GetCurrentClassLogger() {
StackFrame[] sf = new StackTrace().GetFrames();
string callerName = "";
foreach (StackFrame f in sf) {
if (f == sf[0])
continue;
if (f.GetMethod().Name == ".ctor") {
callerName = f.GetMethod().ReflectedType.Name;
break;
}
callerName = f.GetMethod().Name;
break;
}
this._callerClass = callerName;
return this;
}
}
I trimmed this down about as far as I could for use as an example
You can "chain" constructors. it's not a redirection.
public class Test
{
public Test() : this("defaultParam") {}
public Test(string stringParam) { }
}
It will execute Test(string stringParam) first and then Test()
Edit per the comments and the edited question
static method is the way to achieve what you like:
public static Logger GetCurrentClassLogger() {...}
and the instantiation:
var logger = Logger.GetCurrentClassLogger(); // no new key word here
No, this is not possible. C# only allows you to call a base constructor or another constructor of the current class.
BTW the thing TestFromOther is also not a valid syntax, as it it is neither a method nor a constructor. Further, a constructor is not allowed to return anything.
The typical solution here would rather be to use a single constructor (possibly private such that it cannot be accessed from the outside) that does what you want. Or you may use helper methods for the initialization.

How to call a method implicitly after every method call?

Sorry for the terrific Title for the post. I am bit curious to know if below problem does have any solutions or not. The situation is I have a function called SaveSecurity(); which I need to call after every function. Like below:
public void AddUser(string ID, string Name, string Password)
{
///some codes
SaveSecurity();
}
public void DeleteUser(User ObjUser)
{
///some codes
SaveSecurity();
}
public void AddPermission(string ID, string Name, AccessType Access)
{
///some codes
SaveSecurity();
}
public void DeletePermission(Permission ObjPermission)
{
///some codes
SaveSecurity();
}
public void AddRole(string ID, string Name)
{
Roles.AddRole(ID, Name);
SaveSecurity();
}
public void SaveSecurity()
{
///Saves the data
}
And many more. So now if we look there is a similarity to all the function is that at last it calls for the SaveSecurity() after the end of the function. My question is:
Is there a way to call this function after every function with out writing the same line again and again?
My Class Diagram looks like this
You need to look into repository pattern,
Seperate your classes and there operations,
Create another layer (call it business layer) or whatever which will be calling different methods of different classes...
ATM you are trying to follow OOP but all you are doing is functional programming..
Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application
Edit After adding class diagram
Your collection classes are actually repository class, you will need to move your methods like deletePermissions, deleteRole to there respective repository classes like permissionsRepo (keep it named as collections if you want) and roleRepo..
So you already have an object class and a repository class of object (can be together) but I like to keep them separate, repostory classes will do what they need to do, like..
// Make changes to DB
// Make changes to AD
// Makes changes to web services etc...
Your manager class may dulicate methods of repository classes but they will only calling them,
PermissionManager.DeletePermissions(PermissionObject);
Then in PermissionManager Class you will have method,
DeletePermissions(Permissions pObject)
{
PermissionRepo.Delete(pObject);
}
Above is just adding a layer to make your code look more readable and future proof in very short time, but if you have more time to invest you can look into Observer pattern too...
Implement Observer pattern in C#
Each time your object changes it's state you can call SaveSecurity method (which will be in another class (Name it Changes maybe). If you don't want to call SaveSecurity for each change of object, you can add a property to your object e.g. IsSecurityChanged ? if yes then call SaveSecurity.
More to explain but if you look at Observer pattern above you will get an idea.
One more way but I won't personally recommend is, to use IDisposable interface, then in dispose method call SaveSecurity method for the object. BUT ITS NOT RECOMMENDED BY ME.
With just C# you can't, but there are some solutions that might help.
The best I know is PostSharp. It will give you the ability to define actions before and after a method is being called (for example). Some information on it can be found here and here.
The only thing you have to do then is to decorate the methods you want to call SaveSecurity for with an attribute.
If you don't want to use such tools, just keep it as is. It is okay the way it is.
You can use some kind of Aspect oriented programming (don't know how to do it in C#, but try googling it).
Another way that would not be better than simply calling one function at the end of another, would be create helper function with functional parameter that execute its parameter and then call your security function. But then body of each function would look something like (if I remember C# lambda correctly):
CallAndSaveSecurity(() => /* some code */);
So it would contain something extra as much as your original solution.
Btw, maybe you need more in your call anyway. If you want that function to be called even when exception happen, you need
try{
// some code
} finally {
SaveSecurity();
}
and hiding that into functional helper makes sense.
using System;
namespace Shweta.Question
{
public class User
{ }
public class Permission
{ }
public enum AccessType
{
none,
full,
other
}
public class Roles
{
public static void AddRole(string id, string name)
{
}
}
public class Shweta
{
public void AddUser(string ID, string Name, string Password)
{
///some codes
SaveSecurity();
}
public void DeleteUser(User ObjUser)
{
}
public void AddPermission(string ID, string Name, AccessType Access)
{
}
public void DeletePermission(Permission ObjPermission)
{
}
public void AddRole(string ID, string Name)
{
Roles.AddRole(ID, Name);
}
public void SaveSecurity()
{
///Saves the data
}
public TResult CallMethod<TResult>(Func<TResult> func)
{
try
{
return func();
}
catch (Exception e)
{
// Add Handle Exception
// replace the next line by exception handler
throw e;
}
}
public void CallMethod(Action method)
{
this.CallMethod(() => { method(); return 0; });
this.SaveSecurity();
}
public static void test()
{
var s = new Shweta();
s.CallMethod(() => s.AddRole("theId", "theName"));
s.CallMethod(() => s.DeleteUser(new User()));
s.CallMethod(() => s.AddPermission("theId", "theName", AccessType.full));
s.CallMethod(() => s.DeletePermission(new Permission()));
s.CallMethod(() => s.AddRole("theId", "theName"));
}
}
}

Some design-pattern suggestions needed

C#. I have a base class called FileProcessor:
class FileProcessor {
public Path {get {return m_sPath;}}
public FileProcessor(string path)
{
m_sPath = path;
}
public virtual Process() {}
protected string m_sath;
}
Now I'd like to create to other classes ExcelProcessor & PDFProcessor:
class Excelprocessor: FileProcessor
{
public void ProcessFile()
{
//do different stuff from PDFProcessor
}
}
Same for PDFProcessor, a file is Excel if Path ends with ".xlsx" and pdf if it ends with ".pdf". I could have a ProcessingManager class:
class ProcessingManager
{
public void AddProcessJob(string path)
{
m_list.Add(Path;)
}
public ProcessingManager()
{
m_list = new BlockingQueue();
m_thread = new Thread(ThreadFunc);
m_thread.Start(this);
}
public static void ThreadFunc(var param) //this is a thread func
{
ProcessingManager _this = (ProcessingManager )var;
while(some_condition) {
string fPath= _this.m_list.Dequeue();
if(fPath.EndsWith(".pdf")) {
new PDFProcessor().Process();
}
if(fPath.EndsWith(".xlsx")) {
new ExcelProcessor().Process();
}
}
}
protected BlockingQueue m_list;
protected Thread m_thread;
}
I am trying to make this as modular as possible, let's suppose for example that I would like to add a ".doc" processing, I'd have to do a check inside the manager and implement another DOCProcessor.
How could I do this without the modification of ProcessingManager? and I really don't know if my manager is ok enough, please tell me all your suggestions on this.
I'm not really aware of your problem but I'll try to give it a shot.
You could be using the Factory pattern.
class FileProcessorFactory {
public FileProcessor getFileProcessor(string extension){
switch (extension){
case ".pdf":
return new PdfFileProcessor();
case ".xls":
return new ExcelFileProcessor();
}
}
}
class IFileProcessor{
public Object processFile(Stream inputFile);
}
class PdfFileProcessor : IFileProcessor {
public Object processFile(Stream inputFile){
// do things with your inputFile
}
}
class ExcelFileProcessor : IFileProcessor {
public Object processFile(Stream inputFile){
// do things with your inputFile
}
}
This should make sure you are using the FileProcessorFactory to get the correct processor, and the IFileProcessor will make sure you're not implementing different things for each processor.
and implement another DOCProcessor
Just add a new case to the FileProcessorFactory, and a new class which implements the interface IFileProcessor called DocFileProcessor.
You could decorate your processors with custom attributes like this:
[FileProcessorExtension(".doc")]
public class DocProcessor()
{
}
Then your processing manager could find the processor whose FileProcessorExtension property matches your extension, and instantiate it reflexively.
I agree with Highmastdon, his factory is a good solution. The core idea is not to have any FileProcessor implementation reference in your ProcessingManager anymore, only a reference to IFileProcessor interface, thus ProcessingManager does not know which type of file it deals with, it just knows it is an IFileProcessor which implements processFile(Stream inputFile).
In the long run, you'll just have to write new FileProcessor implementations, and voila. ProcessingManager does not change over time.
Use one more method called CanHandle for example:
abstract class FileProcessor
{
public FileProcessor()
{
}
public abstract Process(string path);
public abstract bool CanHandle(string path);
}
With excel file, you can implement CanHandle as below:
class Excelprocessor: FileProcessor
{
public override void Process(string path)
{
}
public override bool CanHandle(string path)
{
return path.EndsWith(".xlsx");
}
}
In ProcessingManager, you need a list of processor which you can add in runtime by method RegisterProcessor:
class ProcessingManager
{
private List<FileProcessor> _processors;
public void RegisterProcessor(FileProcessor processor)
{
_processors.Add(processor)
}
....
So LINQ can be used in here to find appropriate processor:
while(some_condition)
{
string fPath= _this.m_list.Dequeue();
var proccessor = _processors.SingleOrDefault(p => p.CanHandle(fPath));
if (proccessor != null)
proccessor.Process(proccessor);
}
If you want to add more processor, just define and add it into ProcessingManager by using
RegisterProcessor method. You also don't change any code from other classes even FileProcessorFactory like #Highmastdon's answer.
You could use the Factory pattern (a good choice)
In Factory pattern there is the possibility not to change the existing code (Follow SOLID Principle).
In future if a new Doc file support is to be added, you could use the concept of Dictionaries. (instead of modifying the switch statement)
//Some Abstract Code to get you started (Its 2 am... not a good time to give a working code)
1. Define a new dictionary with {FileType, IFileProcessor)
2. Add to the dictionary the available classes.
3. Tomorrow if you come across a new requirement simply do this.
Dictionary.Add(FileType.Docx, new DocFileProcessor());
4. Tryparse an enum for a userinput value.
5. Get the enum instance and then get that object that does your work!
Otherwise an option: It is better to go with MEF (Managed Extensibility Framework!)
That way, you dynamically discover the classes.
For example if the support for .doc needs to be implemented you could use something like below:
Export[typeof(IFileProcessor)]
class DocFileProcessor : IFileProcessor
{
DocFileProcessor(FileType type);
/// Implement the functionality if Document type is .docx in processFile() here
}
Advantages of this method:
Your DocFileProcessor class is identified automatically since it implements IFileProcessor
Application is always Extensible. (You do an importOnce of all parts, get the matching parts and Execute.. Its that simple!)

How to check the type of a list if inheritance is used

I'm currently working on a C# program that creates a List, of object Task, the object Task is a base class and many other inherit from it. What I want to is compare the type of one of the object within said list to see which form should be opened in order to edit it.
This is the code I have already created.
private void itemEdit_Click(object sender, EventArgs e)
{
int edi = taskNameBox.SelectedIndex;
Task checkTask = todoList.ElementAt(edi);
if(checkTask.GetType is Note)
{
noteBuilder editNote = new noteBuilder(todoList);
editNote.Show();
}
else if(checkTask.GetType is extendedTask)
{
extendedTaskBuilder editTask = new extendedTaskBuilder(todoList);
editTask.Show();
}
else if(checkTask.GetType is Reminder)
{
reminderBuilder editReminder = new reminderBuilder(todoList);
editReminder.Show();
}
else if (checkTask.GetType is Appointment)
{
appointmentBuilder editAppointment = new appointmentBuilder(todoList);
editAppointment.Show();
}
}
On a secondary note would it be easier if instead of passing the list between the forms and generating a new object of the form that display information that I instead pass a single object between forms and just update the form every time a new element is added to the list.
Many thanks
Have you tried checking like this:
if (checkTask is Note)
{
}
...
Have you considered creating a base class for all types you are now switching between and call a virtual (abstract) method?
Put all code now in the if in the overridden abstract method.
Advantages:
- The intelligence of the switch is within the classes where it belongs.
- When a new type is added you get a compiler error to also add this feature to the new type.
I suggest that instead of doing that series of ‘if’ clauses, you use inheritance to achieve what ou need. First you create a virtual method in your base class. A virtual method means it won't have any implementation in the base class, only the declaration:
public class Task
{
(...)
public virtual void ShowEditForm(IList todoList);
(...)
}
Then you create the child class methods (I'm assuming the todoList object is a IList, but just change it if it is not).
public class Note: Task
{
(...)
public override void ShowEditForm(IList todoList)
{
(new noteBuilder(taskToEdit)).Show();
}
(...)
}
public class Reminder: Task
{
(...)
public override void ShowEditForm(IList todoList)
{
(new reminderBuilder(taskToEdit)).Show();
}
(...)
}
I didn't write all the classes, but I think you've got the idea. To call the method, you just call the method from Task class, and the right method will be executed:
int edi = taskNameBox.SelectedIndex;
Task checkTask = todoList.ElementAt(edi);
checkTask.ShowEditForm(todoList);
This way, when you want to create new types of Task, you just have to create the child class, with the proper method, and the inheritance system will do the rest.
One more thing, the override keyword in the child method declaration is important, because it says to the compiler that this method should be called even if you call it from the BaseClass.
First, to your second note. What you are talking about doing is having a global object that all forms refer to in some parent. That can work, however you will need to make sure there is some mechanism in place that makes sure all of the forms are synchronized when one changes, and this can get messy and a bit of a mess to maintain. I am not necessarily advocating against it per say, but just adding words of caution when considering it :)
As to your posted code, it would probably be better to turn this into a Strategy Pattern approach, where all forms inherit from a base class/interface which has a Show method. Then all you need to do is call checkTask.Show(todoList);. If you do not want that coming from the Task, then you could have your forms all inherit from the above base and you could use a factory pattern that takes in the Task and list and returns the appropriate form on which you simply call form.Show();
Code like this is difficult to maintain, you are probably better off abstracting this out, like so (assuming Task is not the one included in .net):
public interface IBuilder
{
void Show();
}
public abstract class Task
{
// ...
public abstract IBuilder GetBuilder(TaskList todoList);
// ...
}
public class Note : Task
{
public override IBuilder GetBuilder(TaskList todoList)
{
return new noteBuilder(todoList);
}
// ...
}
// etc.
private void itemEdit_Click(object sender, EventArgs e)
{
int edi = taskNameBox.SelectedIndex;
Task checkTask = todoList.ElementAt(edi);
IBuilder builder = checkTask.GetBuilder(todoList);
builder.Show();
}
Alternately, you can use an injection pattern:
public abstract class Task
{
protected Task(Func<TaskList, IBuilder> builderStrategy)
{
_builderStrategy = builderStrategy;
}
public IBuilder GetBuilder(TaskList todoList))
{
return _builderStrategy(todolist);
}
}
public class Note : Task
{
public Note(Func<TaskList, IBuilder> builderStrategy) : base(builderStrategy) {}
}
// ...
note = new Note(x => return new noteBuilder(x));

Categories