log4cxx -- is it possible to configure a custom appender with custom arguments from a config file? - log4cxx

I need to write a custom appender in log4cxx. This answer describes how to do it. In Java, in log4j, it is possible for a custom appender to devise custom parameters. I add a property and a getter and setter:
private int myParameter = 0;
public void setMyParameter(int p) { myParameter = p; }
public int getMyParameter() { return myParameter; }
Then I can use myParameter in configuration file, and the framework somehow knows how to configure my appender with it.
Question: does log4cxx have a similar capability? For me it is enough if I get a map map<string, string> with properties.

Ok, figured out the answer myself. You need to override member function setOption. It will get called a number of times: once per each read option. You then override function activateOptions and its get called after all options have been processed. It can be used as a trigger to initialize the appender with the read parameters.
Not as convenient as mapping to getters/setters, but it gets the job done:
class CustomAppender : public AppenderSkeleton
{
int _myParameter = 0;
void initialize(int myParameter);
// ...
public:
void setOption(LogString const& option, LogString const& value) override
{
if (option == "MyParameter") try
{
_myParameter = boost::lexical_cast<int>(value);
}
catch (boost::bad_lexical_cast const&) {
// go with default
}
}
void activateOptions(helpers::Pool &) override
{
initialize(_myParameter);
}
};

Related

How can I easily wrap the StackExchange.Redis `IDatabase`?

I want to override methods for specific commands on the IDatabase to modify the results.
FT.SEARCH should never return duplicate keys but it can when there is some sort of corruption.
I am using another library that calls FT.SEARCH in IDatabase so this part can only be done by changing IDatabase.
I can autogenerate a wrapper and then use this, but it would need to be maintained and updated every time the IDatabase interface changes. It would be unfortunate to need to update the wrapper class even when I didn't need to override the method that changed in IDatabase. Is there another option that would have similar performance that this wrapper does?
Assume I had a class called DatabaseWrapper all methods were virtual and that was in another package example code would look like:
public sealed class MyDatabaseOverrides: DatabaseWrapper
{
private const string RediSearchSearchCommandName = "FT.SEARCH";
public MyDatabaseOverrides(IDatabase wrapped) : base(wrapped)
{
}
public override Task<RedisResult> ExecuteAsync(string command, params object[] args)
{
var resultTask = base.ExecuteAsync(command, args);
if (string.Equals(RediSearchSearchCommandName, command, StringComparison.OrdinalIgnoreCase))
{
return SkipAndLogDuplicateKeys(resultTask);
}
return resultTask;
}
private async Task<RedisResult> SkipAndLogDuplicateKeys(Task<RedisResult> resultTask)
{
// implementation omitted for brevity
return await resultTask;
}
}

DeploymentPlanExecutor.OnExecute not Being Called By SqlPackage.exe [duplicate]

I'm trying to program a custom DeploymentPlanExecutor using Microsofts DacFx 3.0 but the OnExecute-Method is never called.
If I use an identical DeploymentPlanModifier instead, OnExecute() is called as expected.
No matter whether I add the Executor, the Modifier, or both, the DAC actually is successfully deployed to the Database.
The Executor seems to be recognized during the Deployment since OnApplyDeploymentConfiguration() is called
Unfortunately I wasn't able to find any examples that use an DeploymentPlanExecutor (only examples with DeploymentPlanModifier) and the documentation of DacFx does not help at all.
My question is, why is OnExecute() in the DeploymentPlanExecutor not called and how can I fix this?
The code for my DeploymentPlanExecutor and DeploymentPlanExecutor:
using System.Collections.Generic;
using Microsoft.SqlServer.Dac.Deployment;
namespace DacTest
{
// The executor that does not work as expected
[ExportDeploymentPlanExecutor(ContributorId, "1.0.0.0")]
public class Executor : DeploymentPlanExecutor
{
public const string ContributorId = "DacTest.Executor";
protected override void OnApplyDeploymentConfiguration(DeploymentContributorContext context, ICollection<DeploymentContributorConfigurationStream> configurationStreams)
{
// Called
}
protected override void OnEstablishDeploymentConfiguration(DeploymentContributorConfigurationSetup setup)
{
// Not called
}
protected override void OnExecute(DeploymentPlanContributorContext context)
{
// Not called!
}
}
// The modifier that does work as expected
[ExportDeploymentPlanModifier(ContributorId, "1.0.0.0")]
public class Modifier : DeploymentPlanModifier
{
public const string ContributorId = "DacTest.Modifier";
protected override void OnApplyDeploymentConfiguration(DeploymentContributorContext context, ICollection<DeploymentContributorConfigurationStream> configurationStreams)
{
// Called
}
protected override void OnEstablishDeploymentConfiguration(DeploymentContributorConfigurationSetup setup)
{
// Not called
}
protected override void OnExecute(DeploymentPlanContributorContext context)
{
// Called!
}
}
}
The code calling the deployment (has to be in a different assembly):
using (DacPackage dacpac = DacPackage.Load(#"C:\Temp\dac.dacpac"))
{
DacDeployOptions dacDeployOptions = new DacDeployOptions();
dacDeployOptions.AdditionalDeploymentContributors = Executor.ContributorId; // + ";" + Modifier.ContributorId;
DacServices dacServices = new DacServices(connectionString);
dacServices.Deploy(dacpac, databaseName, true, dacDeployOptions);
}
The problem was, that you have to explicitly tell DacFx to use Executors. Modifiers are enabled by default though.
dacDeployOptions.RunDeploymentPlanExecutors = true;

Is there any way to pass Output of one workflow to another without using outarguments?

I have recently started working with Workflows.I am able to pass output of one activity as input to another through making use of OutArgument .Is it possible without using OutArgument.
If Possible please suggest me how?
Thanks all
You can use a workflow extension to act as a repository of variables in the scope of the whole workflow.
Create a workflow extension that contains properties.
Add the extension to the workflow application.
Set or Get the value of the properties from within Activities.
See https://msdn.microsoft.com/en-us/library/ff460215(v=vs.110).aspx
In response to your comment below.
You are wrong in your assumption. The extension "holds" the output from activity 1 which is then available to activity 2.
For example:
Create a class to hold properties:
public class PropertyStoreExtension
{
int _myProperty
public int MyProperty
{
get
{
return this._myProperty;
}
set
{
this._myProperty = value;
}
}
}
Add this as an extension to your workflow:
PropertyStoreExtension propertyStoreExtension = new PropertyStoreExtension
WorkflowInvoker myWorkflowInstence = new
WorkflowInvoker(myWorkflowDefinition());
myWorkflowInstence.Extensions.Add(propertyStoreExtension);
myWorkflowInstence.Invoke()
Your workflow contains 2 activities:
The first takes its "output" and stores it in the extension.
public class Activity1_SetProperty: CodeActivity
{
protected override void Execute(CodeActivityContext context)
{
PropertyStoreExtension pse =context.GetExtension<PropertyStoreExtension>();
if (pse != null)
{
pse.MyProperty=outputValue;
}
}
}
The second gets the value out of the extension.
public class Activity2_GetProperty: CodeActivity
{
protected override void Execute(CodeActivityContext context)
{
PropertyStoreExtension pse =context.GetExtension<PropertyStoreExtension>();
if (pse != null)
{
int intputValue; = pse.MyProperty
}
}
}

How can I make AutoMoqCustomization use Strict MockBehavior?

Using AutoFixture with the AutoFixture.AutoMoq package, I sometimes find tests that weren't configured to correctly test the thing they meant to test, but the problem was never discovered because of the default (Loose) Mock behavior:
public interface IService
{
bool IsSomethingTrue(int id);
}
void Main()
{
var fixture = new Fixture()
.Customize(new AutoMoqCustomization());
var service = fixture.Freeze<Mock<IService>>();
Console.WriteLine(service.Object.IsSomethingTrue(1)); // false
}
I'd like to make Mocks get created with Strict behavior, so we're forced to call Setup() for the methods we expect to be called. I can do this for each individual mock like this:
fixture.Customize<Mock<IService>>(c => c.FromFactory(() => new Mock<IService>(MockBehavior.Strict)));
But after combing through source code for AutoMoqCustomization() and the various ISpecimenBuilder and other implementations, I'm pretty lost as to the best way to just make all Mocks get initialized with strict behavior. The framework appears to be very flexible and extensible, so I'm sure there's a simple way to do this--I just can't figure out how.
There's no simple built-in feature that will enable you to do something like that, but it shouldn't be that hard to do.
Essentially, you'd need to change MockConstructorQuery so that it invokes the constructor that takes a MockBehavior value, and pass in MockBehavior.Strict.
Now, you can't change that behaviour in MockConstructorQuery, but that class is only some 9-10 lines of code, so you should be able to create a new class that implements IMethodQuery by using MockConstructorQuery as a starting point.
Likewise, you'll also need to create a custom ICustomization that does almost exactly the same as AutoMoqCustomization, with the only exception that it uses your custom IMethodQuery with strict mock configuration instead of MockConstructorQuery. That's another 7 lines of code you'll need to write.
All that said, in my experience, using strict mocks is a bad idea. It'll make your tests brittle, and you'll waste a lot of time mending 'broken' tests. I can only recommend that you don't do this, but now I've warned you; it's your foot.
For those interested, down below you can find #MarkSeemann's reply translated into code. I am pretty sure it does not cover all use cases and it was not heavily tested. But it should be a good starting point.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Moq;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Kernel;
namespace ConsoleApplication1
{
public class StrictAutoMoqCustomization : ICustomization
{
public StrictAutoMoqCustomization() : this(new MockRelay()) { }
public StrictAutoMoqCustomization(ISpecimenBuilder relay)
{
// TODO Null check params
Relay = relay;
}
public ISpecimenBuilder Relay { get; }
public void Customize(IFixture fixture)
{
// TODO Null check params
fixture.Customizations.Add(new MockPostprocessor(new MethodInvoker(new StrictMockConstructorQuery())));
fixture.ResidueCollectors.Add(Relay);
}
}
public class StrictMockConstructorMethod : IMethod
{
private readonly ConstructorInfo ctor;
private readonly ParameterInfo[] paramInfos;
public StrictMockConstructorMethod(ConstructorInfo ctor, ParameterInfo[] paramInfos)
{
// TODO Null check params
this.ctor = ctor;
this.paramInfos = paramInfos;
}
public IEnumerable<ParameterInfo> Parameters => paramInfos;
public object Invoke(IEnumerable<object> parameters) => ctor.Invoke(parameters?.ToArray() ?? new object[] { });
}
public class StrictMockConstructorQuery : IMethodQuery
{
public IEnumerable<IMethod> SelectMethods(Type type)
{
if (!IsMock(type))
{
return Enumerable.Empty<IMethod>();
}
if (!GetMockedType(type).IsInterface && !IsDelegate(type))
{
return Enumerable.Empty<IMethod>();
}
var ctor = type.GetConstructor(new[] { typeof(MockBehavior) });
return new IMethod[]
{
new StrictMockConstructorMethod(ctor, ctor.GetParameters())
};
}
private static bool IsMock(Type type)
{
return type != null && type.IsGenericType && typeof(Mock<>).IsAssignableFrom(type.GetGenericTypeDefinition()) && !GetMockedType(type).IsGenericParameter;
}
private static Type GetMockedType(Type type)
{
return type.GetGenericArguments().Single();
}
internal static bool IsDelegate(Type type)
{
return typeof(MulticastDelegate).IsAssignableFrom(type.BaseType);
}
}
}
Usage
var fixture = new Fixture().Customize(new StrictAutoMoqCustomization());

Access private static objects in public static method

I'm trying to make a global settings provider for an application. It seemed bulky to have one object duplicated in so many different classes.
I've seeth this method work when the private static variable was something simple, like an integer, but I want it to work for QSettings—an object.
// settings.h
class Settings {
public:
static void Initialize();
static int serverRefreshRate();
private:
QSettings *settings;
};
// settings.cpp
#include "Server/settings.h"
void Settings::Initialize() {
Settings::settings = new QSettings(/* etc */);
}
int Settings::serverRefreshRate() {
return settings->value("server/refreshRate", 10000).toInt();
}
Is there a way I can achieve this, or am I going about it in the wrong way?
Thanks!
EDIT,
Firstly, it needed to be:
static QSettings *settings;
And I needed the following in the .cpp.
QSettings* Settings::settings = NULL;

Resources