"Invalid cross-thread access" when changing a WP8 textBlock - vb.net

I'm coming from VB 6 and am semi-new to VB.NET.
I'm writing a Windows Phone 8 application. There's a grid in which I have several textBlocks that I want to dynamically display data from a file stream (that contains scanned data).
When the WP8 page opens, it automatically loads the data into the textBlocks. This works. Before I load the data from the file, I want to "reset" all textBlocks and hide them. For this I wanted to use a procedure which essentially does the following for every textBlock:
tbl1.Text = ""
tbl1.Visibility = System.Windows.Visibility.Collapsed
This works exactly one time: when the page loads. The procedure does not produce an error.
Now when I call that method again later, when I want to refresh the data shown on the page, I get the following error on the first line of code shown above:
An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll but was not handled in user code
Additional information: Invalid cross-thread access.
I'm a bit lost now. In VB6 I was able to do whatever I wanted with my UI elements. I presume I'm making some kind of newbie mistake here?
I read somewhere about some Dispatcher thing. But that seems overly complicated to simply change a value in a textBlock to me. Is there no simple way?

The solution is indeed to use the Dispatcher.BeginInvoke method.
Dispatcher.BeginInvoke(() =>
{
tbl1.Text = ""
tbl1.Visibility = System.Windows.Visibility.Collapsed
});
The reason why you need this is because you try to access an object that depends on the UI thread from a non-UI thread.

It is probably because you are not calling the method from UI thread. Try using Dispatcher.BeginInvoke:
Dispatcher.BeginInvoke(()=>
{
tbl1.Text = "";
tbl1.Visibility = System.Windows.Visibility.Collapsed;
});

Related

[JETPACK COMPOSE]: is there a way to restart whole app programmatically?

I need a way to make my app close and opens again. Or just restart everything inside of it.
Since the issue with my app can be fixed by closing app and opening again (When creating user the loading function to firebase the collection inside user document does not load for some reason)
Below code can do it:
val context = LocalContext.current
val packageManager: PackageManager = context.packageManager
val intent: Intent = packageManager.getLaunchIntentForPackage(context.packageName)!!
val componentName: ComponentName = intent.component!!
val restartIntent: Intent = Intent.makeRestartActivityTask(componentName)
context.startActivity(restartIntent)
Runtime.getRuntime().exit(0)
So... you could write ways to "restart everything", but I am going to strongly suggest not doing that. When building an app, you will run into edge cases. You will hit some failure states that you can't recover from. That happens. But, solving these cases by just "restarting" doesn't actually address the issue and will probably result in wonky and undesirable UX.
I would instead suggest you post here some steps to reproduce and debugging results.
Under what circumstance/flow does this document stop loading?
When it does happen, can you capture the call to Firebase where it is trying to load the document?
If so, what does that call look like?
Is it looking for the document in the correct place?
Can you show an example of the call when it fails and also what the database hierarchy looks like?
Can you show us a snippet of code where this is failing?
Without more information, this sounds more like a race condition - you might be trying to find the document before it is actually created and not handling the error path for when the document is not found. However, we would need to do some debugging to verify.

Xamarin Xaml force update interface elements

The post has been rewritten to better fit the current problem.
I have a button x:Name="selectVesselButton". On button click, it tries to establish a connection to a server, which takes a sec or two for to do. Originally, I wanted the button to be grayed out while it was downloading and deserializing the json file from the connection.
My old code (before async, and trying to update the button):
// disabling the button to prevent spam clicking.
string buttonText = selectVesselButton.Text;
selectVesselButton.IsEnabled = false;
selectVesselButton.Text = "loading...";
// retrieve data for speed page.
RetrieveData();
// redirect to next info block if build was successfull.
FocusSpeedblock();
// enabling the button again.
selectVesselButton.Text = buttonText;
selectVesselButton.IsEnabled = true;
The issue with this code was that the button visuals did not update until the RetrieveData() was finished, defeating the purpose of doing that at all. This was because the code for updating the interface and the code for downloading and deserializing the object were both on the same thread.
However, following Ivan's advice, I made the downloading and deserializing Async, which fixed this issue (more like moved it).
This works fairly well, but I am still having some trouble updating the interface automatically. I have some labels that need to be updated based on the json file output. The value of the labels update on the background, but only update visually once I interact with the labels (I.E. scrolling the scrollview they are on). Check edit 3 for more detail on that.
EDIT 3:
When the second thread is finished, it should call the UpdateSpeedLabels() and update some labels. However, they update in codebehind, without instantly updating the interface. They only update if I interact with those labels.
The preferred way of doing this on Xamarin is with data binding. As you opted out of this it is still possible.
What you need is to ensure that your long task is not running in the UI thread as it blocks it and prevent its updates. You do this by using Task.Run(() => { your task code }); . However you can't update your user interface inside the Task.Run as it is not running on the UI thread and it would crash the app, so you need to use Device.BeginInvokeOnMainThread(() => { your UI code }); inside Task.Run for that part.

navigationservice.navigate not available on the vs2013 project

I have two page application and the main page is default is "MainPage.xaml" and the second one is "AddPerson.xaml" when user click a button on main page I want the app to take user to "AddPerson" page.
And I wrote following for the Click event of the button
Me.Frame.Navigate(System.Type.GetType("AddPerson.xaml"))
and I am getting the following error
An exception of type 'System.NullReferenceException' occurred in MedicineSchedule.exe but was not handled in user code
Additional information: Object reference not set to an instance of an object.
If there is a handler for this exception, the program may be safely continued.
I tried other method of navigationservice.navigate which I cannot find the class in VS2013 express at all. The only method available is Me.Frame.Navigate in my project, please let me know how I can get this simple thing to work.
If it was .net 2.0 I would simple called new form with form.lod or something similar.
This doesn't work?
this.Frame.Navigate(typeof(AddPerson));
If you want/have to use a string take a look at the reply here:
convert string to type of page

Identifying objects in IBM RFT

While executing my script in RFT, my script got failed due to the slight position change of a button. (This button's position slightly changes according to the option selected for previous combo box due to the label appearing near the button)
As there are 2 positions for this button in window, one of my script fails while other passes.
Please suggest how to identify this same object in 2 different places in RFT?
If you're alright with not using pre-mapped values and instead work with objects directly in code (which I've personally found to be extremely useful... it's allowed me to do great and wondrous things with RFT :), the following ought to work fine:
private void clickObject(String uniqueIdentifier) {
// Find object
RootTestObject root = RootTestObject.getRootTestObject();
TestObject[] matchingObjs = root.find(atProperty(".id", uniqueIdentifier));
if (matchingObjs.length > 0) {
// Click the object
((GuiTestObject) matchingObjs[0]).click();
}
// Clean-up
unregister(matchingObjs);
}
Feel free to replace ".id" with whatever property is best suited for the situation... since I work primarily with a web application, the ".id" property has worked splendidly for me.
Because the method finds the object anew each time, it'll grab the object's position wherever it's at at the time the method's called. The clean-up will also prevent any weird, horrible, and otherwise unfortunate UnregisteredObjectExceptions from cropping up.
Without looking at your pages I cannot be sure, but I think the buttons are actually two different buttons. Maybe they are generated by javascript, or they are just un-hidden after the option you select in the combobox.
If they are two different buttons (record them both and look at the recognition properties) you can either replace some properties with a regular expression or check wich button is visible/exists and then click it:
if (btn_button1.exists()) {
btn_button1.click();
} else if (btn_button2.exists()) {
btn_button1.click();
}
Here's a more complete tutorial on Object Recognition.
You can increase the tolerance of Rational Performance Tester AssureScript in the properties tab or you could set the description but hide the value. You can also make a custom code that updates the object map to prepare for this change in a java IF structure

Play Framework 2.1.1: bindFromRequest() returns the correct data but ignores all data pertaining to relations

I have a form that is supposed to create an entity of type Load, but for some reason, doesn't seem to be actually passing or seeing any of the data related to associations of the entity (load.user, load.client, etc). This all used to work fine but stopped working at some point during a bunch of refactoring (that didn't change any of the fields in any of the models). Now all of the forms in my website have broken the same way and I have no clue where to even look to start fixing it.
From the view, I submit the form for a new Load, printing out the data everywhere I can along the way. Printing out the data being sent to the server before it's sent shows all the data is there like it should be. Printing out Form.form(Load.class).bindFromRequest() in the controller shows the form's data contains everything needed, for example, the value user.id=1 is in the data. However, there is also a validation error saying that the user is missing. How can this be?
Form(of=class models.Load, data={ a bunch of stuff, user.id=1, a bunch more stuff}, value=None, errors={=[ValidationError(,Logged in user is missing or invalid.,[])]})
The validation error is being generated by public String validate() in the Load class, which is simply checking if(user==null) and returning that string if it is. I should note that every form that submits multiple entities (for example, submitting a Dock and then also the Dock's Location) only saves the main entity (in this example, the Dock) and ignores all others (the Dock's Location is never saved, even though Dock cascades in the model to also save the Location). All of our form fields are labelled correctly, this code did used to work at some point before it mysteriously stopped working!
So why did all of my forms suddenly stop correctly dealing with anything but the main model for the form? It is as if they cannot even "see" the data contained in bindFromRequest(). If I print out a variable in the validation method of Load, such as this.status, it prints the correct thing. But if I try to print something like this.user.id or this.client.id I get a null pointer error. Where is the code in Play that actually interprets the data (user.id=1) and turns it into the User associated with the Load, and how could it be breaking?
Edit: Also, yes, I did try "play clean", it was the first thing I tried since usually it fixes weird errors like these! But this time, no dice.
Edit2: I'm including the html from the form, in case it is helpful.
<input type="text" id="user_id" name="user.id" value="1" class="idfield">
Edit3: The only change I made during the refactoring that might have influenced this is that I had to make some setter methods like Load.setBroker() because the ones that are supposedly generated by Play didn't work. For example, load.broker=aBroker would not have set the Load's Broker before, so I had to make a public void setBroker(Broker broker) method in Load. Does Play use the auto-generated setters to bind the data? Could overwriting them cause problems?
Whoops, I figured it out. It was the setters I had written. Some of them were set to private purely by mistake, and apparently this was preventing Play from setting the values when binding the data. Changed them all to public and the mystery error vanished.