how to create a synchronous news feed in UWP - asynchronous

I want to create a simple news feed, I use web API to get the news updates, users can use combox select category (world news & sports news),and the news will be auto updated every 5 seconds, if I only select once, the news feed can auto updated and repeat, But if I change the selection, it start to show me both categories. here is my code
public async void NewsRepeat()
{
RootObject2 myNews = await NewsProxy.GetNews();
RootObject3 mySportNews = await sportsNewsProxy.GetSportNews();
if (newsTpye.SelectedIndex==0)
{
for ( k = 0; k <= 8; k++)
{
newsImage.Source = new BitmapImage(new Uri(myNews.articles[k].urlToImage, UriKind.Absolute));
showTime.Text = myNews.articles[k].publishedAt.ToString();
showDescription.Text = "(" + myNews.source + "): " + myNews.articles[k].description;
await Task.Delay(5000);
}
}
else if (newsTpye.SelectedIndex==1)
{
for (k = 0; k <= 8; k++)
{
newsImage.Source = new BitmapImage(new Uri(mySportNews.articles[k].urlToImage, UriKind.Absolute));
showTime.Text = mySportNews.articles[k].publishedAt;
showDescription.Text = "(" + mySportNews.source + "): " + mySportNews.articles[k].description;
await Task.Delay(5000);
}
}
NewsRepeat();
}
private void newsType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
NewsRepeat();
}

Your code runs continuously / infinite loops. NewsRepeat never finishes - so when you change selection your now running two instances of NewsRepeat side by side. Change it again and you're running three, and so on.
On SelectionChanged you want to somehow stop the previous instance of NewsRepeat from running.
(Also, creating BitmapImages in the ViewModel is a bad idea generally - bind the directly in XAML to the URL property - Windows will carry out some performance and memory enhancements for you)
One possible solution is to use a CancellationTokenSource, which is a very simple object you can use to manually throw OperationCanceledException's when you deem it necessary (
frequently used as a pattern to cancel async Tasks). Keep it mind it does not work automatically - it's something you have to handle.
CancellationTokenSource cts = null;
public async void NewsRepeat()
{
cts?.Cancel();
try
{
var localCts = cts = new CancellationTokenSource();
RootObject2 myNews = await NewsProxy.GetNews();
RootObject3 mySportNews = await sportsNewsProxy.GetSportNews();
localCts.Token.ThrowIfCancellationRequested();
if (newsTpye.SelectedIndex == 0)
{
for (k = 0; k <= 8; k++)
{
newsImage.Source = new BitmapImage(new Uri(myNews.articles[k].urlToImage, UriKind.Absolute));
showTime.Text = myNews.articles[k].publishedAt.ToString();
showDescription.Text = "(" + myNews.source + "): " + myNews.articles[k].description;
await Task.Delay(5000);
localCts.Token.ThrowIfCancellationRequested();
}
}
else if (newsTpye.SelectedIndex == 1)
{
for (k = 0; k <= 8; k++)
{
newsImage.Source = new BitmapImage(new Uri(mySportNews.articles[k].urlToImage, UriKind.Absolute));
showTime.Text = mySportNews.articles[k].publishedAt;
showDescription.Text = "(" + mySportNews.source + "): " + mySportNews.articles[k].description;
await Task.Delay(5000);
localCts.Token.ThrowIfCancellationRequested();
}
}
NewsRepeat();
}
catch (OperationCanceledException)
{
// Swallow this exception only - this is probably
// the one we've thrown ourselves
}
}
private void newsType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
NewsRepeat();
}

Related

Xamarin.Android - How to continue a process while app is minimized or screen is locked

I've created a Xamarin app that checks the users current location every couple minutes. My problem is it doesn't work when I minimize the app or the screen locks. Is there a way for me to continue the process while minimized or when the phone is locked?
This function checks to see if the user is at the destination location.
public bool atLocation(decimal currentLat, decimal currentLong, decimal destLat, decimal destLong)
{
decimal GPSLatitudePadding = 0.001M;
decimal GPSLongitudePadding = 0.001M;
var totalLowerLatitude = Convert.ToDecimal((destLat - GPSLatitudePadding).ToString("#.####"));
var totalLowerLongitude = Convert.ToDecimal((destLong + GPSLongitudePadding).ToString("#.####"));
var totalUpperLatitude = Convert.ToDecimal((destLat + GPSLatitudePadding).ToString("#.####"));
var totalUpperLongitude = Convert.ToDecimal((destLong - GPSLongitudePadding).ToString("#.####"));
if ((Convert.ToDecimal(destLat) >= totalLowerLatitude) &&
(Convert.ToDecimal(destLat) <= totalUpperLatitude) &&
(Convert.ToDecimal(destLong) <= totalLowerLongitude) &&
(Convert.ToDecimal(destLong) >= totalUpperLongitude))
{
return true;
}
return false;
}
If the user is at the destination for 2 instances of 2 minutes the process is ended. This is where you could start a new process or update a database.
int intNumberOfTimesFoundAtLocation = 0;
void OnLocationResult(object sender, Android.Locations.Location location)
{
decimal currentLatitude = Convert.ToDecimal(location.Latitude);
decimal currentLongitude = Convert.ToDecimal(location.Longitude);
decimal destLatitude = Convert.ToDecimal(this.dblDestLatitude);
decimal destLongitude = Convert.ToDecimal(this.dblDestLongitude);
var atLocation = locationQ.atLocation(currentLatitude, currentLongitude, destLatitude, destLongitude);
if (ayLocation == true)
{
intNumberOfTimesFoundAtLocation = intNumberOfTimesFoundAtLocation + 1;
if(intNumberOfTimesFoundAtLocation == 2)
{
client.RemoveLocationUpdates(locationCallback);
}
}
}
I call this function to start the process
MyLocationCallback locationCallback;
FusedLocationProviderClient client;
public async void StartLocationUpdatesAsync()
{
// Create a callback that will get the location updates
if (locationCallback == null)
{
locationCallback = new MyLocationCallback();
locationCallback.LocationUpdated += OnLocationResult;
}
// Get the current client
if (client == null)
client = LocationServices.GetFusedLocationProviderClient(this);
try
{
locationRequest = new LocationRequest()
.SetInterval(120000)
.SetFastestInterval(120000)
.SetPriority(LocationRequest.PriorityHighAccuracy);
await client.RequestLocationUpdatesAsync(locationRequest, locationCallback);
}
catch (Exception ex)
{
//Handle exception here if failed to register
}
}
}
class MyLocationCallback : LocationCallback
{
public EventHandler<Android.Locations.Location> LocationUpdated;
public override void OnLocationResult(LocationResult result)
{
base.OnLocationResult(result);
LocationUpdated?.Invoke(this, result.LastLocation);
}
}
Create a foreground service.
Inside service call the following code to start the request updates.
locationLogger = new LocationLogger();
locationLogger.LogInterval = _currentInterval;
locationLogger.StopUpdates();
locationLogger.StartRequestionUpdates();
Check here for the code
Let me know if you need more help.

Unable to modify xaml controls following NFC tag read

I have a method that adds a label with some text to an existing xaml StackLayout.
The method is called from a couple of places, an event fired by xaml ListView and an NFC tag read. In both scenarios, the method is hit in the code-behind.
The methods both call another method that creates the label and adds it on screen. The one that originates from the ListView event works fine but the one from the NFC tag does nothing. It passes over each row of code without causing an exception but does not add anything to the screen. I can see after this that the child count of the StackLayout is 1 and remains as 1 if you do it again.
The NFC method:
public async void HandleNFC(string convertedtag)
{
int result = 0;
try
{
var mp = (MainPage)App.Current.MainPage;
Label sl1 = mp.CurrentPage.FindByName<Label>("timeLabel");
}
catch (Exception e)
{ }
Label sl = timeLabel;
string time = sl.Text;
PeopleLocationsForUserRoot peoplelocationforuser = await WebDataAccess.GetPeopleLocationForUser(UserInfoRepository.GetUserName(), _locationID);
DateTime dt = Convert.ToDateTime(time);
long timeticks = (long)((dt.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
getServerTime();
string name = "";
try
{
foreach (var person in peoplelocationforuser.locationPeople)
{
if (person.TATokenValue == convertedtag)
{
var action = await DisplayActionSheet(person.FirstName + " " + person.LastName, "Cancel", null, "IN", "OUT");
string act = action;
string formattedact = act;
int swipedirection = 0;
name = person.FirstName + " " + person.LastName;
if (act == "IN")
{
formattedact = "in";
swipedirection = 1;
}
if (act == "OUT")
{
formattedact = "out";
swipedirection = 0;
}
if (act != "Cancel")
{
result = SwipeRepository.ClockUserInOut(person.EB_Counter, _locationID, swipedirection, dt, timeticks, 1, UserInfoRepository.GetLatt(), UserInfoRepository.GetLongi());
addToReadout(name, time, formattedact);
}
}
}
if (name == "")
{
await DisplayAlert("Tag Error", "Tag not recognised", "cancel");
}
}
catch (Exception ex)
{
ErrorRepository.InsertError(ex.ToString());
}
await WebDataAccess.SaveSwipesToCloud();
}
The 'addToReadOut' method that it calls:
public void addToReadout(string name, string time, string inout)
{
try
{
Label label1 = new Label { Text = name + " Successfully clocked " + inout + " # " + time, TextColor = Color.Black };
try
{
readOut.Children.Add(label1);
StackLayout sl = this.FindByName<StackLayout>("readOut");
sl.Children.Add(label1);
sl.Focus();
timeLabel.Text = "test";
}
catch (Exception e)
{ }
// StackLayout sl = mp.CurrentPage.FindByName<StackLayout>("readOut");
if (readOut.Children.Count() < 6)
{
readOut.Children.Add(label1);
readOut.Children.Count();
}
else
{
readOut.Children.RemoveAt(0);
readOut.Children.Add(label1);
readOut.Children.Count();
}
}
catch (Exception ex)
{
ErrorRepository.InsertError(ex.ToString());
}
}
You can see that I have also tried to modify the object called 'timelabel' but does also does not change on screen.
The must be something different happening following the NFC event which is causing an issue here but I can't find what's causing it.
You NFC event is firing on a background thread; your UI updates need to happen on the UI thread
Device.BeingInvokeOnMainThread( () => {
// UI Code goes here
});

JavaFX update bullet position UI in a loop

For my school project i have to make a game where a cannon have to shoot a bullet to a airplane, the problem is, when we shoot we can see all the position (X . Y) of the bullet on console but the bullet doesn't update on the UI
Here's the Test code:
vel = Slider.getValue();
double angle = panelNero.getRotate();
boolean dead = false;
while (dead == false) {
double X = P.getLayoutX();
double Y = P.getLayoutY();
if (X > 1 && Y > 1 && X < MP.getWidth() && Y < MP.getHeight()) {
System.out.println("x: " + X + " y: " + Y + " maxX: " + MP.getWidth() + " maxY: " + MP.getHeight());
double x = P.getLayoutX();
double y = P.getLayoutY();
P.setLayoutX(x += (Math.cos(Math.toRadians(angle)) * vel));
P.setLayoutY(y += (Math.cos(Math.toRadians(angle)) * vel));
System.out.println("VIVO");
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(FileFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
System.out.println("MORTO");
P.setLayoutX(pro.posX);
P.setLayoutY(pro.posY);
dead = true;
}
}
Please take a look at this post: Platform.runLater and Task in JavaFX
You can use Platform.runlater() to update your GUI from a non-GUI thread. In this case, your update request is put in a queue and handled by the GUI thread ASAP.
But since this is a more complex iteration, you can consider using a Task on a new Thread.
I suggest you to use something like this:
Task task = new Task<Void>() {
#Override
public Void call() throws Exception {
while (dead == false) {
Platform.runLater(new Runnable() {
#Override
public void run() {
P.setLayoutX(...);
P.setLayoutY(...);
}
});
Thread.sleep(500);
}
}
};
Thread th = new Thread(task);
th.start();

Error in audio recording WAV

I have two methods that record audio every 10 minutes, alternating each method, properly recorded during the first 6 or 7 hours, but then I generates large files to twice normal to hear hear bad but only happens with a method other Normal still recording. I use to record WaveInEnvent since the method is inside a thread, I think problem is in OnDataAvailable.
Here the code used:
wavein = new WaveInEvent();
wavein.Dispose();
wavein.DeviceNumber = 0;
wavein.NumberOfBuffers = 11;
wavein.BufferMilliseconds = 1000;
wavein.WaveFormat = new WaveFormat(8000, 16, 2);
wavein.DataAvailable += OnDataAvailable;
wavein.RecordingStopped += OnRecordingStopped;
writer = new WaveFileWriter(outfilename, wavein.WaveFormat);
bufferedWaveProvider = new BufferedWaveProvider(wavein.WaveFormat);
bufferedWaveProvider.DiscardOnBufferOverflow = true;
wavein.StartRecording();
private void OnDataAvailable(object sender, WaveInEventArgs e)
{
if (this.InvokeRequired)
{
//Debug.WriteLine("Data Available");
this.BeginInvoke(new EventHandler<WaveInEventArgs>(OnDataAvailable), sender, e);
}
else
{
if (writer != null)
{
try
{
for (int i = 0; i < e.BytesRecorded; i += 2)
{
short sample = (short)((e.Buffer[i + 1] << 8) | e.Buffer[i + 0]);
float sample32 = sample / 32768f;
writer.WriteByte(e.Buffer[i + 0]);
writer.WriteByte(e.Buffer[i + 1]);
}
}
catch (Exception ex)
{
// Log error
}
}
}
}

Auto save of form

I have form in ASP.NET 3.5. Where lot of data elements and where i have Save and Submit buttions. I need to auto save my form every 2 min. What is the best way to implement this kind of functionility in ASP.NET.
I struggled for awhile with the same problem. The trouble was that I didn't want to save into the usual database tables because that would've required validation (validating integers, currencies, dates, etc). And I didn't want to nag the user about that when they may be trying to leave.
What I finally came up with was a table called AjaxSavedData and making Ajax calls to populate it. AjaxSavedData is a permanent table in the database, but the data it contains tends to be temporary. In other words, it'll store the user's data temporarily until they actually complete the page and move onto the next one.
The table is composed of just a few columns:
AjaxSavedDataID - int:
Primary key.
UserID - int:
Identify the user (easy enough).
PageName - varchar(100):
Necessary if you're working with multiple pages.
ControlID - varchar(100):
I call this a ControlID, but it's really just the ClientID property that .NET exposes for all of the WebControls. So if for example txtEmail was inside a user control named Contact then the ClientID would be Contact_txtEmail.
Value - varchar(MAX):
The value the user entered for a given field or control.
DateChanged - datetime:
The date the value was added or modified.
Along with some custom controls, this system makes it easy for all of this to "just work." On our site, the ClientID of each textbox, dropdownlist, radiobuttonlist, etc is guaranteed to be unique and consistent for a given page. So I was able to write all of this so that the retrieval of the saved data works automatically. In other words, I don't have to wire-up this functionality every time I add some fields to a form.
This auto-saving functionality will be making its way into a very dynamic online business insurance application at techinsurance.com to make it a little more user friendly.
In case you're interested, here's the Javascript that allows auto-saving:
function getNewHTTPObject() {
var xmlhttp;
/** Special IE only code */
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end
#*/
/** Every other browser on the planet */
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function AjaxSend(url, myfunction) {
var xmlHttp = getNewHTTPObject();
url = url + "&_did=" + Date();
xmlHttp.open("GET", url, true);
var requestTimer = setTimeout(function() { xmlHttp.abort(); }, 2000);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState != 4)
return;
var result = xmlHttp.responseText;
myfunction(result);
};
xmlHttp.send(null);
}
// Autosave functions
var SaveQueue = []; // contains id's to the DOM object where the value can be found
var SaveQueueID = []; // contains id's for binding references (not always the same)
function ArrayContains(arr, value) {
for (i = 0; i < arr.length; i++) {
if (arr[i] == value)
return true;
}
return false;
}
function GetShortTime() {
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
a_p = "AM";
else
a_p = "PM";
if (curr_hour == 0)
curr_hour = 12;
else if (curr_hour > 12)
curr_hour = curr_hour - 12;
var curr_min = d.getMinutes();
curr_min = curr_min + "";
if (curr_min.length == 1)
curr_min = "0" + curr_min;
return curr_hour + ":" + curr_min + " " + a_p;
}
function Saved(result) {
if (result == "OK") {
document.getElementById("divAutoSaved").innerHTML = "Application auto-saved at " + GetShortTime();
document.getElementById("divAutoSaved").style.display = "";
}
else {
document.getElementById("divAutoSaved").innerHTML = result;
document.getElementById("divAutoSaved").style.display = "";
}
}
function getQueryString(name, defaultValue) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return defaultValue;
}
function urlencode(str) {
return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/#/g, '%40');
}
function AutoSave() {
if (SaveQueue.length > 0) {
var url = "/AjaxAutoSave.aspx?step=" + getQueryString("step", "ContactInformation");
for (i = 0; i < SaveQueue.length; i++) {
switch (document.getElementById(SaveQueue[i]).type) {
case "radio":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
break;
case "checkbox":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
default:
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
}
}
SaveQueue = [];
SaveQueueID = [];
AjaxSend(url, Saved);
}
}
function AddToQueue(elem, id) {
if (id == null || id.length == 0)
id = elem.id;
if (!ArrayContains(SaveQueueID, id)) {
SaveQueue[SaveQueue.length] = elem.id;
SaveQueueID[SaveQueueID.length] = id;
}
}
Add this to your page to make this work:
window.setInterval("AutoSave()", 5000);
And to apply this to a Textbox, DropdownList, Listbox, or Checkbox you just need to add this attribute:
onchange="AddToQueue(this)"
...or this for a RadioButtonList or CheckBoxList:
onchange="AddToQueue(this, '" + this.ClientID + "')"
I'm sure this Javascript could be simplified quite a bit if you used JQuery so you might want to consider that. But in any case, AJAX is the thing to use. It's what Google uses to auto-save your email message in gmail, and the same thing is in blogger when you're writing a new post. So I took that concept and applied it to a huge ASP.NET application with hundreds of form elements and it all works beautifully.
Use the Timer class and the Tick method.

Resources