How to keep track of all the messages - wpf

loosly coupled communication between viewmodels is a nice concept.
I have used Prism Eventaggregator as well as MVVM Light Toolkit's Messanger.
If the project grows I get alot of messages back and forth.
What is best practise of keeping track of my messages? Naming conventions? patterns?
etc...
How do you keep track?

I've found that there is a lot of value in providing a "Messages" namespace that contains your strongly typed messages. Keep in mind that well-defined messages will be more like contracts/DTOs - you want to maintain as much decoupling as possible, so dependencies should be kept to a minimum, otherwise the senders and receivers will both rely on common libraries. Sometimes this is necessary due to the nature of the message.
I think you'll also find that many messages may follow a particular pattern. Two common message patterns are what I'll call the Action and Command. Action is more of a "verb" and a "subject".
For example, you might have MessageAction that exposes T Target, and the action is an enumeration that indicates update, select, add, delete, etc. That's common and a generic message can wrap it, and your handlers listen for the generics that close the type they are interested in.
The Command is an Action that originates from somewhere and then applies an action to a target. For example, maybe you are adding a role to a user. In that case, your item of interest is the role, your target is the user, and your action is adding it. That can be a CommandAction.
Another common way to organize messages would be to implement a common interface or base class. It then becomes trivial to search for implementors in the project to determine where messages are being used.

Good question. Here are the solutions I've been using, but there are probably a lot of alternatives and haven't found any guidance on that.
One way is to define specific events that extend basic events : typical example when using prism is an extension of CompositePresentationEvent.
However, when having a large number of messages, it's sometimes useful to define what is a message. Usually it can be defined by a message header, some message attributes and an actual content. Then you can put these messages into your messagebus.

Related

Portlet event send array of objects

We have multiple projects with multiple portlets and need to send an array of objects between them.
Our situation:
One of the porlets is like a "Master-portlet", it will be responsible for all the REST-calls and consume json-data and parse it to Java-Objects.
All the other portlets will receive an array of objects and show them to the user.
Our thoughts and solution:
We wanted to implement this by sending arrays of objects trough events. One of the "smaller" portlets will send an event to the "Master-portlet" and the "Master-portlet" will then answer with a new event and send the right array of objects back.
Our problem:
We dont know how to send arrays of objects trough events. Is this even possible?
Also we are not sure if this is the right way to solve this. Are events ment to send a bigger amount of data?
Is there a better solution for our case? Maybe it would be better to implement a database and all the portlets get the information from there?
Consider portlet events (and portlets) the UI layer of your application. Based on this, judge if the amount of data that you send back and forth makes sense or not. Also, if you closely couple the portlets, you're just hiding the fact that they can only function together - at least a questionable idea. You rather want them to react to common circumstances (events), but not rely on a specific source of events (master portlet) being available.
That being said: The more complex the data is that you send as payload of a JSR-286 event, the easier you run into classloading problems in cases where your portlets are in different webapplications. If you restrict yourself to Java native types (e.g. String, Map, etc) you will omit problems with the classloader.
Typically you want to communicate changes to the current context (e.g. new "current customer" selected - and an identifier) but not all of the particular data (e.g. the new customer's name and order history). The rest of the data typically comes through the business layer anyway.
That's not to say that you absolutely must not couple your portlets - just that my preference is to rather have them very loosely coupled, so that I can add individual small portlets that replace those that I thought of yesterday.
If you have some time, I've covered a bit of this in a webinar last year, I hope that this adds some clarification where I was too vague in this quick answer.

What are appropriate action types in react.js?

In the Flux examples, the two action types I noticed are view actions & server actions. Are there any other action types to be concerned about from a large app perspective? I'm just thinking of appropriate patterns to use for the long term.
https://github.com/facebook/flux/tree/master/examples
Actions are just actions. If there's an action you use when getting the current user from the server, you could also create that action some other time (such as getting the user from local storage, etc.).
The two most common sources of events are from the UI and the server, however you could also have actions triggered on a timer (setInterval) or from a global event handler (e.g. window's resize), or third party libraries which get it from any source.
Perhaps a better word for and 'action' in flux would be an 'intent'. It doesn't actually do anything on its own, it just suggests something be done; the dispatcher dispatches the intent, and stores can do something (i.e. take action) based on the intent.
"view actions & server actions" is either too specific or too vague. You should either consider all actions equal (my personal take), or consider there to be hundreds of action types.
I'm just thinking of appropriate patterns to use for the long term.
I don't quite see how classifying actions affects patterns you use. Grouping of actions is more about which ones you want to generally expose to which other modules. For example ChatServerActionCreators is only used by utils/ChatWebAPIUtils. It's a matter of encapsulation rather than grouping by related functionality.
Thanks, I suppose I was also indirectly asking why these event sources
exist.
Also there is this discussion on google forums answered by Bill Fisher from FB:
Q: The todo-list example mentions a possible handleServerAction in
addition to handleViewAction - can someone give some color as to why
you might want to handle server actions differently from view actions?
I'm guessing a server action is triggered through polling, sockets, or
some external event, but is there a common case/example where it's
useful to check between the two types of actions? Just curious here,
as nothing obvious jumped out (i.e. marking an item as a favorite
should trigger the same codepath, regardless of where it came from).
A: As far as the server actions vs. the view actions goes, I think it's
more common to detect a view action and act differently upon it. For
example, you might want to only run a validation when the data comes
from user input, rather than on server initialization. I left that in
there just to show that you can do whatever you want with the payload,
that there can be this kind of structure providing metadata around the
Action, allowing you to group different actions together for whatever
purpose you need. You don't have to use these handleViewAction or
handleServerAction or handleServerInitializationAction (etc) methods,
but I've found it to be occasionally useful.

django templates in model logic

I wish to generate automated messages that are associated with a finite (>20, < 100) number of types:
class Message(models.Model):
MSG_CHOICES = (
('MEETING', 'Meeting Reminder'),
('STATUS', 'Status Change Reminder'),
...
)
message = models.CharField(max_length=100)
msg_type = models.CharField(max_length=10, choices=MSG_CHOICES)
The actual message of each will depend on the type and arguments I must feed it at some point. For example, a 'MEETING' message will basically be:
"Hi, you have a meeting at %s with %s." % (time, person_to_meet)
while a 'STATUS' message will be something like
"Hi, this is a reminder that you changed your %s status to %s." % (status_type, new_status)
Now, the complexity here is that we have to render the message differently for the different types. Here's my attempt at brainstorming some different approaches:
revamp the model to have a base message model and a derived one for each, with its own type of constructor, saving the "string templates" inside the constructors for each model. This fits the pattern of separating models with different logic (and I'd usually do this for a model of different "types"), but feels clunky because besides the logic of creating the messages, these guys are basically the same. The only difference in logic comes from creating the messages themselves, and it seems like a waste to split just because of it.
keep the model as is, create class methods in the code to make a factory for each type, saving the "string templates" inside the class (or even inside the database). This is the easiest, but it feels dirty.
this is the creative/crazy one (hence the title): keep the model as is, and save the string templates as actual template files. In the constructors, use the Django template library to render those files and return the strings. This seems good because it separates out hard-coded data from code-logic, but it feels wonky since I'm using templates at two different levels of the code (one for making models and one for the views). It "feels" wrong but I can't really pinpoint why.
So the main questions:
What is the best-practice for this situation? Is it one of these or is it some other approach?
is there a "model" example of this practice somewhere? I feel lots of systems generate automated alerts/messages, so if one has particularly good code I'd like to look at it.
Thanks!
-Yan
IMHO, you shouldn't be storing the message in the db at all. You are storing the msg_type. That should really be enough. Your logic to display the information to the user (via the template) should handle this. This would allow you to localize the message if you needed to at some point in the future based on the Accept-Language header. In my experience, it's a bad idea to store user messages in the db. And, at least to my way of thinking, it's not really true business logic. It seems to belong in the UI layer. Ok. Just my opinion on it. This question is pretty old. I would be curious to read what you ultimately ended up doing here.

event or Action<> on method complete?

Presuming you have an email folder and messages in it. Each message has Body property, which needs to be loaded async and notify you when done, how would you approach this?
1 - Message.LoadBody() + event Message.BodyLoadComplete
2 - Message.LoadBody(Action completeDelegate)
For the sake of completeness WPF and Prism are involved.
Thanks!
Edit:
Message will be a UI entity which will wrap a IMessage interface (that is not UI Ready (no INPC)), so the reason i'm asking is that we have to settle for an interface between UI and business layer.. IMessage. (The Business layer will be using an Imap library that already has some async pattern, but we don't want to depend too much on any imp, thats why i'm trying to figure out the best interface ..
If you're using .NET 4, I'd use:
Task<string> LoadBodyAsync()
(You might want to implement this using TaskCompletionSource<TResult>.)
The caller can then add continuations etc however they wish... and most importantly, in the brave new world of .NET 4.5 and C# 5, this will work seamlessly with the async/await features.
Of your two options:
Message.LoadBody() // Plus an event, Message.BodyLoadComplete
// or ...
Message.LoadBody(Action completeDelegate)
The event option is more flexible and may sometimes be less painful to use. If you don't care when or if LoadBody completes, then you aren't forced to provide a fake callback. And you can bind the completion event to multiple event handlers, which might sometimes be useful (e.g. if multiple UI controls need to be updated).
Both your solutions are non-typical, though. The typical "old" way to do this is for LoadBody to be split into BeginLoadBody and EndLoadBody, and give the user an IAsyncResult. See this article. The typical "new" way to do it is outlined in Jon Skeet's answer.
If you're using Prism you should consider using the EventAggregator and publishing a message to indicate a mail has loaded. This will allow you to easily have multiple loosely-coupled subscribers for this "event".
Using the EventAggregator is an elegant solution for publishing events, and leads to a much cleaner and decoupled architecture which is easier to extend. For instance, if you wish to add a new feature to email loading such as progress indication, you can simply subscribe to the EmailLoaded message and you're done, you don't have to tightly couple your new component to emails via an event or callback, they do not need to know about each other.

Whether we can get WM_IME_* messages when we’re typing in WPF TextBox with IME?

First, thanks for reading this thread and provide your suggestion.
Here’s the detailed description of my question: Due to large scale of legacy code, we need to use Win32 messages. And for UI part, we need to use WPF to modernize our appearance. That part of UI need to direct keyboard messages into the old legacy component. For input messages without IME, we have used ComponentDispatcher.ThreadFilterMessage to get these messages like WM_KEYDOWN, WM_CHAR, ect. But for IME input, we can’t get the corresponding WM_IME_* messages. Do we have a way to get these messages, or at least, get all the input text which corresponds to WM_IME_* messages?
We have tried several ways for that:
First, WPF native methods, like OnPreviewKeyDown(), OnTextInput(). One lackage of that solution is that we can’t get the Win32 messages. And I’ve found that WPF will not respond for some special key, e.g. Space key will not cause OnTextInput() to be invoked.
Second, different hooks, like SetWindowLong(), HwndSource.AddHook(). These solutions will not get the WM_IME_* messages as well.
Third, use InputMethod class. I’ve tried to use InputMethod.ImeConversionMode to determine whether the user input corresponds to WM_IME_* messages. But you know it is a different way with ComponentDispatcher.ThreadFilterMessage, and against several basic laws. At the same time, I’m not sure whether there may be cases overlapped for these two ways, and whether there’re missed cases. There’re so many languages and so many kinds of input methods, each of them has different character set and punctuation (They can be combined separately), then that solution will be risky.
When I’m investigating with class ImmComposition, which can be created by TextBoxBase.OnGotKeyboardFocus(), I’ve seen the hook ImmCompositionFilterMessage() is dealing with WM_IME_CHAR(0x0286), but failed to get it in my hook added after base. OnGotKeyboardFocus():
public class HookedTextBox : TextBox
{
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
base.OnGotKeyboardFocus(e);
InstallHook();
}
}

Resources