Search code examples
c#winformsprinting.net-4.0.net-3.5

c# windows microsoft pointofservice System.TypeInitializationException


I have two Windows Forms applications under the same solution.

A.EXE framework is 4.5.2 targeted to x86.

B.EXE framework is 3.5 targeted to x86.

On button click from A.EXE I open B.EXE.

In B.EXE there is a function to print to an EPSON TMT81.

In B.EXE form load I initialize the Printer object...

m_Printer = new ThermalPrinter();

ThermalPrinter class:

string strLogicalName = "PosPrintTMT81";

try
{
    //Create PosExplorer

    PosExplorer posExplorer = new PosExplorer();

    DeviceInfo deviceInfo = null;

    try
    {
        deviceInfo = posExplorer.GetDevice(DeviceType.PosPrinter, strLogicalName);
        m_Printer = (PosPrinter)posExplorer.CreateInstance(deviceInfo);
    }
    catch (Exception ex)
    {
        string strErrorMsg = ex.Message.ToString() 
            + "\n\nPlease rectify the error and try again.";
        LogException(ex);
        return strErrorMsg;
    }

The line PosExplorer posExplorer = new PosExplorer(); returns an error...

System.TypeInitializationException The type initializer for 'Microsoft.PointOfService.Management.Explorer' threw an exception.


Solution

  • A common solution to this issue is to revert to the legacy .NET Code Access Security (CAS) policy by adding the following to your app.config:

    <configuration>  
        <runtime>  
            <NetFx40_LegacySecurityPolicy enabled="true"/>  
        </runtime>  
    </configuration> 
    

    See here & here for more info.

    You could try adding this to the app.config of both apps to see if it resolves the issue. However, this only applies to apps running in .NET 4 & above.

    If changing this setting is not a long term solution for you, then your B app really must run in .NET 3.5 only. So you will need to investigate what is causing it to run in .NET 4.

    Perhaps it's caused by the particular way you are opening app B from A - you could provide that code.

    Or do you have something like the following in your B app.config?...

    <startup>
        <supportedRuntime version="v4.0"/> 
    

    You could also provide the app.config.