Saturday, March 31, 2012

Where do I put a function I can call from any page?

I have a function I wrote for use on a page.


I now have a need to use that function on many pages, but I don't want to duplicate the same code on each page.


My question is twofold, where should I store the function and how do I call it from different pages?

You can create a class and inside it create a static method which can be accessed in all webforms.

Suppose you have a class called Class1 and a method inside this class called Method1, you do the below

Class1.Method1()

HC


Chris,

To share functionality in your application, create a class within your web project. You can do this Visual Studio or Visual Web Designer by right-clicking on the project in the solution explorer and choosing "Add Item". You will then be prompted to choose the type of item to add. Choose a "Class", give the class a name, and add it to your project.

Within your class, create a static method. In C# this is done by the marking the function "static". In VB this is done by marking the function "Shared". I'll provide a simple example in VB below:

Class ClassForChrisPublic Shared Function HelloWorld(userNameAs String)As String Return"Hello, " + userName +"!"End End Class

This method can be called from any page by calling: ClassForChris.HelloWorld("Chris")


Hope this helps,

pk


I'm a fan of the BasePage approach. I like to create a base page that has common functionality for all subpages (as well as things like SQL connection string and variables). Here's an idea of how to do it:

public class BasePage : Page{protected String connStr ="[connection string]";//other commonly shared variablesprotected virtual void Page_Load(object sender, System.EventArgs e) {//do some stuff that all pages need to do, like check user's session variables... }protected void CommonFunction() {//Common Function stuff }}public class ChildPage : BasePage{protected override void Page_Load(object sender, System.EventArgs e) {base.Page_Load(sender, e);//do some stuff specific to this page CommonFunction();//You can access "CommonFunction()" because you inherited it from BasePage }}

After I figured that out, it took me a few minutes to figure out how to "include" the parent...do it in your compilation script:

csc /out:basepage.dll /r:System.dll,System.Web.dll,System.Data.dll /t:library basepage.cscsc /out:childpage.dll /r:System.dll,System.Web.dll,System.Data.dll,basepage.dll /t:library childpage.cs

That worked great.

Thanks a lot.

Chris

0 comments:

Post a Comment