Custom Label Provider: Can't override Init() method - scichart

I'm trying to access a scaling factor in a viewModel through my CustomNumericLabelProvider.
I'm not quite sure what the best approach is, but I figured I might be able to access it through the parent axis if I used the Init(IAxis parentAxis) method which was shown in the LabelProvider documentation. I've given that a try, but now I'm getting an error telling me that "There is no suitable method for override".
If I comment out the Init() method, CustomNumericLabelProvider works great (with a hard-coded scaling factor).
Any idea why I'm receiving this error message? Or what another good approach would be to gain access to the scaling factor in my viewModel?
Note: I've also tried passing the viewModel into a custom constructor for the label provider (I was able to do something like this with viewportManager), however that didn't seem to work.
Here's the code (With the custom constructor, although I get the same error message without it)
public class CustomNumericLabelProvider : SciChart.Charting.Visuals.Axes.LabelProviders.NumericLabelProvider
{
// Optional: called when the label provider is attached to the axis
public override void Init(IAxis parentAxis) {
// here you can keep a reference to the axis. We assume there is a 1:1 relation
// between Axis and LabelProviders
base.Init(parentAxis);
}
/// <summary>
/// Formats a label for the axis from the specified data-value passed in
/// </summary>
/// <param name="dataValue">The data-value to format</param>
/// <returns>
/// The formatted label string
/// </returns>
public override string FormatLabel(IComparable dataValue)
{
// Note: Implement as you wish, converting Data-Value to string
var converted = (double)dataValue * .001 //TODO: Use scaling factor from viewModel
return converted.ToString();
// NOTES:
// dataValue is always a double.
// For a NumericAxis this is the double-representation of the data
}
}

I would propose passing the scaling factor into the constructor of the CustomNumericLabelProvider, and instantiating it in your viewmodel.
So your code becomes
public class CustomNumericLabelProvider : LabelProviderBase
{
private readonly double _scaleFactor;
public CustomNumericLabelProvider(double scaleFactor)
{
_scaleFactor = scaleFactor;
}
public override string FormatLabel(IComparable dataValue)
{
// TODO
}
public override string FormatCursorLabel(IComparable dataValue)
{
// TODO
}
}
public class MyViewModel : ViewModelBase
{
private CustomNumericLabelProvider _labelProvider = new CustomNumericLabelProvider(0.01);
public CustomNumericLabelProvider LabelProvider { get { return _labelProvider; } }
}
And you then bind to it as follows
<s:NumericAxis LabelProvider="{Binding LabelProvider}"/>
Assuming the datacontext of NumericAxis is your viewmodel.
Please be advised in SciChart v5 there will be new APIs for AxisBindings (similar to SeriesBinding) for dynamically creating axis in ViewModel. This will make dynamic axis in MVVM much easier. You can take SciChart v5 for a test-drive by accessing our WPF Chart Examples here.

Related

private constructor and static constructor in singleton pattern

I'm a c# developer.
I have confused with private constructor and static constructor in singleton pattern.
Here is my sample code in below:
standard singleton pattern and it is thread safe:
public class SingletonTest
{
private static readonly Lazy<RedisCacheManager> CacheManager = new Lazy<RedisCacheManager>(() => new RedisCacheManager());
/// <summary>
/// singleton pattern
/// </summary>
private SingletonTest() { }
public static RedisCacheManager Instance
{
get { return CacheManager.Value; }
}
}
second it changed the private constructor to static constructor:
public class SingletonTest
{
private static readonly Lazy<RedisCacheManager> CacheManager = new Lazy<RedisCacheManager>(() => new RedisCacheManager());
/// <summary>
/// static(single object in our application)
/// </summary>
static SingletonTest() { }
public static RedisCacheManager Instance
{
get { return CacheManager.Value; }
}
}
And my question is the second code still one of the singleton pattern or just it always keep a only one object(RedisCacheManager) in our application?
Somebody help me,thanks.
So to answer you question, we need to go to basic.
Static constructors have the following properties:
A static constructor is called automatically to initialize the class before the first instance is created or any static members are
referenced.
A static constructor cannot be called directly.
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for
the lifetime of the application domain in which your program is
running.
But for standard singleton pattern
It will be loaded, when we call it. So we have control over, when the singleton object will be created.
User has complete control when to call it.
Hope it answers your question.

With respect to the inversion of control pattern, is it strictly better to not have constructor calls outside of the composition root?

I realize the question may be confusing and the word "better" may be problematic, but I could not think of a, well, better way to ask.
Let's say you are writing an application that has a single entry point, like Main, which also serves as the composition root for IoC:
From outside, run application
Main or equivalent
var container = new AwesomeContainer();
container.Install(new CompositionRootInstaller(startArgs));
container.Register( ... );
ApplicationMiddleware = container.Resolve<IMiddleware>();
ApplicationMiddleware.SignalStart();
Here, ApplicationMiddleware might be a ControllerFactory in a web application, for instance.
Now, of course we will have lots of other services located by the container at the appropriate time (per request, for instance).
Sometimes we will run into situations where we don't feel like it's so bad to just assign, say, a default value to a field. But, in my view, this breaks IoC a little bit.
So, is it a true statement that (regardless of the marginal value of doing so) it is always better to avoid calling constructors or factories that call constructors or otherwise get components without calling the container once we leave the entry point?
Example: WinForms program
Here is the setup. It is a contrived example but I'm trying to focus on the issue at hand...
static class Program
{
[STAThread]
static void Main(string[] args)
{
using (var root = new AppCompositionRoot())
{
}
}
}
class AppCompositionRoot : IDisposable
{
private IWindsorContainer _container;
public AppCompositionRoot(IWindsorContainer container = null)
{
_container = container ?? new WindsorContainer();
}
public void Run()
{
var formFactory = _container.Resolve<DefaultFormFactory>();
Application.Idle += delegate
{
formFactory.ApplicationIsIdle();
};
Application.Run();
}
public void Dispose()
{
_container?.Dispose();
}
}
public interface IFormFactory
{
System.Windows.Forms.Form Create();
}
public class DefaultFormFactory : IFormFactory
{
private readonly IWindsorContainer _container;
private Form _lastForm;
public DefaultFormFactory(IWindsorContainer container)
{
_container = container;
}
public Form Create()
{
return _container.Resolve<AppForm>();
}
public void ApplicationIsIdle()
{
_lastForm = _lastForm ?? Create();
_lastForm.Show();
}
}
public class AppForm : Form
{
private readonly string _big; // sensible default is "Welcome!"
private readonly string _little; // sensible default is a string varying by form, time of day, factory
private readonly IList<object> _watched; // sensible default is list empty.
public AppForm(string bigMessage, string littleMessage, IList<object> watched)
{
_big = bigMessage;
_little = littleMessage;
_watched = watched;
}
public void Initialize()
{
// do something with bigMesaage, littleMessage, etc.
}
}
So let's start with concrete AppForm. It needs two strings and a List<object>.
Let's say for all of them there is a natural default that makes sense like 95% of the time, as in something that would be a const string on the class.
Regardless my question is - to really do IoC in the ideal sense, wouldn't it be true that you should always see constructors like these (clean constructors) and any defaults should be injected as well?
Inversion of Control simply states that control (whatever that is) is inverted. It doesn't mean that you have to invert everything; you should invert that which you want to vary.
If you're writing a Hello world application, and you don't want to vary anything, you can create the string within the implementation:
Console.WriteLine("Hello, world!");
On the other hand, if you want to be able to vary the message, you can pass it in as a Primitive Dependency:
public class Helo
{
private readonly string message;
public Helo(string message)
{
this.message = message;
}
public void SayHello()
{
Console.WriteLine(this.message);
}
}
If it helps, Miško Hevery makes the distinction between newables and injectables. On a different note, in my book, I've attempted to make a distinction between stable and volatile dependencies.
You can new up values that you don't need to be able to control from the outside. If you need to control them from the outside (Inversion of Control, remember), then you need to inject them.

How to create internal ctor in ActionScript3

I want to create a internal ctor for class in ActionScript3 to make it immutable. I want that only another builder class will be allow to create instances of this immutable class.
I try to find the answer in Adobe's ActionScrtip 3 specification but it does not explain what happen when no public namespace (accessible) is define for ctor.
Immutable object:
package {
public class Immutable {
private var _value1:int;
private var _value2:int;
private var _value3:int;
public function Immutable(value1:int, value2:int, value3:int) {
_value1 = value1;
_value2 = value2;
_value3 = value3;
}
public function get value1():int {
return _value1;
}
public function get value2():int {
return _value2;
}
public function get value3():int {
return _value3;
}
}
}
As for access modifiers, internal is default.
The internal attribute is similar to the default access control in Java, although in Java there is no explicit name for this level of access, and it can be achieved only through the omission of any other access modifier. The internal attribute is available in ActionScript 3.0 to give you the option of explicitly signifying your intent to make a property visible only to callers within its own package.
As for constructor, you can't specify internal. If you omit access modifier, by default constructor will be accessible (public)

Flex Strongly Typed Proxy Classes for Lazy Instantiation

Does anyone know of a framework, preferably some way to have the Flex compiler run an extension or perhaps just a build step that we could generate strongly typed proxy classes of our application's data models.
There are 2 main things we want to do with the proxy's:
At runtime we want to lazily parse and instantiate the instance as accessed (similiar to how Java's Hibernate has Lazy proxy objects)
In an editor application we want to implement setter calls so we can track which objects have been modified
The Proxy is really necessary in this situation beyond things like programatically setting up ChangeWatcther's because we need to track Array adds/remove and possibly track "reference" objects so that when a "reference key" is changed we know to save those objects that are referencing it by key
In the first case we want the proxy to basically abstract when that object is loaded from serialized data, but still pass around references of it with the same public properties and data access pattern if it were the real object.
Basically the proxy would instantiate the object the first time a method is called on it.
I know we could use some AS3 byte-code libraries like as3-commons-bytecode.
Or possibly repurposing the GraniteDS Code Generation.
I'd prefer to generate code because it is a deterministic thing and it'd be nice if we could have a way to debug it at runtime easier.
Does anyone know if I could do something like MXMLC does when it generates AS3 code from MXML files.
Also is there anyway to control "when" in the compilation pipeline I can generate code, because we have a lot of data objects using public fields instead of getter/setters, but that are [Bindable] and so if I could generate the proxy based on the generated getter/setter methods that would work.
Here's an example application data object and proxy classes:
[Bindable]
public class PersonDTO implements Serializable {
private var _name:String;
private var _age:Number
public function get age():Number {
return _age;
}
public function set age(a:Number):void {
_age = a;
}
public function get name():String {
return _name;
}
public function set name(n:String):void {
_name = n;
}
public void readObject(data:*) {
//...
}
}
// GENERATED CLASS BASED ON PersonDTO
public class LazyProxy_PersonDTO extends PersonDTO {
private var _instance:PersonDTO = null;
private var _instanceData:*;
private function getInstance():void {
if (_instance == null) {
_instance = new PersonDTO();
_instance.readObject(_instanceData);
}
}
override public function get age():Number {
//Ensure object is instantiated
return getInstance().age;
}
override public function get name():String {
//Ensure object is instantiated
return getInstance().name;
}
}
// GENERATED CLASS BASED ON PersonDTO
public class LogChangeProxy_PersonDTO extends PersonDTO {
//This will be set in the application
public var instance:PersonDTO;
//set by application
public var dirtyWatcher:DirtyWatcherManager;
override public function set age(a:Number):void {
dirtyWatcher.markAsDirty(instance);
instance.age = a;
}
}
Digging a little deeper into AS3-Commons byte code library it looks like they support generating proxy classes and interceptors.
http://www.as3commons.org/as3-commons-bytecode/proxy.html
public class DirtyUpdateInterceptor implements IInterceptor {
public function DirtyUpdateInterceptor() {
super();
}
public function intercept(invocation:IMethodInvocation):void {
if (invocation.kind === MethodInvocationKind.SETTER) {
if (invocation.arguments[0] != invocation.instance[invocation.targetMember]) {
invocation.instance.isDirty = true;
}
}
}
}

TypedFactoryFacility: how do i initialize an object with an inline parameter?

How can i produce the same output as specified below using the TypedFactoryFacility?
public class Something
{
public void Initialize(Whatever instance) {}
}
public interface ISomethingFactory
{
Something Create(Whatever instance);
}
internal class SomethingFactory : ISomethingFactory
{
private readonly IWindsorContainer _container;
public SomethingFactory(IWindsorContainer container)
{
_container = container;
}
public Something Create(Whatever instance)
{
Something item = _container.Resolve<Something>();
item.Initialize(instance);
return item;
}
}
So I want to replace the manual factory with a proxy-generated ITypedFactoryFacility, but I cant find a way to invoke something on the resolved component after creation. I looked at commission-concerns, but you don't have a reference to the CreationContext from a custom commision concern so that won't work. I could of course move the dependency to the ctor and provide an ctor override, but I think properties are good when you want to convey non-optional dependencies.
You don't need to invoke stuff on the instance upon creation - Windsor will automagically inject stuff when the name of the parameter in the factory method signature matches something that can be injected - be it constructor paramaters or public properties... short example (using a public property):
interface ISomeFactory
{
Something CreateSomething(object dataSource);
}
class Something
{
public object DataSource { get; set; }
}
Given that these are registered like this:
container.Register(Component.For<ISomeFactory>().AsFactory(),
Component.For<Something>().Lifestyle.Transient)
you can resolve instances of Something like this:
var aintThatSomething = someFactory.CreateSomething(new [] {"ZOMG!", "w00t!"});
Remember that if something inside the burden associated with the instance of Something requires decommissioning, you need to provide an appropriate Release method on the factory as well.