Does someone know library, that reduces amounts of boilerplate code when writing object proxies?
My proxies right now look the following way and I think it's a nasty approach :)
public class SampleTenantProxy : Tenant
{
public override int? Id
{
get { return tenant.Id; }
set { tenant.Id = value; }
}
public override String Code
{
get { return tenant.Code; }
set { tenant.Code = value; }
}
public override String Name
{
get { return tenant.Name; }
set { tenant.Name = value; }
}
public override Decimal Price
{
get { return tenant.Price; }
set { tenant.Price = value; }
}
private readonly Tenant tenant;
public TenantListBoxProxy(Tenant tenant)
{
this.tenant = tenant;
}
}
Most Dependency Injection tools (such as Windsor Castle - have a look here) can do it.
Castle Dynamic Proxy -> http://www.castleproject.org/dynamicproxy/index.html
Related
I've created a new configuration file Special.config:
<?xml version="1.0" encoding="utf-8"?>
<SpecialConfig xmlns:config="urn:telerik:sitefinity:configuration" xmlns:type="urn:telerik:sitefinity:configuration:type" config:version="10.0.6401.0">
<UnicornSettings HornSize="#{HornSize}" HoofColor="#{HoofColor}" />
</SpecialConfig>
Then followed the documentation to set up a pair of classes (and register the config in the Global.asax.cs) file:
public class SpecialConfig : ConfigSection
{
public UnicornSettingsElement UnicornSettings
{
get
{
return (UnicornSettingsElement)this["UnicornSettings"];
}
set
{
this["UnicornSettings"] = value;
}
}
}
public class UnicornSettingsElement : ConfigElement
{
public UnicornSettingsElement(ConfigElement parent) : base(parent)
{
}
public String HornSize
{
get
{
return (String)this["HornSize"];
}
set
{
this["HornSize"] = value;
}
}
public String HoofColor
{
get
{
return (String)this["HoofColor"];
}
set
{
this["HoofColor"] = value;
}
}
}
But even after explicitly instantiating SpecialConfig.UnicornSettings, it's still null:
UnicornSettings config = Config.Get<UnicornSettings>();
config.UnicornSettings = new UnicornSettingsElement(config);
config.UnicornSettings.HornSize = HornSize; //<-- config.UnicornSettings is null
config.UnicornSettings.HoofColor = HoofColor;
ConfigManager manager = ConfigManager.GetManager();
manager.SaveSection(config);
I have no idea how to overcome this particular exception where the reference is null immediately after being set. Anyone see what I'm missing?
Update
After further fiddling, I think there's something wrong with the getter or setter on the SpecialConfig.UnicornSettings... I'm not sure what that could be though.
DISCLAIMER
I understand what a null reference exception is, and generally speaking how to identify and overcome a null reference exception. This is not a duplicate of a particular C# question whose answer is a very non-specific book of information. This is a particular and precise case involving a specific framework that warrants its own question.
Forgot the ConfigurationProperties. I'm guessing these are necessary for the way the getter/setter accesses properties:
public class SpecialConfig : ConfigSection
{
[ConfigurationProperty("UnicornSettings")]
public UnicornSettingsElement UnicornSettings
{
get
{
return (UnicornSettingsElement)this["UnicornSettings"];
}
set
{
this["UnicornSettings"] = value;
}
}
}
public class UnicornSettingsElement : ConfigElement
{
public UnicornSettingsElement(ConfigElement parent) : base(parent)
{
}
[ConfigurationProperty("HornSize", IsRequired = true)]
public String HornSize
{
get
{
return (String)this["HornSize"];
}
set
{
this["HornSize"] = value;
}
}
[ConfigurationProperty("HoofColor", IsRequired = true)]
public String HoofColor
{
get
{
return (String)this["HoofColor"];
}
set
{
this["HoofColor"] = value;
}
}
}
I would like to implement my own IRuntimePolicy. I am following the given example, but I need to access our database or the best would be to have our UserSession object injected.
When is the security object created on runtime? Is this possible? I have not found any examples.
We use Ninject 3.2.3 I believe (or the latest available for MVC 5).
I imagine something like
public class GlimpseSecurityPolicy : IRuntimePolicy
{
private readonly IAclManager aclManager;
private readonly IUserSession userSession;
public GlimpseSecurityPolicy(IUserSession userSession, IAclManager aclManager)
{
this.userSession = userSession;
this.aclManager = aclManager;
}
public RuntimeEvent ExecuteOn
{
// check policy when request ends and when executing a resource (like glimpse.axd)
get { return RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource; }
}
public RuntimePolicy Execute(IRuntimePolicyContext policyContext)
{
if (!this.aclManager.IsUserAllowed(UserAction.AccessGlimpse, this.userSession.GetUser()))
{
return RuntimePolicy.Off;
}
return RuntimePolicy.On;
}
}
Ultimately, we came up with only one option: to use DependencyResolver.Current.GetService<IThing>().
The code result is then straightforward and ugly:
public class GlimpseSecurityPolicy : IRuntimePolicy
{
public RuntimeEvent ExecuteOn => RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource;
public RuntimePolicy Execute(IRuntimePolicyContext policyContext)
{
var aclManager = DependencyResolver.Current.GetService<IAclManager>();
var userSession = DependencyResolver.Current.GetService<IUserSession>();
if (!aclManager.IsUserAllowed(UserAction.AccessGlimpse, userSession.GetUser()))
{
return RuntimePolicy.Off;
}
return RuntimePolicy.On;
}
}
I am working on an app where you can create a Subscription and you can either choose an Individual or Company Subscription which are both classes. But I am having some trouble with the override ToString(). Is it possible to have some kind of an if statement that can say if the object is create as an Individual Subscription return the string formatted for an Individual, else return the one for the Company. Here is my code to make it clearer:
public class Subscription: ObservingClass
{
private IndividualApplicant _individualApplicant;
private CompanyApplicant _companyApplicant;
private SubsAmount _subsAmount;
public IndividualApplicant IndividualApplicant
{
get { return _individualApplicant; }
set
{
_individualApplicant = value;
OnPropertyChanged();
}
}
public CompanyApplicant CompanyApplicant
{
get { return _companyApplicant; }
set
{
_companyApplicant = value;
OnPropertyChanged();
}
}
public SubsAmount SubsAmount
{
get { return _subsAmount; }
set
{
_subsAmount = value;
OnPropertyChanged();
}
}
public Subscription()
{
IndividualApplicant = new IndividualApplicant();
CompanyApplicant = new CompanyApplicant();
}
public override string ToString()
{
return "Subscription Amount: " + SubsAmount + "\n" + IndividualApplicant.ToString();
}
}
Your problem is much worse than that.
can either choose an Individual or Company Subscription which are both classes.
This would indicate inhertance - 2 classes (IndividualSubscription, CompanySubscription) - and then... where is the problem? both override Tostring as they want and need.
But your class model is extremely bad.
public CompanyApplicant CompanyApplicant
{
get { return _companyApplicant; }
set
{
_companyApplicant = value;
OnPropertyChanged();
}
}
WTF? THat should be Applicant - a CompanySubscription may throw an ArgumentExcveption when an IndivdualApplicant is inserted, but it makes little sense and totally convolutes all logic to have different properties for them depending on subtype.
create a Subscription and you can
either choose an Individual or Company Subscription which are both
classes
Then your Subscription class should look like this..
public class Subscription : ObservingClass
{
private Applicant _applicant;
public Applicant Applicant
{
get
{
return _applicant;
}
set
{
_applicant = value;
OnPropertyChanged();
}
}
public Subscription(Applicant applicant)
{
Applicant = applicant;
}
public override string ToString()
{
return "Subscription Amount: " + SubsAmount + "\n" + Applicant.ToString();
}
private SubsAmount _subsAmount
public SubsAmount SubsAmount
{
get { return _subsAmount; }
set
{
_subsAmount = value;
OnPropertyChanged();
}
}
}
With this, Subscription only knows that it has an Applicant which is an abstract class (or make it an interface if you like)
Now, IndividualApplicant and CompanyApplicant should inherit Applicant.
From there, override ToString for both the IndividualApplicant and CompanyApplicant
Suppose that the scenario doesn't allow to implement an immutable type. Following that assumption, I'd like opinions / examples on how to properly design a type that after it's consumed, becomes immutable.
public class ObjectAConfig {
private int _valueB;
private string _valueA;
internal bool Consumed { get; set; }
public int ValueB {
get { return _valueB; }
set
{
if (Consumed) throw new InvalidOperationException();
_valueB = value;
}
}
public string ValueA {
get { return _valueA; }
set
{
if (Consumed) throw new InvalidOperationException();
_valueA = value;
}
}
}
When ObjectA consumes ObjectAConfig:
public ObjectA {
public ObjectA(ObjectAConfig config) {
_config = config;
_config.Consumed = true;
}
}
I'm not satisfied that this simply works, I'd like to know if there's a better pattern (excluded, as said, making ObjectAConfig immutable by design from begin).
For example:
can make sense define a monad like Once<T> that allow the wrapped value to be initialized only once?
can make sense define a type that returns the type itself changing a private field?
What you are implementing sometimes goes under the name "popsicle immutability" - i.e. you can freeze it. Your current approach will work - indeed I use that pattern myself in numerous places.
You can probably reduce some duplication via something like:
private void SetField<T>(ref T field, T value) {
if (Consumed) throw new InvalidOperationException();
field = value;
}
public int ValueB {
get { return _valueB; }
set { SetField(ref _valueB, value); }
}
public string ValueA {
get { return _valueA; }
set { SetField(ref _valueA, value); }
}
There is another related approach, though: a builder. For example, taking your existing class:
public interface IConfig
{
string ValueA { get; }
int ValueB { get; }
}
public class ObjectAConfig : IConfig
{
private class ImmutableConfig : IConfig {
private readonly string valueA;
private readonly int valueB;
public ImmutableConfig(string valueA, int valueB)
{
this.valueA = valueA;
this.valueB = valueB;
}
}
public IConfig Build()
{
return new ImmutableConfig(ValueA, ValueB);
}
... snip: implementation of ObjectAConfig
}
Here there is a truly immutable implementation of IConfig, and your original implementation. If you want the frozen version, call Build().
As is well known, CM doesn't support passing a object of complex type through NavigationService like MVVM Light. So I searched for a workaround and did it like this.
There are two viewmodels: MainPageViewModel and SubPageViewModel.
I first defined 3 classes, namely GlobalData, SnapshotCache and StockSnapshot. StockSnapshot is the type of which the object I want to pass between the 2 viewmodels.
public class SnapshotCache : Dictionary<string, StockSnapshot>
{
public StockSnapshot GetFromCache(string key)
{
if (ContainsKey(key))
return this[key];
return null;
}
}
public class GlobalData
{
private GlobalData()
{
}
private static GlobalData _current;
public static GlobalData Current
{
get
{
if (_current == null)
_current = new GlobalData();
return _current;
}
set { _current = value; }
}
private SnapshotCache _cachedStops;
public SnapshotCache Snapshots
{
get
{
if (_cachedStops == null)
_cachedStops = new SnapshotCache();
return _cachedStops;
}
}
}
public class StockSnapshot
{
public string Symbol { get; set; }
public string Message { get; set; }
}
Next, I call the navigation service on MainPageViewModel like this:
StockSnapshot snap = new StockSnapshot {Symbol="1", Message = "The SampleText is here again!" };
GlobalData.Current.Snapshots[snap.Symbol] = snap;
NavigationService.UriFor<SubPageViewModel>().WithParam(p=>p.Symbol,snap.Symbol).Navigate();
And on SubPageViewModel I've got this:
private string _symbol;
public string Symbol
{
get { return _symbol; }
set
{
_symbol = value;
NotifyOfPropertyChange(() => Symbol);
}
}
public StockSnapshot Snapshot
{
get { return GlobalData.Current.Snapshots[Symbol]; }
}
And that's where the problem lies. When I run the program, I find out that it always runs to the getter of Snapshot first, when Symbol hasn't been initialized yet. So later I've tried adding some extra code to eliminate the ArgumentNullException so that it can run to the setter of Symbol and then everything goes fine except that the UI doesn't get updated anyway.
Could anyone tell me where I've got wrong?
Thx in advance!!
Why not just use:
private string _symbol;
public string Symbol
{
get { return _symbol;}
set
{
_symbol = value;
NotifyOfPropertyChange(() => Symbol);
NotifyOfPropertyChange(() => Snapshot);
}
}
public StockSnapshot Snapshot
{
get { return Symbol!=null? GlobalData.Current.Snapshots[Symbol]:null; }
}
In this case you don't try and get the data from GlobalData when Symbol is null (sensible approach anyway!) and when "Symbol" is set you call NotifyOfPropertyChange() on Snapshot to force a re-get of the property.