• 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

    • That's wonderful. A shame that a few fringe nutjobs will somehow concoct a story to make this something nefarious. I do wish he'd committed to using more of the foundation's funds for scientific/medical research here at home, though. It looks like the U.S. is suddenly poised to become a backwoods nation in research.
    • Scientists explain how water could have actually made Mars the red planet it is today by Sayan Sen For centuries, scientists have wondered why Mars is red. The long-standing theory was that the planet’s rusty color came from hematite, an iron-rich mineral formed in dry conditions. But new research suggests something else might be responsible: ferrihydrite, an iron oxide-hydroxide mineral that forms in wet environments. A study published in Nature Communications by researchers from Brown University and the University of Bern suggests that ferrihydrite (Fe5O8H · nH2O) is the dominant iron-containing mineral in Martian dust. Their findings—based on orbital observations, rover data, and lab experiments—challenge previous ideas about Mars' surface composition. “The fundamental question of why Mars is red has been thought of for hundreds if not thousands of years,” said Adomas Valantinas, a postdoctoral fellow at Brown University. “From our analysis, we believe ferrihydrite is everywhere in the dust and also probably in the rock formations, as well.” Ferrihydrite is formed when iron reacts with oxygen and water. On Earth, it’s commonly found in volcanic rock and ash. Its presence on Mars suggests that the planet was once much wetter, with conditions that could have supported liquid water. This contrasts with hematite, which forms in drier environments. To test their theory, the researchers recreated Martian conditions in a lab. They ground minerals into tiny particles—about 1/100th the width of a human hair—matching the size of real Martian dust. They then studied how light reflected off these particles. The results showed that ferrihydrite remains stable in Mars’ current dry, cold climate, but its structure still holds signs that it formed when the planet had water. “What we know from this study is the evidence points to ferrihydrite forming, and for that to happen there must have been conditions where oxygen and water could react with iron,” Valantinas explained. “Those conditions were very different from today’s dry, cold environment.” To confirm ferrihydrite’s presence, the team studied data from NASA’s Mars Reconnaissance Orbiter and ESA’s Mars Express and Trace Gas Orbiter. They also used spectral readings from rovers like Curiosity, Pathfinder, and Opportunity. Combining all of these sources, they found that the mineral appears widespread on the Martian surface. This discovery challenges previous theories that Mars gradually oxidized in dry conditions. Instead, it suggests that ancient Mars went through a wetter phase before drying out. That shift from a water-rich past to the dry, dusty planet we see today is key to understanding Mars’ climate history—and possibly its ability to support life. “The study is a door-opening opportunity,” said Jack Mustard, senior author of the study. “It gives us a better chance to apply principles of mineral formation and conditions to tap back in time.” While the findings provide strong evidence for ferrihydrite’s role in Mars’ red dust, definitive proof will have to wait until Mars samples—currently being collected by NASA’s Perseverance rover—are brought back to Earth. Scientists hope these samples will confirm the theory and shed more light on the planet’s environmental history. Source: Brown University, University of Bren, Nature | Image via Depositphotos This article was generated with some help from AI and reviewed by an editor. Under Section 107 of the Copyright Act 1976, this material is used for the purpose of news reporting. Fair use is a use permitted by copyright statute that might otherwise be infringing.
    • I would say 98% of people you can't figure out how to install Linux would never attempt to install Windows. It's not news non-tech savvy people can't install an PC OS.
    • Do I really have to tell you that people generally don't make random posts about how Windows is running perfectly for them? Of course you're seeing more posts about people hating Windows, it's just a very loud minority as usual.
    • ...and not really appropriate for most people for desktop usage.
  • Recent Achievements

    • Week One Done
      jrromero17 earned a badge
      Week One Done
    • One Month Later
      jrromero17 earned a badge
      One Month Later
    • Conversation Starter
      johnwin1 earned a badge
      Conversation Starter
    • One Month Later
      Marwin earned a badge
      One Month Later
    • One Year In
      fred8615 earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      237
    2. 2
      snowy owl
      156
    3. 3
      ATLien_0
      142
    4. 4
      +FloatingFatMan
      132
    5. 5
      Xenon
      131
  • Tell a friend

    Love Neowin? Tell a friend!