This is due to some very long standing scoping issues.
Place your code in a function in a script module and then call that script from the Gateway Event.