Publishing Website fails for some pages - c#

I have a strange problem when I publish my website. I inherited this project and the problem started before I arrived so I don't know what conditions lead to the creation of the problem.
Basically, 3 folders below the website project fail to publish properly. When the PrecompiledWeb is transferred to the host these three folders have to be manually copied from the Visual Studio project (i.e. they are no longer the published versions) to the host for it to work.
If the results of the publish operation are left, any page in the folder results in the following error:
Server Error in '/' Application.
Unable to cast object of type
'System.Web.Compilation.BuildResultNoCompilePage'
to type
'System.Web.Compilation.BuildResultCompiledType'.
Description: An unhandled exception
occurred during the execution of the
current web request. Please review the
stack trace for more information about
the error and where it originated in
the code.
Exception Details:
System.InvalidCastException: Unable to
cast object of type
'System.Web.Compilation.BuildResultNoCompilePage'
to type
'System.Web.Compilation.BuildResultCompiledType'.
Source Error:
An unhandled exception was generated
during the execution of the current
web request. Information regarding the
origin and location of the exception
can be identified using the exception
stack trace below.
Stack Trace:
[InvalidCastException: Unable to cast
object of type
'System.Web.Compilation.BuildResultNoCompilePage'
to type
'System.Web.Compilation.BuildResultCompiledType'.]
System.Web.UI.PageParser.GetCompiledPageInstance(VirtualPath
virtualPath, String inputFile,
HttpContext context) +254
System.Web.UI.PageParser.GetCompiledPageInstance(String
virtualPath, String inputFile,
HttpContext context) +171
URLRewrite.URLRewriter.ProcessRequest(HttpContext
context) +2183
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+405 System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
+65
Version Information: Microsoft .NET
Framework Version:2.0.50727.832;
ASP.NET Version:2.0.50727.832
Does anyone have any idea what the possible causes of these pages not publishing correctly could be? Anything I can look at that may indicate the root of the problem?
Addition:
It is a completely clean build each time, so there shouldn't be a problem with old bin files lying around. I've also checked the datestamp on the items in the bin folder and they are up-to-date.
Second Addition:
The project was originally created as a Web Site, not a Web Application. Sorry for the ambiguity.

You might look into trying Microsoft's Web Deployment Projects. They give you much more control over MSBuild, essentially, but it might help solve your deployment/pre-compiling woes.
Are we to infer you are using a Web Site project type (and not Web Application)?

Im guessing that because when you publish, it is compiling your Web Site project and it is hitting a duplicate class name somewhere across different folders or sub folders. Make sure you check your inherit tags and class names so that you dont call 2 classes the same thing. This is fine and wont error when it happens in different folders when coding and debugging, but when you go to publish / deploy it will error. ... Hope that makes sense.

I would try cleaning the bin\ folder.
In any case our shop completely dropped websites in favour of web form applications, which are arguably far better.
EDIT: Migration HOW TO here

I had a similar problem a while back, where the publish would say it was successful, but the publish folder remained empty.
Besides looking at the Web Deployment Projects you should also set the verbosity to Diagnostic (Tools=> Options=>Project and Solutions =>Build and Run=> Msbuild project build output verbosity)
This, in my case had the effect of displaying meaningful compiler errors that helped me resolve the issue.
You could then also run the aspnet_compiler with the -errorstack directive in the shell prompt to display additional errors.

The best answer for this please open you web.config file and add below two setting add in the compilation tag
<compilation targetFramework="4.0" debug="false" batch="false">
Keep coidng, Also i tried following things when i get the same error in my application which i tried to host in the server
1.Click Start, click Run, type iisreset /stop, and then click OK.
2.Open the C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files directory.
3.Delete all files and all folders in the directory that you located in step
4.Click Start, click Run, type iisreset /start, and then click OK.
5.Do a build again and then try to access your site.

Related

How to dynamically Load in Mvc Controllers from a Nuget package. Docker Container Issue

I have multiple microservice endpoints (Gateway) that share common MVC controllers. I would like to extract these controllers to a Nuget package so that they can be shared across the projects and use FeatureManagement to enable/disable the controllers/methods.
Referencing a library directly (same solution) works as intended.
The controller assembly loads and is added via the code below:
services.AddMvc()
.AddApplicationPart(Assembly.LoadFrom($"{Location}/{Configuration["ControllerLibrary"]}"))
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
The first issue I had when extracting the lib to Nuget was the .dll. I had to add the following to the .csproj file.
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
This is a bit heavy (a blanket copy all) but acceptable but also was the first 'code-smell' that caused me to feel I was approaching this the wrong way.
The issue occurs when running inside a docker container as the reference location doesn't appear to be the same as when running in windows(IIS/IISExpress)/LXC containers.
When running (attempting to run) inside a docker container, I get the following error:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly '/app/xxx.xxx.Endpoints.Mvc.dll'. The system cannot find the file specified.at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly)
at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
at System.Reflection.Assembly.LoadFrom(String assemblyFile)
at xxx.xxx.Client.Startup.ConfigureServices(IServiceCollection services) in /src/xxx.xxx.Client/Startup.cs:line 25
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at xxx.xxx.Client.Program.Main(String[] args) in /src/xxx.xxx.Client/Program.cs:line 10
As the container cannot start, I am unable to enter the file director/bash in to see what's going on but understand that the dll isn't where I am expecting it to be (the same location as the executing dll).
private static readonly string Location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
I am a novice with Docker but haven't found anything that would enable me to easily debug the issue.
Firstly, I would like to find out why the different behaviour so I can better understand docker and any potential resolutions. Also, it would be nice to see if I am approaching this the right way or if there are better alternatives (It is starting to feel like a bit of a hack/convoluted workaround).
Thanks for taking the time to read :)
Well, this is embarrassing.
The issue turned out to be that the context inside the docker container did not have permission to access the Nuget feed (Hosted in Azure Dev Ops). As such, the file could not be found was because the restore was failing but NOT causing a breaking/the final error (it did list the error in the console).
The error in the original post was a symptom of this, becoming a little bit of a red herring as I didn't examine the console closely enough.
I needed to add a NuGet.config file (pointer and user/PW), along with the reference to copy it to the correct location (dockerfile) in the docker container.
However, that wasn't the end of the story as it appears our private NuGet server (Azure Dev Ops) had some weird security permissions set somewhere for users. We needed to use the admin account in the end (via key/token) to finally get it to work.

Unable to create ASP.NET Core Web Application but not getting error message

When I try to create a ASP.NET Core Web Application project, I get to choose a template, but all I get is an empty solution with no projects added. If I try to add a new project, the same thing occurs. I do not get any error messages for most of the templates (such as Web application which I'm trying to start), if I choose "Razor Class Library" I get the an error referencing to the ActivityLog.xml which has this as the latest entry:
System.ArgumentException: Value does not fall within the expected
range.
at
Microsoft.VisualStudio.Web.Interop.IVsClientBuildManagerService.DispatchUserWorkItem(IVsClientBuildManagerEventSink
sink)
at
Microsoft.VisualStudio.Html.Package.CBM.CBMWorkItemDispatcher1.Dispatch(ITextBuffer
textBuffer, Func1 toExecute, Action1 callback)
at
Microsoft.VisualStudio.Html.Package.Razor.RazorImportsProvider.Microsoft.Html.Editor.ContainedLanguage.Razor.Def.IRazorImportsProvider.GetImportsAsync(ITextBuffer
textBuffer, Func1 toExecute, Action`1 callback)
at
Microsoft.VisualStudio.Web.Razor.Implementation.Shims.RazorCodeGenerator.DispatchGetRazorNamespacesWorkItem()
at
Microsoft.VisualStudio.Web.Razor.Implementation.Shims.RazorCodeGenerator.<.ctor>b__24_0()
at
Microsoft.Web.Editor.Utility.GuardedOperations.InvokeExtensionPoint(Object
errorSource, Action action)
--- End of stack trace from
previous location where exception was thrown ---
at
Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception
exceptionObject)
How I got here:
I had a working VS2017 installation without ASP.NET Core & Web workload. I installed the latest version of the .NET Core SDK, then I upgraded to the latest version of VS2017 and included the ASP.NET Core & Web workload as well as the Blazor Language Services extension as described here.
What I've tried:
After this, I couldn't create any projects at all and got errors for Unsupported Project Types, same even for my my old C# projects. I searched extensively and eventually uninstalled everything and reinstalled twice, but the same errors. So I uninstalled again, using all the cleaner tools, ran the console with the reconfigure commands, installcleaner commands and everything I could find as well as removing the VS directories and appdata directories. After that I am where I am now. I would think I have a very clean VS installation, now regular console applications and winforms applications work, but no the .NET Core Web applications.
How can I get this fixed? How can I generate a better log file to attach here for more information?
Edit:
When I check the solution directory, a project is being created but not added, if I try to add this as existing project I get the following error message:
Expected 1 export(s) with contract name
"Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.ProjectFactory+ProjectLoadHelper"
but found 0 after applying applicable constraints.
Add MvcRazorCompileOnPublish in your Project
<PropertyGroup>
<MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
</PropertyGroup>
Finally this was fixed after completely uninstalling, cleaning up visual studio directories (and AppData) and reinstalling, and then again clearing the folder found in:
%AppData%\Local\Microsoft\VisualStudio\15.0_7cfaf63e\ComponentModelCache
Even though I had done this step before, this is what finally fixed it for me. An important note here is to clear the folder found in the Local AppData folder, most answers I've found only reference the Roaming folder, so to be sure it's a good idea to clear all of them. I hope this helps someone else in a similar situation!

Orchard CMS failing to discover resources defined in a theme after Publish from Visual Studio

So, I tried to Publish (both Web Deploy and File System) an Orchard instance. I have quite a few custom modules and a custom theme. I have ResourceManifest : IResourceManifestProvider in my theme's project. Yes the theme has its own project and it is included in the solution.
The Scripts and Styles I defined are working beautifully when I debug it and work on my dev environment. So far so good.
Today I tried to setup a test environment of the current version. So I tried to get only the most essential without copy/pasting the whole folder structure. Naturally I tried to Publish the Orchard.Web project. And after a short struggle to get right permissions applied...it worked and I could access the site. Unfortunately when I navigated to one of my custom pages that has Style.Require("Resource defined in the theme") it crashed with an error message that a resource with the name "bla bla" cannot be found.
I tried to Publish both a Debug and a Release configuration but it didn't help. I tried to move the styles from the Theme project to a more concrete CustomModule but it didn't discover it.
Could it be some caching? Should I restart the IIS or only the WebSite in IIS? Somehow these new definitions cannot be detected.
In the end I tried to use Style.Include and it seemed that it won't crash, only to see that when I navigate to my page I receive "The page does not exist message" in the Content area (at least didn't crash)...
I am totally lost with this issue. Any help would be appreciated. I can give you more detailed info just let me know what.
I am running Orchard v.1.8.1.0.
This is my code:
manifest.DefineScript("Bootstrap").SetUrl("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js");
manifest.DefineStyle("Bootstrap").SetUrl("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css");
Error message:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: A 'stylesheet' named 'Bootstrap' could not be found. at Orchard.UI.Resources.ResourceManager.BuildRequiredResources(String resourceType) in
EDIT 03.01.2017
I have abandoned my efforts for quite a while. Today I decided to start battling it again and I found the following:
I moved the resource definitions from the MyThemeProject/ResourceManifest.cs to NonThemeCustomModule/ResourceManifest.cs file (one that I wrote).
I Rebuild and Re-Published using Web Deploy
And it was working!!!!
Which is pretty cool and solves my issue, BUT also is quite unexpected, since I have the same definitions twice and Orchard doesn't complain about it. Which leads me to believe that the ResourceManifest file in the theme is not taken into account for some reason. If anyone from the Orchard team can tell me what I am doing wrong, or if it is a bug of Orchard, that would be great.
Cheers!
I've encouter this situation a couple of time with a different scenario tho. In Orchard the application pool may need to have the rights on the folder where ur ressources are stored. Add it to ur security folder, it may be the problem.

Catch exceptions in ASP.NET resulting from Generic Handler (ashx) file

I am trying to get a different server side stack functioning with my ASP.NET site. My ashx file seems to be throwing a 500 Internal Server Error. How do I figure out what exception this ashx file is throwing or the reason the 500 is being thrown? When I attach to my IIS 7 w3wp.exe process, it doesn't throw an exception, but I'm reading that this is likely the case.
The ashx file lives in the root directory of my ASP.NET site, and the Properties have it set to compile.
GET http://uhc-8:8883/MyApp/ExtDirectProxy.ashx 500 (Internal Server Error) index.html:27
Uncaught TypeError: Cannot read property 'isProvider' of null ext-all-debug.js:74832
allow right click initializing for http://uhc-8:8883/MyApp/index.html rightclick.js:1
allow right click processing http://uhc-8:8883/MyApp/index.html rightclick.js:25
If you have a folder called "App_Code", you can go through headaches
and migranes. Or simply replace "App_Code" with some random name like
"code" or "data" and put your classes in there to fix this. In my
case, my project GUID was a Web Application and C# type.
Best Answer:
App_Code folder issues
Note:
I am running the site using IIS with a static port, not using Visual Studio 2012 with a dynamic port. I have specific server configuration on the web server, so I want the site to behave the same way our released site works. So that's why I run it like that.
Answer to my question:
This occurred because we had duplicate versions of the App_Data classes in the bin folder. The "Compile" version of the *.cs, and the website version of the *.cs. The “isProvider” error happens when more than one class with the same name exists. When we deploy the ASP.NET application, we deploy ONLY the compiled version of the *.cs files. The development environment, we keep them set to Properties > Build Action > None.
Not sure of an easy way around that. It might have to do with having things in the temporary and/or obj folder, but not sure exactly. Will take a little more troubleshooting to discover why. In the mean time, here is a list of things to resolve the issue. Not sure if some or all of these were necessary, but it's working now.
Steps to fix:
change all App_Data *.cs files to Properties > Build Action > Compile
Fix exceptions they throw to get that build working again - Clean Solution > Build Solution ... one exception was not caught with those set to Properties > Build Action > None, so that's why this was necessary. Essentially, Visual Studio 2012 does not throw an exception and says "Build Successful".
then change App_Data *.cs files back to Properties > Build Action > None
remove dlls out of \obj\Debug
remove dlls out of \bin
remove temporary ASP.NET files - C:\WINDOWS\Microsoft.NET\Framework\{.NET version}\Temporary ASP.NET Files\
Build Solution
restart IIS web site
Now things work great!
EDIT:
Actual problem was that I was referencing an external project in Visual Studio, but there was no dll file for it because the project type was Console Application, not Class Library. The real problem was that Visual Studio says it compiles the code fine (in App_Code) when you have a using statement to that other project, but says Built Successfully, even when the Build Action > Compile option is set for all *.cs files in App_Code. When you run the web application, it has to be set back to Build Action > None for it to work. However, since the *.cs files in App_Code didn't actually compile with the new code (if that's how ASP.NET in IIS treats these App_Code *.cs files), it throws the 500 Internal Server error because there's no good CIL code during runtime. To solve it, I just changed the project type to Class Library, and it still has no errors, but now it can reference the dll to the other project.
The isProvider error always occurs when there are duplicate classes found. So I'm not sure why that occurs, but that essentially goes away once you fix the part above.
You can use the Application_Error event in Global.asax file to catch that error.
protected void Application_Error(Object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
Exception exception = ctx.Server.GetLastError();
int httpCode = ((HttpException)exception).GetHttpCode(); // check if it is 500
}

ASP.NET corrupt assembly "Could not load file or assembly App_Web_*"

I've read through many of the other questions posted on the same issue, but I still do not understand the cause and how to prevent it from happening.
In my case, this happens on the production server. I get the same error that has been described in other questions, and I resolve it by re-copying the assemblies into the bin directory. They are not even recompiled files, they are the same ones that were in there before - copied in again, and then it starts working without problems.
The weird part of it is that I am using Web Deployment Projects to rename all of my assembly files into folder-based dll's. So folder.dll and folder.subfolder.dll instead of App_Web_jt8nxllz.dll. Yet the error still names the original App_Web_jt8nxllz.dll file.
Deleting the contents of the C:\WINDOWS\Microsoft.NET\Framework[64]\v...\Temporary ASP.NET Files folder works and is all fine, but does anyone know how to prevent this error from happening? Also, shutting down IIS or restarting it is really not so feasible when it's happening on the production server. Perhaps cleaning out the Temp folder on a scheduler automatically?
What is the real issue here? Is there something in particular that causes this to happen? The site will be humming along no problem at all, and then all of the sudden, one entire folder stops working and produces this error.
Could not load file or assembly 'App_Web_jt8nxllz, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Exception type 'System.IO.FileNotFoundException' was caught.
Source: App_Web_whv5zsvd
Target Site: Void __BuildControlTree(ASP.artists_controls_artistheader_ascx)
Stack Trace:
at ASP.artists_controls_artistheader_ascx.__BuildControlTree(artists_controls_artistheader_ascx __ctrl)
at ASP.artists_controls_artistheader_ascx.FrameworkInitialize()
at System.Web.UI.UserControl.InitializeAsUserControlInternal()
at System.Web.UI.UserControl.InitializeAsUserControl(Page page)
at ASP._artists_artist_master.__BuildControlctlArtistHeader()
at ASP._artists_artist_master.__BuildControlctlContent(Control __ctrl)
at System.Web.UI.CompiledTemplateBuilder.InstantiateIn(Control container)
at ASP.master_mysite_master.__BuildControlMainContent()
at ASP.master_mysite_master.__BuildControlform1()
at ASP.master_mysite_master.__BuildControlBody()
at ASP.master_mysite_master.__BuildControlTree(master_mysite_master __ctrl)
at ASP.master_mysite_master.FrameworkInitialize()
at System.Web.UI.UserControl.InitializeAsUserControlInternal()
at System.Web.UI.MasterPage.CreateMaster(TemplateControl owner, HttpContext context, VirtualPath masterPageFile, IDictionary contentTemplateCollection)
at System.Web.UI.MasterPage.get_Master()
at System.Web.UI.MasterPage.ApplyMasterRecursive(MasterPage master, IList appliedMasterFilePaths)
at System.Web.UI.Page.ApplyMasterPage()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Not to just link up my site but i have run into this issue and i wrote a blog post on the topic. Check it out, it has links to more info on this topic. But to sum it up here are the details:
Problem:
The website is throwing an error trying to load a custom web control. You see in the last release, we added a new custom control to another custom web control that is displayed as needed. Because the outer most/parent control and the new child control are separate controls in source, when the .Net Framework goes to compile one of these two controls and does not recompile the other one at the same time you will have a an out of date file trying to reference the old version of the assembly. The fact that the .Net framework appends a random string to the name of the assembly at compile time the name of the newly compiled file and the previous version of the file cause a file name mismatch and therefore the outer/parent control is looking for a file that no longer exists.
Possible Work Around(s) or Temporary Fixes:
1) By setting the batch property of the compilation tag to false in the web.config file
<compilation debug="false" batch="false" />
2) You can also decrease how often it happens by setting by the numRecompileBeforeAppRestart property:
<compilation debug="false" numRecompilesBeforeAppRestart="50" />
See the KB Article 934839 for more details
Fixes for the Issue after it has already taken place:
1) Delete temp ASP.Net files (this takes down the site)
2) Force the parent/outter control to recompile, edit and save the code file. This is a better option for a fix than #1 because this does not bring down the website.
My Suggestion:
1) First I think that we should put in place the temporary fix #1 from above, this might prevent all issues in the future and could be the only answer we need.
2) Second I would download and install the 934839 hotfix from Microsoft in the QA environment to verify that it does not cause any problems. After some time of testing the hotfix in QA I would install the hotfix to have a permanent fix for this issue. At this time we could remove the temporary work around #1.
Note:
After putting Temp fix #1 I have not had the problem again. I have had this fix in place for over 12 months and all is good!
I've been hit with this, there is a hotfix for it.
http://weblogs.asp.net/scottgu/archive/2007/04/11/public-hotfix-patch-available-for-asp-net-compilation-issues.aspx
Although it doesn't happen with newer machines/setups anymore.
Clearing out the temp files or changing web.config didn't work for me. For me, what fixed it was restarting my computer.

Categories

Resources