BluetoothLEDevice.GetGattServicesAsync() throws "Value does not fall within the expected range." exception - windows

I wrote a simple app that monitors BLE advertisements. When the app receives an advertisement it calls BluetoothLEDevice.FromBluetoothAddressAsync() and if that call returns a non null value GetGattServicesAsync() is called (see code below). Occasionally GetGattServicesAsync() will throw a "Value does not fall within the expected range."
private async void WatcherAdvertisementReceivedAsync(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher sender,
BluetoothLEAdvertisementReceivedEventArgs args)
{
using var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
if (device == null)
return;
try
{
var gatt = await device.GetGattServicesAsync();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}

Related

(AvaloniaUI) ArgumentException being thrown when OpenFileDialog is used in Windows 7

I am deploying my app to Windows 7, Windows 10, and Linux. At one point I am using OpenFileDialog to allow to user to pick a file path. This is working in Windows 10 and Linux, but when run in Windows 7, an ArgumentException is being thrown.
I've tried looking into the exception by displaying the exception message, which is "Value does not fall within expected range." I am not sure what this means. It works fine in Windows 10 so I don't know why it wouldn't work the same here.
I have a method GetPath() that gets the selected path using OpenFileDialog and a button clicked event that calls GetPath() and sets the result to a local variable.
public async Task<string> GetPath()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filters.Add(new FileDialogFilter() { Name = "Csv", Extensions = { "csv" } });
string[] result = await dialog.ShowAsync(this); //sets opened file to a stream
string stream = string.Join(" ", result); //converts string[] to string
return stream; //returns path to selected file
}
private async void MasterBrowse_Clicked(object sender, RoutedEventArgs args)
{
string getPath = string.Empty;
try
{
getPath = await GetPath();
}
catch (ArgumentException e)
{
await MessageBox.Show(this, "Make sure to select a file before continuing\n" + "Exception: " + e.Message, "Error: incorrect file", MessageBox.MessageBoxButtons.Ok);
}
}
Expected:
GetPath() should OpenFileDialog and save the selected path as a string, then return it. MasterBrowse_Clicked() should get the returned string.
Actual:
ArgumentException thrown when OpenFileDialog.ShowAsync() is called.

How to flag that an exception has been handled in bot code?

I have a root dialog that creates a child dialog like so...
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
string userName = context.Activity?.From.Name;
var customerForm = new FormDialog<CarValuationDialog>(
new CarValuationDialog(userName),
() => CarValuationDialog.BuildForm(),
FormOptions.PromptInStart);
context.Call(customerForm, FormSubmitted);
}
The FormSubmitted method looks like....
public async Task FormSubmitted(IDialogContext context, IAwaitable<CarValuationDialog> result)
{
try
{
var form = await result;
}
catch (FormCanceledException<CarValuationDialog> e)
{
string reply;
if (e.InnerException == null)
{
reply = e.Message;
}
else
{
reply = e.InnerException.Message;
}
context.Reset();
await context.PostAsync(reply);
}
}
When an exception occurs in the child dialog, the method FormSubmitted is executed and goes into the catch block. However, when that method finishes, I still see the "Sorry my bot had an issue" type message appear to the user.
How can I tell the bot code not to fire the unhandled exception code, I believe is in PostUnhandledExceptionToUser? Is there a flag type property I need to set to true or something?
It looks like you are making the dialog stack empty when you have an exception: you should not have this context.Reset() below:
public async Task FormSubmitted(IDialogContext context, IAwaitable<CarValuationDialog> result)
{
try
{
var form = await result;
}
catch (FormCanceledException<CarValuationDialog> e)
{
string reply;
if (e.InnerException == null)
{
reply = e.Message;
}
else
{
reply = e.InnerException.Message;
}
context.Reset();
await context.PostAsync(reply);
}
}
Remove this line and the next message will be handled by your root dialog
in your message controller in POST method, use defaultifexception
await Conversation.SendAsync(activity, () => new Dialogs.DialogLUIS().DefaultIfException());

Set the query string, but still get NullReferenceException

I want to show the error message on the other page. I got the NullReferenceException, but the query string is set on the page which has error. Would someone tell me what is wrong with my code?
catch (Exception ex)
{
//Dispatcher.BeginInvoke(new Action(() =>MessageBox.Show(ex.StackTrace,"Error!",MessageBoxButton.OK)));
string query=#"/ErrorPage.xaml?msg=" + ex.StackTrace.ToString() ;
Dispatcher.BeginInvoke(new Action(() =>this.NavigationService.Navigate(new Uri(query, UriKind.Relative))));
}
There is the code for showing the error message when the page is loaded on other page
public ErrorPage()
{
InitializeComponent();
string msg = NavigationContext.QueryString["msg"].ToString();
lstMessage.Items.Add(msg);
}
I should put my code into the MainPage_Load method. It works.
public ErrorPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
MessageBoxResult result = MessageBox.Show(CMSPhoneApp.App.GlobalVariables.strNofifyEmailSubject,
"Report Error", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
//according to the serach it works on real devices (not on the emulator)
//the reason the EmailComposer not pop up because can't set up an email account on the emulator
EmailComposeTask emailcomposer = new EmailComposeTask();
emailcomposer.To = CMSPhoneApp.App.GlobalVariables.reportAddress;
emailcomposer.Subject = CMSPhoneApp.App.GlobalVariables.strNofifyEmailSubject;
emailcomposer.Body = CMSPhoneApp.App.GlobalVariables.errorMsg;
emailcomposer.Show();
}
else
{
App.GoBack();
}
}

Windows Phone 7 - wait for Webclient to complete

I'm developing an app and have run into a problem with asynchronous calls... Here's what i'm trying to do.
The app consumes a JSON API, and, when run, fills the ListBox within a panorama item with the necessary values (i.e. a single news article). When a user selects a ListBox item, the SelectionChanged event is fired - it picks up the articleID from the selected item, and passes it to an Update method to download the JSON response for the article, deserialize it with JSON.NET, and taking the user to the WebBrowser control which renders a html page from the response received.
The problem with this is that I have to wait for the response before I start the NavigationService, but I'm not sure how to do that properly. This way, the code runs "too fast" and I don't get my response in time to render the page.
The event code:
private void lstNews_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstNews.SelectedIndex == -1)
{
return;
}
ShowArticle _article = new ShowArticle();
ListBox lb = (ListBox)sender;
GetArticles item = (GetArticles)lb.SelectedItem;
string passId = ApiRepository.ApiEndpoints.GetArticleResponseByID(item.Id);
App.Current.JsonModel.JsonUri = passId;
App.Current.JsonModel.Update();
lstNews.SelectedIndex = -1;
NavigationService.Navigate(new Uri("/View.xaml?id=" + item.Id, UriKind.Relative));
}
OnNavigatedTo method in the View:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
long sentString = long.Parse(NavigationContext.QueryString["id"]);
string articleUri = ApiRepository.ApiEndpoints.GetArticleResponseByID(Convert.ToInt32(sentString));
//this throws an error, runs "too fast"
_article = App.Current.JsonModel.ArticleItems[0];
}
The update method:
public void Update()
{
ShowArticle article = new ShowArticle();
try
{
webClient.DownloadStringCompleted += (p, q) =>
{
if (q.Error == null)
{
var deserialized = JsonConvert.DeserializeObject<ShowArticle>(q.Result);
_articleItems.Clear();
_articleItems.Add(deserialized);
}
};
}
catch (Exception ex)
{
//ignore this
}
webClient.DownloadStringAsync(new Uri(jsonUri));
}
async callback pattern:
public void Update(Action callback, Action<Exception> error)
{
webClient.DownloadStringCompleted += (p, q) =>
{
if (q.Error == null)
{
// do something
callback();
}
else
{
error(q.Error);
}
};
webClient.DownloadStringAsync(new Uri(jsonUri));
}
call:
App.Current.JsonModel.Update(() =>
{
// executes after async completion
NavigationService.Navigate(new Uri("/View.xaml?id=" + item.Id, UriKind.Relative));
},
(error) =>
{
// error handling
});
// executes just after async call above

Windows Phone app throws exception (quit automatically) when running under 3G, but fine with WIFI. Very weird

I have tried hundreds of times to find errors for this piece of codes.
It only works through WIFI, but When I switch off WIFI on my phone, and run the app again, this app just shut down automatically, which means it thrown an exception.
The app is simple, I used WebClint() to download HTML source and parsed it with HTML Agility Pack, then added them to a list, foreach the list to creat each news object.
I have tried catch the exception stacktrace and bind it to a texblock, It said some of ArgumentOutOfRange exception and Genericlist(int32 index)???
I have no idea about it, It was fine in wifi, but not in 3G network. Can anyone help?
public partial class MainPage : PhoneApplicationPage
{
string srcHTML;
HtmlNode UrlNode;
ObservableCollection<News> newsList = new ObservableCollection<News>();
List<HtmlNode> headlines;
HtmlDocument hd;
News n;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient webClenet = new WebClient();
webClenet.Encoding = new HtmlAgilityPack.Gb2312Encoding();
webClenet.DownloadStringAsync(new Uri("http://www.6park.com/news/multi1.shtml", UriKind.RelativeOrAbsolute));
webClenet.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClenet_DownloadStringCompleted);
}
private void webClenet_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
srcHTML = e.Result;
GetHeadlinePage(srcHTML);
}
private void GetHeadlinePage(string srcHTML)
{
hd = new HtmlDocument();
hd.LoadHtml(srcHTML);
try
{
UrlNode = hd.DocumentNode.ChildNodes[1].ChildNodes[3].ChildNodes[8].ChildNodes["tr"].ChildNodes["td"].ChildNodes["ul"];
headlines = UrlNode.Descendants("a").ToList();
foreach (var headline in headlines)
{
if (headline.Attributes["href"].Value.Contains("6park"))
{
n = new News();
n.NewsTitle = headline.InnerText;
n.NewsUrl = headline.Attributes["href"].Value;
n.NewsDetails = headline.NextSibling.InnerText.Replace("- ", "新闻来源:") + headline.NextSibling.NextSibling.InnerText + headline.NextSibling.NextSibling.NextSibling.InnerText;
newsList.Add(n);
}
}
}
catch (Exception ex)
{
//NewsSource.Text = ex.StackTrace + "\n" + ex.Message;
}
NewslistBox.ItemsSource = newsList;
//NewsHeadlineWebBrowser.NavigateToString(ConvertExtendedASCII(headNews));
}
}
I'd debug the value passed to GetHeadlinePage().
I'd suspect that the response is different based on the network or the request is timing out or you're getting some other error.
I'd assume that the call to LoadHtml() is failing as this isn't inside any exception handling/trapping and you've not validating the value passed to it.

Resources