9

So I have two functions and I'm getting an interesting problem. Essentially I'm aiming to make my code more portable in an easily includeable cs file.

Here's said cs file:

namespace basicFunctions {
public partial class phpPort : System.Web.UI.Page {
    public static string includer(string filename) {
        string path = Server.MapPath("./" + filename);
        string content = System.IO.File.ReadAllText(path);
        return content;
    }
    public void returnError() {
        Response.Write("<h2>An error has occurred!</h2>");
        Response.Write("<p>You have followed an incorrect link. Please double check and try again.</p>");
        Response.Write(includer("footer.html"));
        Response.End();
    }
}
}

Here is the page that is referencing it:

<% @Page Language="C#" Debug="true" Inherits="basicFunctions.phpPort" CodeFile="basicfunctions.cs" %>
<% @Import Namespace="System.Web.Configuration" %>

<script language="C#" runat="server">
void Page_Load(object sender,EventArgs e) {
    Response.Write(includer("header.html"));
    //irrelevant code
    if ('stuff happens') {
        returnError();
    }
    Response.Write(includer("footer.html"));
}
</script>

The error I'm getting is the one listed above, namely:

Compiler Error Message: CS0120: An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Server.get'

On the following line:

Line 5: string path = Server.MapPath("./" + filename);

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 3
    I would HIGHLY recommend you not repeat the mistakes of php. Instead look into how master pages work or just move to MVC. – NotMe May 08 '12 at 22:14
  • 1
    Not all of us see PHP's coding style as mistakes. For those of us with a more traditional coding background that gives us more low-level controls and coding flexibility at the expense of production speed (though not runtime) or a heavily-object-focus, it really does feel a bit more at home. Besides, the documentation's better =P. Also, I find the deeper you go into the ASP.NET rabbit hole, the worse your HTML and JavaScript tend to end up being (as it begins to become heavily generated). XHTML, JSLint, etc. is important to me, so I prefer to keep as much code reliant on myself as possible. –  May 09 '12 at 16:10
  • 1
    There's nothing wrong with the official Microsoft-sanctioned way I suppose. However, to say it is inherently better because it is what people tell you to do is a little disingenuous as it often creates code with a larger memory footprint, more places for common-mistake security holes, and many, many more lines of code. Of course, on the other hand, it's also better in many ways for large production workplaces with many individual programmers working together. Different coding styles, that's all. I'll always be in the PHP-camp though, I'm afraid. –  May 09 '12 at 16:14
  • (Also, modern C# will always have that IIS hindrance as a deterrent for me to use seriously. Mod_Mono can get you decent basic support, but if you want to do anything complex efficiently, you need to use another language for non-Windows/non-IIS servers) –  May 09 '12 at 16:19
  • 1
    @user798080 i suggest to explore the .NET family a bit more ... it's not mainly about ASP.NET. WCF, WPF (and the beloved Silverlight) and of course Console and Service-Applications (and whatever other component you can use with .NET) are another big part. The main benefit of using .NET (and coding in a component-independent style) gives you the big plus-plus of *code-sharing* and reusage - and that's the main issue all the big players are after! As you get a deeper understanding of .NET you'll understand what ChrisLively really meant –  May 09 '12 at 17:50
  • @ChrisLively i do also think, that suggesting MasterPages or ASP.NET MVC is a bit like cracking a nut with a sledgehammer. but you did name the main issue: **MVC** ... you can still go for the **MVC-pattern** with ASP.NET Webforms (even if it's in a limited way) - and that is what i would suggest here! –  May 09 '12 at 17:54
  • @AndreasNiedermair: You're right, I probably should have gone into a better explanation for my comment. However, it looks like you covered it ;) Thanks. For the OP: Each technology has it's own idiosyncrasies and general practices. By grafting one way (php's) onto another (.net's various: webforms, mvc, etc) then you end up in a situation where later programmers will be cursing your name when they have to maintain it. Further you lose out on so much of the ecology of the platform you are working in. Regardless, your mentioning of larger footprint, security holes etc around c# isn't accurate. – NotMe May 10 '12 at 12:46

4 Answers4

10

Server is only available to instances of System.Web.UI.Page-implementations (as it's an instance property).

You have 2 options:

  1. Convert the method from static to instance
  2. Use following code:

(overhead of creating a System.Web.UI.HtmlControls.HtmlGenericControl)

public static string FooMethod(string path)
{
    var htmlGenericControl = new System.Web.UI.HtmlControls.HtmlGenericControl();
    var mappedPath = htmlGenericControl.MapPath(path);
    return mappedPath;
}

or (not tested):

public static string FooMethod(string path)
{
    var mappedPath = HostingEnvironment.MapPath(path);
    return mappedPath;
}

or (not that good option, as it somehow fakes to be static but rather is static for webcontext-calls only):

public static string FooMethod(string path)
{
    var mappedPath = HttpContext.Current.Server.MapPath(path);
    return mappedPath;
}
  • The OP *is* subclassing `System.Web.UI.Page`. This is not the OP's problem. – Kirk Woll May 08 '12 at 19:33
  • **that** is the OP's problem - he is not able to differ between static and instance property! ... i've clearly stated `instance of ...` –  May 08 '12 at 19:34
  • Sure, your answer is now more clear. Your initial answer implied the OP was not using that class. – Kirk Woll May 08 '12 at 19:36
  • She. Let's not assume, shall we? Know what people say when you do that =P. That worked though - thanks! –  May 08 '12 at 19:39
  • @user798080 sry ... would change that, if there's still an edit-button ... i don't want to seem arrogant, but ... i have run into this issue on my own, so i clearly had no doubt 'bout spotting the real issue here (btw i hope my comment does not have a rude touch - but i fear it has ... this was not on intention at all!) ... happy that my answer helped you! –  May 08 '12 at 19:42
1

What about using HttpContext.Current? I think you can use that to get a reference to Server in a static function.

Described here: HttpContext.Current accessed in static classes

Community
  • 1
  • 1
SouthShoreAK
  • 4,176
  • 2
  • 26
  • 48
1

I ran into a similar thing some time back -- put simply you can't pull Server.MapPath() from the .cs code-behind inside a static method (unless that code behind somehow inherits a web page class, which is probably not allowed anyway).

My simple fix was to have the code behind method capture the path as an argument, then the calling web page executes the method with Server.MapPath during the call.

Code Behind (.CS):


public static void doStuff(string path, string desc)
{
    string oldConfigPath=path+"webconfig-"+desc+"-"+".xml";

... now go do something ...
}

Web-Page (.ASPX) Method Call:


...
doStuff(Server.MapPath("./log/"),"saveBasic");
...

No need to bash or talk down to the OP, it seemed a legitimate confusion. Hope this helps ...

Chris
  • 11
  • 1
  • By far the easiest! You can put all sorts of confidential stuff in the CS, passing the mappath command will not give away any secretive information. – Dandymon May 18 '15 at 20:58
0
public static string includer(string filename) 
{
        string content = System.IO.File.ReadAllText(filename);
        return content;
}


includer(Server.MapPath("./" + filename));
Nilish
  • 1,066
  • 3
  • 12
  • 26