C#: Unhandled exception. System.TypeLoadException: Could not load type 'System.Drawing.Color' - c#

ANSWER for this question thanks to Jeremy C.:
There is no KeePass nuget package for the Net5.0 yet. Thats why there is that error message. Thanks Jeremy C. for the help and answers.
QUESTION:
Im getting this error after starting my solution.
Unhandled exception. System.TypeLoadException: Could not load type 'System.Drawing.Color' from assembly 'Splat, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null'.
Already used google and tried to find a fix for it and also red all articles about similiar errors like "System.Drawing.Font" or "System.Drawing.Image". But theres nothing really helpful and nothing really informative about 'System.Drawing.Color'.
Ive got the code example and package from here:
github.com/wismna/ModernKeePassLib
This is my code:
.csproj
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ModernKeePassLib" Version="2.45.1" />
<PackageReference Include="System.Drawing.Common" Version="5.0.2" />
</ItemGroup>
</Project>
And:
using ModernKeePassLib;
using ModernKeePassLib.Interfaces;
using ModernKeePassLib.Keys;
using ModernKeePassLib.Serialization;
using System;
using System.Linq;
using System.Text;
namespace KeePasso
{
class Program
{
static void Main()
{
var dbpath = #"C:\Users\prusinma\Desktop\KeePassDatabase\Database.kdbx";
var keypath = #"C:\Users\prusinma\Desktop\KeePassDatabase\Database.key";
var masterpw = "1234abcd";
Console.WriteLine("init done");
byte[] DBPathBytes = Encoding.ASCII.GetBytes(dbpath);
byte[] KeyPathBytes = Encoding.ASCII.GetBytes(keypath);
var ioConnection = IOConnectionInfo.FromByteArray(DBPathBytes);
var compositeKey = new CompositeKey();
compositeKey.AddUserKey(new KcpPassword(masterpw)); // Password
compositeKey.AddUserKey(new KcpKeyFile(IOConnectionInfo.FromByteArray(KeyPathBytes))); // Keyfile
var db = new PwDatabase();
db.Open(ioConnection, compositeKey, new NullStatusLogger());
var kpdata = from entry in db.RootGroup.GetEntries(true)
select new
{
Group = entry.ParentGroup.Name,
Title = entry.Strings.ReadSafe("Title"),
Username = entry.Strings.ReadSafe("UserName"),
Password = entry.Strings.ReadSafe("Password"),
URL = entry.Strings.ReadSafe("URL"),
Notes = entry.Strings.ReadSafe("Notes")
};
db.Save(new NullStatusLogger());
var contents = db.IOConnectionInfo.Bytes;
string bitString = BitConverter.ToString(contents);
Console.WriteLine(bitString);
Console.WriteLine(kpdata.ToString());
}
}
}

Those classes were moved into their own nuget package. Add it to your project and you should be good to go: https://www.nuget.org/packages/System.Drawing.Common/
From the project directory at the command line:
dotnet add package System.Drawing.Common
Closer inspection reveals ModernKeepPass targets.netstandard1.2 and will not work with 5's System.Drawing nuget package without being upgraded to target the new framework.
https://github.com/wismna/ModernKeePassLib/blob/master/ModernKeePassLib/ModernKeePassLib.csproj
<PropertyGroup>
<TargetFramework>netstandard1.2</TargetFramework>

Related

Roslyn fails to compile a trivial project

I am trying to use Roslyn to compile a trivial project but it fails.
Consider the following setup (assuming c:\temp exists and you have .NET 6 installed):
mkdir c:\temp\TestLib
notepad c:\temp\TestLib\TestLib.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
notepad c:\temp\TestLib\SomeClass.cs
namespace TestLib
{
public class SomeClass
{
void DoThings()
{
Console.WriteLine("Things!");
}
}
}
cd c:\temp\TestLib
dotnet build
Result: Build succeeded
mkdir c:\temp\RoslynTrouble
notepad c:\temp\RoslynTrouble\RoslynTrouble.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build.Locator" Version="1.5.5" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.8.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="3.8.0" />
</ItemGroup>
</Project>
notepad c:\temp\RoslynTrouble\Program.cs
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis.MSBuild;
class TestProgram
{
public static async Task Main(string[] args)
{
string csprojPath = args[0];
var instance = MSBuildLocator.RegisterDefaults();
Console.WriteLine(instance.Name + ": " + instance.Version);
var workspace = MSBuildWorkspace.Create();
var project = await workspace.OpenProjectAsync(csprojPath);
var compilation = await project.GetCompilationAsync();
if (compilation == null)
{
Console.WriteLine("Error: unexpected null compilation");
return;
}
foreach (var diagnostic in compilation.GetDiagnostics())
{
Console.WriteLine(diagnostic);
}
}
}
cd c:\temp\RoslynTrouble
dotnet run c:\temp\TestLib\TestLib.csproj
Expected result: no errors
Actual result: lots of compilation errors:
.NET Core SDK: 6.0.203
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(2,1): error CS0116: A namespace cannot directly contain members such as fields or methods
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(3,1): error CS0116: A namespace cannot directly contain members such as fields or methods
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(4,1): error CS0116: A namespace cannot directly contain members such as fields or methods
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(5,1): error CS0116: A namespace cannot directly contain members such as fields or methods
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(6,1): error CS0116: A namespace cannot directly contain members such as fields or methods
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(7,1): error CS0116: A namespace cannot directly contain members such as fields or methods
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(8,1): error CS0116: A namespace cannot directly contain members such as fields or methods
c:\open\prototypes\TestLib\SomeClass.cs(7,13): error CS0103: The name 'Console' does not exist in the current context
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(2,8): hidden CS8019: Unnecessary using directive.
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(8,8): hidden CS8019: Unnecessary using directive.
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.AssemblyInfo.cs(11,1): hidden CS8019: Unnecessary using directive.
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(7,8): hidden CS8019: Unnecessary using directive.
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(6,8): hidden CS8019: Unnecessary using directive.
c:\open\prototypes\TestLib\obj\Debug\net6.0\.NETCoreApp,Version=v6.0.AssemblyAttributes.cs(2,1): hidden CS8019: Unnecessary using directive.
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(3,8): hidden CS8019: Unnecessary using directive.
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.AssemblyInfo.cs(12,1): hidden CS8019: Unnecessary using directive.
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(4,8): hidden CS8019: Unnecessary using directive.
c:\open\prototypes\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(5,8): hidden CS8019: Unnecessary using directive.
c:\open\prototypes\TestLib\obj\Debug\net6.0\.NETCoreApp,Version=v6.0.AssemblyAttributes.cs(3,1): hidden CS8019: Unnecessary using directive.
What am I missing and how can I fix those errors?
Below you'll find the modifications described in a Note. Try the following:
mkdir c:\temp\TestLib
notepad c:\temp\TestLib\TestLib.csproj
Click Yes
TestLib.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
Save As (save with "UTF-8" encoding)
notepad c:\temp\TestLib\SomeClass.cs
Click Yes
SomeClass.cs:
Note: Made the method public - not much point in having a class with one method and making it private.
namespace TestLib
{
public class SomeClass
{
public void DoThings()
{
Console.WriteLine("Things!");
}
}
}
Save As (save with "UTF-8" encoding)
mkdir c:\temp\RoslynTrouble
notepad c:\temp\RoslynTrouble\RoslynTrouble.csproj
Click Yes
RoslynTrouble.csproj:
Note: Use version 4.4.0 for Microsoft.CodeAnalysis.CSharp.Workspaces and Microsoft.CodeAnalysis.Workspaces.MSBuild.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build.Locator" Version="1.5.5" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="4.4.0" />
</ItemGroup>
</Project>
Save As (save with "UTF-8" encoding)
notepad c:\temp\RoslynTrouble\Program.cs
Click Yes
Program.cs:
Note: Added namespace RoslynTrouble. Changed class name to Program to match the filename (Program.cs).
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis.MSBuild;
namespace RoslynTrouble
{
public class Program
{
public static async Task Main(string[] args)
{
string csprojPath = args[0];
var instance = MSBuildLocator.RegisterDefaults();
Console.WriteLine(instance.Name + ": " + instance.Version);
var workspace = MSBuildWorkspace.Create();
var project = await workspace.OpenProjectAsync(csprojPath);
var compilation = await project.GetCompilationAsync();
if (compilation == null)
{
Console.WriteLine("Error: unexpected null compilation");
return;
}
foreach (var diagnostic in compilation.GetDiagnostics())
{
Console.WriteLine(diagnostic);
}
}
}
}
Save As (save with "UTF-8" encoding)
cd c:\temp\RoslynTrouble
dotnet run "C:\temp\TestLib\TestLib.csproj"
Note: The double-quotes in the command above are optional since there aren't any spaces in the path.
Result:
Note: The result has warnings, but no errors.
.NET Core SDK: 6.0.301
C:\temp\TestLib\obj\Debug\net6.0\.NETCoreApp,Version=v6.0.AssemblyAttributes.cs(2,7): hidden CS8933: The using directive for 'System' appeared previously as global using
C:\temp\TestLib\obj\Debug\net6.0\TestLib.AssemblyInfo.cs(10,7): hidden CS8933: The using directive for 'System' appeared previously as global using
C:\temp\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(5,1): hidden CS8019: Unnecessary using directive.
C:\temp\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(3,1): hidden CS8019: Unnecessary using directive.
C:\temp\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(4,1): hidden CS8019: Unnecessary using directive.
C:\temp\TestLib\obj\Debug\net6.0\TestLib.AssemblyInfo.cs(11,1): hidden CS8019: Unnecessary using directive.
C:\temp\TestLib\obj\Debug\net6.0\.NETCoreApp,Version=v6.0.AssemblyAttributes.cs(2,1): hidden CS8019: Unnecessary using directive.
C:\temp\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(8,1): hidden CS8019: Unnecessary using directive.
C:\temp\TestLib\obj\Debug\net6.0\.NETCoreApp,Version=v6.0.AssemblyAttributes.cs(3,1): hidden CS8019: Unnecessary using directive.
C:\temp\TestLib\obj\Debug\net6.0\TestLib.AssemblyInfo.cs(10,1): hidden CS8019: Unnecessary using directive.
C:\temp\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(7,1): hidden CS8019: Unnecessary using directive.
C:\temp\TestLib\obj\Debug\net6.0\TestLib.GlobalUsings.g.cs(6,1): hidden CS8019: Unnecessary using directive.
If one would like to avoid displaying warnings, one could use the following alternative code for Program.cs:
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis.MSBuild;
namespace RoslynTrouble
{
public class Program
{
public static async Task Main(string[] args)
{
bool errorsExist = false;
string csprojPath = args[0];
var instance = MSBuildLocator.RegisterDefaults();
Console.WriteLine(instance.Name + ": " + instance.Version);
var workspace = MSBuildWorkspace.Create();
var project = await workspace.OpenProjectAsync(csprojPath);
var compilation = await project.GetCompilationAsync();
if (compilation == null)
{
Console.WriteLine("Error: unexpected null compilation");
return;
}
foreach (Microsoft.CodeAnalysis.Diagnostic diagnostic in compilation.GetDiagnostics())
{
if (diagnostic.Severity != Microsoft.CodeAnalysis.DiagnosticSeverity.Hidden &&
diagnostic.Severity != Microsoft.CodeAnalysis.DiagnosticSeverity.Warning)
{
Console.WriteLine(diagnostic);
errorsExist = true;
}
}
if (!errorsExist)
Console.WriteLine($"Successfully compiled '{args[0]}'.");
}
}
}
Resources:
Roslyn Code Analysis returns false build errors from an error free solution

Uploading to Azure File Share from a Razor Page

I am trying to find an example of uploading a file to an Azure file share or blob storage from a razor page. I use this code from the tutorial
but this copy files only to the local filesystem.
Now I found the article here on stackoverflow, but it won't work. I got the error in line
var storageAccount = CloudStorageAccount.Parse(< your creds here>);
the name "CloudStorageAccount does not exist in the current context"
I am using Visual Studio 2022, .Net Core 2.2. Any help would be much appreciated.
Initially even I got the error.
The NuGet package required for CloudStorageAccount is WindowsAzure.Storage.
But in Package Manager you can see WindowsAzure.Storage is deprecated.
You can also see the alternate package Azure.Storage.Blobs is mentioned.
Install the latest Azure.Storage.Blobs NuGet package.
When I tried to Install Azure.Storage.Blobs package, got the below error.
"System.IO.Hashing doesn't support $(TargetFramework). Consider >updating the TargetFramework to netcoreapp3.1 or later." />
The error clearly says to update and use the .NET Core latest version.
I am able to clear the issue in .Net Core 2.1 by installing the below NuGet Package.
Microsoft.Azure.Storage.DataMovement
Add the using namespace using Microsoft.Azure.Storage
My .csproj file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.Azure.Storage.DataMovement" Version="2.0.4" />
</ItemGroup>
</Project>
My Conroller.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.File;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using WebAppMVC.Models;
namespace WebAppMVC.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
if (file != null)
{
using (var stream = new MemoryStream())
{
try
{
await file.CopyToAsync(stream);
stream.Seek(0, SeekOrigin.Begin);
var filename = file.FileName;
var storageAccount = CloudStorageAccount.Parse("YOUR CREDS HERE");
var client = storageAccount.CreateCloudFileClient();
var shareref = client.GetShareReference("YOUR FILES SHARE");
var rootdir = shareref.GetRootDirectoryReference();
var fileref = rootdir.GetFileReference(filename);
await fileref.DeleteIfExistsAsync();
await fileref.UploadFromStreamAsync(stream);
return Ok(new { fileuploaded = true });
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
}
else
{
return BadRequest(new { error = "there was no uploaded file" });
}
}
}
}

Edit and Continue doesn't work with Roslyn compiled class library

Background
I'm trying to get Edit and Continue to work with a class library I'm compiling at runtime using Roslyn. This is for adding modding support to a game I'm developing.
Breakdown of problem
I have one class library project (A) with source files (.cs)
I have another console application project (B) in another solution that does the following:
Compiles all of project A's source files
Emits a dll and pdb
Loads the emitted dll and pdb via an assembly context
Calls a static method defined within project B
My desire is to be able to attach a debugger to a running process of project B in an instance of VS with project A loaded and be able to break, edit project A's code, and continue with my changes being executed
Currently, I am only able to break and continue
Any edits lead to the following notification:
This source file has changed. It no longer matches the version of the file used to build the application being debugged.
Source
Project A: DebuggableClassLibrary.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
Project A: Test.cs
using System;
namespace DebuggableClassLibrary
{
public class Test
{
public static int Ct = 0;
public static void SayHello()
{
Ct++;
Console.WriteLine("Hello World");
}
}
}
Project B: DynamicLoading.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" />
</ItemGroup>
</Project>
Project B: Program.cs
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
namespace DynamicLoading
{
class Program
{
static void Main(string[] args)
{
var references = new MetadataReference[]
{
MetadataReference.CreateFromFile(Assembly.Load("System.Runtime").Location),
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Console).Assembly.Location)
};
var files = Directory.GetFiles(#"C:\Users\mrbri\source\repos\DebuggableClassLibrary\DebuggableClassLibrary", "*.cs");
var assemblyName = "DebuggableClassLibrary.dll";
var debug = true;
var allowUnsafe = false;
var outputDirectory = #"C:\Users\mrbri\Documents\Test";
var preprocessorSymbols = debug ? new string[] { "DEBUG" } : new string[] { };
var parseOptions = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: preprocessorSymbols);
var compilation = CSharpCompilation.Create(
assemblyName: assemblyName,
syntaxTrees: files.Select(f => SyntaxFactory.ParseSyntaxTree(File.ReadAllText(f), parseOptions, f, Encoding.UTF8)),
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
optimizationLevel: debug ? OptimizationLevel.Debug : OptimizationLevel.Release,
allowUnsafe: allowUnsafe
));
var pePath = Path.Combine(outputDirectory, assemblyName);
var pdbPath = Path.Combine(outputDirectory, Path.ChangeExtension(assemblyName, ".pdb"));
using (var peStream = new FileStream(pePath, FileMode.Create))
using (var pdbStream = new FileStream(pdbPath, FileMode.Create))
{
var results = compilation.Emit(
peStream: peStream,
pdbStream: pdbStream,
options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)
);
}
var assemblyLoadContext = new SimpleUnloadableAssemblyLoadContext();
var assembly = assemblyLoadContext.LoadFromStream(File.OpenRead(pePath), File.OpenRead(pdbPath));
var type = assembly.GetTypes().First();
var method = type.GetMethod("SayHello");
while (true)
{
method.Invoke(null, null);
}
}
}
internal class SimpleUnloadableAssemblyLoadContext : AssemblyLoadContext
{
public SimpleUnloadableAssemblyLoadContext(): base(true) { }
protected override Assembly Load(AssemblyName assemblyName) => null;
}
}
Attempts at solutions and observations
Compiling project A manually through VS and loading the generated pdb and dll exactly as I do for the Roslyn compiled one does allow for Edit and Continue
Comparing project A's dlls generated via Roslyn and VS in JetBrains dotPeek did yield some interesting differences that stem from the compilation time generated .NETCoreApp,Version=v5.0.AssemblyAttributes.cs and DebuggableClassLibrary.AssemblyInfo.cs that I do not include when I compile in project B
Going through the trouble of compiling project A via a MSBuildWorkspace Project did not allow Edit and Continue, although did include .NETCoreApp,Version=v5.0.AssemblyAttributes.cs and DebuggableClassLibrary.AssemblyInfo.cs
Alternatives
I am open to Roslyn alternatives/wrappers that do have Edit and Continue support.
Edit and Continue does not support this scenario. The project for the library being edited needs to be loaded in VS (in the current solution) and the program needs to be launched with the debugger attached.

AWS .NET SDK SimpleEmail SendEmail returning 'Could not load type' error

I'm developing an application using AWS SimpleEmail. I'm getting the error below when I try to test SendEmail function.
Could not load type 'Amazon.Runtime.Internal.InvokeOptions' from
assembly 'AWSSDK.Core, Version=3.3.0.0, Culture=neutral,
PublicKeyToken=885c28607f98e604'.
I have AWSSDK.Core v3.3.31.7 and AWSSDK.SimpleEmail v3.3.7.30 installed.
var credentials = new BasicAWSCredentials("key", "secret");
var client = new Amazon.SimpleEmail.AmazonSimpleEmailServiceClient(credentials, Amazon.RegionEndpoint.EUWest1);
var sesResponse = client.SendEmail(new SendEmailRequest
{
Destination = new Destination
{
BccAddresses = new List<string>
{
},
ToAddresses = new List<string> {
"user#cuchuma.net",
"user2#cuchuma.net"
}
},
Message = new Message
{
Body = new Body
{
Html = new Content
{
Charset = "UTF-8",
Data = "This message body contains HTML formatting. It can, for example, contain links like this one: <a class=\"ulink\" href = \"http://docs.aws.amazon.com/ses/latest/DeveloperGuide\" target = \"_blank\"> Amazon SES Developer Guide </a>."
},
Text = new Content
{
Charset = "UTF-8",
Data = "This is the message body in text format."
}
},
Subject = new Content
{
Charset = "UTF-8",
Data = "Test email"
}
},
ReplyToAddresses = new List<string>
{
},
ReturnPath = "",
ReturnPathArn = "",
Source = "no-reply#cuchuma.net",
SourceArn = ""
});
string messageId = sesResponse.MessageId;
The class it cannot load was only added 2 months ago. So my suspicion is that you have an older version of AWSSDK.Core than you have stated (v3.3.31.7).
Now I'm not sure how this happens, but I have seen instances in the past where Nuget gets messed up and a manual entry in the project file causes an incorrect dll to be loaded.
Open up your project file in notepad and look for the SDK references. They should look like the following:
<Reference Include="AWSSDK.Core, Version=3.3.0.0, Culture=neutral, PublicKeyToken=885c28607f98e604, processorArchitecture=MSIL">
<HintPath>..\packages\AWSSDK.Core.3.3.31.7\lib\net45\AWSSDK.Core.dll</HintPath>
</Reference>
<Reference Include="AWSSDK.SimpleEmail, Version=3.3.0.0, Culture=neutral, PublicKeyToken=885c28607f98e604, processorArchitecture=MSIL">
<HintPath>..\packages\AWSSDK.SimpleEmail.3.3.7.30\lib\net45\AWSSDK.SimpleEmail.dll</HintPath>
</Reference>
Check to see that the package names are indeed AWSSDK.Core.3.3.31.7 and AWSSDK.SimpleEmail.3.3.7.30.
Also check that there are no other random AWSSDK.Core entries.
Lastly... Another issue you might run into, if you don't specify them then don't include the following lines with blank string. It will throw an invalid email address error:
ReturnPath = "",
ReturnPathArn = "",
SourceArn = ""
A variation of #Martin Beeby's answer.
Using the fuslogvw tool I saw that the GAC version of AWSSDK.Core is loaded before attempting to load the local copy. My GAC had an outdated version of the AWSSDK.Core assembly and worse I could not safely uninstall it because there were dependencies. What ended up working was: I navigated to the local copy in my project (something like <solution folder>/packages/AWSSDK.Core.3.5.3.1/) and with an elevated PowerShell prompt I issued:
&"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools\gacutil.exe" /i .\AWSSDK.Core.dll
so that the newer version gets installed, and the error went away.
Note: you might have gacutil in a different path and it might even be on the path environment variable so you don't need a path.

Can Json.Net be embedded into the executable?

I set the 'Embed Interop Types' property of the Netwonsoft.Json library to true and it returns an error:
Cannot embed interop types from assembly
'c:\path\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll'
because it is missing either the 'ImportedFromTypeLibAttribute' attribute or
the 'PrimaryInteropAssemblyAttribute' attribute
c:\path\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll
It looks like looking for missing references within the Newtonsoft.Json library, but I am not entirely certain. Is it possible for Json.Net to be embeded into the executable?
You didn't say which language you were using but here is how you'd do it for C#
First, turn off "Embed Interop Types"
Then, to the main executable project, unload and edit the .csproj file, and below the following line:
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
Add this XML to the project file, save, and load it back up.
<Target Name="AfterResolveReferences">
<ItemGroup>
<EmbeddedResource Include="#(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'">
<LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
</EmbeddedResource>
</ItemGroup>
</Target>
You’ll then add a new code file to the main project and add the following code to it (modified to fit how your application is named / structured, in a WPF application, a good place to put it would be App.xaml.cs):
[STAThread]
public static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
App.Main(); // Run WPF startup code.
}
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs e)
{
var thisAssembly = Assembly.GetExecutingAssembly();
// Get the Name of the AssemblyFile
var assemblyName = new AssemblyName(e.Name);
var dllName = assemblyName.Name + ".dll";
// Load from Embedded Resources - This function is not called if the Assembly is already
// in the same folder as the app.
var resources = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(dllName));
if (resources.Any())
{
// 99% of cases will only have one matching item, but if you don't,
// you will have to change the logic to handle those cases.
var resourceName = resources.First();
using (var stream = thisAssembly.GetManifestResourceStream(resourceName))
{
if (stream == null) return null;
var block = new byte[stream.Length];
// Safely try to load the assembly.
try
{
stream.Read(block, 0, block.Length);
return Assembly.Load(block);
}
catch (IOException)
{
return null;
}
catch(BadImageFormatException)
{
return null;
}
}
}
// in the case the resource doesn't exist, return null.
return null;
}
Finally, make sure you update the target method for your main application to be the main method for the project you just added
Source: http://www.paulrohde.com/merging-a-wpf-application-into-a-single-exe/

Categories