C# and ASP.net - code reuse

Torro

Member
Aug 14, 2002
163
0
0
How do i reuse code in multiple code behind pages?
I wrote some code to protect my guestbook from script fiends (so it checks and fixes various scripting hacking techniques)
i now want to use the same piece of code in other places but re-using the same code so as i become more familiar with scripting techniques i can just update that 1 piece of code
 

Torro

Member
Aug 14, 2002
163
0
0
never mind
i realized i could do place the code in a aspx file and include it as such:


function.aspx
*******
<script language="C#" runat="server">
public string function(DateTime x)
{
//function in here
}
</script>
********
file.aspx
*********
html
......
<!-- include virtual=function.aspx -->
</html>
 

Torro

Member
Aug 14, 2002
163
0
0
ok, so the method i mentioned above apparently only works when i call the code from the html file
if i call it from the code behind file, it can't compile (throws an error)
how do i 'include' code snippets to be used in the code behind file?
 

Gaunt

Senior member
Aug 29, 2001
450
0
0
Alright, this assumes you're using Visual Studio.NET, but should give you some info either way.

One way you can do this is to put your script checking code into a new class. Add a new class to the project you're working on, and call it whatever you like. Add your script checking code as a static method to this new class.

In your "code behind" file, just call the static method you created, such as NewClass.ScriptAttackChecker(parameters) and there you have it.

To reuse the code, simple use the class in whatever other projects you'd like.

You can also create a new project to hold the class you create and make it a seperate .NET assembly, which makes it even easier to move between projects since you can keep one copy of the class in a single place, and just have the projects that use it reference it. Whenever you need to make a change to your script checking routines, you only need to change one class.