Threads and session properties

I have created a thread on a web page but whenever I try and access a property in the session it gives me a nil object error. The pAffiliateProfile is set to Global and is defined in a Module.

Session.pAffiliateProfile.ClientSortOrder

“Session” can be confusing because it’s both a class and a function to return the instance of the Session class associated with the currently executing event.

Only events for objects which exist on the client browser have an associated Session instance. Since Threads exist entirely server side, even if they’re on a page in the IDE, there is no Session instance associated with Thread.Run and the Session function will return Nil.

For a Thread that is dragged to a WebPage you can reference the page using Self. From there you can get the Session instance for the page and setup a WebSessionContext so that the Session function works.

Try the code below in the Run event of a Thread on a WebPage.

  Dim objTest As WebSession = Session
  Break 'At this point objTest should be Nil.
  
  'This could be one line, I just like to code in discrete steps.
  Dim objSession As WebSession = App.SessionForControl(Self)
  Dim objContext As New WebSessionContext(objSession)
  
  objTest = Session
  Break 'At this point the Session function should work and objTest should have the Session for the page.

Thanks Daniel, I think that makes sense but it as it is almost midnight here in the UK and I have been coding in Xojo all day my head is totally mashed and I am going to re-read what you have said in the morning. Am I right in thinking that I could also have properties on the page that I preload in the page open event to contain the session variables I want to access in the thread but use the page properties instead as I only need to read them in the thread itself?

Yes, you could do that. Seems like a lot of work though since two lines gives you access to the Session properties in Thread.Run.

Yes you are right, see I said it was late :wink: I understand the reason just need to go and read up on the sessionforcontrol and websessioncontext as these are new to me. Also would I then use objTest instead of session when referencing the session variables I need to access?

If you don’t care about making the Session function work in Thread.Run, you could just use one line:

Dim objSession As WebSession = App.SessionForControl(Self)

And call objSession.myProperty in the rest of Thread.Run.

Regarding Daniel’s code, I would use Session for the class name instead of WebSession. WebSession is the framework generic, Session is your project’s specific subclass. It will allow you access to properties and whatever else you have on your Session class.

Good catch. Not sure what I was thinking using WebSession for the class name.

Well Sessions are bizarre objects, it is easy to get mixed up.