Unable to find assembly on Azure Mobile Service - azure

I have an Azure Mobile Service project which has a dependency to another (persistence) project which is referencing FluentNHibernate. Locally everything is running correctly in Release and Debug mode. Publishing the project seems to be successful (blue smiley). The problems starts when I make a request, where FluentNHibernate is used. I get the following error message:
Unable to find assembly 'FluentNHibernate, Version=2.0.3.0, Culture=neutral, PublicKeyToken=null'.
I already tried a lot of things:
Reinstalling packages
A new plain vanilla Mobile Service
Adding dependentAssembly in Web.config in the main project and App.config in the persistence project.
A little confusing for me is following fact: When I change the version of the FluentNHibernate package, I can see in the publish preview window that this dll will not be updated.
I am really not sure if this problem is depended to this specific package (FluentNHibernate). For example, what means: PublicKeyToken=null?
What else can I try to make the service running in the cloud?

The code below worked for my solution. It wires up a handler to the AppDomain's AssemblyResolve event, which is raised if an assembly cannot be found. In this case, I tell it to check the currently loaded assemblies and return one if there is a match, which there should be for FluentNHibernate. Try sticking this as the first line in WebApiConfig.Register
public static void Register()
{
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
return AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.FullName == args.Name).FirstOrDefault();
};
// the rest of WebApiConfig.Register...
}

Related

Azure function: Could not load file or assembly Microsoft.IdentityModel.Tokens, Version=5.2.1.0

Im writing an azure function to generate a JWT token and return it to the client. The code is tested locally in a console app and all seems to work fine. This is the package reference included in the working console app, and in my functions app:
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.2.1" />
When running the function host locally with func host start and executing the code it results in the error:
Could not load file or assembly 'Microsoft.IdentityModel.Tokens, Version=5.2.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'."
I don't understand why this is happening, the dll is laying in the output folder along with my application dll. The only other thing I can think of is that the function host has its own set of packages that it sources from and this one is not available yet, having been only released 12 days ago.
I'm not sure. Any help on why this is happening or how to get around it?
Details:
Azure Functions Core Tools (2.0.1-beta.22)
Function Runtime Version: 2.0.11415.0
I got this issue and it seems to be related to some kind of bug in the Azure function SDK. the fix was to add:
<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
to your csproj file. As documented here
I had installed this package Microsoft.AspNetCore.Authentication.JwtBearer
And for me, the issue was resolved.
You can uninstall System.IdentityModel.Tokens.Jwt
Because the Microsoft package depends on the system package, so it gets installed automatically.
I was able to solve this exact issue by using an older version of the nuget package. My starting point was that I had copied a class file from an old project to a new one. The class file referenced JwtSecurityToken. This did not compile in the new project, so I added Security.IdentityModel.Tokens.Jwt from nuget package manager. I just added latest version. This worked fine locally, but just like you, it failed when published to azure. I then looked at the old project and noticed that it was using 5.1.4 of that Security.IdentityModel.Tokens.Jwt. So, I downgraded to that version and it now works when published.
fwiw: this is the v2 preview runtime version at the time I did this.
https://<mysite>.azurewebsites.net/admin/host/status?code=<myadminkey>
{
"id": "<mysite>",
"state": "Running",
"version": "2.0.11587.0",
"versionDetails": "2.0.11587.0-beta1 Commit hash: 1e9e7a8dc8a68a3eff63ee8604926a8d3d1902d6"
}
tl;dr
None of the above worked for me and this would randomly happen from time to time until today it happened all the time. The only reason I could see was that Microsoft.IdentityModel.Tokens was not directly referenced in the executing project, but was on a referenced project. The library was sitting in the bin folder, it just wouldn't load.
Reference
Taking a clue from this solution to another problem I was able to resolve it like so:
Solution
Create a static constructor in the app's entry point class
static MainClass()
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
Add the handler
private static System.Reflection.Assembly? CurrentDomain_AssemblyResolve(object? sender, ResolveEventArgs args)
{
var domain = sender as AppDomain;
var assemblies = domain.GetAssemblies();
foreach(var assembly in assemblies)
{
if (assembly.FullName.IsEqualTo(args.Name))
{
return assembly;
}
}
var folder = AppDomain.CurrentDomain.BaseDirectory;
var name = args.GetLibraryName().Name.Split(Symbols.Comma).FirstOrDefault();
var library = $"{name}.dll";
var file = Path.Combine(folder, library);
if (File.Exists(file))
{
return Assembly.LoadFrom(file);
}
return null;
}

Azure Function App ignoring dependencies

I have an Azure Function that connects to a database, but it's failing with the following message -
The type or namespace name 'Npgsql' could not be found (are you missing a using directive or an assembly reference?)
In project.json, I have the following declaration -
{
"frameworks": {
"net46":{
"dependencies": {
"Npgsql": "3.2.2",
"System.Runtime.Serialization.Formatters": "4.3.0"
}
}
}
}
The strange thing is, I have the exact same Function (deployed from Octopus) running on another Function App (a lower environment) without issue.
Is anyone able to explain why my dependancies being ignored in one Function App but not the other?
So this seems that this is happening due to the way that the Function App is deployed. I'm using Octopus, deploying via the "Deploy an Azure Web App" process step, and it seems that all that's happeing is the old files are being deleted, and the updated files copied across.
The trouble is, as far as I can tell, the dependancies in project.json are not resolved unless you edit the file via the Portal and then save it.
I'm not sure if this can be classed as a bug in either Octopus or Azure (or just really lazy implementation Function Apps), but it's very frustrating. Essentially it makes remote deployment of a Function App that includes changes to function.json impossible.

Why doesn't Azure load properly the Interop?

I have a WebApp on Azure that uses a dll. This library needs Interop libraries x86 and x64.
Sometimes, at the restart of the App (I suppose), the App fails due to an exception:
System.EntryPointNotFoundException: Unable to find an entry point named 'sqlite3_config' in DLL 'SQLite.Interop.dll'. at System.Data.SQLite.UnsafeNativeMethods.sqlite3_config_none(SQLiteConfigOpsEnum op) at System.Data.SQLite.SQLite3.StaticIsInitialized() at System.Data.SQLite.SQLiteLog.Initialize() at System.Data.SQLite.SQLiteConnection..ctor(String connectionString, Boolean parseViaFramework) at T_Dox.WebService.SQLiteDb.CreateConnection() at WebService.CeDb.Connect()
The SQLite used is the SQLCipher's one.
What am I missing here? I don't understand why the app stops working suddenly even if I don't make any changes.
The App is a Web Service (.asmx file) that uses a data access layer to perform some business logic.
It was under a web site project, then we moved it into another project, a webapi\mvc project.
The routing bypasses this extension, so it works as before, a simple web service call.
The called web method initializes a business class loaded from another .net library (a VB.Net library).
Inside, this class uses a wrapper to a sqlConnection, in this case the SQLiteConnection.
In its constructor it starts an SQLiteConnection, and normally it works.
Then it performs some CRUD operations ...
So I can represent the operation this way:
[WebService(Namespace = "...")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class SampleService : System.Web.Services.WebService
{
[WebMethod]
public ServerInfo Test()
{
var sampleBusinessClass = new SampleBusinessCLass();
sampleBusinessClass.DoSomething();
using(var connection = new SQLiteConnection()) //the constructor is the parameterless one
{
//...
}
}
}
And the stack will be this (this is not the real one):
System.EntryPointNotFoundException: Unable to find an entry point named 'sqlite3_config' in DLL 'SQLite.Interop.dll'.
at System.Data.SQLite.UnsafeNativeMethods.sqlite3_config_none(SQLiteConfigOpsEnum op)
at System.Data.SQLite.SQLite3.StaticIsInitialized()
at System.Data.SQLite.SQLiteLog.Initialize()
at System.Data.SQLite.SQLiteConnection..ctor(String connectionString, Boolean parseViaFramework)
at xxx.WebService.SampleService.Test()
It always works, but sometimes it starts to launch this error until the stop and start of the web application on iss (in our case: Azure).
Inspecting the System.Data.SQlite.dll I can clearly see the entry point and actually it always passes this internal code (no conditions that can bypass this part) and it generally works.
The System.Data.SQlite.dll (1.0.96.0 version) is provided by SqlCypher product. I think it is the original System.Data.SQLite one because at first sight I can see the same assembly manifest and content.
The interop System.Data.SQLite uses is probably modified by SqlCypher team to give their features.
To avoid possible issues we put the interop in the path /bin/x64, then we compile our web app ONLY in x64 and it runs on a x64 environment.

PCL Retargetable Assembly not redirected inside MS CRM Plugin

Calling
Assembly.Load("System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes");
inside a .net 4.03 application should redirect to the correct 4.0.0.0 System.Core
It works on my machine for a Console App and inside an ASPX page.
However calling it from inside a Dynamics MS CRM Plugin fails with
System.IO.FileNotFoundException: Could not load file or assembly 'System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes' or one of its dependencies. The system cannot find the file specified.
There are no FUSION errors either.
What is special about the way plugins are executed that the redirects are skipped?
I think I know what's happening. CRM very likely calling Assembly.LoadFile on your plug-in assembly. This is telling the CLR binder that it wants to handle all the logic that Fusion would normally handle (including the understanding of portable libraries, binding redirects, publisher policy, etc).
As you can see this is problematic - and calling this API is almost always the wrong thing to do, unless you really know what you are doing. Instead, they should probably be calling Assembly.LoadFrom which automatically applies this logic.
What can you do it about?
Without getting them to change, you should be able to hook up to AppDomain.Current.AssemblyResolve and apply the logic yourself that fusion would normally apply:
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string name = AppDomain.CurrentDomain.ApplyPolicy(args.Name);
try
{
return Assembly.Load(name);
}
catch (FileNotFoundException)
{
}
catch (FileLoadException)
{
}
catch (BadImageFormatException)
{
}
return null;
}
The problem with above is that you aren't going to be able to do this from a portable library. Either you need to this dynamically using Reflection, or have some sort of .NET Framework-specific entry point that runs before your portable assembly is loaded.

Add WebRole.cs - and have it called - in an existing ASP.NET MVC site converted to web role

I have an ASP.NET MVC 4 site running perfectly well in an Azure WebRole. The ASP.NET MVC project was started on its own, after which I added an Azure Cloud Service project to the solution and added the ASP.NET project/site as one of the 'roles' of the service (so it shows up in the 'Roles' folder).
My problem is that I would like to have working a WebRole.cs file within the ASP.NET MVC project, but no matter what I've tried to do, it appears that when deployed, it just never gets called. OnStart and the override of Run (which I know, must never leave the loop) -- these just apparently never get called.
But if you startup a new CloudService project and add, at that time from the start, an ASP.NET MVC project, it automatically has a WebRole.cs file in it, so my guess is that I need to configure something somewhere for the WebRole.cs (actually speaking, the WebRole class, which inherits RoleEntryPoint) to get called. What might that be?
using System;
using System.Web;
//using Microsoft.WindowsAzure.StorageClient;
using System.Diagnostics;
using System.Threading;
namespace Us.WebUI
{
public class WebRole : Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint
{
public override bool OnStart()
{
return true; //return base.OnStart(); // CALL THIS???
}
public override void Run()
{
while (true) {
Thread.Sleep(TimeSpan.FromSeconds(30));
try {
EmailFuncs.SendEmailToUs("An email from our WebRole?????", "Email me this, email me that.");
}
catch { }
}
}
}
}
UPDATE: Thanks, the question has been answered. But I will add: On doing this, while it clearly was working (fully deployed and in emulator), that suddenly I was having problems doing a full publish of the site. After a azure publish took 3 hours:
Verifying storage account 'xyz'... > Uploading Package... > - Updating... [stayed here for 3 hours], it failed with this error: The server encountered an internal error. Please retry the request. So one thing I was wondering is, did I need to override OnStop in WebRole.cs?
UPDATE 2: Those previous problems were fixed, and had nothing to do with this issue. Actually, I've learned this: If you ever have any warnings generated in your build, Azure often will not work with them even when they don't cause problems locally or in other hosts. Since then, I've been much more studious to tackling build warnings (but critical to this is turning off with warning codes the many warning types you want to ignore!).
Adding a class to your Web Project which inherits from RoleEntryPoint is sufficient, it should just work. Did you try setting a breakpoint in the emulator?
What you might be experiencing is that EmailFuncs.SendEmailToUs requires info from the app/web.config and that this info is not available. You need to know that your WebRole class runs in a different process (not your web application), meaning it's not using your web.config. If you want the WebRole.cs to read info from the configuration file, you'll need to add these settings in WaIISHost.exe.config

Resources