예제 #1
0
 public PurchaseService(
     IPurchaseRepository purchaseRepository,
     IAdapterFactory adapterFactory)
 {
     this.purchaseRepository = purchaseRepository;
     this.adapterFactory     = adapterFactory;
 }
예제 #2
0
        public static void ApplyTo <T>(
            this JsonPatchDocument <T> patchDoc,
            T objectToApplyTo,
            IAdapterFactory adapterFactory,
            ModelStateDictionary modelState,
            string prefix = "") where T : class
        {
            if (patchDoc == null)
            {
                throw new ArgumentNullException(nameof(patchDoc));
            }

            if (objectToApplyTo == null)
            {
                throw new ArgumentNullException(nameof(objectToApplyTo));
            }

            if (modelState == null)
            {
                throw new ArgumentNullException(nameof(modelState));
            }

            var objectAdapter = new ObjectAdapter(patchDoc.ContractResolver, jsonPatchError =>
            {
                var affectedObjectName = jsonPatchError.AffectedObject.GetType().Name;
                var key = string.IsNullOrEmpty(prefix) ? affectedObjectName : prefix + "." + affectedObjectName;
                modelState.TryAddModelError(key, jsonPatchError.ErrorMessage);
            }, adapterFactory);

            patchDoc.ApplyTo(objectToApplyTo, objectAdapter);
        }
예제 #3
0
            public void Must_reuse_the_same_assembly_for_all_generated_adapter_factories()
            {
                var fooConfiguration = new MappingConfiguration <Foo, IFooView>();

                fooConfiguration.Map(view => view.Name).From(foo => foo.Name);
                fooConfiguration.Map(view => view.Id).From(foo => foo.Id);
                fooConfiguration.Map(view => view.Factor).From(foo => foo.Factor);

                IAdapterFactory <Foo, IFooView> fooFactory = AdapterFactoryGenerator.Instance.Generate <Foo, IFooView>(fooConfiguration.Mappings);
                var      foo1             = new Foo("test", Guid.NewGuid(), 1);
                IFooView fooView          = fooFactory.Create(foo1);
                var      barConfiguration = new MappingConfiguration <Bar, IFooView>();

                barConfiguration.Map(view => view.Name).From(bar => bar.Name);
                barConfiguration.Map(view => view.Id).From(bar => bar.Id);
                barConfiguration.Map(view => view.Factor).From(bar => null);

                IAdapterFactory <Bar, IFooView> barFactory = AdapterFactoryGenerator.Instance.Generate <Bar, IFooView>(barConfiguration.Mappings);
                var      bar1        = new Bar("test", Guid.NewGuid());
                IFooView barView     = barFactory.Create(bar1);
                Type     fooViewType = fooView.GetType();
                Type     barViewType = barView.GetType();

                Assert.That(fooViewType.Assembly, Is.SameAs(barViewType.Assembly));
            }
예제 #4
0
        /// <summary>
        /// Creates adapters that adapt <paramref name="sourceInstances"/> to instances of <typeparamref name="TTarget"/>.
        /// </summary>
        /// <typeparam name="TSource">The source type.</typeparam>
        /// <typeparam name="TTarget">The target type.</typeparam>
        /// <param name="adapterFactory">An adapter factory.</param>
        /// <param name="sourceInstances"><typeparamref name="TSource"/> instances for which to create adapters.</param>
        /// <returns>Instances of <typeparamref name="TTarget"/> that are created at runtime.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="sourceInstances"/> is null.</exception>
        public static IEnumerable <TTarget> CreateMany <TSource, TTarget>(this IAdapterFactory <TSource, TTarget> adapterFactory, IEnumerable <TSource> sourceInstances)
            where TSource : class
            where TTarget : class
        {
            sourceInstances.ThrowIfNull("sourceInstances");

            return(sourceInstances.Select(adapterFactory.Create));
        }
예제 #5
0
        public AdapterManager(ILogger <AdapterManager> logger, IAdapterFactory adapterFactory, IAdapterRepository adapterRepository, INodeFactory nodeFactory)
        {
            _logger         = logger;
            _adapterFactory = adapterFactory;
            _adapterRepo    = adapterRepository;
            _nodeFactory    = nodeFactory;

            LoadAdapters();
        }
예제 #6
0
 public PaymentService(
     IPaymentRepository paymentRepository,
     IClientAcquiringBank clientAcquiringBank,
     IAdapterFactory adapterFactory)
 {
     this.paymentRepository   = paymentRepository;
     this.clientAcquiringBank = clientAcquiringBank;
     this.adapterFactory      = adapterFactory;
 }
예제 #7
0
 /// <summary>
 /// Initializes a new instance of <see cref="ObjectAdapter"/>.
 /// </summary>
 /// <param name="contractResolver">The <see cref="IContractResolver"/>.</param>
 /// <param name="logErrorAction">The <see cref="Action"/> for logging <see cref="JsonPatchError"/>.</param>
 /// <param name="adapterFactory">The <see cref="IAdapterFactory"/> to use when creating adaptors.</param>
 public ObjectAdapter(
     IContractResolver contractResolver,
     Action <JsonPatchError> logErrorAction,
     IAdapterFactory adapterFactory)
 {
     ContractResolver = contractResolver ?? throw new ArgumentNullException(nameof(contractResolver));
     LogErrorAction   = logErrorAction;
     AdapterFactory   = adapterFactory ?? throw new ArgumentNullException(nameof(adapterFactory));
 }
        public AdapterFactory(
            string role, IAdapterFactory implementation)
        {
            if (string.IsNullOrEmpty(role))
            {
                throw Failure.NullOrEmptyString(nameof(role));
            }

            this.role           = role;
            this.implementation = implementation ?? AdapterFactory.Default;
        }
예제 #9
0
            public void Must_perform_acceptably()
            {
                var configuration = new MappingConfiguration <Foo, IFooView>();

                configuration.Map(view => view.Name).From(foo => foo.Name);
                configuration.Map(view => view.Id).From(foo => foo.Id);
                configuration.Map(view => view.Factor).From(foo => foo.Factor);

                IAdapterFactory <Foo, IFooView> systemUnderTest = AdapterFactoryGenerator.Instance.Generate <Foo, IFooView>(configuration.Mappings);

                // Delay to allow CPU and I/O to drop
                Thread.Sleep(TimeSpan.FromSeconds(2));

                var       foo1 = new Foo("test foo", Guid.NewGuid(), 1);
                const int numberOfInstances = 2000000;
                var       mappingServiceMs  = (long)StopwatchContext.Timed(
                    () =>
                {
                    for (int i = 0; i < numberOfInstances; i++)
                    {
                        systemUnderTest.Create(foo1);
                    }
                }).TotalMilliseconds;
                // ReSharper disable ImplicitlyCapturedClosure
                var hardCodedMs = (long)StopwatchContext.Timed(
                    () =>
                    // ReSharper restore ImplicitlyCapturedClosure
                {
                    for (int i = 0; i < numberOfInstances; i++)
                    {
                        // ReSharper disable ObjectCreationAsStatement
                        new HardCodedFooAdapter(foo1);
                        // ReSharper restore ObjectCreationAsStatement
                    }
                }).TotalMilliseconds;
                double mappingServicePerInstanceSeconds = (mappingServiceMs / 1000.0) / numberOfInstances;
                double hardCodedPerInstanceSeconds      = (hardCodedMs / 1000.0) / numberOfInstances;
                double performanceDifference            = mappingServiceMs / (double)hardCodedMs;

                Console.WriteLine("Generated Adapter:  {0:0.0000000000000}s per instance, {1:0.000}s total, {2} instances.", mappingServicePerInstanceSeconds, mappingServiceMs / 1000.0, numberOfInstances);
                Console.WriteLine("Hard-coded Adapter: {0:0.0000000000000}s per instance, {1:0.000}s total, {2} instances.", hardCodedPerInstanceSeconds, hardCodedMs / 1000.0, numberOfInstances);
                Console.WriteLine();
                Console.WriteLine("Relative time for generated version: {0:00.00}x slower", performanceDifference);
                Console.WriteLine("Cost per 100 instances as percentage of 50ms page load: {0:000.000000}%", ((mappingServicePerInstanceSeconds * 100) / 0.050) * 100.0);

                Assert.That(performanceDifference, Is.LessThan(30.0));
            }
예제 #10
0
        private IEditHandler DoRegister(object uiElement)
        {
            if (handlers.ContainsKey(uiElement))
            {
                return(handlers[uiElement]);
            }
            IAdapterFactory <IEditHandler> factroy = factoryCatalog.GetFactory(uiElement);

            if (factroy == null)
            {
                return(null);
            }
            IEditHandler handler = factroy.GetAdapter(uiElement);

            handlers.Add(uiElement, handler);
            Register(handler);
            return(handler);
        }
예제 #11
0
            public void Must_not_call_mapping_delegate_for_each_property_before_first_access()
            {
                var  fooConfiguration     = new MappingConfiguration <Foo, IFooView>();
                bool nameDelegateCalled   = false;
                bool idDelegateCalled     = false;
                bool factorDelegateCalled = false;

                fooConfiguration.Map(view => view.Name).From(foo =>
                {
                    nameDelegateCalled = true;
                    return(foo.Name);
                });
                fooConfiguration.Map(view => view.Id).From(foo =>
                {
                    idDelegateCalled = true;
                    return(foo.Id);
                });
                fooConfiguration.Map(view => view.Factor).From(foo =>
                {
                    factorDelegateCalled = true;
                    return(foo.Factor);
                });

                var foo1 = new Foo("test", Guid.NewGuid(), 1);
                IAdapterFactory <Foo, IFooView> systemUnderTest = AdapterFactoryGenerator.Instance.Generate <Foo, IFooView>(fooConfiguration.Mappings);
                IFooView fooView = systemUnderTest.Create(foo1);

                Assert.That(nameDelegateCalled, Is.False);
                Assert.That(idDelegateCalled, Is.False);
                Assert.That(factorDelegateCalled, Is.False);

                // ReSharper disable UnusedVariable
                string name   = fooView.Name;
                Guid   id     = fooView.Id;
                int    factor = fooView.Factor.Factor;

                // ReSharper restore UnusedVariable

                Assert.That(nameDelegateCalled, Is.True);
                Assert.That(idDelegateCalled, Is.True);
                Assert.That(factorDelegateCalled, Is.True);
            }
예제 #12
0
            public void Must_wire_up_mapping_delegate_for_each_property()
            {
                var  fooConfiguration     = new MappingConfiguration <Foo, IFooView>();
                bool nameDelegateCalled   = false;
                bool idDelegateCalled     = false;
                bool factorDelegateCalled = false;

                fooConfiguration.Map(view => view.Name).From(foo =>
                {
                    nameDelegateCalled = true;
                    return(foo.Name);
                });
                fooConfiguration.Map(view => view.Id).From(foo =>
                {
                    idDelegateCalled = true;
                    return(foo.Id);
                });
                fooConfiguration.Map(view => view.Factor).From(foo =>
                {
                    factorDelegateCalled = true;
                    return(foo.Factor);
                });

                var foo1 = new Foo("test", Guid.NewGuid(), 1);
                IAdapterFactory <Foo, IFooView> systemUnderTest = AdapterFactoryGenerator.Instance.Generate <Foo, IFooView>(fooConfiguration.Mappings);
                IFooView fooView = systemUnderTest.Create(foo1);
                string   name    = fooView.Name;
                Guid     id      = fooView.Id;
                int      factor  = fooView.Factor.Factor;

                Assert.That(name, Is.EqualTo(foo1.Name));
                Assert.That(id, Is.EqualTo(foo1.Id));
                Assert.That(factor, Is.EqualTo(foo1.Factor.Factor));
                Assert.That(nameDelegateCalled, Is.True);
                Assert.That(idDelegateCalled, Is.True);
                Assert.That(factorDelegateCalled, Is.True);
            }
예제 #13
0
        public static void ApplyTo <T>(
            this JsonPatchDocument <T> patchDoc,
            T objectToApplyTo,
            IAdapterFactory adapterFactory) where T : class
        {
            if (patchDoc == null)
            {
                throw new ArgumentNullException(nameof(patchDoc));
            }

            if (objectToApplyTo == null)
            {
                throw new ArgumentNullException(nameof(objectToApplyTo));
            }

            if (adapterFactory == null)
            {
                throw new ArgumentNullException(nameof(adapterFactory));
            }

            var objectAdapter = new ObjectAdapter(patchDoc.ContractResolver, null, adapterFactory);

            patchDoc.ApplyTo(objectToApplyTo, objectAdapter);
        }
예제 #14
0
        public virtual async Task <T> Patch(string id, JsonPatchDocument <T> patchDoc, IAdapterFactory adapterFactory)
        {
            var e = await GetOne(id);

            if (patchDoc.IsEmpty())
            {
                return(e);
            }

            ForeignEntityPatchHelper.PatchEntityProperties(e, DbContext, patchDoc);
            if (adapterFactory == null)
            {
                patchDoc.ApplyTo(e);
            }
            else
            {
                patchDoc.ApplyTo(e, adapterFactory);
            }

            await SaveChangesAsyncIfNeeded();

            return(e);
        }
예제 #15
0
        public void Compose_zero_implies_null()
        {
            IAdapterFactory fc = AdapterFactory.Compose();

            Assert.Contains("Null", fc.GetType().FullName);
        }
예제 #16
0
        public void GetAdapterType_default_adapter_factory_composed_of_all()
        {
            IAdapterFactory fc = AdapterFactory.Default;

            Assert.Null(fc.GetAdapterType(typeof(IProperties), "StreamingSource"));
        }
예제 #17
0
 /// <summary>
 /// Initializes a new instance of <see cref="ObjectVisitor"/>.
 /// </summary>
 /// <param name="path">The path of the JsonPatch operation</param>
 /// <param name="contractResolver">The <see cref="IContractResolver"/>.</param>
 /// <param name="adapterFactory">The <see cref="IAdapterFactory"/> to use when creating adaptors.</param>
 public ObjectVisitor(ParsedPath path, IContractResolver contractResolver, IAdapterFactory adapterFactory)
 {
     _path             = path;
     _contractResolver = contractResolver ?? throw new ArgumentNullException(nameof(contractResolver));
     _adapterFactory   = adapterFactory ?? throw new ArgumentNullException(nameof(adapterFactory));
 }
예제 #18
0
 public AdapterTypesController(IAdapterFactory deviceFactory)
 {
     _deviceFactory = deviceFactory;
 }
 public CodeFirstServiceMethodProvider(ILoggerFactory loggerFactory, IAdapterFactory adapterFactory)
 {
     m_adapterFactory = adapterFactory;
     m_logger         = loggerFactory.CreateLogger <CodeFirstServiceMethodProvider <TService> >();
 }
예제 #20
0
 public PaymentRequestHandler(IAdapterFactory adapterFactory)
 {
     _adapterFactory = adapterFactory;
 }
예제 #21
0
 protected ValueSerializerFactory(IAdapterFactory implementation)
     : base(AdapterRole.ValueSerializer, implementation)
 {
 }
 /// <summary>
 ///     Initializes a new instance of <see cref="ObjectVisitor" />.
 /// </summary>
 /// <param name="path">The path of the JsonPatch operation</param>
 /// <param name="jsonSerializerOptions">The <see cref="JsonSerializerOptions" />.</param>
 /// <param name="adapterFactory">The <see cref="IAdapterFactory" /> to use when creating adapters.</param>
 public ObjectVisitor(ParsedPath path, JsonSerializerOptions jsonSerializerOptions, IAdapterFactory adapterFactory)
 {
     _path = path;
     _jsonSerializerOptions = jsonSerializerOptions ?? throw new ArgumentNullException(nameof(jsonSerializerOptions));
     _adapterFactory        = adapterFactory ?? throw new ArgumentNullException(nameof(adapterFactory));
 }
예제 #23
0
 public PluginManager(IAdapterFactory deviceFactory, INodeFactory nodeFactory)
 {
     this.deviceFactory = deviceFactory;
     this.nodeFactory   = nodeFactory;
 }
 public AdapterFactoryTests()
 {
     adapterFactory = new AdapterFactory();
 }
예제 #25
0
        public void RegisterFactory(IAdapterFactory <T> factory)
        {
            //Guard.ArgumentNotNull(factory, "factory");

            factories.Add(factory);
        }
예제 #26
0
 public SenderService(IAdapterFactory adapterFactory, int chunkSizeBytes, string sourcePath)
 {
     _adapterFactory = adapterFactory;
     _chunkSizeBytes = chunkSizeBytes;
     _sourcePath     = sourcePath;
 }
예제 #27
0
        // loads an adapter's driver and add the relevant data structures
        // for managing it.
        protected bool LoadAdapter(ProtocolParams args, string driversPath)
        {
            // the user can ignore an adapter
            // so ignore it...
            string ignore = args["ignore"];

            if (ignore != null && ignore == "true")
            {
                return(true);
            }

            string name =
                ProtocolParams.LookupString(args, "name", "unknown");
            string typeName =
                ProtocolParams.LookupString(args, "type", "unknown");
            string id =
                ProtocolParams.LookupString(args, "id", "unknown");

            int mtu = ProtocolParams.LookupInt32(args, "mtu",
                                                 EthernetFormat.MaxFrameSize);
            int txRing  = ProtocolParams.LookupInt32(args, "txRing", 64);
            int rxRing  = ProtocolParams.LookupInt32(args, "rxRing", 64);
            int fwQueue = ProtocolParams.LookupInt32(args, "fwQueue", 64);

            IAdapterFactory factory = null;
            IAdapter        adapter = null;

            try {
                string   factoryTypeName = typeName + "Factory";
                Assembly assembly        = Assembly.LoadFrom(driversPath);
                Type[]   types           = assembly.GetTypes();
                foreach (Type t in types)
                {
                    if (t.IsClass && t.Name.Equals(typeName))
                    {
                        factory = (IAdapterFactory)Activator.CreateInstance(t, null);
                        break;
                    }
                    if (factory == null)
                    {
                        throw new Exception("Can't find Adapter's Factory.");
                    }

                    adapter = factory.CreateAdapter(name, id, txRing, rxRing);
                    Core.Instance().RegisterAdapter(adapter, fwQueue);
                }
            }
            catch (Exception e) {
                adapter = null;
                Console.Out.WriteLine(e.Message);
                Environment.Exit(1);
            }

            IPModule          ipModule   = Core.Instance().GetProtocolByName("IP") as IPModule;
            HostConfiguration hostConfig = ipModule.HostConfiguration;

            for (int i = 0;; i++)
            {
                string ipTag      = String.Format("ip{0}", i);
                string maskTag    = String.Format("mask{0}", i);
                string gatewayTag = String.Format("gateway{0}", i);

                // XXX No point-to-point support here.
                IPv4 address = ProtocolParams.LookupIPv4(args, ipTag,
                                                         IPv4.AllOnes);
                IPv4 netmask = ProtocolParams.LookupIPv4(args, maskTag,
                                                         IPv4.AllOnes);
                IPv4 gateway = ProtocolParams.LookupIPv4(args, gatewayTag,
                                                         IPv4.Zero);
                if (address == IPv4.AllOnes || netmask == IPv4.AllOnes)
                {
                    break;
                }
                hostConfig.Bindings.Add(adapter,
                                        new InterfaceIPConfiguration(address, netmask, gateway, 128)
                                        );
            }

#if DEBUG
            System.Console.Out.WriteLine("[Interface {0}]", args["name"]);
            System.Console.Out.WriteLine("-----------------------------");
#endif
            return(true);
        }
예제 #28
0
 public AdapterTaskService(IAdapterFactory adapterFactory)
 {
     _adapterFactory = adapterFactory;
 }
예제 #29
0
 // DIP: all dependencies are passed via constructor injection
 public AppEngineTestable(IAdapterFactory factory, IFileHelper helper, IOutputAdapter output)
 {
     _factory = factory;
     _helper  = helper;
     _output  = output;
 }
예제 #30
0
        public MyCStreamingService(IAdapterFactory <int, MyCStreamingData> adapterFactory)
        {
            var adapter = adapterFactory.GetAdapter();

            _streamingManager = new StreamingManager <int, MyCStreamingData>(data => data.Key, adapter);
        }