Syntax error caused by <%# Page Language="c#"%> ? ASP.Net - asp.net

Is this invalid to put in an aspx file? I have some static aspx pages and I want to add a bit of C# to one of them. How can I do this?
I figured just adding
<%# Page Language="c#"%>
and then using <% %> to put a bit of C# goodness in there, but it says Syntax Error. with a blue wavy line over this code.

This happens whenever you change the Language attribute of the Page directive. Simply close the file in Visual Studio, and reopen it. The error will go away.

It's not entirely clear from your question, but are you adding multiple Page directives? You can only have one per .aspx file.
Otherwise what you've got there is valid. If your page works fine and VS is still showing it as an error, quit out of VS entirely and restart it.

Related

Visual Studio 2010 BreakPoints not hit on one page but hit on the other

I have a project I inherited on only one of the pages the break points are not being hit. They are not hollow, they are solid and look as if they are going to be hit when I run the code, but when the page loads (one of the break points) it does not break. Now I added a break point to a different page (onLoad) and it does it. I have never come across this before, does anyone one have any insight on this crazy visual studio behavior?
I have tried to clean and rebuild the project and still not working.
aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Screener.aspx.cs" Inherits="Screener.Screener" %>
.cs page:
namespace Screener
{
public partial class Screener : System.Web.UI.Page
One thing I just noticed, the code behind page is 1633 lines long, should that matter?
I just deleted the old page and re-created it and still nothing.
There is another way to force a breakpoint (in code)
Add the System.Diagnostic namespace to your code behind
add an additional line of code Debugger.Break();
This will force the debugger to break (if running) otherwise a dialog box will appear asking to debug. Should identify if this is an issue with visual studio caching something or the code that you wish to debug is not being called.
Do not forget to remove from code when done.
http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break(v=vs.110).aspx

Only Content controls are allowed directly in a content page that contains Content controls in ASP.NET

I have an application which has a master page and child pages. My application is working fine on local host (on my intranet). But as soon as I put it on a server that is on the internet, I get the error shown below after clicking on any menus.
Only Content controls are allowed directly in a content page that contains Content controls.
Double and triple check your opening and closing Content tags throughout your child pages.
Confirm that they
are in existence
are spelled correctly
have an ID
have runat="server"
have the correct ContentPlaceHolderID
I had exactly the same issue. The problem was I had some spaces after the ending content tag:
</asp:Content>
Remove all the spaces, line breaks after the last closing tag.
I was facing a similar issue. Are you surrounding your code with the "content" tag ?
<asp:Content>Add your HTML here</asp:Content>
And have separate content tags for your sections .
A head content for the header declaration and a body content for the body declaration .
Another possibilty is line endings. I copied an older version of code from source control which enforced Unix style line endings. Since it wasn't a checkout, it didn't automatically convert the line endings to the DOS/Windows style. The error message was the "Only Content controls are allowed directly ..." error even though the page was layed out properly. It appears that the lack of Windows style line breaks caused the ASPX parser to fail.
I was able to fix it by pasting the code into a line ending agnostic editor (which caused the line endings to be normalized to the Windows style), re-copying it to the clipboard and pasting it back in Visual Studio, after which the page processed without errors.
In the case presented by Tripati Subudhi in the question, it's entirely possible that something about the deploy process used inadvertently converted line endings to the Unix style, leading to the error.
Another possible issue is HTML comments, I had these surrounding a Content control - I believe ASP.NET converts these into literal controls behind the scenes - hence the error i
another potential cause for this error: tags with the wrong case.
changing <asp:content>... to <asp:Content>... fixed the issue in my case.
the reason for the faulty case was the built-in format document function in visual studio 2012(and 2013) with default settings.
the setting for this can be changed in Tools->Options->Text Editor->HTML (Web Forms)->Formatting: set the tag capitalization to 'as entered' and studio will no longer destroy your files.
Check your document for non-printing characters
My masterpage contained two UTF-8 BOMs right at the start of the file because I pasted the <%# Master %> directive from another page. I was able to make it work by backspacing them out.
For me, it didn't like that I had an Assembly and a Page directive commented out:
<%--<%# Assembly Name="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" %>--%>
<%--<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MyPage.aspx.cs" Inherits="MyClass.MyPage" MasterPageFile="~/_layouts/MyProject/MasterPages/MasterPage.master" %>-->
Even though I had a valid Page directive after that, and was not using System.Core for anything. After just removing them, it loaded fine.
For me it was two content controls that had the same ID - the file had been edited outside of Visual Studio, so the auto-rename of duplicate ID didn't happen. This misleading error was highlighting the first image inside the second content control with the same ID as the first - what a wild goose chase!
Copying the entire page and reposting it over itself solved it, because VS at that point then renamed the duplicate control ID.
In my case I forgot to add assembly reference of AjaxControlToolkit.dll.
When I add the reference the error disappeared.
in SharePoint it happened since a pageLayout wasn't published.
I had a silly syntax error I kept overlooking. There was an extra < at the start of my MasterType tag I couldn't see for the life of me 🤦‍♂️.
<%# Page Language="vb" AutoEventWireup="true" MasterPageFile="~/Site1.Master" CodeBehind="Default.aspx.vb" Inherits="SomeApp.Web._Default" %>
<<%# MasterType VirtualPath="~/Site1.Master" %>

Dynamic partial - viewdata null reference error

I am running a site using MVC 2 and .net 4.0.
I recently added a new partial view to the site that looks like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<% if (!(bool)ViewData["Master_ShowGuide"] )
{ %>
<%= Html.NavigationButton("Guide", "button", "infoIcon", Url.Content("~/Help/ Guide.pdf"), new { title = "Click here to view an in depth user guide." }, new { target="_blank" })%>
<%} %>
What I didn't notice at the time was the addition of the <dynamic> part to this view, where previously my partials just looked like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
This partial was displayed using:
<% Html.RenderPartial("SubLinks"); %>
on my master page.
This appeared to work ok on my development environment, but when deployed to the server, I now run into issues where my ViewData["Master_ShowGuide"] is null. I know that this is not the case, as it is used in other places on the master page just fine.
Can anyone explain why this might be the case - I have 'fixed' the issue by removing the <dynamic> type from the partial definition, but I'm curious as to the cause.
If it's any help, my site runs in an environment with other sites that are running MVC 3.
As a slight addendum, I would note:
The user does not see this error, it just gets reported back to me (through ELMAH).
This code works ok on my test site, but fails with the null reference error on my pre-production deployment site (which is on the same server as the test site and currently running the same code).
I'm a little perplexed.
An answer was found to this issue (as to the root cause of why it is happening), but I'm still not sure why removing dynamic from the partial view declaration would also 'fix' it. If anybody can explain, I'd be interested to hear it.
Found out what the issue was, going to record it for posterity.
Had a url to an image, being generated in a different partial view that was being output using Html.RenderAction. This url was incorrect, resulting in a 404 error being returned.
This wasn't noticed on my dev system.
On live, with custom errors enabled in the web.config, this 404 error tried to return a 'filenotfound' page that we have. Unfortunately, this error page was using the same master page that was causing the problem in the first place, and it errored out, as did the main 'error occurred' page that you were eventually redirected to.
This resulted in a 500 server error being returned, and this seems to have disrupted the viewdata for the subsequent partial being rendered.
Hooray for firebug, as this helped me to track this down.
Hope this helps you out if you find yourself here at some point.

Why does the message BC30560 'mymodule_ascx' is ambiguous in the namespace 'ASP' come up sometimes then go away?

Often when making changes to a VS2008 ASP.net project we get a message like:
BC30560: 'mymodule_ascx' is ambiguous in the namespace 'ASP'.
This goes away after a recompile or sometimes just waiting 10 seconds and refreshing the page.
Any way to get rid of it?
I recently came across this problem and it was only happening on one server even though all were running the same code. I thoroughly investigated the problem to make sure there were no user controls with clashing names, temp files were cleared out, etc.
The only thing that solved the problems (it seems permanently) is changing the batch attribute of the compilation element to false in the web.config, as suggested in the following link:
http://personalinertia.blogspot.com/2007/06/there-bug-in-compiler.html
<compilation debug="true" batch="false">
I firmly believe that this is in fact a bug in the compiler as suggested on that site.
I just solved this problem with the assistance following link:
http://www.netomatix.com/development/usercontrols2.aspx
In a nutshell, your class is called MyModule. However, if you do not specify the ClassName property in the #Control directive, the compiler may append _ascx to the control's class, which results in MyModule_ascx. Since the page can't find MyModule_ascx, it blows up in your face. You need to explicitly tell it the ClassName...
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="MyModule.ascx.vb" ClassName="MyModule" %>
Another possibility:
http://channel9.msdn.com/forums/TechOff/157050-BC30560-mycontrolascx-is-ambiguous-in-the-namespace-ASP/
Seemed to have some success with changing
src="mycontrol.ascx.cs"
to
CodeBehind="mycontrol.ascx.cs"
I've just suffered this. Stuff that worked fine and was untouched for months started randomly failing after some unrelated updates. I'd recompile and the problem would disappear only to reappear somewhere else.
I seem to have resolved it by clearing out the ASP.NET temporary folder, e.g. C:\Windows\Microsoft.NET\Framework\v2.0.xxxxx\Temporary ASP.NET Files. This required an IIS restart to really clean it out.
Update: I tried adding tempDirectory="e:\someotherfolder" to the compilation element of the web.config and that seems to have had some success. Also added batch="false" but not sure if that's had an effect.
I used to have this problem sometimes too. If I remember correctly it was caused by something like the following:
<%# Page Inherits="_Default" %>
or perhaps
<%# Page ClassName="_Default" %>
Or something like that. I'm not 100% sure which attribute it was (it's been a while).
But look look for something like _Default in your Page directive and replace them with actual class names in all of your files. For some reason, ASP.Net doesn't always interpret the _Default correctly, yielding temporary ambiguous references.
Similar to the two previous answers, you'll most probably have a "copy and pasted" copy of an existing page in the same site, and this will then contain the same #Page directives which will lead to a clashing of functions (especially because everything in .Net defaults to Partial Classes.) This little gem has bitten me all-too-often.
Just update the "Inherits" to point to something specific to your page (i.e.: your page name prefixed by an underscore -- as it's more-often-than-not guaranteed to be unique), and ensured that you haven't got two Public Partial Classes named the same in different code-behind files (otherwise Page_Load in _Default [default.aspx], will clash with Page_Load in _Default [copy of default.aspx])
Try to change web.config, set batch to false
<compilation batch="false">
</compilation>
For me this error was a red herring. In reality one of the user controls had errors caused by .NET 2.,0 to 4.5 migration, which had to be fixed in the code, but VS threw this misleading error messages. After multiple attempts to upgrade the projects it finally started erroring on the actual lines of code, but I don't know how to reproduce this after hours of frustration and fruitless attempts to apply solutions from all over the Internet.
Rebuild Solution worked for me.
Also ran into this with MasterPages on projects that were originally .net 1.1 and 2.0 projects and later converted. In both cases, the #MasterType directive referenced the virtualpath. I changed to <%# MasterType TypeName="MasterPages_MasterPage" %>, cleaned the solution and the problem went away. HTH

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

Sometimes when I'm editing page or control the .designer files stop being updated with the new controls I'm putting on the page. I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate the .designer file. I'm using Visual Studio 2008
EDIT: Sorry I should have noted I've already tried:
Closing & re-opening all the files & Visual Studio
Making a change to a runat="server" control on the page
Deleting & re-adding the page directive
If you open the .aspx file and switch between design view and html view and
back it will prompt VS to check the controls and add any that are missing to
the designer file.
In VS2013-15 there is a Convert to Web Application command under the Project menu. Prior to VS2013 this option was available in the right-click context menu for as(c/p)x files. When this is done you should see that you now have a *.Designer.cs file available and your controls within the Design HTML will be available for your control.
PS: This should not be done in debug mode, as not everything is "recompiled" when debugging.
Some people have also reported success by (making a backup copy of your .designer.cs file and then) deleting the .designer.cs file. Re-create an empty file with the same name.
There are many comments to this answer that add tips on how best to re-create the designer.cs file.
Well I found a solution that works, though I don't really like it. I had to delete the .designer.cs file then recreate an empty file with the same name. When I went back in and saved the aspx file again, the designer file was re-generated.
Dodgy!
I use the following method which works everytime:
Select all of the code-in-front (html markup etc) in the editor of the aspx/ascx file.
Cut.
Save.
Paste.
Save.
Recompile.
I recently saw that I was having the same problem. Visual Studio 2010 was refusing to update the designer file.
As it turns out, VS doesn't modify the designer file for a page that uses CodeFile (run off of pages) instead of CodeBehind (DLL). This is true no matter how many times you close VS, reload the project, re-create the control(s), or modify a file. Nothing would prompt VS to regenerate the designer. It's as if it doesn't create the designer file for CodeFile pages but does require it to be there.
I changed it to CodeBehind and saved the page. The designer file updated immediately. Then I just changed it back and everything was still golden. This behavior seems to be new with VS 2010 / .NET 4.0 as VS 2008 by default didn't suffer from this.
It's this part:
<%# Page Language="vb" AutoEventWireup="false" CodeFile="YourPage.aspx.vb" Inherits="YourPageClass" %>
Change CodeFile to CodeBehind, save, and then revert.
There is another possibility: You may have an error in your .aspx file that does not allow Visual Studio to regenerate the designer.
If you switch to Design View, it will show the control as unable to be rendered. Fixing the control (in my case it was an extra quote in the properties) and recompiling should regenerate the designer.
Most of the solutions here don't work if you're running Visual Studio 2013 and possibly 2012. Microsoft probably introduced some optimizations to make the IDE snappier, consequently they've reduced the number of cases that trigger the code generator. The following scenarios that used to work no longer do:
Delete the aspx or ascx file -- No longer checks for this case
Cut all the content and repaste into the aspx or ascx file -- No longer works, no change in the references
Convert to Web Application -- Option no longer available
Arbitrarily changing content on the aspx/ascx file -- No longer works (see 2).
The solution is surprisingly simple, but it's slightly cumbersome. In order to trigger the code generator, change something that would require the designer.aspx.cs to be generated. Changing content that doesn't affect code, such as a CSS style or adding text, won't trigger the code generator. You must change a referenced control. Here's how to do it:
In the ascx or aspx change the ID of the control
<asp:HyperLink ID="MyLink" runat="server" NavigateUrl="~/Default.aspx" Text="Home" />
to
<asp:HyperLink ID="theLINK" runat="server" NavigateUrl="~/Default.aspx" CssClass="tab" Text="Home" />
Go to the ascx.cs or aspx.cs and make sure you rename all references to "MyLink" to "theLINK" as well. Save and do build and the you should be good to go.
the only way I know is to delete the designer file, and do a convert to web app. However when you do this, it usually pops up with the error, as to why it didn't auto-regen in the first place, its usually a control ref that isn't declared in the head of the page.
Convert to Web Application did not work for me.
Deleting designer.cs and pasting a blank designer.cs did not work either.
But yes this worked:
Select all(Default.aspx)
Cut
Save Default.aspx
Paste
Save Default.aspx
Done. New designer.cs generated. :)
I often found that copy/pasting caused this behaviour for me. Most cases can be solved by editing the ID of a server control (just add a character, then delete it).
Also remember that control inside things like Repeaters aren't visible in the designer file.
And yes, there are cases where you need to do the delete-the-file magic listed above - but the name-change solution will work most of the time.
My experience is that if you want to do like in this article, like stated above.
Your markup file (aspx/ascx) has to include the CodeBehind="MyPage.aspx.cs" attribute or else it won´t work. I blogged about it here.
I've found a way to solve this problem without changing any code or running commands like "Convert to Web Application" - and it's simple too!
What I found was that restarting Visual Studio often solves the problem, but sometimes it doesn't. In those cases, if you close Visual Studio and then delete all content in the "obj" directory for the web project before you open it again, it has always worked for me.
(when started again you just add a space and remove it again and then hit save to have the designer file properly regenerated)
(The following comes from experience with VS2005.)
If you edit an ASPX page while debugging, then the codebehind doesn't get updated with the new classes. So, you have to stop debugging, trivially edit the ASPX page (like add a button or something), then click Design View, then delete the button. Then, your designer files should be updated.
If you are having a different issue with VS2008, then I can't help.
When you are in design view, right click on the screen and hit refresh.
Another thing which worked was -
Manually delete & then Create a designer file in filesystem.
Edit Project file.
Add code to include designer
Eg: <Compile Include="<Path>\FileName.ascx.designer.cs">
<DependentUpon>FileName.ascx</DependentUpon>
</Compile>
Reload Project
Open as(c/p)x file in design/view mode & save it.
Check designer file. Code will be there.
If you are using VS2013 or later , make sure that the code referenced with attribute "CodeBehind" not "CodeFile", then do below steps
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="yourControl.ascx.cs" Inherits="yourControl.yourControl" %>
create empty designer page (or clear it if it's already exists "yourControl.ascx.designer.cs")
in the ascx (or aspx) copy all code , the delete it, then save. re-past it again , then save.
the designer file should be populated now.
Select-all in the designer file and delete everything in the file, leaving it blank and then save
Select-all in the ASPX/ASCX file and cut everything and then re-paste it back
The designer file should have regenerated the code
Here is wat i experienced ,
Select the website folder right click in the Solution Explorer, select Convert to Web application for all the aspx file a designer file will get generated.
Sameer
Just to add to the long list of answers here - I've just run into this issue in VS2010 (SP1) with an .aspx file. I tried adding and removing standard ASP controls (which has worked in the past) but in the end, I had to remove one of the runat=server lines from an existing control (and save) to force the designer file to regenerate.
The solution the worked for me is:
I just copied the page and and pasted it in the same portion, then renamed the first page(what ever name) and renamed the copied page as the original page. Now the controls are accessible.
I've encountered the same problem for years now, working in Visual Studio 2008. And I've tried every "solution" on StackOverflow and dozens of blogs, just like I'm sure all of you have. And sometimes they work, and sometimes they don't, just like I'm sure all of you have encountered. And apparently it's still an issue in VS2010 and VS2012.
So finally, a couple of months ago, I decided enough was enough, and over a few weeks I built a tool called "Redesigner" that generates .designer files. It's open-source under the BSD license, with the source code available on SourceForge — free to use, free to steal, free to do anything you please with. And it does what Visual Studio fails to do so often, which is generate .designer files quickly and reliably.
It's a stand-alone command-line tool that parses .aspx and .ascx files, performs all the necessary reflection magic, and spits out correct .designer files. It does all the parsing and reflection itself to avoid relying on existing code, which we all know too well is broken. It's written in C# against .NET 3.5, but it makes pains to avoid using even System.Web for anything other than type declarations, and it doesn't use or rely on Visual Studio at all.
Redesigner can generate new .designer files; and it offers a --verbose option so that when things go wrong, you get far better error messages than "Exception of type System.Exception was thrown." And there's a --verify option that can be used to tell you when your existing .designer files are broken — missing controls, bad property declarations, unreadable by Visual Studio, or otherwise just plain borked.
We've been using it at my workplace to get us out of jams for the better part of the last month now, and while Redesigner is still a beta, it's getting far enough along that it's worth sharing its existence with the public. I soon intend to create a Visual Studio plugin for it so you can simply right-click to verify or regenerate designer files the way you always wished you could. But in the interim, the command-line usage is pretty easy and will save you a lot of headaches.
Anyway, go download a copy of Redesigner now and stop pulling out your hair. You won't always need it, but when you do, you'll be glad you have it!
https://sourceforge.net/projects/redesigner/
TL;DR;
Edit the Inherits attribute of the ASPX page's #Page directive and hit Save. Your designer file should be regenerated.
Ensure that Inherits = <namespace>.<class_name> and CodeBehind = <class_name>.aspx.cs
I was trying to do this on a Sharepoint 2010 project, using VS 2010 and TFS, and none of the solutions above worked for me. Primarily, the option, "Convert to Web Application" is missing from the right-click menu of the .ASPX file when using TFS in VS 2010.
This answer helped finally. My class looked like this:
namespace MyProjects.Finance.Pages
{
public partial class FinanceSubmission : WebPartPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
// more code
}
}
And my #Page directive was (line-breaks here for clarity):
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="FinanceSubmission.aspx.cs"
Inherits="MyProjects.Finance.Pages.FinanceSubmission"
MasterPageFile="~masterurl/default.master" %>
I first changed the Inherits to MyProjects.Finance.Pages, hit Save, then changed it back to MyProjects.Finance.Pages.FinanceSubmission and hit Save again. And wallah! The designer page was regenerated!
Hope this helps someone using TFS!
Within the Visual Studio:
1) Remove your aspx.designer.cs file
2) Right click on your aspx file and select "Convert to Web Application"
This should add the aspx.designer.cs back and up to date.
If you get an error saying:
"Generation of designer file failed: The method or operation is not implemented."
Try close Visual Studio and then reopen your project and do step number two again
How to generate aspx.designer.cs in visual studio?
in solution explorer just right click and select convert to web application. It will generate all the designer files again.
Step 1: Select all your aspx code, Cut [ CTRL+X ] that code and Save.
Step 2: Again paste the same code in the same page and save again
Now your .desinger page will refresh with all controls in .aspx page.
Delete the designer.cs file and then right click on the .aspx file and choose "Convert To Web Application". If there is a problem with your control declarations, such as a tag not being well-formed, you will get an error message and you will need to correct the malformed tag before visual studio can successfully re-generate your designer file.
In my case, at this point, I discovered that the problem was that I had declared a button control that that was not inside of a form tag with a runat="server" attribute.
This is a bug in the IDE; I've seen it since VS 2003. THe solution is simple though.
Save your files. Completely exit the IDE (make sure the process stops, task mgr.)
Reopen the solution, dirty the markup, save. Fixed.
I had two problems... outdated AJAXControlkit - deleted the old dll, removed old controls from toolbox, downloaded new version, loaded toolbox, and dragged and dropped new controls on the page (see http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Studio_.NET_2005/Q_24591597.html)
Also had misspelling in my label control (had used 'class' instead of 'cssclass').
Ta
I had the problem that my new controls would not generate in the designer file when declared in the .ascx file. The problem was that i declared them in the code behind also. So deleting the declaration in the code behind solved my problem.
If you are like me and you add old .ASPX files to a more recent project.
You are probably going to forget some of the controls used on the page.
If so, first thing, if there are multiple files you are installing;
Fix one at a time first.
When you compile, fix errors generated. They will probably be the same
errors in all the files.
Next, if you have Designer files, delete all of the inserted - designer files.
Next, make sure there are not any other errors when you compile, other than
the designer files.
Finally right click your web project and click on Convert to Web Application.
This will insert the designer files you need.
These are the absolute best steps to fix the issues.
One thing that nobody's mentioned is to visit the page. I had my designer file stop regenerating because I was including a user control that didn't exist (for various reasons), and none of the things suggested here worked. For whatever reason, I didn't get any errors in Visual Studio - besides the one complaining about the fact that my client-side controls didn't exist because they weren't being regenerated, of course.
It took actually visiting the page to get ASP.Net to tell me the error.

Resources