How do I handle this msg: Messenger.Default.Send<NotificationMessage<bool>>(msg); - mvvm-light

Given this:
var msg = new NotificationMessage<bool>(isHead, buffer.ToString());
Messenger.Default.Send<NotificationMessage<bool>>(msg);
How do I catch this message?
I'm not sure of the Messenger.Default.Register... syntax,
or the prototype for the action method.
Thx

D'oh, here it is:
Messenger.Default.Register<NotificationMessage<bool>>(this, MessageRx);
private void MessageRx(NotificationMessage<bool> msg)
msg.Notification is the message string, and msg.Content is the value of the bool.

Related

Why do i get "Exception:" when i receive the exception message in dart?

Hi I am new to the dart and flutter framework.
I am throwing error like below from my service class where i am calling the API.
if(res["status"]!=200) throw new Exception("Invalid User");
and receiving in presenter class like below and printing
.catchError((Object error){
print(error);
});
I am expecting the result as "Invalid User", but am getting with additional word like "Exception: Invalid User". Can you please explain me why this additional word 'Exception' is coming? and how can i get only the string which i am passing.
Surprisingly that's how written in exception toString code.
String toString() {
if (message == null) return "Exception";
return "Exception: $message"; // your message will be appended after exception.
}
If you want to avoid this then you have to create custom exception like below:
class HttpException implements Exception {
final String message;
HttpException(this.message); // Pass your message in constructor.
#override
String toString() {
return message;
}
}
You can use the message property of the Exception object
.catchError((error){
print(error.message);
});
This should output Invalid User
I hope this is what you are looking for.
Quick solution:
.catchError((error){
print(
error.toString().substring(11)
);
});
You cut the first 11 message chars, that is, "Exception: ".
You can create an extension function in dart as
extension FormattedMessage on Exception {
String get getMessage {
if (this.toString().startsWith("Exception: ")) {
return this.toString().substring(11);
}else {
return this.toString();
}
}
}
After that you can simply call
exception.getMessage;
to get your extension message without having to implement the Extension class or show the user how the exception is being substring.

GetAsync and PostAsJsonAsync methods passing parameters JsonReaderException error

I am trying to build a client side of making requests. So i do not know how i pass parameters on GetAsync method. The same problem on PostAsJsonAsync method.
Here is my code:
public static async Task<List<Users>> GetUsers(HttpClient client, Users users, string accessToken)
{
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await client.GetAsync("/api/2.0/users/?id=5&name=name");
response.EnsureSuccessStatusCode();
List<Users> listUsers= await response.Content.ReadAsAsync<List<Users>>();
Console.WriteLine("Returned list.");
return listUsers;
}
catch (HttpRequestException e)
{
Console.WriteLine("{0}", e.Message);
Console.ReadLine();
throw;
}
}
When i make this request from postman i get the results that i want. The Users class has more variables than the 2 that i request.
GetAsync without parameters works fine. When i run the project i get the error "JsonReaderException: Input string '100.0' is not a valid integer"
Is there another option to pass arguments on url?
I changed the int type of that integer property to float and the problem solved.

Swift 2.0: throw exception within an asynchronous piece of code

I am trying to implement the log in service for an application, and I would like to throw an exception if the response status code is not equal to 200. I am using Alamofire as HTTP networking library.
static func loginWithUsername(username: String, andPassword password: String) throws {
let action = "SmartShoppers/login"
let url = baseUrl + action
Alamofire.request(.POST, url, parameters: ["username": username, "password": password])
.response { request, response, data, error in
if response?.statusCode != 200 {
throw ServiceError.LogInError
}
}
}
This is the ServiceError enum definition:
enum ServiceError: ErrorType {
case LogInError
}
What I want to do deal this exception when it is thrown in a function which is called when a button is pressed. This function is in the ViewController class associated with the ViewController that contains that button. The code that is going to be executed is:
do {
try Service.loginWithUsername(username, andPassword: password)
} catch {
// SHOW AN ALERT MESSAGE
}
Why am I receiving the message Cannot call value of non-function type 'NSHTTPURLResponse'? Is it the correct way to implement this service? If not please help me.
The closure that you are passing to the response method does not include throws in its signature, so you will not be able to throw an exception from within it.
IMO this is not a case where you would want to throw an exception, anyways - a non-200 response code is not an exceptional error / failure, and I wouldn't try to use an exception here as a means of control flow.

Service Stack:Type definitions should start with a '{', expecting serialized type 'AuthResponse', got string starting with

i am using the following code to athenticate the user using ServiceStack basic auth provider in my asp.net application and receiving serilization exception.Please answer if anyone has solve this problem.Thank you.
I am using the following code in my asp.net application:
<asp:Button ID="btnAuth" runat="server" OnClick="btnAuth_Click" Text="Authenticate"/>
I am recieving exception on clien.Post method in code behind file.
protected void btnAuth_Click(object sender, EventArgs e)
{
try
{
var baseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/api";
var client = new JsonServiceClient(baseUrl);
var authResponse = client.Post<AuthResponse>(new Auth { UserName = "admin", Password = "12345" });
if (authResponse.ResponseStatus.ErrorCode == null)
{
//Do Something here
}
}
catch (WebServiceException ex)
{
throw ex;
}
}
Followin is Exeception Detail which i am recieving on clien.Post method:
[SerializationException: Type definitions should start with a '{', expecting serialized type 'AuthResponse', got string starting with:
Serialization exception that reads "expecting serialized type 'X', got string starting with:" means that the serializer tries to create an object from an empty string instead of a proper json-formatted string ("{Class:{Property:{Sub:value}}}").
In this case, most likely cause is server at baseUrl returning no response (interpreted as empty string) to a POST request. Misconfigured URL or exception on server side, maybe?

flex3 function not returning String properly

im trying to return a string value from a method inside my script tag however it always returns an object and i cant get at the string value.
Here is the code:
i retrieve the object returned from a webservice call;;
private function getNameResults(e:ResultEvent):String{
var name:Array = new Array(e.result);
var site:String = site_names[0].toString();
Alert.show("site - " +site);
return site;
}
the alert prints out the name fine, however when i try use the value in my next method (which calls the web service which calls getNameResults) i get the object tag
private function getInfo(roomName:String):String{
var site:String =userRequest.getRoomZoneInfo(roomName);
return site;
}
however the value returned here is [object AsyncToken]
any ideas?
You are setting the result of getRoomZoneInfo() to the variable site, but you are casting it as a String. getRoomZoneInfo is returning an object, and because the variable you are sticking it in is a string it is like calling .toString() on the object, which yields the [object AsyncToken].
Basically if getRoomZoneInfo is a webservice call, you cannot get the information you are looking for here, you have to wait until the result comes back and get the string you are looking for there. Make sense?
Your getInfo() method isn't calling getNameResults(). It's calling getRoomZoneInfo(). I don't know what that method does, but I'm guessing it's returning an Object, not a String.
I m getting [ObjectAsyncToken] in variable a instead of string, as I'm retrieving data from database
private function init():void
{
ro.initView();
var a:String=String(ro.getID());
}
database function:
public void initView()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:alarmdsn"," "," ");
Statement s = conn.createStatement();
ResultSet r = s.executeQuery("select * from alarm");
while(r.next()) {
a = r.getString(1);
}
}
catch(Exception e) {}
}
public String getID() {
return a;
}

Resources