Sending Generic Messages - mvvm-light

public class Foo<T> where T: Entity
{}
public class Foo1
: Foo<Telephone>
{
}
public class Foo2
: Foo<Home>
{
}
How do I send Foo1 to Foo2? I realize that the message is typed, and hence messages of the same type of recieved - but I need to message between the derived classes...
An example would be very much appreciated.

An alternative is to create your own class that contains the payload you wish to deliver (Foo1 or simply object). Then in Foo2, register to receive messages of the type of the class you just created.
This link explains how with a very easy to understand example.
MVVM Light Toolkit Soup To Nuts 3 - Jesse Liberty

the messaging in mvvmlight is in theory supposed to be fire and forget...the sender doesnt care who gets the message and the receiver doesnt care who sends the message, so long as its the right type that its listening for.
I have found through much trial and error that its much easier to craft your own messages than use the default provided by mvvm-light, they are a good starting point, but sometimes you will just findyourself jumping through hoops..
public class ExceptionMessage : GalaSoft.MvvmLight.Messaging.GenericMessage<System.Exception>
{
public ExceptionMessage(System.Exception content) : base(content) { }
public ExceptionMessage(object sender, System.Exception content) : base(sender, content) { }
public ExceptionMessage(object sender, object target, System.Exception content) : base(sender, target, content) { }
}
Receiver code:
Messenger.Default.Register<Core.Messaging.ExceptionMessage>(this, ex => ShowExceptionMessage(ex));
Sender Code:
public void LogException(Exception content)
{
_messenger.Send<Core.Messaging.ExceptionMessage>(new ExceptionMessage(content));
//GetBw().RunWorkerAsync(content);
WriteToDatabaseLog(content);
}
and yes this does break the suggestion in my first sentence, but in theory I could have several vms or view listening for exception messages.
Maybe another example to help you out... i hate the whole foo thing...its always confuses me...
This is in my core module:
public class SaveNotification<T> : GalaSoft.MvvmLight.Messaging.NotificationMessage<T> where T : GalaSoft.MvvmLight.ViewModelBase
{
public SaveNotification(T content, string notification) : base(content, notification) { }
public SaveNotification(object sender, T content, string notification) : base(sender, content, notification) { }
public SaveNotification(object sender, object target, T content, string notification) : base(sender, target, content, notification) { }
}
here is how I used it in my vm:
public void OnSubmitChanges(SubmitOperation so)
{
if (so.HasError)
{
Infrastructure.GetService<IExceptionLoggingInterface>().LogException(this, so.Error);
}
else
{
//Save Responses
_messenger.Send<Messages.NavigationRequest<SubClasses.URI.PageURI>>(GetNavRequest_HOME());
ClearQuestionaire(true);
_messenger.Send<WavelengthIS.Core.Messaging.SaveNotification<QuestionairreViewModel>>(GetSuccessfulSaveNotification());
}
Wait.End();
}
private WavelengthIS.Core.Messaging.SaveNotification<QuestionairreViewModel> GetSuccessfulSaveNotification()
{
return new WavelengthIS.Core.Messaging.SaveNotification<QuestionairreViewModel>(this, "Save Successfull");
}

Related

Capture ALL WebAPI requests

I would like to capture and save in a log file all the requests that my WebAPI should handle.
Just tried to save the Request.Content from the controller constructor but unfortunately,
the request object is null from the controller constructor scope.
Hope to learn an efficient way to do it.
I would just hook into web api tracing...
http://www.asp.net/web-api/overview/testing-and-debugging/tracing-in-aspnet-web-api
From the above article, you can implement ITraceWriter like so. This example uses System.Diagnostics.Trace.WriteLine, but you could plug in writing to a file here as well.
public class SimpleTracer : ITraceWriter
{
public void Trace(HttpRequestMessage request, string category, TraceLevel level,
Action<TraceRecord> traceAction)
{
TraceRecord rec = new TraceRecord(request, category, level);
traceAction(rec);
WriteTrace(rec);
}
protected void WriteTrace(TraceRecord rec)
{
var message = string.Format("{0};{1};{2}",
rec.Operator, rec.Operation, rec.Message);
System.Diagnostics.Trace.WriteLine(message, rec.Category);
}
}
As you can see from the Trace method, you get access to the HttpRequestMessage here.
I ended up implementing middleware to deal with it.
public class GlobalRequestLogger : OwinMiddleware
{
public override Task Invoke(IOwinContext context)
{
// Implement logging code here
}
}
Then in your Startup.cs:
app.Use<GlobalRequestLogger>();

Signalr & Nancyfx integration

My app flow is as follows (simplified for clarity):
User GETs a page from "/page1"
User performs actions on the page (adds text, clicks, etc..), while Signalr communicates this data to the server, which performs heavy calculations in the background, and the results of those are returned to the page (lets call those "X").
When the user is finished with the page, he clicks a link to "/page2", that is returned by Nancy. This page is built using a Model that is dependent on X.
So, how do I build that Model based on X? How can signalr write to the user session in a way that Nancy can pick up on?
(I'm looking for a "clean" way)
Pending formal integration of Signalr & Nancy, this is what I came with. Basically, I share an IOC container between the two, and use an object (singleton lifetime) that maps users to state.
How to share an IOC container using the built in TinyIOC:
Extend Signalr's DefaultDependencyResolver
public class TinyIoCDependencyResolver : DefaultDependencyResolver
{
private readonly TinyIoCContainer m_Container;
public TinyIoCDependencyResolver(TinyIoCContainer container)
{
m_Container = container;
}
public override object GetService(Type serviceType)
{
return m_Container.CanResolve(serviceType) ? m_Container.Resolve(serviceType) : base.GetService(serviceType);
}
public override IEnumerable<object> GetServices(Type serviceType)
{
var objects = m_Container.CanResolve(serviceType) ? m_Container.ResolveAll(serviceType) : new object[] { };
return objects.Concat(base.GetServices(serviceType));
}
}
Replace Signalr's default DependencyResolver with our new one
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
CookieBasedSessions.Enable(pipelines);
// Replace UserToStateMap with your class of choice
container.Register<IUserToStateMap, UserToStateMap>();
GlobalHost.DependencyResolver = new TinyIoCDependencyResolver(container);
RouteTable.Routes.MapHubs();
}
}
Add IUserToStateMap as a dependency in your hubs and Nancy modules
public class MyModule : NancyModule
{
public MyModule(IUserToStateMap userToStateMap)
{
Get["/"] = o =>
{
var userId = Session["userId"];
var state = userToStateMap[userId];
return state.Foo;
};
}
}
public class MyHub : Hub
{
private readonly IUserToStateMap m_UserToStateMap;
public MyHub(IUserToStateMap userToStateMap)
{
m_UserToStateMap = userToStateMap;
}
public string MySignalrMethod(string userId)
{
var state = userToStateMap[userId];
return state.Bar;
}
}
What I would really want, is a way to easily share state between the two based on the connection ID or something like that, but in the meantime this solution works for me.
Did you arrive hear looking for a simple example of how to integrate Nancy and SignalR? I know I did.
Try this question instead (I self-answered it).
SignalR plus NancyFX : A simple but well worked example

Send object to VIewModel with mvvm-light

I'm pretty new to MVVM light world, and after searches I can't find what I want to do.
My WP7 application contains a pivot, each pivot item content is View1 and viewmodel is VM1.
When loading my application, I'd like to create every pivot item with the same view and view model but with different parameter.
example :
PivotItem 1 -> send param "car" to the view model
PivotItem 2 -> send param "truck" to the view model, etc.
Google told me to use messaging but if I send 2 messages from my MainViewModel, both PivotItem1 and PivotItem2 ViewModel will receive these messages.
Am I wrong with this approach ?
Is there another solution to succeed ?
Thank you in advance for your answer.
PS : be indulgent, english is not my native language, don't hesitate to ask for further information.
Regards,
Aymeric Lagier
To seperate the messages use the second constructor signature whereby you can pass a token. This token can be anything but I generally use an enum to store all my message types within the system.
Create a static class in a common library and reference this in all projects where you need to send or receive messages.
The following code hopefully shows this approach, notice I am sending a string as a value within the message but this can be anything, even a complex object such as one of your business objects.
namespace MyProject.Common
{
public static class AppMessages
{
enum MessageTypes
{
ViewmodelA,
ViewmodelB
}
public static class ViewModelAUpdate
{
public static void Send(string value)
{
Messenger.Default.Send(value, MessageTypes.ViewmodelA);
}
public static void Register(object recipient, Action<string> action)
{
Messenger.Default.Register(recipient, MessageTypes.ViewmodelA, action);
}
}
public static class ViewModelBUpdate
{
public static void Send(string value)
{
Messenger.Default.Send(value, MessageTypes.ViewmodelB);
}
public static void Register(object recipient, Action<string> action)
{
Messenger.Default.Register(recipient, MessageTypes.ViewmodelB, action);
}
}
}
}
How about using a method to set the message you want to receive. (this could be done as a parameter in the constructor or a property as well)
public void RegisterForAppMessage(AppMessages.MessageTypes messageType)
{
switch (messageType)
{
case AppMessages.MessageTypes.PivotViewItem1Message:
AppMessages.PivotViewItem1Message.Register(this,DoSomethingWhenIRecievePivotViewItem1Messages)
break;
case AppMessages.MessageTypes.PivotViewItem2Message:
AppMessages.PivotViewItem2Message.Register(this,DoSomethingWhenIRecievePivotViewItem2Messages)
break;
}
}
private void DoSomethingWhenIRecievePivotViewItem2Messages(string obj)
{
// TODO: Implement this method
throw new NotImplementedException();
}
private void DoSomethingWhenIRecievePivotViewItem1Messages(string obj)
{
// TODO: Implement this method
throw new NotImplementedException();
}
Messaging sounds a bit heavy for this purpose. Could you simply inject a parameter into your ViewModel. If you already have MVVMLight you also have support for SimpleIOC. Maybe let the view locate its ViewModel when the view is resolved and there decide which parameter to use on the view model?
You can see an example of it here

Wicket and responding with "not HTML" to requests

I'm sure this has been answered somewhere else - but I don't know where
I need to respond to HTTP requests from a partner, in our wicket website. The partner expected the response body to say "OK" or anything else in the case of an error
Is there a "nice" way to do this? ... or am I going to be stuck adding a servlet to my (previously) pretty Wicket application?
You can use resources for that:
class OkResource implements IResource {
#Override
public void respond(Attributes attributes) {
WebResponse resp = (WebResponse) attributes.getResponse();
resp.setContentType("text/plain");
resp.write("OK");
}
}
And register it in your Application class
#Override
protected void init() {
super.init();
getSharedResources().add("confirm", new OkResource());
mountResource("confirm", new SharedResourceReference("confirm"));
}
so that it can be accessed through something like http://host/app/confirm.
Just observe that here you registering a single instance of the resource, so it must be thread-safe, since multiple requests can call it simultaneously.
[EDIT]
In Wicket 1.4:
class OkResource extends Resource {
#Override
public IResourceStream getResourceStream() {
return new StringResourceStream("ok", "text/plain");
}
}
#Override
protected void init() {
super.init();
getSharedResources().add("confirm", new OkResource());
mountSharedResource("confirm", "confirm");
}

Auto wiring of Property does not work for me

In my Asp.Net project I wanna use Property Auto-wiring, e.g. for my ILogger. Basically I placed it as Property into class where I need to use it. Like below.
public class UserControlBase : UserControl
{
public ILogger CLogger { get; set; }
....
}
public partial class IPTracking : UserControlBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
//it works
ILogger logger = ObjectFactory.GetInstance<ILogger>();
logger.LogInfo(string.Format("Client IP: {0}", ip));
//it does not work
CLogger.LogInfo(string.Format("Client IP: {0}", ip));
}
}
}
However when calling in inherited control, logger is null. I checked the container and it'a definitely set as above implementation shows. Below is setting which is called from Global.asax.
public static void SetupForIoC()
{
Debug.WriteLine("SetupForIoC");
ObjectFactory.Initialize(x =>
{
x.FillAllPropertiesOfType<ILogger>().Use<EntLibLogger>();
});
Debug.WriteLine(ObjectFactory.WhatDoIHave());
}
Thanks for any advice, tip? X.
Update:
- I didnt mentioned before, but its Asp.Net webforms 3.5.
- I can't see what I am missing. I guess it could be because the injection gets involved later in process and didnt get set in requested class.
Link to desc. of usage: http://structuremap.github.com/structuremap/ConstructorAndSetterInjection.htm#section7
Give something like this a shot.
FillAllPropertiesOfType<ILogger>().AlwaysUnique().Use(s => s.ParentType == null ? new Log4NetLogger(s.BuildStack.Current.ConcreteType) : new Log4NetLogger((s.ParentType)));
Check out another StackOverflow answer I have which discusses using StructureMap to auto wire loggers.
Where do you actually set the CLogger property on the user control? Also, if you wanted to use one logger within the page, you could have the User cotnrol do:
public ILogger CLogger
{
get
{
if (this.Page is PageBase)
return ((PageBase)this.Page).Logger;
else
return null;
}
}

Resources