How do I pass a variable to another Silverlight page? - c#

I have an OnClick event for my Pushpins as below.
void BusStop1061_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("Buses from this station: City Link");
}
I would like to pass the bustop number to another page and to the int "PassedVariable"
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
string site = "http://www.sourceDomain?stop=" + PassedVariable;
webBrowser1.Navigate(new Uri(site, UriKind.Absolute));
}
I was thinking of creating a constant int on the Page one, then passing it to page 2 using urimapping, but it doesn't seem to work and I figured someone might have a better option
I have had a look at similar posts, but they dont quite answer my question.

There are multiple ways to achieve this.
One way, is to create a BustopNumber property in the App.xaml.cs class, a set it in one page, and access it else where.
This is my preferred approach, although you have to guard against the case where the value isn't set or invalid.
Another approach is to pass it in as a query string parameter, similar to what you are doing in your code snippet above. In the navigated to page, you can access the query string parameter via the NavigationContext object and look for by name.
Edit to add:
public partial class App : Application
{
public static int BusStopNumber { get; set;}
}
//And in your application you can access it like so:
App.BusStopNumber = 10;
Obviously there are issues with encapsulation, as this is essentially a hack for global, but if used carefully, can offer a quick and easy way to share information across multiple pages.

One of the approaches is to add a class with common data that can be shared between the views. This is one of the way and may not be the best.
You can have a static class which can create singleton of Session and provide it to XAML as part of User control binding. Session class can be enhanced in future with multiple properties if you want.
View1 View2
^ ^
| |
| |
v v
Session Service (stores user selection)
View1 and View2 should have reference to Session Service.
public class Session
{
public int BusStop {get; set;}
}
You should start looking at MVVM pattern to modularize your code and avoid any such issues in future.

you can use PhoneApplicationService. include the shell namespace. using Microsoft.Phone.Shell;
PhoneApplicationService appSer = PhoneApplicationService.Current;
appSer["busStopNumber"]=number;
and when you want to use it already in another page, do this (initialize the appSer also in the page)
if(appSer["busStopNumber"]!=null)
{
int number = (int)appSer["busStopNumber"];
}

Related

How to return null values for editing in asp.net mvc?

I know this might be a silly question for the MVC pros but it become a headache for me for the last couple of hours so please accept my excuses!
I have a class called DeliveryDetails as below:
Public Class DeliveryDetails
{
Prop1;
Prop2;
Prop3;
PropX;
}
The concept is that i want the logged in users to edit the DeliveryDetails class data as a process of checkout even if there is no data in the backend database table. Is that possible? Or should i first save the DeilveryDetails and on the second time of purchasing i bring up DeliveryDetails in editing mode?
Of the top of my head, based on your input:
You could create DeliveryDetails and store its reference into Session on Session_Start event (you could also load it from database or some other source, if neccessary).
protected void Session_Start(object sender, EventArgs e)
{
Session["DeliveryDetails"] = new DeliveryDetails();
}
Then when you need your DeliveryDetails instance, you just extract it from session like this:
var deliveryDetails = (DeliveryDetails)Session["DeliveryDetails"];
// deliveryDetails.Prop1 = ...
// deliveryDetails.Prop2 = ...
// etc.
But in this way, you must be careful to init/reset DeliveryDetails object inside Session, when it is appropriate.
This way you can decide when to write data into database (if required), but the user will have its DeliveryDetails always available through Session. Of course, if you do not use Sessions, you may not be able to do this.

How to cast SourcePageType as Page?

Well I'm building a WinRT app currently and I am facing this issue.
What I am trying to achieve is that I need to read or modify the properties on previous page that I am navigated from.
So let's say that I have two pages: MainPage and WatchPage.
I am navigating to WatchPage from MainPage and inside the WatchPage's OnNavigatedTo event I need to access a property inside MainPage without using navigation parameters...
How can I achieve this?
protected override void OnNavigatedTo(NavigationEventArgs e){
Type LastPage = rootFrame.BackStack.Last().SourcePageType;
if(LastPage == typeof(MainPage){
// here, for example, say that MainPage has a property called isLoadSuccess
// I need to set that property to false
// or call a method from MainPage
// => this is not working MainPage MP = LastPage as MainPage;
// I know that it should not work anyway, but, how can I achieve this?
}
}
What you are attempting to do cannot be accomplished using the existing framework. That is to say, a reference to the instance of your previous page does not exist in the BackStack. The only thing that exists is, honestly the recipe to re-create the instance. That is to say, the BackStack contains the type and the parameter. With those two elements, you should be able to re-instantiate the class when the user navigates back to it in the Frame. These ingredients, by the way, include the type and the serializable parameter - only with a serializable parameter can the app save the BackStack to NavigationState and reliably restore it should your application be suspended/terminated.
That's the story, now to your problem. I see several possible solutions, to be honest, and I think any of them are acceptable.
The first caveat is that you MUST use NavigationCacheMode = Enabled. Without this, your page (including the previous page) will be re-created with every navigation, including Back. This is an important behavior of UWP because it assumes your page is removed from memory to save the overall footprint. Setting NavigationCacheMode will override that.
Create a static reference
This is easy enough right? Something like this:
public readonly static MainPage Instance;
public MainPage() {
Instance = this;
}
Beware of this, because it requires your views to have a reference to each other. This is a pretty minimal risk, IMHO.
Pass a reference
This is easiest to accomplish with Navigate(parameter) like this.
// MainPage
public void GoAway() {
this.Frame.Navigate(typeof(SecondPage), this);
}
// SecondPage
MainPage MainPage;
public void OnNavigatedTo(object parameter) {
MainPage = parameter as MainPage;
}
Beware of this because it requires you to pass something that cannot be serialized. Sometimes, though, this is acceptable.
Any of those make sense?
Best of luck.
I'd recommend to create a static class with static properties and methods.. I don't think what you try to achieve is a good practice.. instead, here's my example:
public static class Shared
{
public static string property = "something..";
public static async Task<bool> Method()
{
await Task.Delay(400);
return false;
}
}
Then, you can call the method, get or set the property from any where:
bool result = await Shared.Method();

What options besides using $_SESSION

I am working on a .net project that relies on pulling some information from a database upon login and persisting the information while the person is logged in.
The site is complex, but I feel that overuse of the Session variable may be occurring. I will right now say that I'm using session to store about 5 int values and 3 or 4 string values. I don't have any complex objects stored in it. Every page of my site utilizes these values multiple times, and I feel that posting them each time would be ridiculous. I don't think that viewstate is any better than session at this point either, but i'm open to suggestions.
Example current usage of Session variable
this.Session["vendorCategoryId"]
this.Session["ftp_directory_name"]
this.Session["VendorCodeOptionRefId"]
I thought about implementing a struct in a class and having a set method there that I use from Global.asax.cs in the Session_Start() event might be one solution...
(EDIT: This solution is designed to avoid having to hammer the db every time any piece of code wants to access the variables).
In VendorSessionData.cs class
public struct VendorData
{
public int VendorCategoryId;
public int NKIAccountingCode;
public int OptionCodeRefId;
public string FtpDirName;
}
/// <summary>
/// The set vendor session data.
/// </summary>
public class VendorSessionData
{
#region Public Methods
public static VendorData GetVendorData(Guid vendorGuid)
{
VendorData retVal = new VendorData();
using (NKIDBDataContext db = new NKIDBDataContext())
{
vendorInfo vendorRefs = (from vendorInfo in db.vendorInfos where vendorInfo.guid == vendorGuid.ToString() select vendorInfo).SingleOrDefault();
if (vendorRefs != null)
{
retVal.VendorCategoryId = vendorRefs.category_id;
retVal.NKIAccountingCode = vendorRefs.nki_vendor_id;
retVal.OptionCodeRefId = vendorRefs.option_ref_id;
retVal.FtpDirName = vendorRefs.ftp_directory_name;
}
}
return retVal;
} ......
And in global.asax.cs
public class Global : HttpApplication
{
public static VendorData CurrentVendorData;
public void Session_Start(object sender, EventArgs e)
{
/////////////////FYI tmpVendorGuid is set in code above this point
Guid tmpVendorGuid;
if (Guid.TryParse(vendorGuid, out tmpVendorGuid))
{
CurrentVendorData = VendorSessionData.GetVendorData(tmpVendorGuid);
}
Would it be better to try to attack this using hidden fields on the master page? Every search I've done says "don't use session, don't use globals.." basically any idea I have, there is some page stating its the worst idea ever :)
Any suggestions would be appreciated.
The amount of data isn't particularly surprising, but the choice is.
Normally a session would store user information (typically just their ID - you fetch the rest from the DB). "ftp_directory_name" sounds like a config variable or a per-user setting.
I'm surprised you don't store VendorData in the database with a unique ID and then just fetch the details (you'd need to store the Vendor ID in the session - if that's not the same as the User).
This solution is designed to avoid having to hammer the db every time any piece of code wants to access the variables
This seems like it might be a solution to a problem that doesn't exist - are you seeing problems with access time and are you sure this is the right solution? You're going to have to hit the DB for most pages anyway. One extra query per page load is unlikely to be a problem.
I'd say you're probably already doing it right... Session was designed for storing information for the user's "session"... I don't think you're taxing it too much as if you were storing an entire DataSet or something... A few int variables and a string take up less than 1K of memory... If you had 1,000 users logged in at the same time, their collective "Session" footprint would still be about 1MB... pitons on today's servers.

Using a class once it's properties have been set in c#

i have a small class with just a couple properties in it.
here is an example:
public class clsRepLogs
public string those;
public string these;
public void setThoseandThese
{
//call a stored procedure
//get results
this.those = something;
this.these = somethingElse;
}}
from my first.aspx.cs
i call the set function:
clsRepLogs cLog - new clsRepLogs()
cLog.setThoseandThese()
so now the properties have been assigned values.
i now want to use them in another aspx.cs file to populate a form... but can't figure out how to get to them...
i tried
clsRepLogs cLog;
lblThese.text = cLog.these;
but it's giving me an error: "Use of unassigned local variable 'cLog'
basically, how do i tell it to use the values i've already assigned to that class instance from before?
i hope i'm explaining this right, but i might be way of on what i'm doing. any help appreciated.
It sounds like you want to access the same instance of the class from multiple ASPX pages. There are multiple ways to do this; a per-user solution is to use session state.
// page 1
var c = new clsRepLogs();
c.setThoseAndThese();
Session["mykey"] = c;
// page 2
var c = (clsRepLogs)Session["mykey"];
"mykey" can be any string. You may also want to check if Session contains the value before accessing it, e.g. if( Session["mykey"] != null ){ ... }
Keep in mind:
Session isn't durable; restarting the web worker process will reset all in-process sessions.
It's usually not a good idea to store many large objects in Session.
If the data is confidential, be aware of Session fixation attacks.
Session can be load balanced across servers, so this solution will scale.
For reference (alternative approaches):
You could use the Cache object when you don't care about per-user isolation and want control over data expiration.
You could use the Application object; similar to Cache but no control over expiration.
You could store the object in the database and load it on each page. This is useful when you to don't want a heavy session, and/or wish to save the data more permanently (such as a shopping cart which persists across multiple sessions).
You need to initialize or set cLog to the instance of clsReport that you want.
You aren't instantiating your class. It should be
clsRepLogs cLog = new clsRepLogs();
Or, if I misunderstood your code,
clsReport cLog = new clsReport();
EDIT:
If you need to preserve these, it should be a static class so that it cannot be instantiated.
public static class clsReport
{
public static string those;
public static string these;
public static void setThoseandThese
{
//call a stored procedure
//get results
this.those = something;
this.these = somethingElse;
}
}
A lot of this depends on how you need this to function. In addition, I'm no expert on perpetuating objects/classes in memory in Webforms applications. If you wanted to re-access the class to get those values, I'm not sure they would still be in memory.
You will need to initialize your cLog class :
clsRepLogs cLog = new clsReport();
lblThese.text = cLog.these;

Global Variables vs. ASP.NET Session State

This is probably going to sound rather naive, but I'm developing a web application that spans multiple pages. All of these pages instantiate the same class object w/ methods that accesses a CMS using their API. Currently, when a user starts creating content, I'm storing variables like a folder ID where the content is located in a Session variable.
My question is this: Can I instantiate a single instance of a class that can be used across all pages without having to do it on every page? If so, would each person accessing that page be given their own version of the class? I assume that using static variables and methods isn't the way to go since they are shared in memory. And also, where/how is something declared if it is going to be used globally in a Web Application in a .net C# application?
I recommend making a base class which inherits from System.Page. Then have your page code behind inherit from that.
Then, inside the base class, create a property that is a reference to your object. Like this, for example:
public class BasePage : System.Web.UI.Page
{
public Foo CurrentFoo
{
get
{
return (Foo)Session["FooSessionObject"];
}
set
{
if(Session["FooSessionObject"] == null)
{
// instantiate a new one
Session["FooSessionObject"] = new Foo();
}
Session["FooSessionObject"] = value;
}
}
}
Then, from anywhere in any page, just do a CurrentFoo. and you will have access to any of the properties.
This makes for nice and clean code behind.
You should use Session state if you want to store information that is specific only to the current user.
For example in one page of the application you could store some value into the session:
SomeType someValue = ...
Session["someKey"] = someValue;
and then later on other page retrieve it from the session:
SomeType someValue = (SomeType)Session["someKey"];
The pattern you are looking for is quite easy. There are a couple of ways to accomplish it.
Create an object and store it in session
Create a multi-part form and leave the items in viewstate
Each has its benefits.
Bad thing about doing this and using global over sessions for website is the simple fact that global variables could be accessed by any user accessing the regardless of session. For example take the code below.
public class globals
{
static string _test = "MyTest";
public static string test
{
get
{
return _test;
}
set
{
_test = value;
}
}
After I created the global class I added a label to my default from and assigned the global variable text to the label.
protected void Page_Load(object sender, EventArgs e)
{
globals.test = "Some Data";
}
now you will see this on every form of you page however the down side to this is anyone else that accesses your page will also be able to see this data. If its data that needs to be shared across multiple sessions you could do this. If its data that just needs to be shared by the current user over multiple classes you need to use session variables.

Categories

Resources