Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Custom Class property sharing

Status
Not open for further replies.

tjw2006

Programmer
Nov 16, 2006
103
GB
Ok, so I'm new to object orientated programming - so I've got a custom class which I've created, within this class I've got some Public properties. Now, say I've instantiated that class in my code behind a page and set the values for the properties, how can I reference those values in the code behind a different page without having to instantiate the class? So basically, set the properties once and then share those values throughout the application.

Any help with this would be great.

Thanks
 
you are looking for state in a stateless environment. there are many ways to handle this. the "best" choice depends on the context the data is used.

are the values changing, or do they remain static (at least consistent)?
what does the data represent? (if it's a connection string put it in the web.config and reference it from there)
who needs access to this data (all users, the current user, a group of users)?

these will determine the best way to pass the object. as an example you have the following options:
application bag
cache bag
session bag
query string
form bag
database
custom intermediate service layer

a more general question to ask is? why not instantiate the object on the 2nd page?
if the answer is DRY (don't repeat yourself) then that makes sense. no point duplicating code. You can create another object to build your desired object (Factory pattern).
if the answer is preformance. well, premature optimization is the death of maintainability.
1st get it working
2nd make is readable/maintainable
3rd optimize it

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Well, in essence it's a simple question - is it possible to set a property in a user-defined class and then reference that property's value on other pages within the application? Basically, reference the class without having to instantiate it as a new instance - whereby reseting all it's properties values.
 
the simple answer is yes you can. but there are many things to consider as I listed above. the context in which this information is utilized will determine the best course of action.

that said what is the context of your scenario. beyond passing values from page 1 to page 2.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
ok, since you're a baker take this scenario, a user enter a value in a text field on a form, the value is 'bun', on the click event a class string property called 'TypeOfBakeryProduct' is set to the value of the textbox i.e. 'bun'. The user is then redirected to another page, this page needs to reference the 'TypeOfBakeryProduct' value which was set on the first page - how is this achieved?
 
I wouldn't do it this way. in the onclick I would redirect the user to page2 and pass the typeofbakeryproduct in the querystring. in page 2 I would initialize the class and set the property.
Code:
protected void Button1_Click(object sender, EventArgs e)
{
   var productType = TypeOfBakeryProduct.Text;
   Response.Redirect("page2.aspx?typeOfBakeryProduct="+productType);
}
Code:
protected void Page_Load(object sender, EventArgs e)
{
   var productType = Request.QueryString["typeOfBakeryProduct"];
   var product = new Product
                     {
                         TypeOfBakeryProduct = productType 
                     };
   //do something with product.
}

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Ok, thanks for that, but what if you wanted to get the value of the 'typeofbakeryproduct' property on pages 3 and 4 without exposing the value in a querystring or going to the bother of doing a form request?
 
web is stateless and what your describing is keeping state. this would be dead simple in a windows application (at least I think, I've never built one).
1st I would ask; what's the problem or issue with passing the value around? why do I need to pass the value to so many pages? what are the pitfalls or risks of putting this value in a bag other than form/querystring?

with the information provided so far, I think you are better off passing the value via form/querystring, rather that instantiating the object once and keeping state between requests.

you *could* put the value into Session. but then you have to deal with the problem of managing the Session between all the pages that may use the value. this could be abstracted behind another object, but then you have the issue of whether this type of information belong in Session.
the hammer and nail analogy... I have a hammer (Session bag) and everything looks like a nail (data between requests).

the only time I access session directly is when I'm designing multiple pages to act as a user wizard. but even then i can reduce the usage of Session to zero using ajax and a few other client scripts.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
So then what's the point of having classes if their properties can't be shared across an asp.net application? You might as well just use variables on each page.
 
For your seniero, instantiate the class where it is best suited(on the first page?). Get all your values from user input, set the properties on the object, then set the object in a session variable since you want to access the object and properties on subsequent pages. When you want to access the object and properties cast the session variable to the object type.
 
the objects are shared across the context (request/response). between request/response is just string dictionaries. that's the nature of web at some level the objects are (de)serialized to text (or byte[] arrays).

here is another way to think of it. treat eaach request/response pair as an atomic unit of work. it starts with receiving the request. which is really a glorified dictionary of string keys with string values. you can do whatever you want within this unit of work. it commonly envolves hydrating values from strings into an object. database calls, logic, changes to the objects from the database, saving changes to the database, and finally sending a response back to the client. the response is text or byte[].

between sending the response and getting the next request you have:
application state
cache
session
there is very little you need to put into these containers, each has it's own behavior which you need to consider when storing information in it.

1. application state is shared by everyone. and is alive for the duration from the very 1st response to ~20 minutes after the very last response.
2. cache is shared by everyone, but will purge itself of data when thresholds are met (the thresholds are configurable)
3. session is specific to the user for the duration of the current set of requests. by default it expires after 20 minutes of no activity, or when Session.Logout is called. I think that's the name of it.

when you begin to store modified values in these containers the unit of work (current context) can get nasty side effects and bugs become more difficult to track down.

jbenson, yes he could stuff this into session and get the object, but that is the hammer and nail analogy. "any time i need an object I'll stuff it into session".

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Thanks jbenson, it's a way of sharing the object - it would be nice if you could declare a class as public and once instantiated it could be referenced throughout the application, but if it requires to be in a session - so be it.
 
it would be nice if you could declare a class as public and once instantiated it could be referenced throughout the application, but if it requires to be in a session - so be it.
As Jason has explained, a web is stateless, unlike a windows application. If you wrote this as a windows application, you would simply instantiate the object once, and it would be accessable to all windows in the app. However, this is not the case with a web application. If you want it to would the way a windows app would, then you have to store that ojbect somewhere that persists, ie. session, viewstate, cache, application object, all dependent on what you need.
 
jbenson, yes he could stuff this into session and get the object, but that is the hammer and nail analogy. "any time i need an object I'll stuff it into session".
Well if you have numerous values that need to be persisted, then using the querysting is not an option, since it does have a limit. Also, someone may not want to expose what is being passed, or rather not encrypt the querystring. A user object would logically encapsulate items that need to be grouped.
 
Ok, don't know much about cache or application objects, but it sounds like sticking the class into a session will probably suit my purposes - still don't really see the point of user-defined classes in asp.net if their scope is limited to just a page though.
 
still don't really see the point of user-defined classes in asp.net if their scope is limited to just a page though.
It has nothing to do with ASP.NET, it is any web programming language. You should first understand how web programming works, as Jason has suggested. Although the web is stateless, you can still code using OOP principals.
 
still don't really see the point of user-defined classes in asp.net if their scope is limited to just a page though.
Exactly! asp.net is about servicing web requests. a web request is just a bag of strings. the objects come into play when performing you logic. And you logic should be independent of how a client interacts with it. the logic (domain) could be accessible from a website, desktop application, console, windows service, or RESTful web request. in all of these situations the domain doesn't change, only how to access the domain.

asp.net is good for 1 thing - responding to requests
webforms is good for 1 thing - rendering html

neither of these frameworks deal with business logic. that is left to the developer. that is where your objects come into play.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top