AutoBogus configuration and Bogus Determinism - bogus

When using the AutoBogus builder configurations with either the Create or Generate methods, I can't seem to find the way I can provide the deterministic way to seed random. UseSeed is not available.
For example:
var orderFaker = AutoFaker.Create(builder => builder.WithOverride(new OrderOverride()));
orderFaker
// .UseSeed(<int>) is not available on orderFaker
.Generate(5);
Similarly,
List<Order> sut = AutoFaker.Generate<Order>(5,
builder => builder.WithOverride(new OrderOverride())
);
Am I missing something or is it just not available at this level?
As a workaround, my override class just has a static method for the Rules being applied, making applicable in the override as well as when instantiating AutoFaker<Order>. This seems to be working, but just wondering if there's a better way...
Faker<Order> orderFaker = new AutoFaker<Order>().Rules(
OrderOverride.OrderGenerator);
List<Order> actual = orderFaker
// https://github.com/bchavez/Bogus/tree/cc2f894e46be08e3a1521f31b464017666f4f8c7#determinism
// UseSeed at the faker level ensures consistent output
.UseSeed(1338)
.Generate(5)
.ToList();
public class OrderOverride : AutoGeneratorOverride
{
public override bool CanOverride(AutoGenerateContext context)
{
return context.GenerateType == typeof(Order);
}
public override void Generate(AutoGenerateOverrideContext context)
{
var o = context.Instance as Order;
var f = context.Faker;
OrderGenerator(f, o);
}
public static void OrderGenerator(Faker f, Order o)
{
o.LineItems = new AutoFaker<OrderLineItem>().GenerateBetween(2, 5);
o.Notes = f.Lorem.Text();
}
}

Related

DryIoc, Spring.Net's GetObjectsOfType equivalent?

With Spring.Net, it's possible to query all objects of a certain (ancestor) type.
var ctx = ContextRegistry.GetContext();
var setUsers = ctx.GetObjectsOfType(typeof(ISetUser)).Values.OfType<ISetUser>().ToList();
How can this be done with DryIoc?
The direct answer given sample classes and interfaces would be:
public interface IA { }
public interface IB { }
public class AB : IA, IB { }
public class AA : IA { }
[Test]
public void Resolve_all_services_implementing_the_interface()
{
var container = new Container();
container.Register<IB, AB>();
container.Register<AA>();
// resolve IA's, even if no IA service type was registered
var aas = container.GetServiceRegistrations()
.Where(r => typeof(IA).IsAssignableFrom(r.Factory.ImplementationType ?? r.ServiceType))
.Select(r => (IA)container.Resolve(r.ServiceType))
.ToList();
Assert.AreEqual(2, aas.Count);
}
If you will want to retrieve some interface, it probably good to register it from the start (plan for it):
[Test]
public void Resolve_automatically_registered_interface_services()
{
var container = new Container();
// changed to RegisterMany to automatically register implemented interfaces as services
container.RegisterMany<AB>();
container.RegisterMany<AA>();
// simple resolve
var aas = container.Resolve<IList<IA>>();
Assert.AreEqual(2, aas.Count);
}

Decoration using Castle DynamicProxy and StructureMap 3 in a Convention - DecorateAllWith

How to use DecorateAllWith to decorate with a DynamicProxy all instances implements an interface?
For example:
public class ApplicationServiceInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
// ...
invocation.Proceed();
// ...
}
}
public class ApplicationServiceConvention : IRegistrationConvention
{
public void Process(Type type, Registry registry)
{
if (type.CanBeCastTo<IApplicationService>() && type.IsInterface)
{
var proxyGenerator = new ProxyGenerator();
// ??? how to use proxyGenerator??
// ???
registry.For(type).DecorateAllWith(???); // How to use DecorateAllWith DynamicProxy ...??
}
}
}
I could decorate some interfaces to concrete types using (for example):
var proxyGenerator = new ProxyGenerator();
registry.For<IApplicationService>().Use<BaseAppService>().DecorateWith(service => proxyGenerator.CreateInterfaceProxyWithTargetInterface(....))
But havent able to using DecorateAll to do this.
To call registry.For<>().Use<>().DecorateWith() I have to do this:
if (type.CanBeCastTo<IApplicationService>() && !type.IsAbstract)
{
var interfaceToProxy = type.GetInterface("I" + type.Name);
if (interfaceToProxy == null)
return null;
var proxyGenerator = new ProxyGenerator();
// Build expression to use registration by reflection
var expression = BuildExpressionTreeToCreateProxy(proxyGenerator, type, interfaceType, new MyInterceptor());
// Register using reflection
var f = CallGenericMethod(registry, "For", interfaceToProxy);
var u = CallGenericMethod(f, "Use", type);
CallMethod(u, "DecorateWith", expression);
}
Only for crazy minds ...
I start to get very tired of StructureMap, many changes and no documentation, I have been read the source code but ... too many efforts for my objective ...
If someone can give me a bit of light I will be grateful.
Thanks in advance.
In addition ... I post here the real code of my helper to generate the expression tree an register the plugin family:
public static class RegistrationHelper
{
public static void RegisterWithInterceptors(this Registry registry, Type interfaceToProxy, Type concreteType,
IInterceptor[] interceptors, ILifecycle lifecycle = null)
{
var proxyGenerator = new ProxyGenerator();
// Generate expression tree to call DecoreWith of StructureMap SmartInstance type
// registry.For<interfaceToProxy>().Use<concreteType>()
// .DecoreWith(ex => (IApplicationService)
// proxyGenerator.CreateInterfaceProxyWithTargetInterface(interfaceToProxy, ex, interceptors)
var expressionParameter = Expression.Parameter(interfaceToProxy, "ex");
var proxyGeneratorConstant = Expression.Constant(proxyGenerator);
var interfaceConstant = Expression.Constant(interfaceToProxy);
var interceptorConstant = Expression.Constant(interceptors);
var methodCallExpression = Expression.Call(proxyGeneratorConstant,
typeof (ProxyGenerator).GetMethods().First(
met => met.Name == "CreateInterfaceProxyWithTargetInterface"
&& !met.IsGenericMethod && met.GetParameters().Count() == 3),
interfaceConstant,
expressionParameter,
interceptorConstant);
var convert = Expression.Convert(methodCallExpression, interfaceToProxy);
var func = typeof(Func<,>).MakeGenericType(interfaceToProxy, interfaceToProxy);
var expr = Expression.Lambda(func, convert, expressionParameter);
// Register using reflection
registry.CallGenericMethod("For", interfaceToProxy, new[] {(object) lifecycle /*Lifecicle*/})
.CallGenericMethod("Use", concreteType)
.CallNoGenericMethod("DecorateWith", expr);
}
}
public static class CallMethodExtensions
{
/// <summary>
/// Call a method with Generic parameter by reflection (obj.methodName[genericType](parameters)
/// </summary>
/// <returns></returns>
public static object CallGenericMethod(this object obj, string methodName, Type genericType, params object[] parameters)
{
var metod = obj.GetType().GetMethods().First(m => m.Name == methodName && m.IsGenericMethod);
var genericMethod = metod.MakeGenericMethod(genericType);
return genericMethod.Invoke(obj, parameters);
}
/// <summary>
/// Call a method without Generic parameter by reflection (obj.methodName(parameters)
/// </summary>
/// <returns></returns>
public static object CallNoGenericMethod(this object obj, string methodName, params object[] parameters)
{
var method = obj.GetType().GetMethods().First(m => m.Name == methodName && !m.IsGenericMethod);
return method.Invoke(obj, parameters);
}
}
Almost two years later I have needed return this issue for a new project. This time I have solved it this time I have used StructureMap 4.
You can use a custom interceptor policy to decorate an instance in function of his type. You have to implement one interceptor, one interceptor policy and configure it on a registry.
The Interceptor
public class MyExInterceptor : Castle.DynamicProxy.IInterceptor
{
public void Intercept(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("-- Call to " + invocation.Method);
invocation.Proceed();
}
}
The interceptor policy
public class CustomInterception : IInterceptorPolicy
{
public string Description
{
get { return "good interception policy"; }
}
public IEnumerable<IInterceptor> DetermineInterceptors(Type pluginType, Instance instance)
{
if (pluginType == typeof(IAppService))
{
// DecoratorInterceptor is the simple case of wrapping one type with another
// concrete type that takes the first as a dependency
yield return new FuncInterceptor<IAppService>(i =>
(IAppService)
DynamicProxyHelper.CreateInterfaceProxyWithTargetInterface(typeof(IAppService), i));
}
}
}
Configuration
var container = new Container(_ =>
{
_.Policies.Interceptors(new CustomInterception());
_.For<IAppService>().Use<AppServiceImplementation>();
});
var service = container.GetInstance<IAppService>();
service.DoWork();
You can get a working example on this gist https://gist.github.com/tolemac/3e31b44b7fc7d0b49c6547018f332d68, in the gist you can find three types of decoration, the third is like this answer.
Using it you can configure the decorators of your services easily.

Creating an instance of a generic type in DART

I was wondering if is possible to create an instance of a generic type in Dart. In other languages like Java you could work around this using reflection, but I'm not sure if this is possible in Dart.
I have this class:
class GenericController <T extends RequestHandler> {
void processRequest() {
T t = new T(); // ERROR
}
}
I tried mezonis approach with the Activator and it works. But it is an expensive approach as it uses mirrors, which requires you to use "mirrorsUsed" if you don't want to have a 2-4MB js file.
This morning I had the idea to use a generic typedef as generator and thus get rid of reflection:
You define a method type like this: (Add params if necessary)
typedef S ItemCreator<S>();
or even better:
typedef ItemCreator<S> = S Function();
Then in the class that needs to create the new instances:
class PagedListData<T>{
...
ItemCreator<T> creator;
PagedListData(ItemCreator<T> this.creator) {
}
void performMagic() {
T item = creator();
...
}
}
Then you can instantiate the PagedList like this:
PagedListData<UserListItem> users
= new PagedListData<UserListItem>(()=> new UserListItem());
You don't lose the advantage of using generic because at declaration time you need to provide the target class anyway, so defining the creator method doesn't hurt.
You can use similar code:
import "dart:mirrors";
void main() {
var controller = new GenericController<Foo>();
controller.processRequest();
}
class GenericController<T extends RequestHandler> {
void processRequest() {
//T t = new T();
T t = Activator.createInstance(T);
t.tellAboutHimself();
}
}
class Foo extends RequestHandler {
void tellAboutHimself() {
print("Hello, I am 'Foo'");
}
}
abstract class RequestHandler {
void tellAboutHimself();
}
class Activator {
static createInstance(Type type, [Symbol constructor, List
arguments, Map<Symbol, dynamic> namedArguments]) {
if (type == null) {
throw new ArgumentError("type: $type");
}
if (constructor == null) {
constructor = const Symbol("");
}
if (arguments == null) {
arguments = const [];
}
var typeMirror = reflectType(type);
if (typeMirror is ClassMirror) {
return typeMirror.newInstance(constructor, arguments,
namedArguments).reflectee;
} else {
throw new ArgumentError("Cannot create the instance of the type '$type'.");
}
}
}
I don't know if this is still useful to anyone. But I have found an easy workaround. In the function you want to initialize the type T, pass an extra argument of type T Function(). This function should return an instance of T. Now whenever you want to create object of T, call the function.
class foo<T> {
void foo(T Function() creator) {
final t = creator();
// use t
}
}
P.S. inspired by Patrick's answer
2022 answer
Just came across this problem and found out that although instantiating using T() is still not possible, you can get the constructor of an object easier with SomeClass.new in dart>=2.15.
So what you could do is:
class MyClass<T> {
final T Function() creator;
MyClass(this.creator);
T getGenericInstance() {
return creator();
}
}
and when using it:
final myClass = MyClass<SomeOtherClass>(SomeOtherClass.new)
Nothing different but looks cleaner imo.
Here's my work around for this sad limitation
class RequestHandler {
static final _constructors = {
RequestHandler: () => RequestHandler(),
RequestHandler2: () => RequestHandler2(),
};
static RequestHandler create(Type type) {
return _constructors[type]();
}
}
class RequestHandler2 extends RequestHandler {}
class GenericController<T extends RequestHandler> {
void processRequest() {
//T t = new T(); // ERROR
T t = RequestHandler.create(T);
}
}
test() {
final controller = GenericController<RequestHandler2>();
controller.processRequest();
}
Sorry but as far as I know, a type parameter cannot be used to name a constructor in an instance creation expression in Dart.
Working with FLutter
typedef S ItemCreator<S>();
mixin SharedExtension<T> {
T getSPData(ItemCreator<T> creator) async {
return creator();
}
}
Abc a = sharedObj.getSPData(()=> Abc());
P.S. inspired by Patrick
simple like that.
import 'dart:mirrors';
void main(List<String> args) {
final a = A<B>();
final b1 = a.getInstance();
final b2 = a.getInstance();
print('${b1.value}|${b1.text}|${b1.hashCode}');
print('${b2.value}|${b2.text}|${b2.hashCode}');
}
class A<T extends B> {
static int count = 0;
T getInstance() {
return reflectClass(T).newInstance(
Symbol(''),
['Text ${++count}'],
{Symbol('value'): count},
).reflectee;
}
}
class B {
final int value;
final String text;
B(this.text, {required this.value});
}
Inspired by Patrick's answer, this is the factory I ended up with.
class ServiceFactory<T> {
static final Map<Type, dynamic> _cache = <String, dynamic>{};
static T getInstance<T>(T Function() creator) {
String typeName = T.toString();
return _cache.putIfAbsent(typeName, () => creator());
}
}
Then I would use it like this.
final authClient = ServiceFactory.getInstance<AuthenticationClient>(() => AuthenticationClient());
Warning: Erik made a very good point in the comment below that the same type name can exist in multiple packages and that will cause issues. As much as I dislike to force the user to pass in a string key (that way it's the consumer's responsibility to ensuring the uniqueness of the type name), that might be the only way.

Converting Caching Pattern from Structuremap to AutoFac

I'm switching over from structure map to Autofac. I've use a caching pattern from Scott Millett's book ASP.net Design Patterns which implements an interface for both Cache and the Repository and switches in the appropriate object depending on the constructor parameter name
The interface looks like this
public interface ISchemeRepository
{
List<Scheme> GetSchemes();
}
The cache object looks like this
public class SchemeRepository : BaseRepository, ISchemeRepository
{
/***************************************************************
* Properties
***************************************************************/
private readonly ISchemeRepository schemeRepository;
/***************************************************************
* Constructors
***************************************************************/
public SchemeRepository()
: this(ObjectFactory.GetInstance<ISchemeRepository>(), ObjectFactory.GetInstance<IConfigurationSetting>())
{
}
public SchemeRepository(ISchemeRepository realSchemeRepository, IConfigurationSetting configurationSetting)
{
schemeRepository = realSchemeRepository;
this.configurationSetting = configurationSetting;
}
/**************************************************************
* Methods
***************************************************************/
public List<Scheme> GetSchemes()
{
string key = Prefix + "Schemes";
if (!MemoryCache.Default.Contains(key))
{
MemoryCache.Default.Add(key, schemeRepository.GetSchemes(), new CacheItemPolicy());
}
return (List<Scheme>)MemoryCache.Default.Get(key);
}
}
The repository looks like this
public class SchemeRepository : BaseLocalRepository, ISchemeRepository
{
/***************************************************************
* Properties
***************************************************************/
private readonly IConnectionSetting connectionSetting;
/***************************************************************
* Constructors
***************************************************************/
public SchemeRepository()
: this(ObjectFactory.GetInstance<IConnectionSetting>())
{
}
public SchemeRepository(IConnectionSetting connectionSetting)
{
this.connectionSetting = connectionSetting;
}
/**************************************************************
* Methods
***************************************************************/
public List<Scheme> GetSchemes()
{
var response = new List<Scheme>();
var conn = new SqlConnection(connectionSetting.CQBConnectionString);
var command = new SqlCommand("proc_GetSchemes", conn) { CommandType = CommandType.StoredProcedure };
conn.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
response.Add(
new Scheme
{
SchemeId = reader["Scheme_Id"].ToString().Trim(),
GuaranteeText = reader["Guarantee_Text"].ToString().Trim()
}
);
}
conn.Close();
return response;
}
}
The structure map call is below
InstanceOf<Repository.Local.Contract.IProviderRepository>().Is.OfConcreteType<Repository.Local.Core.ProviderRepository>().WithName("RealProviderRepository");
ForRequestedType<Repository.Local.Contract.IProviderRepository>().TheDefault.Is.OfConcreteType<Repository.Local.Cache.ProviderRepository>().CtorDependency<Repository.Local.Contract.IProviderRepository>().Is(x => x.TheInstanceNamed("RealProviderRepository"));
Structure map looks at the constructor and if it contains a parameter called "realSchemeRepository" then it implements the object that connect to the database, if not it implements the cache object that checks the cache and calls the database if nothing is in the cache and populates the cache.
How do I do this in Autofac? Is there a better way of doing this in Autofac?
I believe what you're asking how to do is set up a decorator between your two repository classes. I'm gonna pretend the two class names are CacheSchemeRepository and RealSchemeRepository because naming them exactly the same is confusing and terrible. Anyways...
builder.Register(c => new RealSchemeRepository(c.Resolve<IConnectionSetting>())
.Named<ISchemeRepository>("real");
builder.RegisterDecorator<ISchemeRepository>(
(c, inner) => new CacheSchemeRepository(inner, c.Resolve<IConfigurationSetting>()),
"real");

Sharepoint 2007 - cant find my modifications to web.config in SpWebApplication.WebConfigModifications

I cant seem to find the modifications I made to web.config in my FeatureRecievers Activated event. I try to get the modifications from the SpWebApplication.WebConfigModifications collection in the deactivate event, but this is always empty.... And the strangest thing is that my changes are still reverted after deactivating the feature...
My question is, should I not be able to view all changes made to the web.config files when accessing the SpWebApplication.WebConfigModifications collection in the Deactivating event? How should I go about to remove my changes explicitly?
public class FeatureReciever : SPFeatureReceiver
{
private const string FEATURE_NAME = "HelloWorld";
private class Modification
{
public string Name;
public string XPath;
public string Value;
public SPWebConfigModification.SPWebConfigModificationType ModificationType;
public bool createOnly;
public Modification(string name, string xPath, string value, SPWebConfigModification.SPWebConfigModificationType modificationType, bool createOnly)
{
Name = name;
XPath = xPath;
Value = value;
ModificationType = modificationType;
this.createOnly = createOnly;
}
}
private Modification[] modifications =
{
new Modification("connectionStrings", "configuration", "<connectionStrings/>", SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode, true),
new Modification("add[#name='ConnectionString'][#connectionString='Data Source=serverName;Initial Catalog=DBName;User Id=UserId;Password=Pass']", "configuration/connectionStrings", "<add name='ConnectionString' connectionString='Data Source=serverName;Initial Catalog=DBName;User Id=UserId;Password=Pass'/>", SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode, false)
};
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSite siteCollection = (properties.Feature.Parent as SPWeb).Site as SPSite;
SPWebApplication webApplication = siteCollection.WebApplication;
siteCollection.RootWeb.Title = "Set from activating code at " + DateTime.Now.ToString();
foreach (Modification entry in modifications)
{
SPWebConfigModification webConfigModification = CreateModification(entry);
webApplication.WebConfigModifications.Add(webConfigModification);
}
webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
webApplication.WebService.Update();
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPSite siteCollection = (properties.Feature.Parent as SPWeb).Site as SPSite;
SPWebApplication webApplication = siteCollection.WebApplication;
siteCollection.RootWeb.Title = "Set from deactivating code at " + DateTime.Now.ToString();
IList<SPWebConfigModification> modifications = webApplication.WebConfigModifications;
foreach (SPWebConfigModification modification in modifications)
{
if (modification.Owner == FEATURE_NAME)
{
webApplication.WebConfigModifications.Remove(modification);
}
}
webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
webApplication.WebService.Update();
}
public override void FeatureInstalled(SPFeatureReceiverProperties properties)
{
}
public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
{
}
private SPWebConfigModification CreateModification(Modification entry)
{
SPWebConfigModification spWebConfigModification = new SPWebConfigModification()
{
Name = entry.Name,
Path = entry.XPath,
Owner = FEATURE_NAME,
Sequence = 0,
Type = entry.ModificationType,
Value = entry.Value
};
return spWebConfigModification;
}
}
Thanks for your time.
/Hans
Finally today I figured out what was wrong with my code (that is why the WebConfigModifications collection was empty when i queryied it in the deactivate event) it seems you must apply the changes in a different manner than I had done.
My original approach to applying the changes involved the following code:
Activate event
webApplication.Farm.Services.GetValue().ApplyWebConfigModifications();
webApplication.WebService.Update();
The "correct" way of doing it is this:
SPWebService.ContentService.ApplyWebConfigModifications();
webApplication.Update();
Although I am still at a loss why my original code did not work.. could someone with more knowlege of the configuration object in Sharepoint enlighten me?

Resources