Overridable methods in constructors with InitMembers() - constructor

I have carried the method here on almost all of the areas where I have had overridable methods and managed to fix them but there is one part where the method doesnt work in the same way on a different contexted piece of code:
public Employee()
{
this.InitMembers();
}
private void InitMembers()
{
// Init the collection so it's never null
this.Territories = new List<Territory>();
}
public Employee(string firstName, string lastName): this()
{
this.reffirstName = firstName;
this.reflastName = lastName;
}
> public virtual IList<Territory> Territories { get; protected set; }
Where again the > is the code causing the error, I do however get an intellisense option to "Convert to auto property", which simply reverts the code to when it was started and not fixing the problem.
Anyone know what modifications need to be made to this part to elimiate the fxcop violation?

The error appears because your private constructor is calling a method that can be overridden from a derived class. To fix the warning, you need to remove any calls to virtual methods from within the constructor.
In the example you list, InitMembers uses 'this.Territories', which is causing the violation. According to your later comment you have added a private member - use that instead.

Related

How to Assign Async Value to Razor Component [Parameter] Property?

I am attempting to create my first Razor Component in a Blazor Server-side project. The Razor Component is named MyComponent and has a property configured to retrieve its value from input:
MyComponent.razor
[Parameter]
public int Count {get; set;}
I am pulling the count from an injected service configured via IServiceCollection, which looks like this:
public interface ICountingService
{
ValueTask<int> Get();
}
The hosting page, Index.razor looks like the following:
#page "/"
#inject ICountingService Counter
<h1>Hello World!</h1>
<MyComponent Count="#Counter.Get()" />
However, I cannot seem to bind the correct value for the Count property.
I get the following error:
cannot convert from 'System.Threading.Tasks.ValueTask<int>' to 'int'
All of the examples I have found for assigning [Parameter] values to Razor Components are synchronous, and the only asynchronous values I have found are for callbacks and methods (not parameters).
Further, searching online did not return anything obvious so I am posting here in hopes of finding an answer.
Note that I am aware of using protected override async Task OnInitializedAsync and storing a value in there, but that seems like a lot of required ceremony compared to the approach above, especially when considering the multiple services and properties that I will ultimately have to bind.
So, how does one assign values from an asynchronous call to a Razor Component [Parameter] property in the way that I would prefer?
The problem is, Counter.Get() isn't an int value; it's a Task that will have an int at some undefined point either now or in the future. So you can't assign its value to something that's expecting an int right now, because that int doesn't necessarily exist yet.
You've already got the answer, and though it "seems like a lot of ceremony", it's really the only way to do this:
Create an int property to hold the value.
Declare an async method
In that method, assign the awaited value of Counter.Get() to the int that's holding the value
Set the component's Count property equal to the int property
It may feel like a lot of ceremony, but you should be grateful. Asynchrony is inherently very complicated, and having async/await available already takes care of about 95% of the hard work for you. If you think this solution is messy, you oughtta see what it would take to get it right without async/await!
Try this.
#page "/"
#inject ICountingService Counter
<h1>Hello World!</h1>
<MyComponent Count="#CounterValue" />
#code{
public int CounterValue {get; set;}
protected override async Task OnInitializedAsync()
{
CounterValue = await Counter.Get();
}
}
After #mason-wheeler and #rich-bryant provided their answers, I went to think about this a little more and found my solution, which I have posted here:
https://github.com/Mike-E-angelo/Blazor.ViewProperties
I am calling it a ViewProperty which looks like the following:
public interface IViewProperty
{
ValueTask Get();
}
public sealed class ViewProperty<T> : IViewProperty
{
public static implicit operator ViewProperty<T>(ValueTask<T> instance) => new ViewProperty<T>(instance);
readonly ValueTask<T> _source;
public ViewProperty(ValueTask<T> source) => _source = source;
public T Value { get; private set; }
public bool HasValue { get; private set; }
public async ValueTask Get()
{
Value = await _source;
HasValue = true;
}
public override string ToString() => Value.ToString();
}
You then pair it with a component base type that then iterates through the component's view properties and invokes their respective asynchronous operations:
public abstract class ViewPropertyComponentBase : ComponentBase
{
protected override async Task OnParametersSetAsync()
{
var properties = GetType().GetRuntimeProperties();
foreach (var metadata in properties.Where(x => x.GetCustomAttributes<ParameterAttribute>().Any() &&
typeof(IViewProperty).IsAssignableFrom(x.PropertyType)))
{
if (metadata.GetValue(this) is IViewProperty property)
{
await property.Get().ConfigureAwait(false);
}
}
}
}
A sample razor component that uses the above:
MyComponent.razor
#inherits ViewPropertyComponentBase
#if (Count.HasValue)
{
<p>Your magic number is #Count.</p>
}
else
{
<p>Loading, please wait...</p>
}
#code {
[Parameter]
public ViewProperty<int> Count { get; set; }
}
The resulting use is a clean view with direct bindings and no need for overrides or other additional ceremony:
#page "/"
#inject ICounter Count
<h1>Hello, world!</h1>
Welcome to your new app.
<MyComponent Count="#Count.Count()" />
(NOTE that my posted example and above uses reflection, which is slow. In the actual version of the solution that I am using, I compile the member access as lambda expressions and cache the result. You can find that by starting here if you are brave enough to poke around.)
It feels a bit hacky, but you could do something like this:
<MyComponent Count="#Counter.Get().Result" />

Cannot Bind Json to Object

I am having an issue while trying the WebAPI of net core.
For some reason my object always comes empty no matter what I try. I've checked several other SO questions regarding this but cannot find a solution for what I am facing.
My model:
My controller (getting the null object):
And the POSTMAN request:
I've tried both with and without the [FromBody] option as I've seen in other SO questions that some people solved their issues with it.
Any ideas?
All the auto-implemented properties must have an public modifier before them to for JSON.NET to safely deserialize them.
public class APIRequest
{
string Action { get; set; }
}
Because in the above example no access modifier is given, thereby making it as private, so the default value of the property is assigned which is default(string) that is null.
public class APIRequest
{
public string Action { get; set; }
}
By default all class members are private and the class itself is internal, so you have to mark your property with public modifier.

In actionscript 3, what is the difference between using get and set for a variable and just making it public?

My question is specific to as3.
When I use this language, it seems to me that any variable with a getter and setter should be made public instead.
Whether you do this :
public class Test
{
private var _foo:String;
public function Test()
{
foo = "";
}
public function get foo():String
{
return _foo;
}
public function set foo(value:String):void
{
_foo = value;
}
}
or this :
public class Test
{
public var foo:String;
public function Test()
{
foo = "";
}
}
you will end up doing this eventually (to get or set your foo variable from another class) :
testObject.foo
And using a public variable looks much cleaner to me.
I know that I am missing something.
Could you please show me what it is?
Before we continue, understand that when you define getters and setters, they don't actually need to be associated with a property defined within the class. Getters simply have to return a value, and setters have to accept a value (but can do absolutely nothing if you wish).
Now to answer the question:
The most simple reason is that you can make properties read or write only, by declaring one without the other. In regards to read only, take a moment to consider the benefits of having a class expose a value without other parts of your application being able to modify it. As an example:
public class Person
{
public var firstName:String = "Marty";
public var lastName:String = "Wallace";
public function get fullName():String
{
return firstName + " " + lastName;
}
}
Notice that the property fullName is the result of firstName and lastName. This gives a consistent, accurate value that you would expect if firstName or lastName were to be modified:
person.firstName = "Daniel";
trace(person.fullName); // Daniel Wallace
If fullName was actually a public variable alongside the other two, you would end up with unexpected results like:
person.fullName = "Daniel Wallace";
trace(person.firstName); // Marty - Wait, what?
With that out of the way, notice that getters and setters are functions. Realize that a function can contain more than one line of code. This means that your getters and setters can actually do a lot of things on top of simply getting and setting a value - like validation, updating other values, etc. For example:
public class Slideshow
{
private var _currentSlide:int = 0;
private var _slides:Vector.<Sprite> = new <Sprite>[];
public function set currentSlide(value:int):void
{
_currentSlide = value;
if(_currentSlide < 0) _currentSlide = _slides.length - 1;
if(_currentSlide >= _slides.length) _currentSlide = 0;
var slide:Sprite = _slides[_currentSlide];
// Do something with the new slide, like transition to it.
//
}
public function get currentSlide():int
{
return _currentSlide;
}
}
Now we can transition between slides in the slideshow with a simple:
slideshow.currentSlide = 4;
And even continuously loop the slideshow with consistent use of:
slideshow.currentSlide ++;
There are actually many good reasons to consider using accessors rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier.
Here are some of the reasons:
Encapsulation of behavior associated with getting or setting the property
this allows additional functionality (like validation) to be added more easily later.
Hiding the internal representation of the property while exposing a property using an alternative representation.
Insulating your public interface from change allowing the public interface to remain constant while the implementation changes without affecting existing consumers.
Controlling the lifetime and memory management (disposal) semantics of the property particularly important in non-managed memory environments (like C++ or Objective-C).
Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.
Improved interoperability with libraries that are designed to operate against property getter/settersMocking, Serialization, and WPF come to mind.
Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.
Allowing the getter/setter to be passed around as lambda expressions rather than values.
Getters and setters can allow different access levels for example the get may be public, but the set could be protected.

Accessing protected or private property

In ActionScript 3 is there a way (a hack - maybe through square brackets, maybe through cloning an Object, maybe through prototype, maybe through namespaces, ...) to change a private or protected member of a class?
For example if I have an IconToast class delivered by a someLibrary.swc and I know it has a
protected var windowOptions:WindowOptions;
Can I change it somehow? I've tried many things, for example:
var errorToast:IconToast = new IconToast();
errorToast.addButton("Dismiss");
errorToast.message = "Error when connecting";
errorToast['windowOptions'].timeout = 10 * 1000;
errorToast.show();
(gives me runtime error ReferenceError: Error #1069: Property windowOptions not found on IconToast and there is no default value).
Do this by extending the base class and giving public access to the private/protected method/property etc.
public class MyIconToast extends IconToast
{
public function getWindowOptions():WindowOptions
{
return windowOptions;//here you can access protected (not private though:);
}
}
for private it may not be possible but similar to above solution to some extent it can be done
Best regards
Nope, There is no way to change its modifier directly( That's why it's defined as public, protected and private, right?). The solution of Lukasz 'Severiaan' Grela is OK, but it can be better: use getter/setter to retrieve read/write function.
public function set windowOption(option:int):void;
public function get windowOption():int;
and the private attributes belong ONLY to their class, so if they're packed into SWC, you can't see any of them:D.

Windsor Func<T> property injection

Using Windsor 2.5.2, the following works:
public class Foo
{
public IBar Bar { get; set; }
}
To delay creation of IBar, this also works:
public class Foo
{
public Foo(Func<IBar> barFactory)
{
}
}
However, if I combine property injection with Func<T>, the following results in a null reference:
public class Foo
{
public Func<IBar> Bar { get; set; }
}
How can I make Windsor inject the Func<IBar>?
That's a great question Paul. I'm glad you asked.
For implicitly registered Funcs Windsor is looking at the property, sees it's optional, and it just doesn't bother trying to get it, since... well - it's optional, so you surely are happy not having the dependency populated.
To have it populated, you either register the factory explicitly
container.Register(Component.For<Func<IBar>>().AsFactory().Lifestyle.Transient);
or you mark the dependency as required (on ComponentModel using Require method) which is probably best done via an IComponentModelConstructionContributor