CAS .NET 4.0 and RDLC ReportViewer

In .NET 4.0 Code Access Security (CAS) has been deprecated.

Well I never liked CAS very much, so it’s definitely a good thing!
Unfortunately because of that some things are done differently now (in .NET 4.0).

Especially when you use RDLC ReportViewer control.

If you need to use your assembly in ReportViewer (like for example Barcode.dll barcode component) you need to follow this steps:

1.

First make sure that your assembly (Barcode.dll) is registered in GAC (Barcode.dll installer does that).
You can use:
gacutil -l Barcode
to check, and
gacutil -i Barcode.dll
to register.

As Code Access Security was deprecated you have to options:

2a.

You can add NetFx40_LegacySecurityPolicy entry in your App.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <runtime>
   <!-- enables legacy CAS policy for this process -->
   <netFx40_LegacySecurityPolicy enabled="true" />
 </runtime>
</configuration>

and use this code (it is used in samples in Form1_Load method):

// C#

this.ReportViewer1.LocalReport.ExecuteReportInCurrentAppDomain(
  Assembly.GetExecutingAssembly().Evidence);
this.ReportViewer1.LocalReport.AddTrustedCodeModuleInCurrentAppDomain(
  "Barcode, Version=2.0.0.20, Culture=neutral, PublicKeyToken=6dc438ab78a525b3");
this.ReportViewer1.LocalReport.AddTrustedCodeModuleInCurrentAppDomain(
  "System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
' VB.NET

Me.ReportViewer1.LocalReport.ExecuteReportInCurrentAppDomain( _
  Assembly.GetExecutingAssembly().Evidence)
Me.ReportViewer1.LocalReport.AddTrustedCodeModuleInCurrentAppDomain( _
  "Barcode, Version=2.0.0.20, Culture=neutral, PublicKeyToken=6dc438ab78a525b3")
Me.ReportViewer1.LocalReport.AddTrustedCodeModuleInCurrentAppDomain( _
  "System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

or the second approach which is easier:

2b.

Use the following code in Form1_Load method:

// C#

PermissionSet permissions = new PermissionSet(
  PermissionState.Unrestricted);
this.ReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(
  permissions);
' VB.NET

Dim permissions As New PermissionSet( _
  PermissionState.Unrestricted)
Me.ReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain( _
  permissions)

You can find samples how to use Barcode.dll with RDLC in C#, VB.NET in Windows Forms and ASP.NET in the Barcode.dll download package.

Questions?

Consider using our Q&A forum for asking questions.