• 0

Global code and functions in ASP.net


Question

I'm designing a site in ASP.NET C#. I'm used to programming in Classic ASP (Javascript) but .NET is somewhat different.

In Classic ASP I used to have an include file with all my global functions defined in it. I would then use the "include file=" tag to include that global file in all of my ASP pages. That way I never had to re-write code, I had a single file containing all the common code that I used.

Basicly I want to do the same thing in ASP.net, but I cant quite figure out how to do it. At the moment my basic site structure has a ASPX file with markup only in it, then I have a seperate code behind file for each ASPX page.

Is there any way that I can have a group of global functions defined in a file that can also be included in all my pages like I did in Classic ASP?

For example I'd like:

* an ASPX file with HTML and ASP markup tags and Layout

* a custom code behind file for each individual ASPX file

* a global code behind file which contains commonly used functions and variables

Of course if there is a better way of achieveing my aim I'm definatley open to suggestions.

Thanks in advance for any help! :)

Link to comment
https://www.neowin.net/forum/topic/143945-global-code-and-functions-in-aspnet/
Share on other sites

13 answers to this question

Recommended Posts

  • 0

This is how I do things in VB.

<%@ Page Language="VB" SRC="/inc/Global.vb" ContentType="text/html" %>

But that eliminates your individual CodeBehind I guess...

so why now just do:

<%@ Page Language="VB" SRC="/inc/INDIVIDUAL CODEBEHIND.vb" ContentType="text/html" %>
<!--#include virtual="/inc/global.aspx" -->

and have global.aspx:

<script runat="server" language="VB">

Sub thisFunctionOwns(AndIsGlobal as Boolean) as String

End Sub
</script>

vb of course.

However, depending on the size of the site, you could do one global code behind.

  • 0

Thanks Original_, another question, I have managed to create a global.asax file, with a global.asax.cs code behind file.

This is the basic layout of my "global.asax.cs" file:

using System;
using blah-blah;

public class Global : System.Web.HttpApplication {

    public void Session_Start (object Sender, EventArgs e) {

        // CODE IN HERE

    }

    public string SomeLeetThing () {

        // CODE IN HERE
        return "whatever";

    }

}

On my pages I am referencing the SomeLeetThing function as:

string GoodString = Global.SomeLeetThing()

But I always get the following compilation error:

  Quote
Compiler Error Message: CS0246: The type or namespace name 'Global' could not be found (are you missing a using directive or an assembly reference?)

I've tried a lot of variations, none work, so just wondering, do you know how to reference Global objects in C# (but I will also take VB)

Thanks

  • 0

how about object orientated programing.


(common.aspx.cs)

---------------------------

namespace Whatever

{

public class common

{

//your code here

}

}

(test.aspx.cs)

-----------------------------------

namespace Whatever

{

Whatever.common cm;

public class test

{

public test()

{

cm = new common();

}

}

}

  • 0

Thanks rundkaas,

Basicly what you have explained above is how to access functions from the common.aspx.cs from within the text.aspx.cs file (by setting up a common object). But what you havent explained (or what i think you havent explained) is how to initially import the file common.aspx into the test.aspx.cs file so that I can set up the common.aspx.cs object.

EXAMPLE:

Lets just say I have the following 3 files in my site:

test.aspx <- the file with all the markup in it

test.aspx.cs <- C# code designed specificly for the test.aspx page

common.aspx.cs <- Global C# code with functions and values that I can use throughout the whole site.

I want to use the above 3 files together, so I can access the code from common.aspx.cs in my test.aspx.cs file.

What code do I need to use to initally get access to the common.aspx.cs file from within the test.aspx.cs file?

Thanks,

I REALLY appreciate the help, but would you mind clarifying what you wrote above? :)

  • 0

I'm not sure what you want, but I just call the needed functions from in this case test.aspx.cs,

but if I get you correct you want the code to work like it's in the file physicaly?

If that is the case then I don't realy have an answer, but I know you could use another class as page, or better to use the global file as an interface.

These are just sugestions, and I'm still not sure I got what you wanted, but a combination of the before mention tricks should do it.

  • 0

In reference to your common/include page that you had before.

You could create a class that handles all your common code that you were talking about. Then in each page, you can inherit that class, which would give you the functionality of the common class.

You didn't specify whether your include file was a clientside or server side include file. But with this class inheritance it would be doing the server side functionality

  • 0

In reference to your global question.

It sounds like you may be missing a reference to global in your pages. I'm not sure why you would be doing this though. I'm pretty sure the global is run only once, when the application first starts. I would recommend putting that functionality elsewhere, get it out of the global file.

  • 0

(common.aspx.cs)
---------------------------
namespace Whatever
{
public class common
{
//your code here
}

}

(test.aspx.cs)
-----------------------------------
namespace Whatever
{
 Whatever.common cm;
 public class test
  {
   public test()
   {
   cm = new common();
   }
  }
}

In the above example it is showing how to create an object inside the text.aspx.cs file which represents the class "Whatever.common", that namespace and class exists in the common.aspx.cs file.

Thats fine, I understand that bit, but when I recreate somthing similar to the above example on my site I get an error saying the namespace/class "Whatever.common" doesnt exist.

I assume this is because there is no reference to the common.aspx.cs file inside the text.aspx.cs file, hence it cant find the "Whatever.common" namespace/class.

So my question is, how do I tell the file text.aspx.cs that the namespace/class "Whatever.common" is inside the common.aspx.cs file?

(Basicly you guys are showing step 2, which is accessing my global code, but your not telling me step 1 which is how to get access to my global code file in the first place).

Again, I really appreciate they help, but as you can see I'm having trouble getting the message across about what I need to know (which is prolly my fault)

  • 0
  Jelly2003 said:
This is the basic layout of my "global.asax.cs" file:

using System;
using blah-blah;

public class Global : System.Web.HttpApplication {

    public void Session_Start (object Sender, EventArgs e) {

        // CODE IN HERE

    }

    public string SomeLeetThing () {

        // CODE IN HERE
        return "whatever";

    }

}

On my pages I am referencing the SomeLeetThing function as:

string GoodString = Global.SomeLeetThing()

But I always get the following compilation error:

I've tried a lot of variations, none work, so just wondering, do you know how to reference Global objects in C# (but I will also take VB)

Thanks

Make the method, SomeLeetThing, static. Then you can refer to it with the Global.SomeLeetThing() syntax.

Or, you could add a reference to the current application to the Session state OnSessionStart.

public class Global : System.Web.HttpApplication
	{
  /// &lt;summary&gt;
  /// Required designer variable.
  /// &lt;/summary&gt;
  private System.ComponentModel.IContainer components = null;

  public Global()
  {
 	 InitializeComponent();
  }	
  
  protected void Application_Start(Object sender, EventArgs e)
  {
            
  }

  protected void Session_Start(Object sender, EventArgs e)
  {
                     this.Session.Add( "GlobalRef", this );
  }
            // ... other events	and the SomeLeetThing method definition.
	}

You can access the reference and use it like so:

 private void Page_Load(object sender, System.EventArgs e)
  {
 	 // Put user code to initialize the page here
 	 Global app = (Global)Session["GlobalRef"];
 	 Response.Write( app.SomeLeetThing () );
  }

You should also clear the session state collection on session end

  • 0

Test.aspx:

&lt;%@ Page language="c#" Codebehind="test.aspx.cs" AutoEventWireup="false" Inherits="whatever.test"%>

I have to point it out that I', using Visual Studio, and that compilles it to a dll,

and I hope you got application right for the directory you are working in

  • 0

Thats probably the answer! VS.NET is probably compiling and putting the resulting DLL inside the /bin/ folder, so all you need to do is create an object to represent that DLL file!

I'm using Dreamweaver which doesn't auto compile, I just let it all compile on first run of my application (like when i type in "http://localhost/my_leet_application/").

I suppose I shall have to learn how to use CSC to compile my global code b4 running my web application.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Rustdesk. https://rustdesk.com/ You can even set up your own relay server (if you desire).
    • ICYMI: 4TB Corsair MP700 PRO SE SSD is still selling at its lowest price by Fiza Ali Amazon US and Newegg are still offering the 4TB Corsair MP700 PRO SE solid-state drive at its new lowest price. The MP700 PRO SE is an M.2 2280 SSD that employs a PCIe 5.0 ×4 interface with NVMe 2.0, delivering sequential read speeds of up to 14,000MB/s and sequential write speeds of up to 12,000MB/s. It uses high-density 3D TLC NAND and carries a Total Bytes Written (TBW) rating of 3000. Furthermore, the drive can withstand vibration from 20Hz to 80Hz at 1.52mm and 80Hz to 2000Hz at 20G, as well as shocks up to 1500G. The drive incorporates AES 256-bit encryption and supports Microsoft DirectStorage, allowing compatible games to load assets directly to the GPU for reduced load times. Moreover, it operates within a temperature range of 0°C to +70°C, and can be stored between –40°C and +85°C at up to 93% relative humidity (40 °C). A heatsink is not included, so users must provide their own or rely on a motherboard’s integrated SSD cooling solution to maintain optimal thermals. Finally, the MP700 PRO SE is compatible with Windows 10, Windows 11, and macOS systems that provide an M.2 slot, and communicates via a standard M.2 2280 interface connector. 4TB Corsair MP700 PRO SE SSD: $549.99 (Amazon US) 12% off - $549.99 (Newegg) 9% off This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. You can also check out other SSD deals here. For hard disk drives, you can head over to our HDD deals section to see if anything from there matches your requirements. Make sure you also browse through Amazon US, Amazon UK, and Newegg US to find some other great tech deals. As an Amazon Associate, we earn from qualifying purchases.
    • "requiring individual licences from all rights-holders would impose an unmanageable administrative burden and could deter AI investment in the UK." Ah so plebs (humans) will forever be required to secure license, but AI should get a broad pass because it's too complicated. Not so "intelligent" after all? Plus, every opt out I have signed regarding Meta using my data was never presented to me in a clear way, I had to discover it here on neowin or some other news site with a link to do it. So what the government is saying is that they prefer to offer an opt out just to cover their asses, but good luck us plebs finding such a thing!
    • The look speaks volumes, doesn't it?  
  • Recent Achievements

    • First Post
      ClarkB earned a badge
      First Post
    • Week One Done
      Epaminombas earned a badge
      Week One Done
    • Week One Done
      Prestige Podiatry Care earned a badge
      Week One Done
    • Week One Done
      rollconults earned a badge
      Week One Done
    • Week One Done
      lilred1938 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      136
    2. 2
      Xenon
      129
    3. 3
      ATLien_0
      123
    4. 4
      +Edouard
      102
    5. 5
      snowy owl
      96
  • Tell a friend

    Love Neowin? Tell a friend!