Central Message Manager for managing different messages between different classes - c#

I am writing an application in C#. Now i am thinking over and over again about its design. Have already changed my mind 3 or 4 times but thankfully for the good.
After few iterations i come up with a solution but i am still wondering what is the best way to achieve that with C#.
Basically i will have a class lets call it MessageManager, and after each action different classes will send a message to MessageManager and MessageManager will send the message depending on the response. Then i will have another manager call it UIManager it will perform all the UI switching or inform the MessageManager in case of any core/helper operation is required.
Now the thing is messages could make up to like 50-60 types each will have different type of arguments. And i want to design it in a way if i have new messages in future it can accommodate that as well.
What is the best way to accomplish that in C# like what will be the best for such case delegates, events. Flexibility is the most important thing.

I believe that combining the Observer pattern (publish/subscribe logic) along side with the Mediator one can be a good solution to your problem. Your Mediator class will act as an Event Manager (most of your classes will depend on it as a mediator rather than depending on each others) :
public class MessageManager{
private Dictionary<string,List<MessageListener>> listeners;
public void sendMessage(Message m){
//loop over listeners of m
}
public void addMessageListener(MessageListener ml){
//add a listener
}
public void removeMessageListener(MessageListener ml){
//remove a listener
}
}
Message would be the parent interface, having a generic abstraction at this level is very important as it avoids the MessageManager from distinguishing between your 50-60 types of messages and thus becoming a nightmare to maintain. The specificity of depending on a particular sub-type of Message should be moved to a lower level: the direct consumers.

Related

What is the difference between using MessagingCenter and standard .NET event handlers for informing interested parties of changes?

What is the difference between using MessagingCenter and standard .NET event handlers for informing interested parties of changes?
Two (untested) implementations of the same thing are below to demonstrate:
public class FooClass {
public event EventHandler SomeEvent;
public void DoSomeWork() {
// ... stuff
if(SomeEvent != null)
SomeEvent(this, EventArgs.Empty);
}
}
public class BarClass {
FooClass _foo;
public BarClass() {
_foo = new FooClass();
_foo.SomeEvent += delegate {
// ... did something
};
}
}
Verses:
public class FooClass {
public const string SomeEventName = "SomeEvent";
public void DoSomeWork() {
// ... stuff
MessagingCenter.Send<FooClass>(this, SomeEventName);
}
}
public class BarClass : IDisposable {
public BarClass() {
MessagingCenter.Subscribe<FooClass>(this, FooClass.SomeEventName, delegate {
// .. did something
});
}
public void Dispose() {
MessagingCenter.Unsubscribe<FooClass>(this, FooClass.SomeEventName);
}
}
From what I can tell there doesn't seem to be any difference, but if anyone can suggest any pros or cons for either, that'd help me understand. Currently, I've been using event handlers.
Is there any point in switching to using MessagingCenter? Or any new best practice?
The MessagingCenter from Xamarin is used to reduce coupling between ViewModels, as the sender and receiver do not need to know each other.
You can still build a similar structure by creating something like an "EventHub"/"EventAggregator" which knows sender and receiver and uses .NET events.
The MessagingCenter itself is kind of an EventAggregator
ImageSource : https://msdn.microsoft.com/en-us/library/ff921122.aspx
Here is a nice explanation of EventAggregators.
An Event Aggregator is a simple element of indirection. In its
simplest form you have it register with all the source objects you are
interested in, and have all target objects register with the Event
Aggregator. The Event Aggregator responds to any event from a source
object by propagating that event to the target objects.
To Answer the question:
Is there any point in switching to using MessagingCenter? Or any new
best practice?
If you are not using something like an EventAggregator it is a good choice to switch to the MessagingCenter, or build an EventAggregator on your own.
As Saruman made a good hint on explaining what coupling is. You allways want to reduce coupling for a clean code.
MessagingCenter is basically used in the Model-View-ViewModel
pattern.
It is a great way to communicate and pass data or notify about
updates among ViewModels without knowing who sent it to whom via a simple Message Contract.
Ex. In one screen if you make any service call to fetch the new data
and you want to notify other screens to update their UI via
broadcasting message from your current screen, then MessagingCenter
is the best approach.
It decouples them without making any dependency among ViewModels,
while EventHandlers makes dependency and may prohibit something
from being released. You explicitly have to decouple event handlers
from the events to better release the resources.
MessagingCenter should be applied when the receiver doesn't care
who sent the message and the sender doesn't care who will receive it.
Events should be used when the receiver needs to know who sent the
message, but the sender still doesn't care who handles it.
It is good to use MessagingCenter over Events but, if you make too much use of
too many Messages using MessagingCenter, it would be hard to
identify who sent it and when sent it, the relation between messages
would be hard to guess, thus making it hard time while debugging the
app.
If you have access to those classes (i.e from where you want to call your methods) then there really is not a lot of difference.
However if you don't have access to those classes(i.e inside a view model or decoupled class) then message subscription event aggregation is a useful tool
Message center reduces coupling and enables view models and other
components to communicate with without having to know anything about
each other besides a simple Message contract.
Coupling
In software engineering, coupling is the degree of interdependence
between software modules; a measure of how closely connected two
routines or modules are the strength of the relationships between
modules.

How to use Caliburn Micro's EventAggregator to send empty events (no payload)?

I found articles about and solutions to this question pertaining to Prism, but I didn't find anything pertaining to Caliburn Micro. I checked all questions here tagged with Caliburn.Micro and EventAggregator, but didn't find anything Caliburn specific about this seemingly basic issue.
Scenario: I want to publish events to the EventAggregator that don't have any information, other than signaling that something happened.
Problem: First, in Caliburn Micro, the EventAggregator's Publish() method requires an instance of a type to be sent. Second, subscribing and handling events require the implementation of the IHandle<T> interface, where T is the type of instances that we want to receive. It seems that this is fully designed around publishing and handling actual data.
Goal: To be able to publish simple events without having to create and instantiate multiple empty/dummy classes, and without having to Handle() unnecessary events that I need to filter further with conditionals.
My solution so far
This is what I want to improve/replace. (Obviously, this solution is problematic because it creates tighter coupling around the concrete classes, but in my use case this is not a big issue, since it's a small project with singular publishing components for a given event, and the EventAggregator serves other practical goals.)
I made a generic Signal<T> class that implements the singleton pattern, providing a static instance of itself through the Instance property:
public class Signal<T>
{
public static readonly Signal<T> Instance = new Signal<T>();
private Signal() { }
}
So I can publish events in the following way (SignalSourceClass is an example):
_eventAggregator.PublishOnUIThread(Signal<SignalSourceClass>.Instance);
And handle events by declaring the implementation of IHandle<T> in the following way:
IHandle<Signal<SignalSourceClass>>
This way I can send and receive "empty" events by creating only this single Signal class. (Of course this is a limited solution, since components can only send one event this way.)
I suspect that this solution is primitive (well, let's just call it a fact), and that there is something better that I'm overlooking.
Just create a enum with all possible signals you want:
public enum ProjectSignals
{
Connected,
Disconnected,
Openned
}
then just
_eventAggregator.PublishOnUIThread( ProjectSignals.Connected );
and
class SomeClass : IHandle<ProjectSignals>
{
public void Handle( ProjectSignals signal )
{
switch (signal)
{
case Connected:
break;
}
}
}

Learning Single Responsibility Principle with C#

I am trying to learn the Single Responsibility Principle (SRP) but it is being quite difficult as I am having a huge difficult to figure out when and what I should remove from one class and where I should put/organize it.
I was googling around for some materials and code examples, but most materials I found, instead of making it easier to understand, made it hard to understand.
For example if I have a list of Users and from that List I have a
class Called Control that does lots of things like Send a greeting and
goodbye message when a user comes in/out, verify weather the user
should be able to enter or not and kick him, receive user commands and messages, etc.
From the example you don't need much to understand I am already doing too much into one class but yet I am not clear enough on how to split and reorganize it afterwards.
If I understand the SRP, I would have a class for joining the channel, for the greeting and goodbye, a class for user verification, a class for reading the commands, right ?
But where and how would I use the kick for example ?
I have the verification class so I am sure I would have all sort of user verification in there including weather or not a user should be kicked.
So the kick function would be inside the channel join class and be called if the verification fails ?
For example:
public void UserJoin(User user)
{
if (verify.CanJoin(user))
{
messages.Greeting(user);
}
else
{
this.kick(user);
}
}
Would appreciate if you guys could lend me a hand here with easy to understand C# materials that are online and free or by showing me how I would be splitting the quoted example and if possible some sample codes, advice, etc.
Let’s start with what does Single Responsibility Principle (SRP) actually mean:
A class should have only one reason to change.
This effectively means every object (class) should have a single responsibility, if a class has more than one responsibility these responsibilities become coupled and cannot be executed independently, i.e. changes in one can affect or even break the other in a particular implementation.
A definite must read for this is the source itself (pdf chapter from "Agile Software Development, Principles, Patterns, and Practices"): The Single Responsibility Principle
Having said that, you should design your classes so they ideally only do one thing and do one thing well.
First think about what “entities” you have, in your example I can see User and Channel and the medium between them through which they communicate (“messages"). These entities have certain relationships with each other:
A user has a number of channels that he has joined
A channel has a number of users
This also leads naturally do the following list of functionalities:
A user can request to join a channel.
A user can send a message to a channel he has joined
A user can leave a channel
A channel can deny or allow a user’s request to join
A channel can kick a user
A channel can broadcast a message to all users in the channel
A channel can send a greeting message to individual users in the
channel
SRP is an important concept but should hardly stand by itself – equally important for your design is the Dependency Inversion Principle (DIP). To incorporate that into the design remember that your particular implementations of the User, Message and Channel entities should depend on an abstraction or interface rather than a particular concrete implementation. For this reason we start with designing interfaces not concrete classes:
public interface ICredentials {}
public interface IMessage
{
//properties
string Text {get;set;}
DateTime TimeStamp { get; set; }
IChannel Channel { get; set; }
}
public interface IChannel
{
//properties
ReadOnlyCollection<IUser> Users {get;}
ReadOnlyCollection<IMessage> MessageHistory { get; }
//abilities
bool Add(IUser user);
void Remove(IUser user);
void BroadcastMessage(IMessage message);
void UnicastMessage(IMessage message);
}
public interface IUser
{
string Name {get;}
ICredentials Credentials { get; }
bool Add(IChannel channel);
void Remove(IChannel channel);
void ReceiveMessage(IMessage message);
void SendMessage(IMessage message);
}
What this list doesn’t tell us is for what reason these functionalities are executed. We are better off putting the responsibility of “why” (user management and control) in a separate entity – this way the User and Channel entities do not have to change should the “why” change. We can leverage the strategy pattern and DI here and can have any concrete implementation of IChannel depend on a IUserControl entity that gives us the "why".
public interface IUserControl
{
bool ShouldUserBeKicked(IUser user, IChannel channel);
bool MayUserJoin(IUser user, IChannel channel);
}
public class Channel : IChannel
{
private IUserControl _userControl;
public Channel(IUserControl userControl)
{
_userControl = userControl;
}
public bool Add(IUser user)
{
if (!_userControl.MayUserJoin(user, this))
return false;
//..
}
//..
}
You see that in the above design SRP is not even close to perfect, i.e. an IChannel is still dependent on the abstractions IUser and IMessage.
In the end one should strive for a flexible, loosely coupled design but there are always tradeoffs to be made and grey areas also depending on where you expect your application to change.
SRP taken to the extreme in my opinion leads to very flexible but also fragmented and complex code that might not be as readily understandable as simpler but somewhat more tightly coupled code.
In fact if two responsibilities are always expected to change at the same time you arguably should not separate them into different classes as this would lead, to quote Martin, to a "smell of Needless Complexity". The same is the case for responsibilities that never change - the behavior is invariant, and there is no need to split it.
The main idea here is that you should make a judgment call where you see responsibilities/behavior possibly change independently in the future, which behavior is co-dependent on each other and will always change at the same time ("tied at the hip") and which behavior will never change in the first place.
I had a very easy time learning this principle. It was presented to me in three small, bite-sized parts:
Do one thing
Do that thing only
Do that thing well
Code that fulfills those criteria fulfills the Single-Responsibility Principle.
In your above code,
public void UserJoin(User user)
{
if (verify.CanJoin(user))
{
messages.Greeting(user);
}
else
{
this.kick(user);
}
}
UserJoin does not fulfill the SRP; it is doing two things namely, Greeting the user if they can join, or rejecting them if they cannot. It might be better to reorganize the method:
public void UserJoin(User user)
{
user.CanJoin
? GreetUser(user)
: RejectUser(user);
}
public void Greetuser(User user)
{
messages.Greeting(user);
}
public void RejectUser(User user)
{
messages.Reject(user);
this.kick(user);
}
Functionally, this is no different from the code originally posted. However, this code is more maintainable; what if a new business rule came down that, because of recent cybersecurity attacks, you want to record the rejected user's IP address? You would simply modify method RejectUser. What if you wanted to show additional messages upon user login? Just update method GreetUser.
SRP in my experience makes for maintainable code. And maintainable code tends to go a long ways toward fulfilling the other parts of SOLID.
My recommendation is to start with the basics: what things do you have? You mentioned multiple things like Message, User, Channel, etc. Beyond the simple things, you also have behaviors that belong to your things. A few examples of behaviors:
a message can be sent
a channel can accept a user (or you might say a user can join a channel)
a channel can kick a user
and so on...
Note that this is just one way to look at it. You can abstract any one of these behaviors until abstraction means nothing and everything! But, a layer of abstraction usually doesn't hurt.
From here, there are two common schools of thought in OOP: complete encapsulation and single responsibility. The former would lead you to encapsulate all related behavior within its owning object (resulting in inflexible design), whereas the latter would advise against it (resulting in loose coupling and flexibility).
I would go on but it's late and I need to get some sleep... I'm making this a community post, so someone can finish what I've started and improve what I've got so far...
Happy learning!

Serial communication design pattern

I'm currently assigned to a task to develop a software module to communicate with a stepper motor controller. The project is written in C#, I have a C++ dll to communicate with the controller. The communication runs via the Serial port. I'm planning to write the whole piece in C# by importing the necessary methods by DllImport. The key method looks something like :
ComSendReceive(pHandle, bufferIn,sizeBufferIn,bufferOut,ref bufferOut)
There are several types of messages :
You send message and expect confirmation (not the same for every message, sometimes it's OK, sometimes it's COMPLETE etc..
You send message and receive message - you can receive an error or data (for instance GET_CONTROLLER_ID)
Several other types
Of course I need to control the communication for time-outs.
My question is: Is there any "design pattern" to use for that kind of problem? I'm sure this is quite a common problem many developers have solved already.
To contribute a little - I dealt with similar problem in my last job and I solved it this way :
I had a class to communicate with the Com port and a class AT_message with bunch of overloaded constructors :
class AT_Message
{
public bool DoResponseCheck;
public string ExpectedResponse;
public AT_COMMAND command;
public string data;
public bool AddCarriageReturn;
...
//Plenty of ctors
}
class UnfriendlyInterface
{
Response SendMessage(AT_Message msg)
{
//Communicates directly with C++ dll, send message, check timeouts etc....
}
}
And I had a class the main application was communicating with, it had human friendly methods like
class FriendlyInterface
{
bool AutodetectPortAndOpenComm();
Result AnalyzeSignal(byte[] buffer)
{
Response response = UnfriendlyInterface.SendMessage(new Message(AT_Command.PrepareForSignal, (doResponseCheck)true, ExpectedResponse.Ok,Timeout.short);
Response response = UnfriendlyInterface.SendMessage(new Message(buffer,(doResponseCheck)false,Timeout.long);
//.... Other steps
}
//... other methods
}
Since last time I was really in a big hurry, I implemented first solution that came to my mind. But is there a way to do it better? Now the device I'm communicate with is more complex than the previous one so if there's a way how to do it better, I'd like to do it that way.
This seems like a textbook facade pattern. The answer to all of this is to encapsulate your variation. For example, try to create a generic interface for commands that give an acknowledgement, and write client code to use that interface. Then concrete types can decide how to interpret various acknowledgements into a uniform signal (Ok = Complete = Good, or whatever)
Here's a good article on the facade pattern. Also see the wikipedia article.

C# -Priority based delegates and chaining in delegates possible? or Windows Work Flow?

Whenever i feel hungry i will publish i am hungry.This will be notified to the service providers say (MealsService,FruitService,JuiceService ).(These service providers know what to serve).
But the serving priority is the concern. Priority here means my first choice is MealsService when there are enough meal is available my need is end with MealsService.To verify the enough meal is availabe the MealsService raises the event "updateMeTheStockStatus" to the "MealsServiceStockUpdateListener" .
The "MealsServiceStockUpdateListener" will only reply back to "MealsService" . No other Service providers ( FruitService,JuiceService ) will be notified by the "MealsServiceStockUpdateListener" .If there is no sufficient stock then only the MealsService passes notification to the JuiceService (as it is the second priority).As usual it checks the stock.If stock is not sufficient it passes message to FruitService,so the flow continues like this.
How can i technically implement this?
Any implemention like priority based delagates and delegate chaining make sense ?
(Somebody! Please reframe it for good readability ).
Update : In this model there is no direct communication between "StackUpdateListener" and "me".Only The "Service Providers" will communicate me.
Like other answerers, I'm not entirely convinced that an event is the way forward, but let's go along with it for the moment.
It seems to me that the business with the MealsServiceStockUpdateListener is a red herring really - you're just trying to execute some event handlers but not others. This sort of thing crops up elsewhere when you have a "BeforeXXX" event which allows cancellation, or perhaps some sort of exception handling event.
Basically you need to get at each of your handlers separately. There are two different ways of doing that - either you can use a normal multicast delegate and call GetInvocationList() or you can change your event declaration to explicitly keep a list of handlers:
private List<EventHandler> handlers = new List<EventHandler>();
public event EventHandler MealRequired
{
add { handlers.Add(value); }
remove
{
int index = handlers.LastIndexOf(value);
if (index != -1)
{
handlers.RemoveAt(index);
}
}
}
These two approaches are not quite equivalent - if you subscribe with a delegate instance which is already a compound delegate, GetInvocationList will flatten it but the List approach won't. I'd probably go with GetInvocationList myself.
Now, the second issue is how to detect when the meal has provided. Again, there are two approaches. The first is to use the normal event handler pattern, making the EventArgs subclass in question mutable. This is the approach that HandledEventArgs takes. The second is to break the normal event pattern, and use a delegate that returns a value which can be used to indicate success or failure (and possibly other information). This is the approach that ResolveEventHandler takes. Either way, you execute the delegates in turn until one of them satistfies your requirements. Here's a short example (not using events per se, but using a compound delegate):
using System;
public class Test
{
static void Main(string[] args)
{
Func<bool> x = FirstProvider;
x += SecondProvider;
x += ThirdProvider;
Execute(x);
}
static void Execute(Func<bool> providers)
{
foreach (Func<bool> provider in providers.GetInvocationList())
{
if (provider())
{
Console.WriteLine("Done!");
return;
}
}
Console.WriteLine("No provider succeeded");
}
static bool FirstProvider()
{
Console.WriteLine("First provider returning false");
return false;
}
static bool SecondProvider()
{
Console.WriteLine("Second provider returning true");
return true;
}
static bool ThirdProvider()
{
Console.WriteLine("Third provider returning false");
return false;
}
}
Rather than publish a message "I'm hungry" to the providers, publish "I need to know current stock available". Then listen until you have enough information to make a request to the correct food service for what you need. This way the logic of what-makes-me-full is not spread amongst the food services... It seems cleaner to me.
Message passing isn't baked into .NET directly, you need to implement your own message forwarding by hand. Fortunately, the "chain of responsiblity design pattern" is designed specifically for the problem you're trying to solve, namely forwarding a message down a chain until someone can handle it.
Useful resources:
Chain of Responsibility on Wikipedia
C# implementation on DoFactory.com
I'm not sure if you really need a priority event. Anyways, let's suppose we want to code that just for fun.
The .NET Framework has no support for such a peculiar construct. Let me show one possible approach to implement it.
The first step would be to create custom store for event delegates (like described here);
Internally, the custom event store could work like a priority queue;
The specific EventArgs used would be HandledEventArgs (or a subclass of it). This would allow the event provider to stop calling handlers after one of them sets the event as Handled;
The next step is the hardest. How to say to tell the event provider what is the priority of the event handler that is being added?
Let me clarify the problem. Usually, the adding of a handler is like this:
eater.GotHungry += mealsService.Someone_GotHungry;
eater.GotHungry += juiceService.Someone_GotHungry;
eater.GotHungry += fruitService.Someone_GotHungry;
The += operator will only receive an delegate. It's not possible to pass a second priority parameter. There might be several possible solutions for this problem. One would be to define the priority in a custom attribute set at the event handler method. A scond approach is discussed in the question.
Compared to the chain of responsibility implementation at dofactory.com, this approach has some advantages. First, the handlers (your food services) do not need to know each other. Also, handlers can be added and remove at any time dynamically. Of course, you could implement a variation of a chain of responsibility that has this advantages too.
I don't think delegates are the proper solution to your problem. Delegates are a low-level service provided by C# for relatively tightly coupled events between components. If I understand your question properly (It is worded a little oddly, so I am not sure I clearly understand your problem), then I think what you need is a mediated consumer/provider.
Rather than having your consumers directly consume the meal, juice, and fruit providers, have them request a food item from a central mediator. The mediator would then be responsible for determining what is available and what should be provided to the consumer. The mediator would be a subscriber to events published by all three services. Whenever stock is added/updated in the Meal, Juice, or Fruit services, they would publish their current stock to all subscribers. The mediator, being a subscriber, would track current stock reductions on its own, and be able to determine for itself whether to send a meal, juice, or fruit to a food consumer when a get food request is made.
For example:
|---------- (GetFoodResponse) ----------------
V |
FoodConsumer ---- (GetFoodRequest) ------> FoodProvider <-----> [ Local Stock Data ]
^
|
|
MealService ---- (PublishStockMessage) ----------|
^
JuiceService --- (PublishStockMessage) ----------|
^
FruitService --- (PublishStockMessage) ----------|
The benefits of such a solution are that you reduce coupling, properly segregate responsibility, and solve your problem. For one, your consumers only need to consume a single service...the FoodProvider. The FoodProvider subscribes to publications from the other three services, and is responsible for determining what food to provide to a consumer. The three food services are not responsible for anything related to the hunger of your food consumers, they are only responsible for providing food and tracking the stock of the food they provide. You also gain the ability to distribute the various components. Your consumers, the food provider, and each of the three food services can all be hosted on different physical machines if required.
However, to achieve the above benefits, your solution becomes more complex. You have more parts, and they need to be connected to each other properly. You have to publish and subscribe to messages, which requires some kind of supporting infrastructure (WCF, MSMQ, some third party ESB, custom solution, etc.) You also have duplication of data, since the food provider tracks stock on its own in addition to each of the food services, which could lead to discontinuity in available stock. This can be mitigated if you manage stock updated properly, but that would also increase complexity.
If you can handle the additional complexity, ultimately, a solution like this would more flexible and adaptable than a more tightly connected solution that uses components and C# events in a local-deployment-only scenario (as in your original example.)
I am having a bit of trouble understanding your analogy here, which sounds like you're obscuring the actual intent of the software, but I think I have done something like what you are describing.
In my case the software was telemarketing software and each of the telemarketers had a calling queue. When that queue raises the event signifying that it is nearing empty, the program will grab a list of available people to call, and then pass them through a chain of responsibility which pushes the available call into the telemarketer's queue like so:
Each element in the chain acts as a priority filter: the first link in the chain will grab all of the people who have never been called before, and if it finishes (ie. went through all of the people who have never been called) without filling up the queue, it will pass the remaining list of people to call to the next link in the chain - which will apply another filter/search. This continues until the last link in the chain which just fires off an e-mail to an administrator indicating that there are no available people to be called and a human needs to intervene quickly before the telemarketers have no work to do.

Categories

Resources