I have a problem. In my Xamarin Forms app I have the following code to toggle a device in my network:
public ICommand cmdTogglePower
{
get
{
return new Command<int>((x) => TogglePower_Handler(x));
}
}
public Task TogglePower_Handler(int Id)
{
return TogglePower(Id);
}
private async Task TogglePower(int Id)
{
foreach (var item in knownDeviceList)
{
if (item.Id == Id)
{
if (item.State == 1) { item.State = 0; }
else if (item.State == 0) { item.State = 1; }
switch (item.State)
{
case 1:
item.StateShown = "Turned on";
item.PowerStateColor = "#FFFFFF";
item.DeviceImageColor = item.Color;
break;
case 0:
item.StateShown = "Turned off";
item.PowerStateColor = "#707070";
item.DeviceImageColor = "#707070";
break;
}
foreach (var device in App.KnownDeviceList)
{
if (device.Id == Id)
{
device.State = item.State;
int rgb = Convert.ToInt32(item.Color, 16);
int r = (rgb & 0xff0000) >> 16;
int g = (rgb & 0xff00) >> 8;
int b = (rgb & 0xff);
string status = await App.RestService.SendCommand(r, g, b);
break;
}
}
break;
}
}
}
And I want the app to call a Task SendCommand, which sends a https command over the network to that device in another class. Here is the code of that Task:
public async Task<string> SendCommand(int Red, int Green, int Blue)
{
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("red", Red.ToString()));
postData.Add(new KeyValuePair<string, string>("green", Green.ToString()));
postData.Add(new KeyValuePair<string, string>("blue", Blue.ToString()));
var content = new FormUrlEncodedContent(postData);
var weburl = "mysite.org";
string response = await PostResponseSendCommand(weburl, content);
return response;
}
public async Task<string> PostResponseSendCommand(string weburl, FormUrlEncodedContent content)
{
var response = await client.PostAsync(weburl, content);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
But the code stops after int rgb = Convert.ToInt32(item.Color, 16);
Now the Task never gets executed, so somehting is going wrong!
Why is this not working !?
The problem:
Your color values start with a "#", which Convert.ToInt32()
can't process, it causes a System.FormatException: Could not find any recognizable digits
. And that exception "disappears" because it happens inside the asynchronous state machine.
The fix:
Chop off the leading "#", e.g. like this:
int rgb = Convert.ToInt32(item.Color.Substring(1), 16);