Results 1 to 14 of 14

Thread: [RESOLVED] Classes and instances in ASP.Net

  1. #1

    Thread Starter
    Frenzied Member FishGuy's Avatar
    Join Date
    Mar 2005
    Location
    Bradford UK
    Posts
    1,708

    Resolved [RESOLVED] Classes and instances in ASP.Net

    Bit of a dummy couple of questions but im going to ask anyway.

    If I have a class (well collection class of class objects) and they are instanciated by calling a DAL class which is instanciated on a page load event.

    this works so far as I can bind a gridview to the collection.

    When I do a postback I cannot seem to access the collection again i.e. when I use the selected index change event of the gridview I am wanting to lookup the selected item in the collection and return its object value.

    Is this impossible or am I doing something wrong?

    Second question if I select an object in the collection, is there a way to reference that object on another page or if not pass the object to another page?

    Code:
    public partial class Outlines_usercontrols_CourseOutlines : System.Web.UI.UserControl
    {
        DAL_Outlines DALOutlines;
        string code;
        int OutlineID;
    
        public string Code
        {
            get { return code; }
            set { code = value; }
        }
        public int selectedOutline
        {
            get { return OutlineID; }
            set { OutlineID = value; }
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack == false)
            {
    
                if (Page.PreviousPage != null && Page.PreviousPage.IsCrossPagePostBack)
                {
                    DALOutlines = new DAL_Outlines();
                    DALOutlines.Fill_Outlines();
                   
                    ContentPlaceHolder BodyContent = (ContentPlaceHolder)Page.PreviousPage.Master.FindControl("maincontent");
                    ASP.usercontrols_courses_ascx test = (ASP.usercontrols_courses_ascx)BodyContent.FindControl("Courses1");
                    code = test.Code;
                    this.lblCode.Text = code;
                    
                    this.GridView1.DataSource = DALOutlines.myOutlinesCollection;
                    this.GridView1.DataBind();
    
                    this.FreeTextBox1.Text = DALOutlines.myOutlinesCollection.Item(0).Overview;
                    
                   
                }
    
                else
                {
                    this.lblCode.Text = "Code Not Found";
                }
            }
        }
    
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataKey key;
            key = this.GridView1.SelectedDataKey;
            selectedOutline = (int)key.Value;
            this.FreeTextBox1.Text = DALOutlines.myOutlinesCollection.Item(selectedOutline).Overview;
        }
    }

  2. #2
    King of sapila
    Join Date
    Oct 2006
    Location
    Greece
    Posts
    6,763

    Re: Classes and instances in ASP.Net

    I don't think you can maintain your values automatically.
    This is not winforms, you must somehow keep the values stored someplace.
    For DAL i cannot advice, haven't used it in asp.net.
    ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
    πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·

  3. #3
    Frenzied Member brin351's Avatar
    Join Date
    Mar 2007
    Location
    Land Down Under
    Posts
    1,293

    Re: Classes and instances in ASP.Net

    The web is referred to as "stateless" and "disconnected". Meaning once the server finishes processing your code and sends it to the browser nothing is retaind in memory, everything is distroyed. So When the same browser makes subsequent requests the server treats it like the first. This makes sence when you imagine servers holding connections open, and resurving memory for all clients (browsers).

    IIS and asp.net bridge this gap in several ways.

    1. Sessions - unless turned off in IIS all clients are given a unique session ID and a cookie placed on them. Sessions are unique to each user, last for the life of the browser being open or untill timeout and are secure. You can add extra values to a users session but this should be limited to small key/values not data/objects.

    2.viewstate - asp.net adds a hiddeen form field to all pages to persist control values accross postbacks ,some controls require it to wire up events on the server. It's user and page specific and you can add values, objects etc to it. It's encrypted but not secure, controls like girdview can make it very large and slow down postbacks so you need to be mindful of this.

    3. cache - stores pages, userControls, objects etc in the cache object. These are held in memory until they expire or are distroyed and are not user specific. So commonly used objects etc that may use considerable resources to create can be cached and serverd from memory.

    asp.net, and IIS are designed to create and distroy objects, DB connections efficiently. don't be affraid to recreate them every request and just pass refrence/key data about what needs to be done.

    You can pass info between pages using the URL queryString, set a button to postback to another page or use server.transfer to another page.

    Hope that helps
    The problem with computers is their nature is pure logic. Just once I'd like my computer to do something deluded.

  4. #4
    PowerPoster motil's Avatar
    Join Date
    Apr 2009
    Location
    Tel Aviv, Israel
    Posts
    2,143

    Re: Classes and instances in ASP.Net

    I just want to add some clarification to what brin351 said, while most of it is true there are couple of things I should mention:

    1) Session are indeed secure but not bullet proof, there is the concept of "Session Hijacking" which the attacker use the session_id cookie to try and get control of other users sessions -> information, while its not an easy task, it still can be accomplish by ingenious attacker.

    if you use SSL then sessions become highly secure and eliminated the possibility for Session Hijacking.

    2) Sessions can hold any serializable .NET data types, that of course includes objects.
    and the word "small" is very relative here, don't start store tables or thousands of objects for each users but as long as you have modern server you can store considerable amount of data for each user. though I never used it but I Believe that the built-in ASP.NET membership provider save user roles with session, I know that I created my own mechanism that holds users preference into class -> session while they're on our company site its contains about 30+ (and growing) properties which contain data (I tried to use byte as much as I can but I also use decimal, string etc...) so far even with 4000 - 6000 users online this only takes as about 100MB to 150MB of memory in our case we have 8G of memory on our server but even if we had 4G it was still not problem.. so don't be too afraid to use session.

    I'm happy to pay 150MB of our server memory in return to the thousands database access we are saving each day.

    last thing, there also applications which just as cache you can store global data in it
    Last edited by motil; Feb 12th, 2011 at 07:12 AM.
    * Rate It If you Like it

    __________________________________________________________________________________________

    "Programming is like sex: one mistake and you’re providing support for a lifetime."

    Get last SQL insert ID

  5. #5

    Thread Starter
    Frenzied Member FishGuy's Avatar
    Join Date
    Mar 2005
    Location
    Bradford UK
    Posts
    1,708

    Re: Classes and instances in ASP.Net

    But if I used a dataset i would only fill it once on page load right and not on every postback, however because I want to fill an object collection instead of a dataset this is not persisted between postbacks unless I manually store them in session variables?

  6. #6
    Hyperactive Member
    Join Date
    Jun 2008
    Posts
    407

    Re: Classes and instances in ASP.Net

    The best way describe web programming is client/server.

    Client code is run when the page doesn't have to call the server. Mostly javascript. So if you are able to click on a button and it changes color or something and the page doesn't reload that's client code. The server has no idea that the button caused something to happen. HTML controls are client code. Client code will get wiped when a call to the server is made.

    Server code is run when postback occurs. This stuff is in the .vb file. These controls have runat=server in the aspx file. These controls also retain their state when postback occurs. If you have a textbox that has "hello" then it will keep that until it is changed.

    There's ways to deal make it look like the page is continuous. One of the ways is to use a hidden field. You could write up a javascript function to find the client control then set the hidden field to that value. So when the server gets called now you have that value on the server.

    In your case the best thing to do is to create a control that runs on the server. Then you'll be able to see all the values. Dropdown menu's and listboxes are server controlled.
    My Websites
    SharpMP3 - MP3 Design Articles www.sharpmp3.com
    Yobbers - Job Search www.yobbers.com
    Lets Trend - Methods For Riding Stock Trends www.letstrend.com

  7. #7

    Thread Starter
    Frenzied Member FishGuy's Avatar
    Join Date
    Mar 2005
    Location
    Bradford UK
    Posts
    1,708

    Re: Classes and instances in ASP.Net

    I have a server control is an asp.net grid view runat server.
    It is bound to a collection of objects, each object has many properties but only 2 of which are displayed in the grid.

    When a user is selecting a row in the grid I am wanting to display the rest of the information by retrieving it from the object collection. Except when I try to do so the collection is null.

  8. #8
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Classes and instances in ASP.Net

    you're making the same mistake I made when I first started doing a little bit of web dev and experimenting with the postback feature.

    With that understanding, let me see if I can break it down for you ...

    A page is requested... the data is retrieved, bound to a grid, various properties is set, including an automaticpostback when something is selected. So far so good, ASP.NET assembles all this, generates the appropriate HTML and JAvascript, and sends it out to the browser, where it gets rendered. At this point, the server is done with its processing. That means, everything is lost... including your datatable.

    Seriously.

    It doesn't magically remain in memory. Even though your gris set to RunAt=Server doesn't mean it actually runs on the server. What it does behind the scenes is generates Javascript code that when the action happens invokes ala AJAX a method call to the server, which results in your event handler for the grid being called. It's all stuff you can actually wire up yourself if so inclined. It's just that the ASP.NET controls make it a bit easier.

    But the thing to remember is when those calls are made back to the server, the server objects you created when the page was rendered, do NOT exist any more. You have to re-build it. suxors I know, but that's the reality of it. Unless you persist the data somehow, you'll need to get it again from the database... I guess either way, you need to somehow retrieve the data before you can try to deal with it again.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  9. #9
    Frenzied Member brin351's Avatar
    Join Date
    Mar 2007
    Location
    Land Down Under
    Posts
    1,293

    Re: Classes and instances in ASP.Net

    So.... knowing that objects are not presisted between requests or postbacks there is a choice.
    1. recreate the objects each requset
    2. store the objects on the client or server.

    the firist is the most common, just recreate the objects each request. The second is normally only used under certain conditions, mainly when server performance is the priority. For example the data/objects require considerable server resources to create and the page that uses them is heaverly trafficed, 100's or 1000's of concurrent users.

    If you store objects/data in server memory for every page and every user you will place a user/memory limit on the website after which it will crash. Storeing data/objects on the client in viewstate slow down the postbacks because that info has to be sent along with the postback request to the server.

    General rule of thumb. Do not use viewstate, turn it off on the page or controls unless it's needed and if needed keep it as small as possible. Only use session for small amounts of data (like a username), a cookie is placed on the client to identify the browser to the session but the objects are stored in server memory. If server resources/performance is not an issue (low traffic) there is no need to persist data/objects accross postbacks just recreate them.

    Hope that helps
    The problem with computers is their nature is pure logic. Just once I'd like my computer to do something deluded.

  10. #10
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: Classes and instances in ASP.Net

    Quote Originally Posted by FishGuy View Post
    I have a server control is an asp.net grid view runat server.
    It is bound to a collection of objects, each object has many properties but only 2 of which are displayed in the grid.

    When a user is selecting a row in the grid I am wanting to display the rest of the information by retrieving it from the object collection. Except when I try to do so the collection is null.
    The point that should be made here also is that you should only pull back the information from the database that you actually need to display, at that point in time. What is the point in pulling back 10000 rows, with 100 columns of data, if you are only displaying 5 rows, with two columns of data.

    There is nothing to stop you later retrieving some information, based on a row in the GridView, and then caching that information somewhere for later use.

    Gary

  11. #11
    PowerPoster motil's Avatar
    Join Date
    Apr 2009
    Location
    Tel Aviv, Israel
    Posts
    2,143

    Re: Classes and instances in ASP.Net

    Quote Originally Posted by brin351 View Post
    .. Only use session for small amounts of data (like a username)
    this is true only if the year now is 1995 and you run your server on 486AT with 128RAM ...

    stop living in the past and quote what you've read 10-16 years ago.
    * Rate It If you Like it

    __________________________________________________________________________________________

    "Programming is like sex: one mistake and you’re providing support for a lifetime."

    Get last SQL insert ID

  12. #12
    Frenzied Member brin351's Avatar
    Join Date
    Mar 2007
    Location
    Land Down Under
    Posts
    1,293

    Re: Classes and instances in ASP.Net

    Quote Originally Posted by motil View Post
    this is true only if the year now is 1995 and you run your server on 486AT with 128RAM ...

    stop living in the past and quote what you've read 10-16 years ago.
    Ouch.

    I stand by what I said about session usage as a general rule of thumb because you need an indepth understanding of the state management process and hosting server limits before you commit large amounts of data to state. It's not easy to measure how much resources state is using so it's important to be aware that heavy use of state impacts on performance and places a limit on how many users can be on a website at one time. The time you become aware state is overused is when the website goes down. Most websites are on shared hosting for affordability and 100 users can consume considerable resources let alone a 1000.

    Hear is what MSDN are currently recommending regarding state management.

    http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx
    The problem with computers is their nature is pure logic. Just once I'd like my computer to do something deluded.

  13. #13
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Classes and instances in ASP.Net

    I'm not a huge fan of the ViewState either... like a lot of other things, it's easily abused and can result in a LOT of data being passed back and forth between the client and server...the ViewState data is transmitted on every single one-way trip... so if you have 10k worth of data in your viewstate, you just sent 20k worth of data round trip and that doesn't include any other information of the page, such as session, headers, cookies, the actual HTML itself, images, css, and so on... it's handy and useful for small bits of data... but you need to be careful with the data management.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  14. #14
    PowerPoster motil's Avatar
    Join Date
    Apr 2009
    Location
    Tel Aviv, Israel
    Posts
    2,143

    Re: Classes and instances in ASP.Net

    Hi

    @Brin351:
    I'm not saying you can abuse sessions, even when you have your own server with good hardware, of course that you still need to know what you're doing, calculate the amount of memory your sessions will consume (as much as you can) this is what I did and it's working much better then my expectations.

    and here is a quote from microsoft article that you posted above:

    Code:
    Session-state variables that contain blocks of information, such as large datasets, can adversely affect Web-server performance as server load increases
    just as I wrote earlier, do NOT save large tables or data in sessions but general information such as user preference and other basic data which otherwise you'll have to connect to your database almost in every page you should save in sessions or the built in ASP.NET feature member profile (which I didn't had the chance to use yet)

    @techgnome
    you aware that we're talking about sessions and not viewstate right?

    I dislike the ASP.NET viewstate feature as well and very rarely you'll find it not disabled in my web projects pages.
    * Rate It If you Like it

    __________________________________________________________________________________________

    "Programming is like sex: one mistake and you’re providing support for a lifetime."

    Get last SQL insert ID

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width