Retrieve target element in CodeAccessSecurityAttribute - c#

I realize you can't get the target entity in the Attribute itself, but what about in an associated Permission object when using a CodeAccessSecurityAttribute? The Permission object gets called at runtime so it seems there should be a way but I'm at a loss.
public sealed class MySecurityAttribute : CodeAccessSecurityAttribute
{
public override IPermission CreatePermission()
{
MySecurityPermission permission = new MySecurityPermission();
//set its properties
permission.Name = this.Name;
permission.Unrestricted = this.Unrestricted;
return permission;
}
}
public class MySecurityPermission : IPermission, IUnrestrictedPermission
{
public MySecurityPermission(PermissionState state)
{
// what method was the attribute decorating that
// created this MySecurityPermission?
}
public void Demand()
{
// Or here?
}
}

What about walking the call stack? At least that would narrow down what you need to reflect over. Grab System.Diagnostics.StackTrace and use GetFrame to get the stack frame one step up from where you are.
It's rather nasty though - CAS attributes really, in my opinion, shouldn't be conditional on what was decorated, rather they should depend on the conditions set in their parameters.

Well, I guess you could use reflection to scan through all the loaded assemblies, looking for any class/member that has this as an attribute. It'd be quite slow, though, so it's not something you'd want to do often, or in a large project.

Related

How to reset JsonProperties in a class with new JSON string

I've deserialized JSON into a c# object, but with an incomplete JSON such that some properties are missing. At the time of deserializing the object, I don't have access to the full JSON. I can get the full JSON by making another API call, but I don't want to make that call if I don't have to.
I would like my property getters to work such that they return the property if it's not null. If it is null, it should make the call to the API to get the full JSON and update all of the JsonProperties in the class, and then return the property I've asked for.
public class Car
{
private string _make;
private string _model;
[JsonProperty("make")]
public string Make
{
get
{
if (_make != null)
{
return _make;
}
else
{
UpdateProperties();
return _make;
}
}
}
[JsonProperty("model")]
public string Model
{
get
{
if (_model != null)
{
return _model;
}
else
{
UpdateProperties();
return _model;
}
}
}
[JsonProperty("self")]
public Uri Self { get; set; }
public void UpdateProperties()
{
}
}
In the UpdateProperties() method above, I can make it use the Self property to get and deserialize a new instance of a Car class, but I want it to refresh the properties of the current Car class instance instead. I can do this manually by setting each property individually again, but since I need to do this for many classes, I would appreciate a better way. Is this possible?
Or am I going about this all wrong?
EDIT:
Here is an example of the JSON the API would return. Lets say I make a call to get information about the vehicle fleet. It would return:
{
"details" : "something"
"car": {
"make": "Ford",
"self": "https://..."
}
"truck": {
"age": 30,
"self": "https://..."
}
}
where when you access the url provided by car.self, it would return the following JSON:
{
"make" : "Toyota",
"model" : "Camry",
"self" : "https://..."
}
So, let me offer a different perspective. The problem description seems straightforward enough- I have two API calls, one which returns a partial object, and one which returns a complete object. I don't want to make two calls if I don't have to. So, I'll just make the second call and "fill in the details" if I need to, right?
Wrong.
The proposed approach is not a good idea.
This goes off the rails from the beginning with the design of the API. The objects returned by the API should not be so complicated so as to require multiple calls to return the "full" object as described in the code. But, let's assume I have no control over the design of the API - what should I do?
Programmers are frequently faced with the task of confronting a badly-designed API. These create leaky abstractions like the one described in this problem, where there is a strong desire to "paper over" the bad API design. The problem is that not all bad designs can be papered over. This is one.
What is proposed here is to introduce a painful side-effect of a get accessor. This is arguably the worst way to solve the problem of a bad API design. A typical get method returns with a negligible amount of time - it's a simple memory access. This proposed get accessor could potentially take seconds to return, it could fail, it could throw an exception. Worse yet, there is no indication to the caller that this is, in fact, access to an external interface. At the end of the day, the state of your object is not deterministic, which is the arguably the worst thing you can have in a program.
If that wasn't bad enough, get accessors have no provision for asynchronous operations, which are common when dealing with remote APIs. User experience will suffer. By taking this approach, I will have actually taken one problem and made a new problem everywhere this class is used.
A better approach:
The API has two separate functions, so really, this implies two separate result types. I would create one type for the partial class and a second type for the full class. After all, I'm writing code - and unless the code is in the habit of re-writing itself, I should know at the time of writing whether I need the full or the partial representation of the object.
To get the full representation, I'll provide a separate access to the API, with appropriate methods to allow for asynchronous execution (e.g. observables). This will have the added benefit of allowing me to examine (via the "where used" function) where in the program these different API calls are used. This might build a case for me to return to the API designer and suggest a change to the design, based on how I'm using it.
The only way with your current setup to reset all of the properties manually.
You're right to want to have this be automatic, since that's a lot of boilerplate code. This is a common problem and the most common solution to it is to use the DTO or Data Transfer Object pattern.
You would introduce a new class called a CarDto and instead of Car exposing private fields, it would expose the properties on the CarDto.
See Below:
public class Car {
private CarDto _dto = null;
public Car(CarDto dto = null) {
//If we pass in a dto, use it, otherwise create a new one
_dto = dto ?? new CarDto();
}
[JsonProperty("make")]
public string Make {
get {
if (_dto.Make == null) {
UpdateProperties();
}
return _dto.Make;
}
}
[JsonProperty("model")]
public string Model {
get {
if (_dto.Model == null) {
UpdateProperties();
}
return _dto.Model;
}
}
[JsonProperty("self")]
public Uri Self { get; set; }
public void UpdateProperties() {
//The API would return a CarDto.
CarDto newDto = APICall(); //Mock code
_dto = newDto;
}
}
public class CarDto {
public string Make { get;set; }
public string Model { get;set; }
}
So now, if you ever have a null property, you will make a call to UpdateProperties. This will then return a new CarDto that you use as your private _dto field.
This is a SUPER useful and common pattern, and one that makes things a lot easier so it's great to implement and get practice using! Let me know if anything is unclear.

A single DTO with multiple constructors - does this seem like an appropriate solution?

I have an entity called "Set" which contains Cards. Sometimes I want to see the entire card and its contents (card view), when sometimes I just want to know how many cards are in the Set (table views). In my effort to keep things DRY, I decided to try and re-use my SetDto class with multiple constructors like this:
public class SetDto
{
public SetDto()
{
Cards = new List<CardDto>();
}
// Called via SetDto(set, "thin")
public SetDto (Set set, string isThin)
{
var setDto = new SetDto()
{
SetId = set.SetId,
Title = set.Title,
Details = set.Details,
Stage = set.Stage,
CardCount = set.Cards.Count
};
return setDto;
}
// Called via SetDto(set)
public SetDto(Set set)
{
SetId = set.SetId;
UserId = set.UserId;
Title = set.Title;
Details = set.Details;
FolderId = set.FolderId;
Stage = set.Stage;
IsArchived = set.IsArchived;
Cards = new List<CardDto>();
foreach (Card card in set.Cards)
{
Cards.Add(new CardDto(card));
}
}
/// property definitions
I originally had two different DTOs for sets - ThinSetDto and FullSetDto - but this seemed messy and tougher to test. Does the above solution seem ok, or am I breaking a known best-practice? Thank you for your time!
I would create three methods in the SetManager class (a class handling CRUD operations) not in the DTO.
The dto shold have no such a logic inside. Anyway I agree with you that the replication is useless (and evil).
public class BaseSetDTO
{
public BaseSetDTO()
{
Set();
}
internal virtual void Set()
{
//Do your base set here with base properties
}
}
public class SetDTO : BaseSetDTO
{
internal override void Set()
{
//Do a full set here
}
}
Create a base class, then let your types handle what they are supposed to set. Create a new on for your ThinSetDTO and override again.
Instead, I would prefer extension method by declaring all properties in Set class and modifying the properties by passing required parameters. Otherwise initialize a baseDTO and have various versions by adding required properties and call extension method to create required version DTO and return baseDTO.
public static Set SetDto(this Set set, bool isThin)
{
if(isThin)
{
}
return objSet;
}
A common solution to this is to have the repository (or equivalent) return the 'flavor' of the DTO/entity you want by either having different access methods ie: Get() ... GetSet(), or to enumerate your 'flavors' of the entity in question and pass that to your 'Get' (or equivalent) method ie:
enum ContactCollectionFlavors { Full, CountOnly, CountWithNames .... }
...
foo = ContactRepository.GetByLastName('Jones', ContactCollectionFlavors.CountWithNames);
This can get a little messy, from experience the entity in question should have some way of knowing what 'flavor' it is, which smells bad since it breaks encapsulation and seperation of concerns - but in my opinion its better hold your nose and keep some out of band data, so that later you can have lazy loading of the entity allowing you to turn 'light flavors' into fully populated entities.

Simulating parent class, reverse polymorphism

I have 2 already defined classes, we'll call them DogActivityType and HorseActivityType.
They have the same fields, same methods, but they write to 2 different tables in the database, and of course, are named differently.
I have a function with all the business rules already working for one class, and the other class uses the same business rules.
Restrictions:
I have to use these 2 classes since they are used throughout other parts of the project
I can't create one class and add another column (field) to distinguish between both types of classes.
I can't edit the source for these 2 classes.
.
Here is my simplified version of the code:
public doAllCalculations(){
// retrieve collection
foreach (DogActivityType activity in allActivities){
// a lot of code here
// more code...
createMoreOf(activity); // this is overloaded since it needs to know which DB to write to
}
}
// using overload for same function name
private createMoreOf(DogActivityType doggyActivity){
/// do some specific when it is a dog
}
private createMoreOf(HorseActivityType horse){
/// do some specific when it is a horse
}
Now, the problem is: doAllCalculations() is very extensive and complicated and may change during the course of development. I don't want to have 2 different functions (doAllCalculationsDOG() and doAllCalculationsHORSE() ) in order to do the same analysis, just because I need one for the Dog and another for the Horse class. One day someone in the project may forget to update both functions or any other bad scenario...
So, I want to use the same function for both classes. So if I edit a rule in the big calculation function, I will know it works for both classes.
I'm thinking I'll end up with something like this:
public class AnimalActityType {
}
public doAllCalculations(){
// retrieve collection
foreach (AnimalActivityType activity in allActivities){
// a lot of code here
// more code...
createMoreOf(activity);
}
}
AnimalActityType will simulate an abstract parent, I'll call it reverse polymorphism...
But how do DogActityType and HorseActityType know about this parent? Can I force the parent?
Is it possible? Any ideas?
I can't edit the source for these 2 classes.
Assuming this means you can't create a base class or even an interface to me this says that even if you come up with a solution it's going to be nothing but a messy hack job. I'd sooner try to find a way around this self imposed restriction than come up with some perverted form of polymorphism.
you can try to use decorator pattern, but in very unusual way.
class Decorator
{
private object instance;
public Decprator(object instance)
{
this.instance = instance;
}
public <type> SomeCommonProp
{
get{
if(instance is DogActivityType)
{
return (instance as DogActivityType).SomeValueOrPropertyOrCall;
}
else
{
return (instance as HorseActivityType).SomeValueOrPropertyOrCall;
}
}
}
}
class MyCalculations
{
private Decorator instance;
public MyCalculations(Decorator inst)
{
instance = inst;
}
public <type> SomeCalculationMethod()
{
// here you will use instance.SomeCommonProp for your calculations
}
}

Why do I even need to Serialize in the first place?

So, I'm working with the following assembly, which has the following defined (fairly harmless):
public class QueryDefinition
{
private List<QueryFilter> TheCurrentFilters = null;
public List<QueryFilter> CurrentFilters
{
set { TheCurrentFilters = value; }
get { return TheCurrentFilters; }
}
// other code
public class QueryFilter
{
// member variables are: seven public string's & two public int's
public override string ToString()
{
return FilterText;
}
}
}
Within another assembly, we have a UserControl:
public partial class QueryWizard : UserControl
{
private List<QueryDefinition.QueryFilter> TheCurrentFilters = null;
public List<QueryDefinition.QueryFilter> CurrentFilters
{
set { TheCurrentFilters = value; }
get { return TheCurrentFilters; }
}
// other code
}
Interesting code, but that's what I have to work with.
Anyhow, if I go to another project (that references this UserControl), create a Form, and then drop the control onto the Form, I get this error:
'System.Runtime.Serialization.SerializationException: Type QueryDefinition+QueryFilter' in Assembly ... is not marked as serializable.'
I'm not actually using any Serialization code, so what of this List of QueryFilter's is the reason for a SerializationException?
I have used the [Serializable] tag, to get rid of this. But recently we were rebuilding projects (Visual WebGUI upgrade) and now I run into the "unable to load type required for deserialization" issue. Instead of figuring out that problem, I decided to try and figure out why we need the Serialization tags in the first place! Thanks.
It is because the designer tries to serialize the contents of the usercontrols "CurrentFilters" property into the form initialization code.
Check the DesignerSerializationVisibility attribute: http://msdn.microsoft.com/en-us/library/system.componentmodel.designerserializationvisibility.aspx
If you don't intend to support designtime editing of the CurrentFilters property, setting it to hidden should fix the problem (I think, was ages since I built winforms controls)
The actual values for the CurrentFilters are getting serialized using BinaryFormatter and stored in a .resx file. You almost certainly don't want this to happen. For one, you'll take a dependency on the [AssemblyVersion] number of the assembly that contains your QueryFilter class. Which should explain the "unable to load type" exception you get now.
First find out how CurrentFilters ended up with values at design time. You'll need to beware of events that run at design time. The typical candidates are the constructor and the Load event. Use the Control.DesignTime property to prevent code from running.
Next, ensure that the property value doesn't get persisted by applying an attribute:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public List<QueryFilter> CurrentFilters
{
}

More private than private? (C#)

Sometimes you have a private field that backs a property, you only ever want to set the field via the property setter so that additional processing can be done whenever the field changes. The problem is that it's still easy to accidentally bypass the property setter from within other methods of the same class and not notice that you've done so. Is there a way in C# to work around this or a general design principle to avoid it?
IMHO, it is not used, because:
The class must trust itself
If your class gets as large that one part does not know the other, it should be divided.
If the logic behind the property is slightly more complex, consider to encapsulate it in an own type.
I'd consider this a nasty hack and try to avoid it if possible, but...
You can mark the backing field as obsolete so that the compiler will generate a warning when you try to access it, and then suppress that warning for the property getter/setter.
The warning codes that you'd need to suppress are CS0612 for the plain Obsolete attribute and CS0618 if the attribute has a custom message.
[Obsolete("Please don't touch the backing field!")]
private int _backingField;
public int YourProperty
{
#pragma warning disable 612, 618
get { return _backingField; }
set { _backingField = value; }
#pragma warning restore 612, 618
}
There's no inbuilt way to do what you want to do, but by the sounds of things you need another layer of abstraction between your class and that value.
Create a separate class and put the item in there, then your outer class contains the new class, and you can only access it through its properties.
No, there isn't. I'd quite like this myself - something along the lines of:
public string Name
{
private string name; // Only accessible within the property
get { return name; /* Extra processing here */ }
set { name = value; /* Extra processing here */ }
}
I think I first suggested this about 5 years ago on the C# newsgroups... I don't expect to ever see it happen though.
There are various wrinkles to consider around serialization etc, but I still think it would be nice. I'd rather have automatically implemented readonly properties first though...
You CAN do this, by using a closure over a local in the constructor (or other initialisation function). But it requires significantly more work that the helper class approach.
class MyClass {
private Func<Foo> reallyPrivateFieldGetter;
private Action<Foo> reallyPrivateFieldSetter;
private Foo ReallyPrivateBackingFieldProperty {
get { return reallyPrivateFieldGetter(); }
set { reallyPrivateFieldSetter(value); }
}
public MyClass() {
Foo reallyPrivateField = 0;
reallyPrivateFieldGetter = () => { return reallyPrivateField; }
reallyPrivateFieldSetter = v => { reallyPrivateField = v; };
}
}
I suspect that the underlying field type Foo will need to be a reference class, so the two closures are created over the same object.
There is no such provisioning in C#.
However I would name private variables differently (e.g. m_something or just _something) so it is easier to spot it when it is used.
You can put all of your private fields into a nested class and expose them via public properties. Then within your class, you instantiate that nested class and use it. This way those private fields are not accessible as they would have been if they were part of your main class.
public class A
{
class FieldsForA
{
private int number;
public int Number
{
get
{
//TODO: Extra logic.
return number;
}
set
{
//TODO: Extra logic.
number = value;
}
}
}
FieldsForA fields = new FieldsForA();
public int Number
{
get{ return fields.Number;}
set{ fields.Number = value;}
}
}
It just provides a level of obstruction. The underlying problem of accessing private backing fields is still there within the nested class. However, the code within class A can't access those private fields of nested class FieldForA. It has to go through the public properties.
Perhaps a property backing store, similar to the way WPF stores properties?
So, you could have:
Dictionary<string,object> mPropertyBackingStore = new Dictionary<string,object> ();
public PropertyThing MyPropertyThing
{
get { return mPropertyBackingStore["MyPropertyThing"] as PropertyThing; }
set { mPropertyBackingStore["MyPropertyThing"] = value; }
}
You can do all the pre-processing you want now, safe in the knowledge that if anyone did access the variable directly, it would have been really really hard compared to the property accessor.
P.S. You may even be able to use the dependency property infrastructure from WPF...
P.P.S. This is obviously going to incur the cost of casting, but it depends on your needs - if performance is critical, perhaps this isn't the solution for you.
P.P.P.S Don't forget to initialise the backing store! (;
EDIT:
In fact, if you change the value property stored to a property storage object (using the Command pattern for example), you could do your processing in the command object...just a thought.
Can't do this in standard C#, however you could
define a custom attribute say OnlyAccessFromProperty
write your code like
[OnlyAccessFromProperty(Name)]
String name
Name
{
get{return name;}
}
etc …
Then write a custom rule for FxCop (or another checker)
Add FxCop to your build system so if your custom rule find an error the build is failed.
Do we need a set of standard custom rules/attributes to enforce common design patens like this without the need to extend C#
C# has no language feature for this. However, you can rely on naming conventions, similar to languages which have no private properties at all. Prefix your more private variable names with _p_, and you'll be pretty sure that you don't type it accidentally.
I don't know C# but in Java you may have a base class with only private instance variables and public setters and getters (should return a copy of the instance var.) and do all other in an inherited class.
A "general design principle" would be "use inheritance".
There is no build in solution in C#, but I think your problem can be solved by good OO design:
Each class should have a single purpose. So try to extract the logic around your field into a class as small as possible. This reduces the code where you can access the field by accident. If you do such errors by accident, your class is probably to big.
Often interface are good to restrict access to only a certain "subset" of an object. If that's appropriate for your case depends on your setting of course. More details about the work to be done would help to provide a better answer.
You say that you do additional processing. Presumably this would be detectable under the correct conditions. My solution, then, would be to create unit tests that implement conditions such that if the backing field is used directly the test will fail. Using these tests you should be able to ensure that your code correctly uses the property interface as long as the tests pass.
This has the benefit that you don't need to compromise your design. You get the safety of the unit tests to ensure that you don't accidently make breaking changes and you capture the understanding of how the class works so that others who come along later can read your tests as "documentation."
Wrap it in a class? The property thing is a bit like that anyway, associating data with methods - the "Encapsulation" they used to rave about...
class MyInt
{
private int n;
public static implicit operator MyInt(int v) // Set
{
MyInt tmp = new MyInt();
tmp.n = v;
return tmp;
}
public static implicit operator int(MyInt v) // Get
{
return v.n;
}
}
class MyClass
{
private MyInt myint;
public void func()
{
myint = 5;
myint.n = 2; // Can't do this.
myint = myint + 5 * 4; // Works just like an int.
}
}
I'm sure I'm missing something? It seems too normal...
BTW I do like the closures one, superbly mad.
My favorite solution to this (and what I follow) is to name private backing fields that are never intended to be used directly with a leading underscore, and private fields that are intended to be used without the underscore (but still lowercase).
I hate typing the underscore, so if I ever start to access a variable that starts with the underscore, I know somethings wrong - I'm not supposed to be directly accessing that variable. Obviously, this approach still doesn't ultimately stop you from accessing that field, but as you can see from the other answers, any approach that does is a work around and/or hardly practical.
Another benefit of using the underscore notation is that when you use the dropdown box to browse your class, it puts all of your private, never-to-be-used backing fields all in one place at the top of the list, instead of allowing them to be mixed in with their respective properties.
As a design practice, you could use a naming convention for "private properties" that's different from normal public members - for instance, using m_ItemName for private items instead of ItemName for public ones.
If you're using the C# 3.0 compiler you can define properties which have compiler-generated backing fields like this:
public int MyInt { get; set; }
That will mean there is only one way to access the property, sure it doesn't mean you can only access the field but it does mean that there's nothing but the property to access.
I agree with the general rule that the class should trust itself (and by inference anybody coding within the class).
It is a shame that the field is exposed via intellisense.
Sadly placing [EditorBrowsable(EditorBrowsableState.Never)] does not work within that class (or indeed the assembly(1))
In Visual C#, EditorBrowsableAttribute does not suppress members from a class in the same assembly.
If you really do wish to solve this aspect of it the the following class may be useful and makes the intent clear as well.
public sealed class TriggerField<T>
{
private T data;
///<summary>raised *after* the value changes, (old, new)</summary>
public event Action<T,T> OnSet;
public TriggerField() { }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(T initial) { this.data=initial; }
public TriggerField(Action<T,T> onSet) { this.OnSet += onSet; }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(Action<T,T> onSet, T initial) : this(onSet)
{
this.data=initial;
}
public T Value
{
get { return this.data;}
set
{
var old = this.data;
this.data = value;
if (this.OnSet != null)
this.OnSet(old, value);
}
}
}
Allowing you to (somewhat verbosely) use it like so:
public class Foo
{
private readonly TriggerField<string> flibble = new TriggerField<string>();
private int versionCount = 0;
public Foo()
{
flibble.OnSet += (old,current) => this.versionCount++;
}
public string Flibble
{
get { return this.flibble.Value; }
set { this.flibble.Value = value; }
}
}
alternatively you can go for a less verbose option but accessing Flibble is by the not idiomatic bar.Flibble.Value = "x"; which would be problematic in reflective scenarios
public class Bar
{
public readonly TriggerField<string> Flibble;
private int versionCount = 0;
public Bar()
{
Flibble = new TriggerField<string>((old,current) => this.versionCount++);
}
}
or solution if you look at the community content!
The new Lazy class in .net 4.0
provides support for several common
patterns of lazy initialization
In my experience this is the most common reason I wish to wrap a field in a private properly, so solves a common case nicely. (If you are not using .Net 4 yet you can just create your own “Lazy” class with the same API as the .Net 4 version.)
See this and this and this for details of using the Lazy class.
Use the "veryprivate" construct type
Example:
veryprivate void YourMethod()
{
// code here
}

Categories

Resources