I am trying to figure out a way to have a class full of static objects which each can have a variety of static properties.
I want to be able to pass these properties around and even set them as static properties of other object and I also want to be able to switch through the objects.
Here is an example illustrating what I mean:
Creating and Sending a Message
class Program
{
static void Main(string[] args)
{
MarketOrder Order = new MarketOrder("DELL", MessageProperties.SecurityType.Equity, MessageProperties.ExchangeDestination.ARCA.PostOnly);
SendOrder(Order);
Console.ReadLine();
}
public static void SendOrder(MarketOrder Order)
{
switch (Order.SecurityType)
{
case MessageProperties.SecurityType.Equity:
// Equity sending logic here
break;
case MessageProperties.SecurityType.Option:
// Option sending logic here
break;
case MessageProperties.SecurityType.Future:
// Future sending logic here
break;
}
}
}
This does not want to compile because it won't let me switch the Order.SecurityType object.
MarketOrder Class
public class MarketOrder
{
public readonly string Symbol;
public readonly MessageProperties.SecurityType SecurityType;
public readonly MessageProperties.ExchangeDestination ExchangeDestination;
public MarketOrder(string Symbol, MessageProperties.SecurityType SecurityType, MessageProperties.ExchangeDestination ExchangeDestination)
{
this.Symbol = Symbol;
this.SecurityType = SecurityType;
this.ExchangeDestination = ExchangeDestination;
}
}
MessageProperties Class
public abstract class MessageProperties
{
public class ExchangeDestination
{
public readonly string Value;
public readonly double ExchangeFee;
public ExchangeDestination(string Value, double ExchangeFeed)
{
this.Value = Value;
this.ExchangeFee = ExchangeFee;
}
public abstract class ARCA
{
public static ExchangeDestination Only = new ExchangeDestination("ARCA.ONLY", 0.01);
public static ExchangeDestination PostOnly = new ExchangeDestination("ARCA.ONLYP", 0.02);
}
public abstract class NYSE
{
public static ExchangeDestination Only = new ExchangeDestination("NYSE.ONLY", 0.01);
public static ExchangeDestination PostOnly = new ExchangeDestination("NYSE.ONLYP", 0.03);
}
}
public class SecurityType
{
public readonly string Value;
public SecurityType(string Value)
{
this.Value = Value;
}
public static SecurityType Equity = new SecurityType("EQ");
public static SecurityType Option = new SecurityType("OPT");
public static SecurityType Future = new SecurityType("FUT");
}
}
Enums work perfectly for what I am trying to do except it is hard to have multiple properties of an enum value. I considered using Attributes on Enums to set the properties but getting those vs. getting static properties of objects is substantially slower and my application is extremely speed/latency sensitive.
Is there perhaps a better way of accomplishing what I am trying to do?
Thanks in advance for your help!
William
Related
I am trying to create my custom configuration object from Map using model mapper. Everything gets mapped properly excepts the fields property which is coming fro Generic super class.
My target object is
public class ADParserConfig extends CustomParserConfig<ADParserConfigField> {
private String pattern;
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
}
This extends generic class CustomParserConfig
public class CustomParserConfig<T extends CustomParserConfigField> {
protected List<T> fields;
protected String timeStampField;
public List<T> getFields() {
return fields;
}
public void setFields(List<T> fields) {
this.fields = fields;
}
public String getTimeStampField() {
return timeStampField;
}
public void setTimeStampField(String timeStampField) {
this.timeStampField = timeStampField;
}
}
Where CustomParserConfigField is
public class CustomParserConfigField {
protected String name;
protected Integer index;
protected String type;
protected String format;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
I am trying to map Map using below function
ADParserConfig adParserConfig = getConfig(map,ADParserConfig.class);
public <T extends CustomParserConfig> T getConfig(Map<String,Object> configObject, Class<T> classType){
ModelMapper modelMapper = new ModelMapper();
return modelMapper.map(configObject,classType);
}
Everything excepts fields gets mapped properly for the below map.
{fields=[{name=timeStamp, type=timestamp, format=dd/mm/yyyy HH:MM:SS a}, {name=logName, type=string}], pattern=(?<timeStamp>\d{2}\/\d{2}\/\d{4}\s\d{2}:\d{2}:\d{2}\s[AMPMampm]{2})?\s(LogName=(?<logName>[\w\s\W]+))?\sSourceName=(?<sourceName>[\w\s\W]+)\sEventCode=(?<eventCode>[0-9]*), timeStampField=timestamp}
Please help. Why is issue happens only for fields object ? Do I need to specify something else in mapper configurations ?
It looks like a bug and it had been fixed by #370
i encoutered problem with unity, i want to use property injection, here is what i had in my code :
config of the container :
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<GTModelContainer, GTModelContainer>(new HttpContextLifetimeManager<GTModelContainer>())
.RegisterType<IUnitOfWork, UnitOfWorkGT>()
.RegisterType<ILogger, Logger>(new ContainerControlledLifetimeManager())
.RegisterType<ISocieteServices, SocieteServices>() ;
}
SocieteService Class :
public class SocieteServices : ISocieteServices
{
private IUnitOfWork UnitOfWork;
public SocieteServices(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
}
i tried to use property injection (i can't use constructor injection with custom data annotation) and here what i had done :
public class CodeSocieteUniqueAttribute : ValidationAttribute
{
[Dependency]
public ISocieteServices SocieteService {get; set;}
[InjectionMethod]
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string codeSociete = value as string;
var societe = SocieteService.getSocieteByCode(codeSociete);
if (societe == null) return ValidationResult.Success;
else return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
the problem is that the societeService in CodeSocieteUniqueAttribute class is not injected.
Assuming that your class for registering types is publicly accessible and has a IUnityContainer object, ie:
public static class Resolver
{
public static IUnityContainer Container { get; set; }
public static void RegisterTypes(IUnityContainer container)
{
// type registrations here
container.RegisterType<GTModelContainer, GTModelContainer>(new HttpContextLifetimeManager<GTModelContainer>())
.RegisterType<IUnitOfWork, UnitOfWorkGT>()
.RegisterType<ILogger, Logger>(new ContainerControlledLifetimeManager())
.RegisterType<ISocieteServices, SocieteServices>() ;
// Now, set the container
Container = container;
}
}
You could access the container you've built up and resolve these types during method execution.
For instance,
public class CodeSocieteUniqueAttribute : ValidationAttribute
{
[Dependency]
public ISocieteServices SocieteService { get; set; }
[InjectionMethod]
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var societeServices = Resolver.Container.Resolve<ISocieteServices>();
SocieteService = societeServices; // Or, you know, just use this since it's resolved.
string codeSociete = value as string;
var societe = SocieteService.getSocieteByCode(codeSociete);
if (societe == null) return ValidationResult.Success;
else return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
This is actually pretty standard practice, and this MSDN article describes resolving items during runtime.
Another option is to pop the resolution into a default constructor like this:
public class CodeSocieteUniqueAttribute : ValidationAttribute
{
[Dependency]
public ISocieteServices SocieteService {get; set;}
public CodeSocieteUniqueAttribute()
{
var societeServices = Resolver.Container.Resolve<ISocieteServices>();
SocieteService = societeServices;
}
// the rest of the class omitted for brevity
}
I have some problem.
I have some object :
public class TestParameter {
private Long par1;
private Long par2;
public Long getPar1() {
return par1;
}
public void setPar1(final Long par1) {
this.par1 = par1;
}
public Long getPar2() {
return par2;
}
public void setPar2(final Long par2) {
this.par2 = par2;
}
}
And I have form with this bean :
#FormData(value = PurchaseConditionsEditFormData.class, sdkCommand = FormData.SdkCommand.CREATE)
public class TestForm extends AbstractForm {
private TestParameter m_testParameter;
#FormData
public TestParameter getTestParameter() {
return m_testParameter;
}
#FormData
public void setTestParameter(final TestParameter testParameter) {
m_testParameter = testParameter;
}
}
My problem is that I can use this in form data, because inside form data this is created
/**
* access method for property TestParameter.
*/
public TestParameter getTestParameter() {
return getSearchParameterProperty().getValue();
}
/**
* access method for property TestParameter.
*/
public void setSearchParameter(TestParameter testParameter) {
getTestParameterProperty().setValue(testParameter);
}
public TestParameterProperty getTestParameterProperty() {
return getPropertyByClass(TestParameterProperty.class);
}
public static class TestParameterProperty extends
AbstractPropertyData<TestParameter> {
private static final long serialVersionUID = 1L;
public TestParameterProperty() {
}
}
Problem is that setSearchParameter() is never called, and that getTestParameterProperty() returns object with value= null.
How to fix it ?
I know that dirty solution would be to put all properties outside object and directly in form, but I don't want that solution.
I figure out what was my problem.
Object needs to be Serializable, then it works.
I am trying to learn IOC principle from this screencast
Inversion of Control from First Principles - Top Gear Style
I tried do as per screencast but i get an error while AutomaticFactory try create an object of AutoCue. AutoCue class has contructor which takes IClock and not SystemClock. But my question is , in screencast IClock is resolved with SystemClock while inside AutomaticFactory .But in my code , IClock does not get resolved . Am i missing something ?
class Program
{
static void Main(string[] args)
{
//var clarkson = new Clarkson(new AutoCue(new SystemClock()), new Megaphone());
//var clarkson = ClarksonFactory.SpawnOne();
var clarkson = (Clarkson)AutomaticFactory.GetOne(typeof(Clarkson));
clarkson.SaySomething();
Console.Read();
}
}
public class AutomaticFactory
{
public static object GetOne(Type type)
{
var constructor = type.GetConstructors().Single();
var parameters = constructor.GetParameters();
if (!parameters.Any()) return Activator.CreateInstance(type);
var args = new List<object>();
foreach(var parameter in parameters)
{
var arg = GetOne(parameter.ParameterType);
args.Add(arg);
}
var result = Activator.CreateInstance(type, args.ToArray());
return result;
}
}
public class Clarkson
{
private readonly AutoCue _autocue;
private readonly Megaphone _megaphone;
public Clarkson(AutoCue autocue,Megaphone megaphone)
{
_autocue = autocue;
_megaphone =megaphone;
}
public void SaySomething()
{
var message = _autocue.GetCue();
_megaphone.Shout(message);
}
}
public class Megaphone
{
public void Shout(string message)
{
Console.WriteLine(message);
}
}
public interface IClock
{
DateTime Now { get; }
}
public class SystemClock : IClock
{
public DateTime Now { get { return DateTime.Now; } }
}
public class AutoCue
{
private readonly IClock _clock;
public AutoCue(IClock clock)
{
_clock = clock;
}
public string GetCue()
{
DateTime now = _clock.Now;
if (now.DayOfWeek == DayOfWeek.Sunday)
{
return "Its a sunday!";
}
else
{
return "I have to work!";
}
}
}
What you basically implemented is a small IoC container that is able to auto-wire object graphs. But your implementation is only able to create object graphs of concrete objects. This makes your code violate the Dependency Inversion Principle.
What's missing from the implementation is some sort of Register method that tells your AutomaticFactory that when confronted with an abstraction, it should resolve the registered implementation. That could look as follows:
private static readonly Dictionary<Type, Type> registrations =
new Dictionary<Type, Type>();
public static void Register<TService, TImplementation>()
where TImplementation : class, TService
where TService : class
{
registrations.Add(typeof(TService), typeof(TImplementation));
}
No you will have to do an adjustment to the GetOne method as well. You can add the following code at the start of the GetOne method:
if (registrations.ContainsKey(type))
{
type = registrations[type];
}
That will ensure that if the supplied type is registered in the AutomaticFactory as TService, the mapped TImplementation will be used and the factory will continue using this implementation as the type to build up.
This does mean however that you now have to explicitly register the mapping between IClock and SystemClock (which is a quite natural thing to do if you're working with an IoC container). You must make this mapping before the first instance is resolved from the AutomaticFactory. So you should add the following line to to the beginning of the Main method:
AutomaticFactory.Register<IClock, SystemClock>();
How to read variable length String from a C struct using Javolution API?
For example the code below is used to get a fixed size String-
public final UTF8String data= new UTF8String(100);
Can anyone give me an example for reading variable length String.
This is what we have and we are learning as well:
public class EvDasTestResults extends AbstractServiceJavolutionObject
{
public final Signed32 result = new Signed32();
public final UTF8String description;
public EvDasTestResults(int size)
{
description = new UTF8String(size);
}
}
public abstract class AbstractServiceJavolutionObject extends Struct
{
#Override
public ByteOrder byteOrder()
{
return ByteOrder.nativeOrder();
}
#Override
public boolean isPacked()
{
return true;
}
}