• 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

    • I agree, if Intel wants to make those 50% margins, they really should stick to sockets longer, someone is more likely to upgrade their CPU when they don't need to purchase a motherboard, then looking at maybe RAM, might as well buy a whole new PC at that point, then before you know they've talked themselves out of the whole thing.
    • not sure why people care about the developers so much. let them do whatever they want. if it succeeds, it can benefit us. if it doesn't, then who cares, your life will go on. i'm glad there are still people who do things without thinking whether the output will be productive to society...
    • this man really knows how to embarass americans! i thought he was platforming on "bringing back respect to america!". really sad to see the grip he has over working class americans. he could (and i might argue already has) spit on the working class and half would kiss his shoe. at least this you gotta give him credit for. who else can do this with applause and cheer.
    • Get this 27-inch ASUS VA279QG 120Hz monitor for dirt-cheap by Taras Buria If you are on a very tight budget but you still want to upgrade your monitor to something more exciting than a standard 60Hz office monitor, ASUS has a perfect deal for you. The VA279QG is currently available for as little as $109, and for this money, you get quite a lot of a monitor. The ASUS VA279QG is a big 27-inch IPS monitor with a classic FullHD resolution and a wide 178-degree viewing angle. It can operate with a refresh rate of 120Hz, which is more than enough for buttery-smooth gaming. And since the monitor is FullHD, you will be able to see high refresh rates in more games since your GPU will have to render fewer pixels at 120Hz. Besides, the monitor supports variable refresh rate (VRR), a feature that can further reduce stutters by dynamically adjusting the refresh rate to your FPS. Other display specs include a 1ms MPRT response time, 16.7 million colors, 99% sRGB coverage, and a typical brightness of 300 nits. It is also covered with an anti-glare coating to reduce reflections. Ports-wise, you get one DisplayPort 1.2, one HDMI 1.4, one VGA, and one headphone jack. There are also two 2W speakers, but set your expectation right—these are unlikely to blow your mind with high-quality audio. Finally, there is a VESA 100 mount and a cutout in the base, which lets you mount your phone, namecard, or other small items for extra convenience. 27-inch ASUS VA279QG 120Hz IPS Gaming Monitor - $109 | 22% off on Amazon US 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. As an Amazon Associate, we earn from qualifying purchases.
    • lol See... one is only 100% when it's by itself. I live for exceptions to the rule... our talk point was in reference in comparing Vista (not SP1/2) release vs. 7. Any OS will run stable once enough work has been put into it... hell, even Windows 95 had six versions before she was finally complete(d)... just about, what, six or seven months before 98 became available?
  • Recent Achievements

    • Explorer
      treker_ed went up a rank
      Explorer
    • Apprentice
      CHUNWEI went up a rank
      Apprentice
    • Veteran
      1337ish went up a rank
      Veteran
    • Rookie
      john.al went up a rank
      Rookie
    • Week One Done
      patrickft456 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      652
    2. 2
      ATLien_0
      269
    3. 3
      +FloatingFatMan
      176
    4. 4
      Michael Scrip
      155
    5. 5
      Steven P.
      136
  • Tell a friend

    Love Neowin? Tell a friend!