WPF MVVM Toolkit library doesn't send the registered values - eventhandler

I am registering the events using MVVM Toolkit library (Microsoft.Toolkit.Mvvm.Messaging) as below.
//code
messenger.Register<EventHandler, MessengerRequestMessage<(string loadpointId, System.Windows.Point doubleClickLocation, IPartInfo partInfo)>,string>
(this, "MouseDoubleClick" ,DoubleClickedHandler);
//code
messenger is IMessenger with value messenger = WeakReferenceMessenger.Default;
checking whether event is registered or not
bool isReg = messenger.IsRegistered<MessengerRequestMessage<(string loadpointId, System.Windows.Point doubleClickLocation, IPartInfo partInfo)>, string>(this, "MouseDoubleClick");
getting true value that it's registered.
//event handler to execute
public void DoubleClickedHandler(EventHandler recipient, MessengerRequestMessage<(string loadpointId, System.Windows.Point doubleClickLocation, IPartInfo partInfo)> message)
{
}
//assigning value of the tuple
internal class MessengerRequestMessage<T>
{
public (string str, Point point, IPartInfo partInfo) t_str_pnt_prtInfo;
private (string, bool, bool) tuple_str_bln_bln;
private (bool, string) tuple_bool_str;
private (string, string) tuple_str_str;
private (List<NodeInfo>, List<ConnectorInfo>) tuple_list_node_connector;
private (string, Point) tuple_string_point;
private (string, string, bool) tuple_str_str_bln;
private string str;
private Point pnt;
private IPartInfo partInfo;
public MessengerRequestMessage(string str, Point pnt, IPartInfo partinfo)
{
this.str = str;
this.pnt = pnt;
this.partInfo = partinfo;
}
public MessengerRequestMessage((string, Point, IPartInfo) t)
{
this.t_str_pnt_prtInfo = t;
}
public MessengerRequestMessage((string, bool, bool) t)
{
this.tuple_str_bln_bln = t;
}
public MessengerRequestMessage((bool, string) t)
{
this.tuple_bool_str = t;
}
public MessengerRequestMessage((string, string) t)
{
this.tuple_str_str = t;
}
public MessengerRequestMessage((List<NodeInfo>, List<ConnectorInfo>) t)
{
this.tuple_list_node_connector = t;
}
public MessengerRequestMessage((string s, Point p) t)
{
this.tuple_string_point = t;
}
public MessengerRequestMessage((string, string, bool) t)
{
this.tuple_str_str_bln = t;
}
}
I am sending parameter as below. It assigns value of tuple but doesn't send the value to handler method above. it's not invoked. I am not sure what's wrong with this? as parameters are passed as expected
//code
(string loadpointId, System.Windows.Point doubleClickLocation, IPartInfo partInfo) tuple = (this.LoadpointId, doubleClickLocation, partInfo);
MessengerRequestMessage<(string loadpointId, System.Windows.Point doubleClickLocation, IPartInfo partInfo)> tuple1 =
new MessengerRequestMessage<(string loadpointId, System.Windows.Point doubleClickLocation, IPartInfo partInfo)>(tuple);
_messenger.Send<MessengerRequestMessage<(string loadpointId, System.Windows.Point doubleClickLocation, IPartInfo partInfo)>, string>
(tuple1, "MouseDoubleClick");
I have registered the event and passing the relevant parameters as above code snippet which is expected. after send messege the event is not getting invoked. can someone guide what's wrong?

Related

Test with JUnit an request

I wanna to test an request with JUnit with an request like this but RxUtils.applySchedulersAndErrorMapper() return null. Is any possibilities to test that?
override fun onContinueClicked(phoneNumber: String) {
mView.showLoading()
mUserService.checkUserApprovedStatus(phoneNumber)
.compose(RxUtils.applySchedulersAndErrorMapper())
.subscribe({ response ->
//Success
}, { error ->
//Error
})
}
here is where I setup the presenter and mUserService for presenter
#Mock
private PhoneContract.View view;
#Mock
private UserService userService;
#Before
public void setup() {
presenter = new PhonePresenter(this.view);
presenter.mUserService = userService;
}
here is the test method
#Test
public void onContinueClicked_SendJustNumbers() {
String phoneNumber = "(01234567890)";
// when
presenter.onContinueClicked(phoneNumber);
// then
verify(view, times(1)).showLoading();
}
and here is the RXUtils class:
class RxUtils {
companion object {
#SuppressLint("CheckResult")
fun <E> applySchedulersAndErrorMapper(): ObservableTransformer<E, E> {
return ObservableTransformer { o ->
o.flatMap(Function<E, ObservableSource<E>> { element ->
val genericResponse = element as GenericResponse<*>
#Suppress("UNCHECKED_CAST")
return#Function Observable.just(genericResponse as E)
}).onErrorResumeNext(Function<Throwable, ObservableSource<E>> { t ->
if (t is ApiException) {
return#Function Observable.error(t)
}
var genericResponse: GenericResponse<*>? = null
return#Function Observable.error(ApiException(t.message ?: "", genericResponse?.result ?: Result()))
})
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
}
}
}
}
Here is the stacktrace where I receive null for RxUtils.applySchedulersAndErrorMapper()
java.lang.NullPointerException
If it relates to the SDK, it probably won't work in a unit test. You didn't include your imports, so it's impossible to tell at a glance, but I know from experience that you can't use this in a unit test
AndroidSchedulers.mainThread()
You need to replace that with, say, Schedulers.trampoline()
Example of how to set a custom scheduler for testing
Note, this is only an example, and there are other valid solutions.
class RxUtils {
companion object {
// add this
#VisibleForTesting var mainScheduler = AndroidSchedulers.mainThread()
#VisibleForTesting var ioScheduler = Schedulers.io()
#SuppressLint("CheckResult")
fun <E> applySchedulersAndErrorMapper(): ObservableTransformer<E, E> {
return ObservableTransformer { o ->
o.flatMap(Function<E, ObservableSource<E>> { element ->
val genericResponse = element as GenericResponse<*>
#Suppress("UNCHECKED_CAST")
return#Function Observable.just(genericResponse as E)
}).onErrorResumeNext(Function<Throwable, ObservableSource<E>> { t ->
if (t is ApiException) {
return#Function Observable.error(t)
}
var genericResponse: GenericResponse<*>? = null
return#Function Observable.error(ApiException(t.message ?: "", genericResponse?.result ?: Result()))
})
.observeOn(mainScheduler)
.subscribeOn(ioScheduler)
}
}
}
}
And in your test:
#Before fun setup() {
RxUtils.mainScheduler = Schedulers.trampoline()
RxUtils.ioScheduler = Schedulers.trampoline()
}
#After fun teardown() {
RxUtils.mainScheduler = AndroidSchedulers.mainThread()
RxUtils.ioScheduler = Schedulers.io()
}
EDIT in response to updated post with more information on test
First of all, you should post WAY MORE CODE. It's frustrating having to pull it out of you by dribs and drabs. Anyway. You have the following:
#Mock
private UserService userService;
That creates a mock UserService, sure, but it doesn't stub anything. When you call userService.anyFunctionAtAll(), it will return null by default. There's your NPE. You have to stub it. For example:
Mockito.when(userService.anyFunctionAtAll()).thenReturn(somePredeterminedValue)
Please refer to the Mockito website for more information.

custom hamcrest matcher succeeds but the test fails

I have this custom matcher:
public class CofmanStringMatcher extends TypeSafeMatcher<String> {
private List<String> options;
private CofmanStringMatcher(final List<String> options) {
this.options = Lists.newArrayList(options);
}
#Override
protected boolean matchesSafely(final String sentResult) {
return options.stream().anyMatch(option -> option.equals(sentResult));
}
public static CofmanStringMatcher isCofmanStringOnOfTheStrings(List<String> options) {
return new CofmanStringMatcher(options);
}
#Override
public void describeTo(final Description description) {
System.out.println("in describeTo");
// description.appendText("expected to be equal to of the list: "+options);
}
}
which compares a string to few options for strings.
when i run this test code:
verify(cofmanService, times(1))
.updateStgConfigAfterSimulation(argThat(isCofmanStringOnOfTheStrings(ImmutableList.of(expectedConditionsStrings , expectedConditionsStrings2))), eq(Constants.addCommitMsg+SOME_REQUEST_ID));
I get this error:
Comparison Failure: <Click to see difference>
Argument(s) are different! Wanted:
cofmanService.updateStgConfigAfterSimulation(
,
"add partner request id = 1234"
);
-> at com.waze.sdkService.services.pubsub.callback.RequestToCofmanSenderTest.localAndRtValidationSucceeds_deployCofmanStg(RequestToCofmanSenderTest.java:131)
Actual invocation has different arguments:
cofmanService.updateStgConfigAfterSimulation(
"some text"
);
The test fails even though the method updateStgConfigAfterSimulation calls with 1st arg that matches on of the list elements
I'm using
mockito 1.10 and hamcrest 1.3
here is the method's signature
void updateStgConfigAfterSimulation(String conditionsMap, String commitMsg) throws Exception

write regex in JsonFormat pattern

#JsonFormat(shape = JsonFormat.Shape.STRING, pattern ="yyyy-MM-dd'T'HH:mm:ss.SSS")
is it possible to write regex in pattern? I could not
pattern ="yyyy-MM-dd'T'HH:mm:ss.SSS(Z?)"
I want to make Z as optional
any links suggestions?
I ended up creating custom deserializer based on LocalDateDeserializer.INSTANCE and moved the regex there.
After registering the deserializer the object mapper as a custom module the #JsonFormat annotation is no longer required:
#Bean
public ObjectMapper createObjectMapper() {
return new ObjectMapper()
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule())
.registerModule(new CustomTimeModule());
}
and defined the deserializer in the CustomTimeModule
class CustomTimeModule extends SimpleModule {
public CustomTimeModule() {
super();
addDeserializer(LocalDate.class, CustomLocalDateDeserializer.INSTANCE);
}
}
and finally the regex part, in my case was cutting of the optional non-standard time zone that i was sometimes getting after the date, but could be easily extended to match your case:
public class CustomLocalDateDeserializer extends JSR310DateTimeDeserializerBase<LocalDate> {
private static final long serialVersionUID = 1L;
private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE;
public static final CustomLocalDateDeserializer INSTANCE = new CustomLocalDateDeserializer();
private CustomLocalDateDeserializer() {
this(DEFAULT_FORMATTER);
}
public CustomLocalDateDeserializer(DateTimeFormatter dtf) {
super(LocalDate.class, dtf);
}
#Override
protected JsonDeserializer<LocalDate> withDateFormat(DateTimeFormatter dtf) {
return new CustomLocalDateDeserializer(dtf);
}
#Override
public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
if (parser.hasToken(JsonToken.VALUE_STRING)) {
String string = parser.getText().trim();
if (string.length() == 0) {
return null;
}
// >>>>>>> regex part comes here <<<<<<<
string = parser.getText().trim().substring(0, 10);
// >>>>>>> regex part comes here <<<<<<<
// as per [datatype-jsr310#37], only check for optional (and, incorrect...) time marker 'T'
// if we are using default formatter
try {
return LocalDate.parse(string, _formatter);
} catch (DateTimeException e) {
return _handleDateTimeException(context, e, string);
}
}
if (parser.isExpectedStartArrayToken()) {
JsonToken t = parser.nextToken();
if (t == JsonToken.END_ARRAY) {
return null;
}
if (context.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
&& (t == JsonToken.VALUE_STRING || t==JsonToken.VALUE_EMBEDDED_OBJECT)) {
final LocalDate parsed = deserialize(parser, context);
if (parser.nextToken() != JsonToken.END_ARRAY) {
handleMissingEndArrayForSingle(parser, context);
}
return parsed;
}
if (t == JsonToken.VALUE_NUMBER_INT) {
int year = parser.getIntValue();
int month = parser.nextIntValue(-1);
int day = parser.nextIntValue(-1);
if (parser.nextToken() != JsonToken.END_ARRAY) {
throw context.wrongTokenException(parser, handledType(), JsonToken.END_ARRAY,
"Expected array to end");
}
return LocalDate.of(year, month, day);
}
context.reportInputMismatch(handledType(),
"Unexpected token (%s) within Array, expected VALUE_NUMBER_INT",
t);
}
if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
return (LocalDate) parser.getEmbeddedObject();
}
// 06-Jan-2018, tatu: Is this actually safe? Do users expect such coercion?
if (parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
return LocalDate.ofEpochDay(parser.getLongValue());
}
return _handleUnexpectedToken(context, parser, "Expected array or string.");
}

Castle MonoRail with asynchronous action view render exception

I'm trying to use async actions in MonoRail but when the view is rendered I get an NullReference exception, also tested with emtpy view file.
I also tried to call RenderView("uploadTags.vm") in EndUploadTags.
When I call RenderText(s) in EndUploadTags I don't get the exception.
Stacktrace:
[NullReferenceException: Object reference not set to an instance of an object.]
Castle.MonoRail.Framework.Services.DefaultCacheProvider.Get(String key) +163
Castle.MonoRail.Framework.Views.NVelocity.CustomResourceManager.GetResource(String resourceName, ResourceType resourceType, String encoding) +68
NVelocity.Runtime.RuntimeInstance.GetTemplate(String name, String encoding) +57
NVelocity.Runtime.RuntimeInstance.GetTemplate(String name) +82
NVelocity.App.VelocityEngine.GetTemplate(String name) +47
Castle.MonoRail.Framework.Views.NVelocity.NVelocityViewEngine.Process(String viewName, TextWriter output, IEngineContext context, IController controller, IControllerContext controllerContext) +564
Castle.MonoRail.Framework.Services.DefaultViewEngineManager.Process(String templateName, TextWriter output, IEngineContext context, IController controller, IControllerContext controllerContext) +237
Castle.MonoRail.Framework.Controller.ProcessView() +146
Castle.MonoRail.Framework.Controller.EndProcess() +1579
Castle.MonoRail.Framework.BaseAsyncHttpHandler.EndProcessRequest(IAsyncResult result) +141
[MonoRailException: Error processing MonoRail request. Action uploadtags on asyncController vendor]
Castle.MonoRail.Framework.BaseAsyncHttpHandler.EndProcessRequest(IAsyncResult result) +461
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +86
This is my test code:
private Output output;
public delegate string Output();
private string DoNothing()
{
return "nothing";
}
private string Upload()
{
return "upload";
}
public IAsyncResult BeginUploadTags(HttpPostedFile xmlFile, Boolean doUpload)
{
if (IsPost)
{
output = Upload;
return output.BeginInvoke(ControllerContext.Async.Callback, null);
}
output = DoNothing;
return output.BeginInvoke(ControllerContext.Async.Callback, null);
}
public void EndUploadTags()
{
var s = output.EndInvoke(ControllerContext.Async.Result);
PropertyBag["logging"] = s;
}
This is a bug in old versions of MonoRail. It works in MonoRail 2.1 RC, but not in an old version I just tried, I got the same null ref exception.
This is what revision 5688 looked like in Subversion, which is where the NullReferenceException is coming from. The code no longer uses the HttpContext for the cache.
public object Get(String key)
{
if (logger.IsDebugEnabled)
{
logger.DebugFormat("Getting entry with key {0}", key);
}
return GetCurrentContext().Cache.Get(key);
}
private static HttpContext GetCurrentContext()
{
return HttpContext.Current;
}

How to anonymous classes in TypeScript

I am trying to create a helper function, to add currying, to generate common setups for classes. For example:
class Person {
private name: string;
private sex: string;
constructor (name: string, sex: string) {
this.name = name;
this.sex = sex;
}
}
var newPersonSex = function (sex: string) {
return function (name: string) {
return new Person(name, sex);
}
}
var MalePerson = newPersonSex('male');
var FemalePerson = newPersonSex('female');
So that now when MalePerson and FemalePerson objects are created, it actually just returns a new instance of Person instead.
var m = new MalePerson( 'john' );
In order for the type system allow me to still use 'new', MalePerson needs to be a constructor type. For example: 'new (name:string) => Person'. That also needs to be the return type of the function.
However with those declarations added, I cannot return a function from inside 'newPersonSex'. For example this is invalid:
var newPersonSex = function (sex: string) : new(name:string) => Person {
return function (name: string) {
return new Person(name, sex);
}
}
How can I create and return a new constructor function or class on the fly?
Try this definition of newPersonSex:
var newPersonSex = function (sex: string) {
return <new (name: string) => Person> <any> function (name: string) {
return new Person(name, sex);
}
}
The problem with your code is that functions just have call signatures, not construct signatures. My example above works around this by first asserting that the type of that function is any, and then asserting that the any type is actually a constructor.
Note that the type of newPersonSex will be inferred from its return type so no need to add a function annotation.