2

I made a web application in Visual Studio 2010 using C# and ASP.NET MVC 4 (mobile template application). Now its worked fine when I have run it through Visual Studio. But now I have hosted it on my site, I keep getting this error:

Server Error in '/test' Application.

Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

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.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

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.

[ReflectionTypeLoadException: Unable to load one or more of the requested types.      Retrieve the LoaderExceptions property for more information.]
System.Reflection.RuntimeModule.GetTypes(RuntimeModule module) +0
System.Reflection.RuntimeModule.GetTypes() +4
System.Reflection.Assembly.GetTypes() +78
System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.<.ctor>b__1(Assembly a) +11
System.Linq.<SelectManyIterator>d__14`2.MoveNext() +238
System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) +395
System.Data.Entity.ModelConfiguration.Mappers.TypeMapper..ctor(MappingContext mappingContext) +253
System.Data.Entity.DbModelBuilder.MapTypes(EdmModel model) +114
System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) +112
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +59
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +62
System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +117
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +453
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +56
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) +67
System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity) +150
System.Data.Entity.DbSet`1.Add(TEntity entity) +42
PrayerTimes.Models.MosqueRepository.AddError(String error) in MosqueRepository.cs:74
PrayerTimes.Controllers.MosqueController.Index() in MosqueController.cs:57
lambda_method(Closure , ControllerBase , Object[] ) +40
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +188
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()+28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult syncResult) +29
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +59
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +240
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +31
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +23
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +128
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50

System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +26 System.Web.Mvc.<>c_DisplayClass1d.b_18(IAsyncResult asyncResult) +14 System.Web.Mvc.Async.<>c_DisplayClass4.b_3(IAsyncResult ar) +25 System.Web.Mvc.Async.WrappedAsyncResult1.End() +55 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +41 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25 System.Web.Mvc.Async.WrappedAsyncResult1.End() +55 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +28 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.<>c_DisplayClass8.b_3(IAsyncResult asyncResult) +28 System.Web.Mvc.Async.<>c_DisplayClass4.b_3(IAsyncResult ar) +25 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +30 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970141 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

I have tried searching online for a solution and I have come across many, which I've tried but nothing seems to work. one of the solutions was to use this:

try
{
 //The code that causes the error goes here.
}
catch (ReflectionTypeLoadException ex)
{
StringBuilder sb = new StringBuilder();
foreach (Exception exSub in ex.LoaderExceptions)
{
    sb.AppendLine(exSub.Message);
    if (exSub is FileNotFoundException)
    {
        FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
        if(!string.IsNullOrEmpty(exFileNotFound.FusionLog))
        {
            sb.AppendLine("Fusion Log:");
            sb.AppendLine(exFileNotFound.FusionLog);
        }
    }
    sb.AppendLine();
 }
 string errorMessage = sb.ToString();
 //Display or log the error based on your application.
 }

I made an error table in my database and tried to add the error from the above code to the table, but that has not worked either. Can any please help? many thanks

archie
  • 179
  • 4
  • 15
  • 1
    Do you have checked your web server settings for .net framework version of the website on your host? it must be equal with .net framework version of your project. – Ramin Bateni Apr 10 '13 at 20:13
  • yes my project and host are both using .NET framework 4 – archie Apr 10 '13 at 20:16
  • 1
    Have you tried publishing a bare-bones MVC4 project? That will at least tell you if the problem is MVC or something specific with your project (like 3rd party dependencies, build configuration, etc.) – Joe Enos Apr 10 '13 at 20:17
  • I havent published a barebones project, so to speak. But the project that isnt working currently was published in its early stages and worked fine before. – archie Apr 10 '13 at 20:21

2 Answers2

5

Often an MVC error while hosting means that MVC is not installed on the server, so it's failing to load one of the required DLLs.

You can get around this by copying all the DLLs to the bin directory of your app.

If you set the "Copy Local" flag to true on the references in your project for the MVC stuff (System.Web.Mvc, System.Web.Routing, etc.), it will copy them to the bin directory for you for publish. There's an easier way, but I forget the shortcut.

EDIT

Here it is - deployable dependency. But if the comments are accurate, this feature was in VS2010, but removed in VS2012, so you'd still have to do the "copy local" thing.

Community
  • 1
  • 1
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • thanks, yes that is one of the solutions that I have come across. I have set all my references to true. – archie Apr 10 '13 at 20:13
  • after using the deployable dependencies option I hosted my application again. I now get this error: Could not load file or assembly 'DotNetOpenAuth.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies. The system cannot find the file specified. – archie Apr 10 '13 at 20:28
  • Booya, there you go. That's a 3rd party library that lives somewhere on your machine, so it just needs to be copied. If it's not referenced directly in your project, it must be indirectly referenced. To get that locally into your bin, you can either add a reference, or create a `_bin_deployableAssemblies` directory in your project and add it there, and it will automatically be copied to bin. – Joe Enos Apr 10 '13 at 20:36
  • do you find "DotNetOpenAuth.Core.dll" in your published website? if not, so copy there... (copy all file in the bin folder on your website project to your host (into bin folder)) – Ramin Bateni Apr 10 '13 at 20:36
  • I have also tried what you said @RAM I copied all files from project bin folder to host bin folder. I am still getting Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. – archie Apr 10 '13 at 21:04
  • Please read this guide page and do it step by step again: http://msdn.microsoft.com/en-us/library/dd410407%28v=vs.90%29.aspx – Ramin Bateni Apr 10 '13 at 21:08
  • this may seem as a really newbie question, but the bin folder in my project solution is whited out. do I have to manually include this is in my project(right click option) before hosting or is it automatically done? – archie Apr 11 '13 at 09:57
  • 1
    In Visual Studio, you don't need to include the bin directory in your project. You only need to include input files (code files, references, etc.). The bin directory is for output files (compiled DLLs). When you publish from Visual Studio, it will publish the files that it needs (web pages, config files, DLLs). For MVC, your published directory should include your Views directory, web.config, global.asax, any content (CSS, JS, images, etc.), and a bin directory containing all of your DLLs (the one for this project, plus each of your references). – Joe Enos Apr 11 '13 at 13:52
  • thanks @joe. Well Ive tried about everything I could Ive had no luck whatsoever. how can I " Retrieve the LoaderExceptions property for more information."? The code above didnt work for me – archie Apr 11 '13 at 17:24
  • 1
    If it still isn't working, I'd have to believe it's got to do with your third-party library - DotNetOpenAuth.Core (that's the only one you mention - if you have more, it could be any of them). It is probably not MVC or ASP.NET or .NET or any framework-related stuff. I think your only course is to either gradually remove (temporarily) things from your project and keep publishing until it works, or start from a clean slate and gradually add things and publish until it doesn't. Once you can prove that it's the library causing the problems, there's a much better chance you'll find an answer. – Joe Enos Apr 11 '13 at 17:32
  • @archie, also test your codes with the instructions of my answer. – Ramin Bateni Apr 11 '13 at 19:01
  • @RAM I have been through the list that you mentioned below, Im still getting the same error – archie Apr 11 '13 at 19:22
2

When you have a website project and every thing is ok on your computer and some things are incorrect on the hosted website, so i suggest you to do the following works:

  • Check .net framework version of your project vs .net framework version of your web server on the host. they must be equal.

  • Copy all referenced file in your project to the hosted web site (local bin ---to---> hosted bin)

    • For this work you can set "Copy To Local" property of each reference in the project to "TRUE". for example for MVC project you can follow this guide page: "Deploy an ASP.NET MVC Application"

    • Find all dependencies of the reference files and copy them to the bin folder on the host (you can use Add Deployable Dependencies feature of VS)

  • Check read and write permission of your files & folders on the host (temp folders, log folders, upload folders and...)

  • Check the project again for change local addresses and convert them to relative address (e:\a\b\website\images\1.jpg... =to=> images\1.jpg OR http:// localhost/images/1.jpg =to=> images/1.jpg)

  • Restart some services (for example web server or...) on the host when you change some base setting (for example .net version).

  • If you are using some COM references so check they are installed on the target machine with same version

EDIT:

    <system.web>
        <securityPolicy>
              <trustLevel name="Full" policyFile="internal"/>
        </securityPolicy>
    </system.web>

Edit: In this issue you can test your code with the following method (by @BenGripka):

This error has no true magic bullet answer. The key is to have all the information to understand the problem. Most likely a dynamically loaded assembly is missing a referenced assembly. That assembly needs to be in the bin directory of your application.

Use this code to determine what is missing.

using System.IO;
using System.Reflection;

try
{
    //The code that causes the error goes here.
}
catch (ReflectionTypeLoadException ex)
{
    StringBuilder sb = new StringBuilder();
    foreach (Exception exSub in ex.LoaderExceptions)
    {
        sb.AppendLine(exSub.Message);
        if (exSub is FileNotFoundException)
        {
            FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
            if(!string.IsNullOrEmpty(exFileNotFound.FusionLog))
            {
                sb.AppendLine("Fusion Log:");
                sb.AppendLine(exFileNotFound.FusionLog);
            }
        }
        sb.AppendLine();
    }
    string errorMessage = sb.ToString();
    //Display or log the error based on your application.
}
Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98
  • this code above, where do I put it? I tried in my controller but it didnt do anything – archie Apr 11 '13 at 19:23
  • also, how will I display errorMessage on screen? I mean after I have published online – archie Apr 11 '13 at 19:37
  • if the name of your controller is "test" use the above template in index action of test controller. put all codes of your action code in the TRY block. then use "return Content(errorMessage);" in the last line of your CATCH block. – Ramin Bateni Apr 12 '13 at 09:46
  • 1
    @archie , i edited my answer. i added a new item to my list ("Trust levels for ASP.NET application"). try it also... – Ramin Bateni Apr 12 '13 at 09:54
  • I cannot return Content(errorMessage); in catch statement because it is expecting return View(); – archie Apr 12 '13 at 09:59
  • I have finally managed to find on of the errors! I put the errorMessage in a Viewbag and returned it to my view to see this error: Could not load type Microsoft.Office.Interop.Excel._Application – archie Apr 12 '13 at 11:08
  • i found the solution to that here: http://stackoverflow.com/questions/5858089/could-not-load-type-microsoft-office-interop-excel-application – archie Apr 12 '13 at 11:09