Tuesday, July 12, 2005

VB.Net Modules in ASP.NET - Trick or Treat in July

Here is the story of a feature in VB.Net that is at the same time very useful and potentially very dangerous.

Microsoft carried the construct of a Module forward from Visual Basic 6 into VB.Net (reluctantly as I understand it). A popular feature among VB6 programmers, it can be viewed as a global class available to all other forms and classes. VB6 programmers commonly used it to hold global variables and methods that would be needed by multiple forms. No instantiation needed, it was just there and global. Very convenient.

VB6 was used primarily to write single-user desktop windows applications. Yes, with the proper level of skill and prayer it could be used for more advanced purposes, but it truly shined as a way to quickly deliver high-quality desktop applications. In a single user environment, a shared global module is not a problem. Use of a module in a single user VB.Net application is still not a problem for the same reason.

Now consider the impact of a module in an ASP.Net application running on a IIS web server. Herein lies the power and the danger.

First the danger. Like before, a module is a class that automatically global to the entire application without requiring any instantiation. But now that single application is being used simultaneously by potentially hundreds or thousands of users. See the problem yet? Any variable declared at the module level is single-instance shared global among all users. If you casually define a module level variable of 'UserName' and base your security permissions on that, you will experience tremendous security issues as incoming users take on whatever security permissions were enabled by the last client that set the 'UserName' variable. Ouch!

Now the power. Modules are a great way to share single-instance methods for very efficient memory usage in VB.Net web applications. Only one copy of each module method is loaded in memory for all users of the application. As long as each of these modules are designed with shared usage in mind and do not depend on any static variables or try to maintain state across calls, this can be a very powerful and efficient design strategy.

Conclusion: In VB.Net web applications, use module level variables with great care, or not at all if possible. Use module methods with care to ensure that they can be safely shared.

I hope you find this information helpful. I wish I had known it earlier and saved myself some grief. Your comments are welcome.

Disclaimer: This post is based on some painful lessons learned from personal experience and not the result the detailed research on the topic. All of the statements in this post are correct to the best of my knowledge but please verify any use of this information with sufficient testing in your particular environment.

Joe Kunk

No comments: