• 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

    • Men are real idiots justifying using any nuclear arms.  
    • OBS Studio 31.1.0 RC1 by Razvan Serea OBS Studio is software designed for capturing, compositing, encoding, recording, and streaming video content, efficiently. It is the re-write of the widely used Open Broadcaster Software, to allow even more features and multi-platform support. OBS Studio supports multiple sources, including media files, games, web pages, application windows, webcams, your desktop, microphone and more. OBS Studio Features: High performance real time video/audio capturing and mixing, with unlimited scenes you can switch between seamlessly via custom transitions. Live streaming to Twitch, YouTube, Periscope, Mixer, GoodGame, DailyMotion, Hitbox, VK and any other RTMP server Filters for video sources such as image masking, color correction, chroma/color keying, and more. x264, H.264 and AAC for your live streams and video recordings Intel Quick Sync Video (QSV) and NVIDIA NVENC support Intuitive audio mixer with per-source filters such as noise gate, noise suppression, and gain. Take full control with VST plugin support. GPU-based game capture for high performance game streaming Unlimited number of scenes and sources Number of different and customizable transitions for when you switch between scenes Hotkeys for almost any action such as start or stop your stream or recording, push-to-talk, fast mute of any audio source, show or hide any video source, switch between scenes,and much more Live preview of any changes on your scenes and sources using Studio Mode before pushing them to your stream where your viewers will see those changes DirectShow capture device support (webcams, capture cards, etc) Powerful and easy to use configuration options. Add new Sources, duplicate existing ones, and adjust their properties effortlessly. Streamlined Settings panel for quickly configuring your broadcasts and recordings. Switch between different profiles with ease. Light and dark themes available to fit your environment. …and many other features. For free. At all. OBS Studio 31.1.0 RC1 changelog: Fixed an issue where a Browser Source or Browser Dock would crash OBS Studio on macOS 13 or older [jcm93/PatTheMav/RytoEX] Fixed an issue where browser error pages could not scroll [WizardCM] Fixed an issue on macOS where menu items would launch unintended actions when OBS was set to certain languages [gxalpha] Fixed an issue in Beta 1-2 where the group icon in the Sources list was not positioned correctly in the System theme [shiina424] Fixed an issue in Beta 2 where the preview zoom button tooltip translations were incorrect [shiina424] Download: OBS Studio 31.1.0 RC1 | Portable | ARM64 | ~200.0 MB (Open Source) View: OBS Studio Homepage | Other Operating Systems | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Nice little improvement One improvement I would like to see. Being able to use a voice commands in Firefox "Firefox, 2FA (enter a 2FA code)". "Firefox, Close all tabs right" "Firefox, Pin tab" "Firefox, Bookmarks (name of Bookmark to open a Bookmark)" "Firefox, Settings, X" among others.
    • Microsoft Defender XDR gets TITAN-powered Security Copilot recommendations by Paul Hill Guided Response, a Copilot-powered capability in Microsoft Defender XDR that guides analysts through step-by-step investigation and response flows, is getting a big upgrade with the introduction of TITAN recommendations. With TITAN, Microsoft wants to give security analysts real-time, threat-intel-driven recommendations so they can better prepare against attacks, before they even happen. TITAN is an adaptive threat intelligence graph that uses data from first and third-party telemetry and employs guilt-by-association techniques to warn analysts about unknown IP addresses that could pose a threat, due to their association with known malicious addresses. The primary benefit of TITAN is that security analysts get faster warnings about potential threats before they even have a chance to cause a problem. TITAN is an enhancement of Security Copilot Guided Response, rather than a replacement to it. With this extra tool, security analysts will be able to better keep up with evolving threats. Understanding TITAN's AI-powered threat intelligence The Redmond giant said that TITAN “represents a new wave of innovation” built upon its threat intelligence capabilities that introduces a real-time, adaptive threat intelligence graph. It takes telemetry from first and third-party sources such as Microsoft Defender for Threat Intelligence, Microsoft Defender for Experts, and customer feedback. The graph uses guilt-by-association techniques to mark unknown devices as threats, if they’re associated with known malicious entities. This gives security analysts a window of opportunity to take action and prevent harm. To identify potential threats, Microsoft uses a semi-supervised label propagation technique that assigns reputation scores to nodes based on the score of their neighbors. These reputation scores allow Microsoft’s unified security operation platform to implement containment and remediation actions via attack disruption. Practical impact and future outlook The new TITAN suggestion now appears within Guided Response as triage and containment recommendations. When a suspicious IP is detected, a Guided Response recommendation is automatically generated. These can help security analysts deal with various threats including IP addresses, IP ranges, and email senders. Microsoft said in early testing its TITAN recommendations have shown good results. TITAN boosted Guided Response triage accuracy by 8%, it reduced the time needed to investigate and respond to incidents, and its explainable recommendations gave analysts more confidence in the actions they take. As threats become more sophisticated, Microsoft’s TITAN will help to tackle threats before they even become an issue.
    • China wants the tech... if they were to invade, TSMC would destroy it's fabs and other critical information first. Plus, you can bet they have backups stored NOT in Taiwan.
  • Recent Achievements

    • Enthusiast
      Motoman26 went up a rank
      Enthusiast
    • Mentor
      M. Murcek went up a rank
      Mentor
    • Explorer
      treker_ed went up a rank
      Explorer
    • Apprentice
      CHUNWEI went up a rank
      Apprentice
    • Veteran
      1337ish went up a rank
      Veteran
  • Popular Contributors

    1. 1
      +primortal
      677
    2. 2
      ATLien_0
      267
    3. 3
      Michael Scrip
      177
    4. 4
      +FloatingFatMan
      176
    5. 5
      Steven P.
      139
  • Tell a friend

    Love Neowin? Tell a friend!