C# ASP.Net - Global.asax full of errors - c#

I am attempting to use the Global.asax file and it is failing miserably. Every line in the code has an error but the funny thing is that it does not matter how many lines, what the lines contain, etc have as it always reports an error. This makes me thing there is a configuration setting that isn't right but wouldn't know where to begin.
The project is a Web Site rather than a Web Application but I read up on Global.asax and it appears to be acceptable to use it in a Web Site. I have provided the code I am using to test that the Global.asax works in the project before writing the code needed for the project.
<%# Application Language="C#" %>
<script runat="server">
static string _pagePath;
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
_pagePath = Server.MapPath("~/Folder/Page.aspx");
}
// ...
void Application_BeginRequest(object sender, EventArgs e)
{
string path = Request.PhysicalPath;
if (path == _pagePath)
{
Response.Write("Page viewed");
Response.End();
}
}
</script>
I have also provided a list of example error messages that are cropping up
'Class' statement must end with a matching
'End Class' 'If', 'ElseIf', 'Else', 'End If', 'Const', or 'Region' expected
'Namespace' statement must end with a matching 'End Namespace'
Statement cannot appear outside of a method body/multiline lambda.
Hopefully someone can pick out what I did wrong so I can use the Global.asax. Any help is widely appreciated!

add Language="C#" property to the directive at the top of your global.asax. right click on the file, choose view markup, add the property and rebuild.
<%# Application Codebehind="Global.asax.cs" Inherits="GLOBAL CLASS" Language="C#" %>

Related

ASP.NET Getting compiler error message intermittently

I have an aspx page using only inline C# without a codebehind.
Running from Visual Studio it works, however adding the aspx file to the wwwroot of my local machine gives the message
Compiler Error Message: CS1513: } expected
If I rearrange the code to have the method above the code the message is instead
CS1519: Invalid token 'try' in class, struct, or interface member declaration
I expect it is something to do with server configuration, though I don't really know where to start.
The issue only occurs if there is methods, removing method1 from the below results in correct running.
This is the minimum entire file I was able to cause the error with
html
<%# Page Language="C#" %>
<%
try
{
string message = "Text";
Response.Write(method1(message));
}
catch
{
Response.Write("Err");
}
string method1(string source)
{
return source;
}
%>
If you're embedding code directly on the aspx page, that code still has to go in a method. Ex:
<%# Page Language="C#" %>
<%
void Page_Load(Object sender, EventArgs e)
{
try
{
string message = "Text";
Response.Write(method1(message));
}
catch
{
Response.Write("Err");
}
}
string method1(string source)
{
return source;
}
%>
By the way - we don't typically put C# code directly in the .aspx file. That's what the code behind system is for.
And we don't typically write directly to the response. It's hard to control where the markup will end up. In Web Forms, it's better to declare a control on the page and then add markup to that (or show/hide controls). Of course if we're going to talk about doing things well - then don't use Web Forms in the first place. It's a dead technology.
I have messed around with the Visual Studio project, running on an earlier version of .NET/C# yields the following error, It seems possible that this is the actual problem I have had
Error CS8059 Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater.
I am unsure why it thinks method1 is a local function and details are hard to come by.
Edit: To solve my problem I put the method in script tags instead of embedded code blocks. The methods then could be used from the embedded blocks and the script tag.
<script runat="server">
string method1(string source)
{
return source;
}
<script>

Circular references on every page when opening project on another computer

In order to work on my website on a second computer, I put the project on an usb key and opened it.
The initial project is building correctly, but whenever I try to open it on the second machine, I have a circular reference issue on every single page and can't figure out why.
For each aspx page, I've got:
Circular file references are not allowed. MyPage.aspx. Line 1.
For instance, here's the first line of "Profile.aspx":
<%# Page Title="" Language="C#" MasterPageFile="~/Game/Site.master" AutoEventWireup="true" CodeFile="Profile.aspx.cs" Inherits="Profile" %>
Site.master is actually in the same folder "Game" as all the other pages, and moving this master page in another folder seems to do the trick. However, this doesn't make sens since this is working correctly elsewhere...
Another odd thing: If I keep the project on the usb key (not working if I move the folder) and comment those lines, there is no circular references anymore:
public static class Database
{
private static string conxString = "";
static Database()
{
/*System.IO.StreamReader dataBaseFile = new System.IO.StreamReader("~/Files/DataBase.txt");
conxString = dataBaseFile.ReadToEnd();
dataBaseFile.Close();*/
}
}
Where database.txt contains the local database connection string.
If anyone has any idea please feel free, I really don't know how to address this matter.

how do you manage a virtually empty asax file?

I have a virtually empty asax file that has just one line of code:
<%# Application Language="C#" CodeBehind="Global.asax.cs" Inherits="Applications.Global" %>
Shouldn't there be more accompanying code?
Applications.Global is defined in the code-behing like this:
namespace Applications
{
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
//Helper.CacheMasterTemplate();
}
}
}
but the compiler complains that it cannot load type 'Applications.Global' from the first line of the asax file. How can I change the code to make this work?
You need to fix the problem. Most often, you get that error because the output path has been changed. It should be bin. If you target x86, Visual Studio changes it to bin\x86\Debug. Change it back. Go to PROJECT > YourProject Properties > Build and check the Output Path.

How to concat a variable into some <asp: .. /> attribute?

I'm working on small web form,in C#/ASP.NET. I want to store the errors messages into variables of C# class; something like this:
public static class ErrorMessages {
public static string fooX = "baa";
// etc..
}
And then concat it in some attribute of an ASP tag:
<asp:RegularExpressionValidator runat="server"
ControlToValidate="baain"
ErrorMessage= *ErrorMessages.fooX*
/>
Is it possible? if yes, how to do this?
In the aspx page you may try:
ErrorMessage='<%# ErrorMessages.fooX %>'
In your code behind on page load call DataBind();:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}
I am not sure about concatenating the aspx part of the page, you can set the ErrorMessage property of your RegularExpressionValidator in the code behind. Something like:
RegularExpressionValidator1.ErrorMessage = "Your message";
or
RegularExpressionValidator1.ErrorMessage = ErrorMessages.fooX;
One approach to this, is to create your own custom expression builder.
The ExpressionBuilder class is the base class for expression builders, such as the AppSettingsExpressionBuilder class, that create code expressions during page parsing.
Expression builders parse declarative expressions and create code to retrieve values bound to a control property. In no-compile scenarios, an expression builder that supports a no-compile feature evaluates the expression during run time.
Please see the link from msdn for more detailed explanation and example.
http://msdn.microsoft.com/en-us/library/system.web.compilation.expressionbuilder.aspx
This is simple, have you tried this:
<%= YourNamespace.YourConstant %>
Or (.Net 4, this option will automatically encode the text)
<%: YourNamespace.YourConstant %>
There are several operators:
<%# Used for data binding
<%$ Used for expressions, not code; often seen with DataSources:
<%= Returns a string
<%: Same as <%= but it auto-html-encodes the value within the tag
Edit 1
Well I just tested and it appears that you cannot use inline code with server controls...
So alternative approaches:
Simply assign the value using code behind
this.myRegularExpressionValidator.ErrorMessage = ErrorMessages.Foo;
Use resources instead. With resources you will gain many benefits like localization for your site and since resources are simply xml files, you can drop them in your site without recompile (assuming you are not using satellite assemblies to store your resources)
<asp:RegularExpressionValidator runat="server" ErrorMessage="<%$ Resources:Resource, MyResource %>" />
Where
Resource refers to the global resource file
MyResource refers to the key in the resource file containing the text
The global resources must be placed in the App_GlobalResources ASP.Net special folder, as an example the resource file name: Resource.resx
Example of the resource file
<?xml version="1.0" encoding="utf-8"?>
<root>
<data name="MyResource" xml:space="preserve">
<value>My error message</value>
</data>
</root>
The resource files can be added and managed using Visual Studio so you do not have to deal manually with the XML

Why won't my ascx file pick up my code behind properties?

My web app is a solution built on top of another solution. The base solution is meant to be a platform for multiple products. For the most part, this works fine, but weird things happen when I create product specific views.
I am using ViewUserControl<SomeViewModel> for my code behind class. In my code behind, I have access to this.Model and all the other goodies I'd expect from this class. But in my ascx file, I get red squiggley lines when I try to access this.Model or other properties defined in ViewUserControl. I also get red squiggley lines when I try to access properties defined directly in my code behind.
What's more interesting is, I don't get any real errors from this. The view renders just fine at run time and does not give me any build errors. But my ascx file thinks there will be errors. If I create the exact same view in the platform namespaces, it works fine. No red squiggles.
I find this to be really annoying. It's not a show stopper by any means, but if I'm going to be using an IDE with intellisense and all that jazz, I'd sure like it to work properly, and pick up the properties that are supposed to be there.
Has anyone else run into this? Do you know of a way to fix this?
Thanks!
Edit
It was requested that I post some code. Here's the code behind:
namespace MyProject.MyProduct.Web.Views
{
public class EditSearch : ViewUserControl<SearchResultsViewModel>
{
public bool IsSearchTypeA()
{
...............
}
public bool IsSearchTypeB()
{
...............
}
}
}
And here's my ascx:
<%
if (!this.IsSearchTypeB())
{
string categoryPageTitle = this.Model.SearchWidgetParameters.Search.CategoryPageTitle;
string categoryPageUrl = this.Model.SearchWidgetParameters.Search.Filters.CategoryPageUrl;
if (!string.IsNullOrEmpty(categoryPageUrl))
{
%> <div id="coid_website_backtoCategoryPageLink"> <%
string tocGuid = this.Model.SearchWidgetParameters.Search.Filters.TocGuid;
if (!string.IsNullOrEmpty(tocGuid))
{
categoryPageUrl += "?guid=" + tocGuid;
}
var backToLink = new HyperLink();
if (this.IsSearchTypeA())
{
backToLink.Text = "Edit Search";
}
else
{
backToLink.Text = "Back to " + TranslatedHtmlTextWriter.Translate(categoryPageTitle);
}
backToLink.NavigateUrl = TransactionOperations.AddContextToUrl(categoryPageUrl.StartsWith("/Browse/") ? categoryPageUrl : "/Browse/" + categoryPageUrl,
WebsiteTransitionType.Default, // Requested: CategoryPage
TransactionOperations.DefaultContextData);
backToLink.RenderControl(this.Writer);
%>
</div>
<%
}
}
%>
Edit
For those of you who are telling me that ASP.NET MVC cannot or does not use code behind, I'm sorry but this is horse hockey. This project has existed for years and there is a widely used product that runs on it. My product is only just recently jumping onto the Platform. The Platform solution uses code behind all over the place, and it works fine. In fact, it works fine at runtime in my product's solution as well, I just have the problem that my ascx file doesn't seem to know about my code behind. Furthermore, ViewUserControl is a System.Web.MVC class. Are you still going to tell me that code behind isn't used in ASP.NET MVC?
Since you are developing MVC you cannot use code behind. Instead, what do you think about adding this at the top of your .acsx file:
<%# Import Namespace="Namespace.Model" %>
Then you can access everything you have in there without so much complication.
ASP.NET MVC does not use code behind. It sounds like you are mixing ASP.NET MVC and ASP.NET WebForm pages.
I suggest you take a look at http://www.asp.net/mvc. It has some great tutorials on getting started with MVC and how it works.

Categories