简体   繁体   中英

C# .net web application with dll deployed from matlab

I searched the similar problem on the website which seems a 32/64 bit thing. But I still can't figure it out even by the method provided such as toggling between 86/64 target platform

The software used here are Visual Studio 2010 and Matlab 2015a. I am testing on a very simple Matlab code in a single .m file which is supposed to plot a sine curve in a figure. There is no input or output for this program:

function [] = testPlot()
x = 0:pi/100:2*pi;
y = sin(x);
%Create a line plot of the data.

figure % opens new figure window
plot(x,y)

It is deployed to dll named testPlotN using matlab NE builder (I guess the dll should be 64bit), which is planned to use in ac# web project. I can successfully test it on ac# console application (no matter the target platform is x86 or x64 seemingly)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
using testPlotN; //dll

namespace ConsoleApplication1

{
    class Program
    {
        static void Main(string[] args)
        {
            testP obj = new testP();//class from dll
            obj.testPlot();//matlab function
            Console.ReadKey();
        }
    }
}

However when I test it in ac# web application, with the main file WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        hello my name is<asp:TextBox ID="TextBox1" runat="server" 
            ontextchanged="TextBox1_TextChanged"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="OK" />
        <br />
        <br />
        <br />
        <asp:Label ID="lbloutput" runat="server"></asp:Label>
        <br />

    </div>
    </form>

</body>
</html>

And on click call for the button is in the file WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading.Tasks;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
using testPlotN;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {       
            testP obj = new testP();
            obj.testPlot();
        }
    }
}

When I use choose any cpu by default as platform target when building, it shows the page perfectly without any problem

1

But when I click the button, the error came out

Server Error in '/' Application.
--------------------------------------------------------------------------------


 An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) 
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.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

Source Error: 






Line 36:             testP obj = new testP();
Line 37:             obj.testPlot();
Line 38:         }

Source File: C:\Users\M\Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\WebForm1.aspx.cs    Line: 36 

Stack Trace: 





[BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)]
   MathWorks.MATLAB.NET.Arrays.MWArray.mclmcrInitialize2(Int32 primaryMode) +0
   MathWorks.MATLAB.NET.Arrays.MWArray..cctor() +553

[TypeInitializationException: The type initializer for 'MathWorks.MATLAB.NET.Arrays.MWArray' threw an exception.]
   MathWorks.MATLAB.NET.Utility.MWMCR..cctor() +1864

[TypeInitializationException: The type initializer for 'MathWorks.MATLAB.NET.Utility.MWMCR' threw an exception.]
   testPlotN.testP..cctor() +97

[TypeInitializationException: The type initializer for 'testPlotN.testP' threw an exception.]
   testPlotN.testP..ctor() +0
   WebApplication2.WebForm1.Button1_Click(Object sender, EventArgs e) in C:\Users\M\Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\WebForm1.aspx.cs:36
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9659822
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +108
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639

While I turned to x64 target platform, the first page can not even show up! And the error message appeared immediately

Server Error in '/' Application.
--------------------------------------------------------------------------------


 Could not load file or assembly 'WebApplication2' or one of its dependencies. An attempt was made to load a program with an incorrect format. 
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.BadImageFormatException: Could not load file or assembly 'WebApplication2' or one of its dependencies. An attempt was made to load a program with an incorrect format.

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.


Assembly Load Trace: The following information can be helpful to determine why the assembly 'WebApplication2' could not be loaded.





=== Pre-bind state information ===
LOG: DisplayName = WebApplication2
 (Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: WebApplication2 | Domain ID: 5
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/M/Documents/Visual Studio 2010/Projects/WebApplication2/WebApplication2/
LOG: Initial PrivatePath = C:\Users\M\Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\M\Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\web.config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/M/AppData/Local/Temp/Temporary ASP.NET Files/root/3bb260af/e3ca09a0/WebApplication2.DLL.
LOG: Attempting download of new URL file:///C:/Users/M/AppData/Local/Temp/Temporary ASP.NET Files/root/3bb260af/e3ca09a0/WebApplication2/WebApplication2.DLL.
LOG: Attempting download of new URL file:///C:/Users/M/Documents/Visual Studio 2010/Projects/WebApplication2/WebApplication2/bin/WebApplication2.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.


Stack Trace: 





[BadImageFormatException: Could not load file or assembly 'WebApplication2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +36
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +21
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'WebApplication2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +738
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +217
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +92
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +290
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +531

[HttpException (0x80004005): Could not load file or assembly 'WebApplication2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9920756
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +456



--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.81.0 

I have spent two days to debug this. But I still can't figure it out even by the method provided such as toggling between 86/64 target platform and setting of iis to enable 32 bit application.

Any clue would be much appreciated!

the problem was resolved in my case by enabling Use the 64 bit version of IIS Express for websites and projects

click on tools --> Options --> Projects and Solutions --> Web Projects

Click on the check box to enable Use the 64 bit version of IIS Express for websites and projects

This is likely to do with the version of .NET that you are using and what the DLL was built in. Try adding the following to the configuration file (Web.Config):

<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>

Also, the "Managed Pipeline" should be set to Classic in IIS

I had this same problem with my MatLab to .NET code. Here are two things to look at:

  1. In Visual Studio, under Project Properties --> Build, set the Platform Target to x64. This will get it to work for testing in IIS Express.

  2. When you deploy, make sure your application pool is set to 64bit only by changing Enable 32-Bit Applications to False.

This worked for me when I had this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM