Pass data between pages in WP8 application - c#

I am building a simple Sports Tracker application. I want to start a DispatcherTimer and a GeoCoordinateWatcher at Page 1, and in Page 2 I want a map view. And I am looking for the best practice how to pass the timers and the watchers value between pages, so I can show the updated information on the map.
I've seen suggestions to save it to an XML or into the IsoStorage. What is the best solution for this problem ?

Directly you can pass strings between your pages:
NavigationService.Navigate(new Uri("/destinationPage.xaml?dataKey="+dataValue.ToString()));
If you want to pass an object the first thing that hits is:
NavigationService.Navigate(new Uri("/destinationPage.xaml?dataKey="+dataObject.ToString()));
Here comes the problem:
1) You need to deserialize your object in your destination page. Or even worse,
2) Memory problem. Say you need to pass an image (captured in 41 mega pixel) and you are not allowed to use this much memory:
So here is another solution:
PhoneApplicationService.Current.State["yourparam"] = param;
Then you navigate to your destination page and you can access your object:
var k = PhoneApplicationService.Current.State["yourparam"];
Note: This thing would write your object in isolated Storage. So may be a bit slow.
Third option:
Use a static class to hold your dataValue between your pages. like:
static class Transporter
{
public static object container;
}
Now in your source page you can write:
Transporter.container = MyGeoCoordinateWatcherObj;
You can access this in your destination page. (here remains the problem of memory, but in your case you can use it safely.)
Note: Sometime microsoft recommends mvvm pattern to pass objects.

Related

Best way to pass complex object between requests in ASP.Net Core MVC

I am still learning asp.net core and need to know if I'm going about this problem the correct way. Within my app I have a page that is acting as a wizard to create a complex object. I am using a view model to control the inputs. A brief overview of the viewmodel is:
Master Object
-2 Child Objects (that contain 3 child objects each)
-Second Child Object (that contains 1 child object)
I have gotten to the point where I can create the Master Object and all children without any issues. The next step is to add a search option for the 2 child objects.
Currently I have a link to a search page for the child object, I am using TempData to pass the ID of the selected object back (since TempData doesn't support complex objects). On my originating controller I am checking the TempData for the key, and if it exists I am querying the database (via _context) for the selected object.
Child Controller:
TempData["ChildObjectId"] = SelectedID;
return Redirect(MasterObjectControllerCreationURL);
Master Object Controller:
if (TempData.ContainsKey("ChildObjectId"))
{
ViewData["ChildObject"] = _context.ChildObject.Include(x => x.SubObject).Where(x => x.ChildObjectId == Convert.ToInt32(TempData["ChildObjectId"])).FirstOrDefault();
TempData.Remove("ChildObjectId");
}
Master Object Create Page:
if (ViewData.ContainsKey("ChildObject"))
{
Set field variables for the fields we want.
}
Ultimately this is resulting in 2 database calls, one for the search, and then one for the next retrieval. Is this the most efficient way to handle the problem, or is there a better solution? It seems like there should be a more efficient way to handle this. I know I could just set TempData for all of the fields in question, but that would result in 40 possible fields being stored in TempData. Maybe this isn't a problem and is the correct way, I just don't know enough about ASP.Net Core and MVC to know.

Xamarin Pass Entry Value to new page from old

Hi i have a page where i get the user to fill out their fast name and last name and then when they hit the next button it performs an:
await Navigation.PushModalAsync(new VisitorHSAgreement());
to the next page, what I want to do is bring them values to display in a label on the next page I have currently tried this but it's coming back null can anybody help me.
public string VisitorFirstName { get; set; }
public string VisitorLastName { get; set; }
var visitorPage = new VisitorPage();
VisitorFirstName = visitorPage.FindByName<Entry>("FirstNameEntry").Text;
When on VisitorPage, there is an instance of the class VisitorPage. This instance contains controls, which are instances, too, and might have values set in their properties.
Now you navigating to VisitorHSAgreement and try to get a value from the VisitorPage by creating a new object of this class. Each object of this class comes with its own values and the controls are newly created. Unless you create some static field in VisitorPage you will never be able to access the values that are set in the first instance from the new instance. You should really read up on basic concepts of OOP, because this is really OOP 101.
I'd suggest to use MVVM along with the Prism library, this will really make your Xamarin.Forms life easier. Anyway, if you can't or don't want to at the moment (it's up to you in the end), there is still a solution. Since your properties are public, you can set them before navigating to VisitorHSAgreement
var page = new VisitorHSAgreement()
{
VisitorFirstName = FirstNameEntry.Text,
VisitorLastName = LastNameEntry.Text
};
await Navigation.PushModalAsync(page);
You need to learn how to work with Object Oriented programming.
As mentioned in the previous answer, you are trying to access empty values from a recently created object (which will obviously empty). While what you need to do is assign the values to the object you want to send, and then send that object (data filled in) to the page you want to use it.
Then in your page, receive that object sent from the previous page and explore its properties to obtain your values.

ASP.NET Control visibility dilemma

I've got a Page, a GridView using an ObjectDataSource with a SelectMethod and a DropDownList. The SelectMethod, among other things, gets a string-array containing several IDs (to filter the Data) - but I also need it as DataSource for the DropDownList.
Alas, I cannot DataBind the DropDownList inside the SelectMethod since it's null.
An Idea would be to bind this string[] to a Session-Variable, but then I'd have to either re-set it upon every Page_Load or remove it from Session on every other page if I want it to update in case something on the Database changed.
What I'm looking for is some kind of variable that is available both in Page_Load and my ObjectDataSources SelectMethod, but that removes itself upon leaving the page (i.e. navigating to any other page on my Web-Application (preferably without having to call a method on EVERY other Page).
I hope you could understand my problem.
Thanks,
Dennis
As I understand the need to fetch the string array arises from the performance hit that a separate roundtrip will cause. To work around this you may create a separate object to feed your object data source. This object will have two methods one for getting the string array and another for getting the data for the grid (i.e. the select method)
You may then put an object like this in your page and fetch the data in it in a lazy manner. If the object makes a call for any of the data it stores the other part in a field. You can then use the ObjectDataSource ObjectCreating event to pass this object on your page to the ObjectDataSource
protected void odsSomething_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = YourInsntanceAlreadyInThePage;
}
This way you will avoid the roundtrip.
Also consider making two web service calls at the same time using the asynchronous client calls so that you can make both calls for the same time. If this is viable depends on the flow of your logic.
What I'm looking for is some kind of variable that is available both in Page_Load and my ObjectDataSource's SelectMethod, but that removes itself upon leaving the page (i.e. navigating to any other page on my Web-Application (preferably without having to call a method on EVERY other Page).
In a similar situation, I've used the Items property of the current HttpContext. It's an IDictionary (non-generic), so can hold arbitrary objects keyed by arbitrary objects, and its lifetime is precisely the duration of the current request, so will go away as soon as the request is ended. To use:
// Where you first get the data
HttpContext.Current.Items["SomeKey"] = new [] { "string1", "string2" };
// Where you want to to use the data
var strings = (string[])HttpContext.Current.Items["SomeKey"];

Monotouch: send data back down the stack to another ViewController

I have a question concerning Monotouch.
The situation: I have 2 ViewControllers. The first (let's call it VC-A) looks similar to the contacts edit screen, meaning it has a TableView with multiple Sections each containing Buttons and TextFields. Now when the user clicks one of these Buttons, he will get to the second ViewController (VC-B), which displays a TableView containing data from the database. When the user clicks on any of these rows, VC-B will be closed and i want to display the selected database entry (string) as the title of the Button (in VC-A) which opened VC-B in the first place.
When I did an objective-C project last year, I managed to send data back down the stack by using delegates, but I haven't found a way yet how this works in Monotouch.
I have read several questions here on SO about using the AppDelegate or using singletons, but I'm not sure that this is the right way of returning data from a subview.
You can kind of copy the delegate pattern. Add a C# delegate to your VC-B that takes one parameter, some data structure.
In VC-B's "ViewWillDisappear", call the delegate it it is not null and pass the data on to it.
This way, your calling VC can get acces to the data but you don't need tight coupling between the two controllers. All it has to do, is register a delegate-method in VC-B.
As MonoTouch is .NET4 you can use Func<MyDataStructure> or Action<MyDataStructure> and don't need to use full qualified delegate types.
I have a static singleton class that I use to store "state" type data about my app - current settings and selections that are needed in many different places in the app. That's one way to approach this.
You could also pass VC-B a reference to VC-A when you create VC-B, so that it can explicitly access it's parent view and pass back values that way.
I actually prefer to use TinyMessenger for cross container calls I find this to be very very useful when you don't want to keep references to your heavy viewcontrollers around which could potentially result in memory leaks!
var messageHub = new TinyMessengerHub();
// Publishing a message is as simple as calling the "Publish" method.
messageHub.Publish(new MyMessage());
// We can also publish asyncronously if necessary
messageHub.PublishAsync(new MyMessage());
// And we can get a callback when publishing is completed
messageHub.PublishAsync(new MyMessage(), MyCallback);
// MyCallback is executed on completion
https://github.com/grumpydev/TinyMessenger

Alternative to Query Strings to Pass Data Between ASP.Net Pages?

I am currently using a number of query string parameters to pass some data from one page to a second page (the parameters hold confirmation/error messages to display in the second page), that due to a third party product can no longer work correctly in the production environment. The user completes an action on the first page, and is then transferred to the second page. What are the possible alternatives to use instead of a query string and GET - session variables, POST data, or something completely different?
Thanks, MagicAndi.
You could create public properties in a source page and access the property values in the target page when using a server transfer. You could also get control information in the target page from controls in the source page by referencing the Page.PreviousPage property.
Both of these methods are oulined here: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
Both POST data and session variables would work just fine. POST data has the drawback that it can be changed by the client and session variables take up memory, so you can choose based on that. I personally don't think that you should pass such messages to the client for the reason stated above but I guess you are already doing that, so...
you can use this if you use window.open("openTheotherPage",...etc)
so form the opened page you can do something like this
var valuefromCallerPage = window.opener.document.FormNmae.textbox.value
or button or anything on the caller page

Categories