Configuring .net installer project - configuration

I am using .net4 installer project to install my application which is written in .net 4 now the problem is that i am using tow assembly from .net2 in my installer so when i run the installer it fails with this message
"Mixed mode assembly is built against version 'v2.0.50727' of the run-time and cannot be loaded in the 4.0 run-time without additional configuration information." now the problem can solved with this lines in app.config
<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
the problem is i could not do this in installer class
what can i do ?

finally after a deep search i found the solution
it is to user useLegacyV2RuntimeActivationPolicy by code
public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; }
static RuntimePolicyHelper()
{
ICLRRuntimeInfo clrRuntimeInfo =
(ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
Guid.Empty,
typeof(ICLRRuntimeInfo).GUID);
try
{
clrRuntimeInfo.BindAsLegacyV2Runtime();
LegacyV2RuntimeEnabledSuccessfully = true;
}
catch (COMException)
{
// This occurs with an HRESULT meaning
// "A different runtime was already bound to the legacy CLR version 2 activation policy."
LegacyV2RuntimeEnabledSuccessfully = false;
}
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
void xGetVersionString();
void xGetRuntimeDirectory();
void xIsLoaded();
void xIsLoadable();
void xLoadErrorString();
void xLoadLibrary();
void xGetProcAddress();
void xGetInterface();
void xSetDefaultStartupFlags();
void xGetDefaultStartupFlags();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BindAsLegacyV2Runtime();
}
}
then i use it in my code like this
if (RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully)
{
//my mixed mode dell call goes here
}

Related

JUnit 5 + Apache Surefire Plugin - How to use custom listener

I'm taking my first steps into testing, so don't be strict.
How I can use my custom listener in JUnit 5, if I use Apache Surefire Plugin for running my tests? It TestNG it is easy because I can use annotation #Listeners or write my listener in .xml with the suite of tests. It JUnit I can't find working decision.
My custom listener:
public class OnrTestListener implements TestExecutionListener {
private static final Logger LOG = LogManager.getRootLogger();
#Override
public void executionSkipped(TestIdentifier testIdentifier, String reason) {
LOG.info("SKIPPED Test by reason: {}", reason);
}
#Override
public void executionStarted(TestIdentifier testIdentifier) {
LOG.info("Test {} successfully started.", testIdentifier.getDisplayName());
}
#Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
if (testExecutionResult.getStatus() != TestExecutionResult.Status.SUCCESSFUL) {
String message = "Page screenshot.";
File screenshot = ScreenshotUtils.takeScreenshot();
ScreenshotUtils.attachToReportPortal(message, screenshot);
}
}
My additional class ScreenshotUtils
public class ScreenshotUtils {
private static final OnrLogger LOG = new OnrLogger();
private ScreenshotUtils() {
}
public static void attachToReportPortal(String message, File screenshot) {
ReportPortal.emitLog(message, "info", new Date(), screenshot);
}
public static File takeScreenshot() {
return ((TakesScreenshot) DriverFactory.getDriver()).getScreenshotAs(OutputType.FILE);
}
}
My tests marked some annotations (because I can't find some decision for making suite) and run my tests like:
mvn clean test -Dgroups=some_tag
How I tried to use my listener:
I tried to use annotation:
#ExtendWith(OnrTestListener.class)
#Tag("all")
public abstract class BaseUITest {
...
}
Using config in surefire plugin
<configuration>
<properties>
<property>
<name>listener</name>
<value>com.google.listeners.OnrTestListener</value>
</property>
<configurationParameters>
junit.jupiter.extensions.autodetection.enabled = true
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
junit.jupiter.execution.parallel.mode.classes.default = concurrent
junit.jupiter.execution.parallel.config.strategy = fixed
junit.jupiter.execution.parallel.config.fixed.parallelism = 5
</configurationParameters>
</properties>
</configuration>
But it doesn't work.
I would be grateful for any help. Thank you
You can use the SPI mechanism.
Add a file org.junit.platform.launcher.TestExecutionListener to the /src/main/resources/META-INF/services/ folder.
Then add the full name of your listener {your package}.OnrTestListener to this file.
The listener will be applied automatically.

File Not Found Exception Visual Studio 2015

I am getting file not found error though I have the needed file inside the project directory.There are no compilation errors.
Here is my startup.cs class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
namespace OdeToFood
{
public class Startup
{
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("config.json");
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
var message = Configuration["greeting"];
await context.Response.WriteAsync(message);
});
}
}
}
And this is the error message I get when I build it.
System.IO.FileNotFoundException: The configuration file 'config.json' was not found and is not optional.
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at OdeToFood.Startup..ctor()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.StartupLoader.LoadMethods(IServiceProvider services, Type startupType, String environmentName)
at Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions.<>c__DisplayClass1_0.b__1(IServiceProvider sp)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureStartup()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Screenshot showing the file present
How should I rectify this?
Thanks
I think you forget to use Server.MapPath function.
You can edit your Constructor with following code :
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile(HttpContext.Current.Server.MapPath("~/config.json"));
Configuration = builder.Build();
}
Hope it helps you :)

Azure WebJob- QueueTrigger Staging and Production

I have an Azure WebJob that will be used for Staging and Production. The keys for the proper environments are set in the app.config file.
A ConfigManager class reads the properties from the app.config file.
public static string FirstQueue
{
get { return ConfigurationManager.AppSettings["FirstQueue"]; }
}
I would like the QueueTrigger to read the from the proper queue specified in the app.config file.
public static void ProcessFirstQueue([QueueTrigger(ConfigManager.FirstQueue)] string message)
{
//some function
}
However, the QueueTrigger doesn't seem to like this. I get "An attribute argument must be a constant expression, type of expression...." Any suggestions to set this up. I do not want to hard code values in the queue trigger.
Thanks
You can resolve the queue name at runtime using the
INameResolver
Here's an example to demonstrate this:
WebJob Code:
public class Program
{
private static void Main(string[] args)
{
var config =
new JobHostConfiguration("insert connection string")
{
NameResolver = new QueueNameResolver()
};
var host = new JobHost(config);
host.RunAndBlock();
}
public static void ProcessNotification([QueueTrigger("%queueKey%")] string item)
{
//Handle message
}
public static void ProcessPoison([QueueTrigger("%queueKeyPoison%")] string item)
{
//Handle poison message
}
}
Here's the QueueNameResolver class:
public class QueueNameResolver : INameResolver
{
//name = queueKey or queueKeyPoison
public string Resolve(string name)
{
//Use the name to get it from the app.config or somewhere else.
}
}
Hope this helps,

Castle Windsor WCF integration - DefaultServiceHostFactory, Kernel, etc

I'm nearly done with a big NHibernate upgrade that ended up also being a Castle upgrade. I'm nearly there except the ASP.NET website won't run, because I'm getting an error where ServiceSecurityContext.Current is null. I could be wrong (I'm still new to Castle) but I think it has something to do with the change I made to registering the WCF facility.
Previously (in a class called ServiceLocator.cs) there was code like this:
/// <summary>
/// Register the WindsorServiceHostFactory with the container
/// </summary>
public static void RegisterWcfServer()
{
RegisterWcfFacility();
DefaultServiceHostFactory.RegisterContainer(Container.Kernel);
}
where the RegisterWcfFacility() method looked like this:
private static void RegisterWcfFacility()
{
IFacility[] facilities = Container.Kernel.GetFacilities();
bool hasWcfFacility = false;
foreach (IFacility facility in facilities)
{
if (facility.GetType() != typeof (WcfFacility))
continue;
hasWcfFacility = true;
break;
}
if (!hasWcfFacility)
Container.AddFacility<WcfFacility>();
}
Subsequently I've changed it to this (because I was trying to get it to compile obviously, and the DefaultServiceHostFactory no longer has a "RegisterContainer" method):
/// <summary>
/// Register the WindsorServiceHostFactory with the container
/// </summary>
public static void RegisterWcfServer()
{
RegisterWcfFacility();
// see: http://stackoverflow.com/questions/9729395/castlewindsor-3-0-and-defaultservicehostfactory-registercontainer
// obsolete:
//DefaultServiceHostFactory.RegisterContainer(Container.Kernel);
Container.Register(Component.For<DefaultServiceHostFactory>());
}
And my new version of "RegisterWcfFacility()" looks like this:
private static void RegisterWcfFacility()
{
var facilities = Container.Kernel.GetFacilities();
var hasWcfFacility = facilities.Any(facility => facility.GetType() == typeof (WcfFacility));
if (!hasWcfFacility)
Container.AddFacility<WcfFacility>();
}
I'm just posting this mainly to ask things like: am I completely barking up the wrong tree? Is the way I'm registering this facility legitimate? Could any of this explain why my ServiceSecurityContext.Current is null? (and yes I have seen this):
https://groups.google.com/forum/#!topic/castle-project-devel/VOQKW4XlvLM%5B1-25%5D
thanks for any advice. Cheers, -Dave
I just had the same problem and found the answer here. Turns out you just an initialise class in the folder App_Code that looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Castle.Windsor;
using Castle.Facilities.WcfIntegration;
namespace YourNamespace
{
public static class InitialiseService
{
public static void AppInitialize()
{
var container = new WindsorContainer();
container.AddFacility<WcfFacility>();
}
}
}
Of course this relies on the WCF Castle Facility being installed from the package manager via:
install-package Castle.WcfIntegrationFacility
Hope this helps :)

pooling with Windsor

I've tried out the pooling lifestyle with Windsor.
Lets say I want multiple CustomerTasks to work with a pool of ILogger's.
when i try resolving more times than maxPoolSize, new loggers keeps getting created.
what am I missing and what exactly is the meaning of max pool size?
the xml configuration i use is (demo code):
<component id="customertasks" type="WindsorTest.CustomerTasks, WindsorTestCheck" lifestyle="transient" />
<component id="logger.console" service="WindsorTest.ILogger, WindsorTestCheck" type="WindsorTest.ConsoleLogger, WindsorTestCheck" lifestyle="pooled" initialPoolSize="2" maxPoolSize="5" />
Code is:
public interface ILogger
{
void Log(string message);
}
public class ConsoleLogger : ILogger
{
private static int count = 0;
public ConsoleLogger()
{
Console.WriteLine("Hello from constructor number:" + count);
count++;
}
public void Log(string message)
{
Console.WriteLine(message);
}
}
public class CustomerTasks
{
private readonly ILogger logger;
public CustomerTasks(ILogger logger)
{
this.logger = logger;
}
public void SaveCustomer()
{
logger.Log("Saved customer");
}
}
I have found this article in dotnetslackers that pretty much cleared things up for me.
maxPoolSize is the maximal number of instances that will be returned to the pool upon release. subsequent releases will result in objects being discarded.
one inaccuracy i've noticed is that initialPoolSize is the number of instances created upon first resolve and NOT container creation like the article claims (probably due to version changes since it was written)