Executing a Quartz.NET job from a separate assembly - assemblies

I'm trying to execute a Quartz.net job from a separate assembly. The class inherits from the IJob interface, implements the Execute method, and has been copied into the same folder as Quartz.Server.exe, but I'm getting the following error:
Error scheduling jobs: Could not load file or
assembly 'TestJobs' or one of its dependencies. An attempt was made to load a p
rogram with an incorrect format.
System.BadImageFormatException: Could not load file or assembly 'TestJobs' or on
e of its dependencies. An attempt was made to load a program with an incorrect format.
File name: 'TestJobs'
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError,
Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, Bool
ean loadTypeFromPartialName, ObjectHandleOnStack type)
... (snipped)
I'm using version 2 beta 2. The server application has been unzipped into a separate folder and is being executed by running Quartz.Server.exe at the command line.
My sample job is a separate assembly named TestsJobs with a very basic job to write to a text file:
public class TestJob : IJob
{
public void Execute(IJobExecutionContext context)
{
try
{
string path = #"c:\test.txt";
while (true)
{
var line = DateTime.Now.ToString() + " - " + Guid.NewGuid();
File.AppendAllText(path, line);
Thread.Sleep(500);
}
catch (Exception ex)
{
throw new JobExecutionException("Error", ex, false);
}
}
}
}
This is a basic class library project targeting .NET 4. It is copied into the Quartz.Net server folder where Quartz.Server.exe is being run from.
The quartz_jobs.xml file has the job set using the default file, with just the job type changed to reflect the new assembly and class:
<job-type>TestJobs.TestJob, TestJobs</job-type>
Thought this might be something to do with framework versioning, but Quartz.net seems to be using .NET 4 as well (Quartz.dll has dependencies on v4 assemblies).
There's another question on SO about the same type of issue, but it doesn't have a clear answer.
Is there anything else I need to do so that the job can be loaded and executed?

The solution to this turned out to be a bit simpler that I thought. It was caused by my assembly with the test job being compiled for x86 instead of AnyCPU (or x64) and using Windows 7 x64.

Related

ASP.NET Web API cause exceptions while running on raspberry pi 2 (ARM)

I have coded a Web API in Ubuntu using .NET Core recently and I need to use database to store the application data so that I decided to use EF Core. I ran this project on Ubuntu machine and everything worked appropriately.
I've also tried to run it on my raspberry pi 2 but I wasn't lucky enough to make it work properly. I did the instruction on this website and got this output as soon as I tried to access the api/dooz on Firefox while accessing my RP through Remmina Remote Desktop.
If the problem is with the database, how can I include the .db file to the iDooz_1/bin/Release/netcoreapp2.1/linux-arm/publish folder to make it work?
How can I solve it?
c343#RP:~/publish_idooz1$ ./iDooz_1
Hosting environment: Production
Content root path: /home/c343/publish_idooz1
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
Failed to determine the https port for redirect.
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HLFUSJJ3S54N", Request id "0HLFUSJJ3S54N:00000001": An unhandled exception was thrown by the application.
Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'no such table: Players'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
at Microsoft.Data.Sqlite.SqliteCommand.PrepareAndEnumerateStatements(Stopwatch timer)+MoveNext()
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteDbDataReader(CommandBehavior behavior)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
at Microsoft.EntityFrameworkCore.Storage.Internal.NoopExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.GetResult[TResult](IEnumerable`1 valueBuffers, Boolean throwOnNullResult)
at lambda_method(Closure )
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable`1.GetEnumerator()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Boolean& found)
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.<CompileQueryCore>b__0(QueryContext qc)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
at iDooz.Controllers.DoozController..ctor() in /home/c343/Documents/iDooz_1/Controllers/DoozController.cs:line 24
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
^CApplication is shutting down...
However, api/values, the default API in the webapi application worked properly and I got the correct output as in I got earlier on Ubuntu.
NOTE: First, this project is generally made to build a Tic Toc Toe and to learn about REstful APIs using ASP.NET Core Web API. So, I made a database using Entity Framework called Dooz.db and that is in the main directory of the project. Second, I'm doing dotnet publish -c Release -r linux-arm because the .NET Core SDK is not available for ARM-Processors.
Third, this is the part of the code in which the terminal had output an error
at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
at iDooz.Controllers.DoozController..ctor() in /home/c343/Documents/iDooz_1/Controllers/DoozController.cs:line 24
Here is the code:
public class DoozController : ControllerBase
{
public DoozController()
{
if(db.Players.Count() == 0)
{
db.Players.Add(new Player { PlayerID = 1, Username = "Alex123", Password = "1234", ProfilePic = "ProfilePics/Alex123.jpg" });
db.Players.Add(new Player { PlayerID = 2, Username = "Ashkan_007", Password = "12345", ProfilePic = "ProfilePics/Ashkan_007.jpg" });
.
.
.
db.SaveChanges();
}
}
.
.
.
You need to copy the database file into publish folder.

Provider org.togglz.slf4j.Slf4jLogProvider not a subtype

I have a library, built with Maven, that uses Spring 4.0.3.RELEASE and Togglz 2.2.0.Final. I'm trying to write a JUnit 4.11 test of my Spring class and running into the following error on the first test that gets executed:
testCreateItem_throwsItemServiceBusinessException(impl.ItemServiceImplTest) Time elapsed: 1.771 sec <<< ERROR!
java.util.ServiceConfigurationError: org.togglz.core.spi.LogProvider:
Provider org.togglz.slf4j.Slf4jLogProvider not a subtype
Here is the relevant java test snippet:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
#PrepareForTest({ ItemServiceImpl.class })
public class ItemServiceImplTest {
#Rule
public TogglzRule togglzRule = TogglzRule.allDisabled(Features.class);
#Rule
public PowerMockRule powerMockRule = new PowerMockRule();
#Test(expected = ItemServiceBusinessException.class)
public void testCreateItem_throwsItemServiceBusinessException() throws Exception {
PowerMockito.doReturn(mockMetricsData).when(serviceUnderTest, START_METRICS_METHOD_NAME, any(MetricsOperationName.class), any(RequestContext.class));
when(mockDao.createItem(any(Item.class), any(RequestContext.class))).thenThrow(dataBusinessException);
serviceUnderTest.createItem(item, context);
verify(mockItemServiceValidator).validate(any(Item.class), any(RequestContext.class));
PowerMockito.verifyPrivate(serviceUnderTest).invoke(START_METRICS_METHOD_NAME, any(MetricsOperationName.class), any(RequestContext.class));
verify(mockDao).createItem(any(Item.class), any(RequestContext.class));
}
}
Subsequent test calls get the following error:
java.lang.NoClassDefFoundError: Could not initialize class org.togglz.junit.TogglzRule
Here are some relevant dependencies I have:
org.mockito:mockito-all=org.mockito:mockito-all:jar:1.9.5:compile,
org.powermock:powermock-module-junit4=org.powermock:powermock-module-junit4:jar:1.5.6:test,org.powermock:powermock-module-junit4-common=org.powermock:powermock-module-junit4-common:jar:1.5.6:test,
org.powermock:powermock-reflect=org.powermock:powermock-reflect:jar:1.5.6:test,
org.powermock:powermock-api-mockito=org.powermock:powermock-api-mockito:jar:1.5.6:test,
org.powermock:powermock-api-support=org.powermock:powermock-api-support:jar:1.5.6:test,
org.powermock:powermock-module-junit4-rule=org.powermock:powermock-module-junit4-rule:jar:1.5.6:test,
org.powermock:powermock-classloading-base=org.powermock:powermock-classloading-base:jar:1.5.6:test,
org.powermock:powermock-core=org.powermock:powermock-core:jar:1.5.6:test,
org.powermock:powermock-classloading-xstream=org.powermock:powermock-classloading-xstream:jar:1.5.6:test,
org.togglz:togglz-core=org.togglz:togglz-core:jar:2.2.0.Final:compile,
org.togglz:togglz-slf4j=org.togglz:togglz-slf4j:jar:2.2.0.Final:compile,
org.togglz:togglz-spring-core=org.togglz:togglz-spring-core:jar:2.2.0.Final:compile,
org.togglz:togglz-testing=org.togglz:togglz-testing:jar:2.2.0.Final:test,
org.togglz:togglz-junit=org.togglz:togglz-junit:jar:2.2.0.Final:test
And I have provided a LogProvider (org.togglz.slf4j.Slf4jLogProvider) via SPI, located at META-INF/serivces/org.togglz.core.spi.LogProvider
This error is baffling as Slf4jLogProvider should be assignable from LogProvider. Sorry for the verbosity, but I wanted to try and show a complete picture. The code in class "under test" is making a call to see if a single feature is enabled inside the create method.
First of all: You don't need to configure the log provider in your application. Including togglz-slf4j on your application path is sufficient because this jar contains the corresponding SPI file.
Could you please check if there are multiple conflicting versions of the Togglz JAR files on your classpath? For example using togglz-core-2.2.0.Final.jar together with togglz-slf4j-2.1.0.Final.jar could result in an error like this.
This can happen if you update Togglz and your IDE didn't remove the old archives. Running a clean build and/or selecting "Update Maven Configuration" on Eclipse will fix this problem.

ASP.NET 5, EF 7 and SQLite - SQLite Error 1: 'no such table: Blog'

I followed the Getting Started on ASP.NET 5 guide about Entity Framework 7 and I replaced MicrosoftSqlServer with Sqlite, the only difference in the code is in Startup.cs:
services.AddEntityFramework()
.AddSqlite()
.AddDbContext<BloggingContext>(options => options.UseSqlite("Filename=db.db"));
When I run the website and navigate to /Blogs, I get an error:
Microsoft.Data.Sqlite.SqliteException was unhandled by user code
ErrorCode=-2147467259 HResult=-2147467259 Message=SQLite Error 1:
'no such table: Blog' Source=Microsoft.Data.Sqlite
SqliteErrorCode=1 StackTrace:
at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc,
Sqlite3Handle db)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior
behavior)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteDbDataReader(CommandBehavior
behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.d__1`2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at Microsoft.Data.Entity.Query.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at EFGetStarted.AspNet5.Controllers.BlogsController.Index() in d:\arthur\documents\visual studio
2015\Projects\EFGetStarted.AspNet5\src\EFGetStarted.AspNet5\Controllers\BlogsController.cs:regel
18 InnerException:
I understand this as if there is no table called 'Blog', but when I open the .db file in DB Browser for SQLite, there actually is a table called 'Blog':
Does SQLite require other changes in the code, or is this an error in the SQLite connector for Entity Framework?
It is very likely the database actually being opened by EF is not the file you are opening in DB Browser. SQLite use the process current working directory, which if launched in IIS or other servers, can be a different folder than your source code directory. (See issues https://github.com/aspnet/Microsoft.Data.Sqlite/issues/132 and https://github.com/aspnet/Microsoft.Data.Sqlite/issues/55).
To ensure your db file is in the right place, use an absolute path. Example:
public class Startup
{
private IApplicationEnvironment _appEnv;
public Startup(IApplicationEnvironment appEnv)
{
_appEnv = appEnv;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlite()
.AddDbContext<MyContext>(
options => { options.UseSqlite($"Data Source={_appEnv.ApplicationBasePath}/data.db"); });
}
}
I did this and was still having trouble loading the database. I added the following code in the constructor for the database context:
Database.EnsureCreated();
Now my context file looks like this:
It created a new database on my new Azure hosting site, so if you have a lot of existing data to migrate, this won't work. It worked for me so figured I'd share.
Taken from EF Core documentation...
Run from Visual Studio
To run this sample from Visual Studio, you must set the working
directory manually to be the root of the project. Ifyou don't set the
working directory, the following Microsoft.Data.Sqlite.SqliteException
is thrown: SQLite Error 1: 'no such table: Blogs'.
To set the working directory:
In Solution Explorer, right click the project and then select Properties.
Select the Debug tab in the left pane.
Set Working directory to the project directory.
Save the changes.
I had this issue on netcoreapp2.0. There's a related issue that may be at fault, but I didn't want to solve it by going to a nightly build.
The solution for me was to create and pass an SqliteConnection instead of using the builder string.
So for this setup:
string id = string.Format("{0}.db", Guid.NewGuid().ToString());
var builder = new SqliteConnectionStringBuilder()
{
DataSource = id,
Mode = SqliteOpenMode.Memory,
Cache = SqliteCacheMode.Shared
};
Compose for the DI like so:
var connection = new SqliteConnection(builder.ConnectionString);
connection.Open();
connection.EnableExtensions(true);
services.AddDbContext<SomeDbContext>(options => options.UseSqlite(connection));
The error I had was using this style of init:
services.AddDbContext<SomeDbContext>(options => options.UseSqlite(builder.ConnectionString));
My scaffolding also has a one-time call to:
var dbContext = serviceScope.ServiceProvider.GetService<SomeDbContext>();
dbContext.Database.OpenConnection();
dbContext.Database.EnsureCreated();
Using this approach all my DI-instantiated copies of SomeDbContext would all point at a valid SQLite db, and that db would have auto-created schema as per my entities.
Looks like things have changed because IApplicationEnvironment has been replaced with IHostingEnvironment.
Removing IApplicationEnvironment \ IRuntimeEnvironment
public class Startup
{
private IHostingEnvironment _appHost;
public Startup(IHostingEnvironment appHost)
{
_appHost = appHost;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlite()
.AddDbContext<MyContext>(
options => { options.UseSqlite($"Data Source={_appHost.ContentRootPath}/data.db"); });
}
}
I Had the same problem and I found the answer in this link:
https://www.youtube.com/watch?v=yRmMYrSROPs
Just update your database via command:
dotnet ef update database
you can set up the configuration adding;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source = path//DatabaseName.db");
}
the example uses SQLite, but you can choose your own DB.
If you have multiple DataContexts, the EnsureCreated method will only work on the first call. See its documentation:
If the database exists and has any tables, then no action is taken
To create tables of additional DataContexts, use
RelationalDatabaseCreator databaseCreator =
(RelationalDatabaseCreator) secondDbContext.Database.GetService<IDatabaseCreator>();
databaseCreator.CreateTables();

Asp.Net Bundle - How to raise exception when minification fails

I'm using Asp.Net MVC 5 and the bundling and minification system from System.Web.Optimization 1.1.0.0:
bundles.Add(new ScriptBundle("~/angularLibraries").Include(
......
));
and then to render the Bundle:
#Scripts.Render("~/angularLibraries")
From time to time I manually check the state of my bundles by opening the corresponding url in the browser, and sometimes I find them with errors. Example:
/* Minification failed. Returning unminified contents.
(262,145-152): run-time error JS1019: Can't have 'break' outside of loop: break a
(40,297-304): run-time error JS1019: Can't have 'break' outside of loop: break a
*/
Because the bundling mechanism returns the unminified contents when the minification fails, I'm unaware of the error until I manually open that bundle in a browser.
How can I setup the Bundling system to raise an exception when minification fails so I can immediately be aware of the error?
Found a solution. I have created a custom class that derives from ScriptBundle and overrides the method ApplyTransforms:
public class CustomScriptBundle : ScriptBundle
{
public CustomScriptBundle(string virtualPath)
: base(virtualPath)
{
}
public CustomScriptBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{
}
public override BundleResponse ApplyTransforms(BundleContext context, string bundleContent, IEnumerable<BundleFile> bundleFiles)
{
BundleResponse bundleResponse = base.ApplyTransforms(context, bundleContent, bundleFiles);
if (bundleResponse.Content.StartsWith("/* Minification failed. Returning unminified contents."))
ExceptionManager.LogMessage("Minification failed for following bundle: " + context.BundleVirtualPath);
return bundleResponse;
}
}
I ended up logging a message (an receiving an email notification from Elmah) and not throwing an exception because I have minification enabled by default only on production, and the app will continue working ok anyway.
If you throw an exception, you'll see it like this:
This solution is also applicable for StyleBundle.

Exception running application when adding insights to application using Application Insights Status Monitor Preview

I'm playing around with the preview, and tried adding insights to a IIS web application deployed locally on my machine. It's a .Net 4.5 application running in a nothing out of the ordinary application pool. When starting the application after adding insights, I get this exception:
Could not load file or assembly 'Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll' or one of its dependencies. The module was expected to contain an assembly manifest.
I tried "Enable 32-Bit Applications" to both true and false with no difference in result.
Has anyone experienced a similar error?
Unfortunately ASP.NET tries to load literally everything that is in \bin as managed assemblies
Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll is not a managed assembly, but ASP.NET Web App should not fail with yellow page in this case, you would see it only in FusLogvw.
Do you use any web publishing?
Did you precompile your web site on publish?
Could you provide full stack trace of the exception?
I've just come across this issue, and after a few hours found it was due to a conflict with FluentSecurity.
It's detailed here: https://github.com/kristofferahl/FluentSecurity/issues/70
The work-around was to add the following lines just before calling SecurityConfigurator.Configure():
SecurityDoctor.Current.EventListenerScannerSetup = scan =>
{
scan.ExcludeAssembly(file => Path.GetFileName(file).Equals("Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll"));
scan.ExcludeAssembly(file => Path.GetFileName(file).Equals("Microsoft.ApplicationInsights.Extensions.Intercept_x86.dll"));
};
Hope this helps somebody else.
My inner exception pointed to WebActivator. So I Uninstall-Package WebActivator -Force, added the appropriate calls in Application_Start and all was good again.
I'm still testing this but I think I've resolved this problem....
The solution is based on the same solution as the SQL Spatial Types native .dll solution; if you know this you'll see the similarity between this and that package.
Step 1
Go Create a new subdirectory in the MVC project and under this two more sub-directories; I used :
MVCRoot ---> ApplicationInsights/x86
---> ApplicationInsights/x64
Under each directory add a linked item from the package directory, this was :
../packages\Microsoft.Diagnostics.Instrumentation.Extensions.Intercept.0.12.0-build02810\lib\native\x64\Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll
and
../packages\Microsoft.Diagnostics.Instrumentation.Extensions.Intercept.0.12.0-build02810\lib\native\x86\Microsoft.ApplicationInsights.Extensions.Intercept_x86.dll
respectively.
I then add this code in a file in the 'root' of the AppplicationInsights folder called loader.cs which looked like this:
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
namespace ApplicationInsights
{
/// <summary>
/// Utility methods related to CLR Types for SQL Server
/// </summary>
internal class Utilities
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr LoadLibrary(string libname);
/// <summary>
/// Loads the required native assemblies for the current architecture (x86 or x64)
/// </summary>
/// <param name="rootApplicationPath">
/// Root path of the current application. Use Server.MapPath(".") for ASP.NET applications
/// and AppDomain.CurrentDomain.BaseDirectory for desktop applications.
/// </param>
public static void LoadNativeAssemblies(string rootApplicationPath)
{
var nativeBinaryPath = IntPtr.Size > 4
? Path.Combine(rootApplicationPath, #"ApplicationInsights\x64\")
: Path.Combine(rootApplicationPath, #"ApplicationInsights\x86\");
CheckAddDllPath(nativeBinaryPath);
// LoadNativeAssembly(nativeBinaryPath,
// IntPtr.Size > 4
// ? "Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll"
// : "Microsoft.ApplicationInsights.Extensions.Intercept_x86.dll");
}
public static void CheckAddDllPath(string dllPath)
{
// find path to 'bin' folder
var pathsToAdd = Path.Combine(new string[] { AppDomain.CurrentDomain.BaseDirectory, dllPath });
// get current search path from environment
var path = Environment.GetEnvironmentVariable("PATH") ?? "";
// add 'bin' folder to search path if not already present
if (!path.Split(Path.PathSeparator).Contains(pathsToAdd, StringComparer.CurrentCultureIgnoreCase))
{
path = string.Join(Path.PathSeparator.ToString(), new string[] { path, pathsToAdd });
Environment.SetEnvironmentVariable("PATH", path);
}
}
private static void LoadNativeAssembly(string nativeBinaryPath, string assemblyName)
{
var path = Path.Combine(nativeBinaryPath, assemblyName);
var ptr = LoadLibrary(path);
if (ptr == IntPtr.Zero)
{
throw new Exception(string.Format(
"Error loading {0} (ErrorCode: {1})",
assemblyName,
Marshal.GetLastWin32Error()));
}
}
}
}
I then added this to the global.asax this so:
protected override void Application_Start(object sender, EventArgs e)
{
ApplicationInsights.Utilities.LoadNativeAssemblies(Server.MapPath("~/bin"));
}
So far it seems to be passed events so far as I can tell. All come back and update this should I find a problem with what I've done.
At least the MVC application now starts :-)
UPDATE: This is not the end of the story :-(
I had to also modify the Microsoft.Diagnostics.Instrumentation.Extensions.Intercept.props file which is under the build directory of the package to make it not include the files into the bin directory.
When I was done it looked like this :
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<None Include="$(MSBuildThisFileDirectory)\..\lib\native\x86\Microsoft.ApplicationInsights.Extensions.Intercept_x86.dll">
<CopyToOutputDirectory>None</CopyToOutputDirectory>
</None>
<None Include="$(MSBuildThisFileDirectory)\..\lib\native\x64\Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll">
<CopyToOutputDirectory>None</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
I've had to check in this package into my source control system as I think I'm now going to be faced with the problem with Continuous Build restoring a fresh copy of the package which I don't want.
I can't wait for MS to come up with a proper fix for this.
I've just deleted everything in my /bin folder and it seemed to have resolved the issue. Not sure what happen or anything, it's a project i haven't touched in ages. But it solved it :)

Resources