Static method as part of a contract - c#

I am implementing an infrastructure for access control of models in a web application. The library has a context class that controllers (and maybe views) use for determining if the current user has access to a certain object. For keeping relevant information close to the target object, I've decided to pass on the access check request to the models themselves from the context object.
Implementing this mechanism for model object modification is almost trivial. Declare an interface, say, ICheckModifyAccess; and implement it in your model. The same goes for delete check. In both these cases, it is possible to ask an instance of a model whether it is OK to modify or delete them.
Unfortunately, it is not the case for read and create operations. These operations require that I ask the question to the model class. So using an interface for this is not an option.
I ended up creating an attribute, CheckCreateAccessAttribute, and then ended up using this attribute to mark a static function as the interface function. Then, in my context object, I can use reflection to check if such a marked function exists, if it matches the signature I expect, and eventually call it. In case it makes a difference, the method for create access check is public bool CanCreate<TObj>();. A typical model that supports access control would add something like the following to the class:
[CheckCreateAccess]
public static bool CanCreate()
{
return true;
}
I am not very fluent in C# yet, and I have a nagging feeling that I'm doing something wrong. Can you suggest a more elegant alternative? Especially, can you get rid of examining TObj by reflection?

It sounds like you've combined concerns in your object classes instead of separating them.
The temptation to "keep relevant information close to the target object" has perhaps led you to this structure.
Perhaps you could instead handle permissions in a separate class, see for example this article.

I think you shouldn't ask some specific user whether you can modify him (unless the modify right is per concrete entity). Just create a class that handles the rights (or use appropriate existing class).
This would eliminate your need for static classes and reflection.
If you are going to have lots of types, with custom rules (i.e. code) for every one of them, you could have a generic abstract type (interface or abstract class) that is able to check the rules for one type and some repository to retrieve the specific instance.

Related

How to distinguish 'Role' interfaces from 'Result' interfaces?

This issue comes up for me so often in my coding that I'm astonished I can find so little reference to it, and would value other people's thoughts and ideas.
I define lots of APIs, for the frameworks I work on, and within large domain models that I want to break up. Those APIs consist almost entirely of interfaces (meaning, in my case, C# interfaces). I find, over and over again, that I want to distinguish between two kinds of interface. In the absence of finding any more widely used terms, I define these two as follows:
'Role' interfaces are intended to be implemented by objects outside of the API, in order that those objects can be used as arguments for methods defined on the API.
'Result' interfaces are implemented by objects inside the API and made available to other parts of the system via the API. The intent of defining a result interface rather than exposing the object that implements it is to restrict the view of the object to the outside world.
To pick one example, a Payments sub-system might define IPayableItem as a Role interface, implemented by many types in other parts of the application in order that Payments may be generated for them. Those generated Payment objects may be retrieved via the API but defined by the Result interface IPayment.
The only way I can currently distinguish these is by naming convention and/or commenting. Ideally, I would like the distinction enforced by the language, and have it enforce the rule: you can't implement a Result interface outside the API, only use it. But C# doesn't provide any such mechanism. (Can anyone advise me of a language that does?). I could define an attribute, but this still wouldn't enforce anything.
Another important significance of the distinction lies in Semantic Versioning of the API. If I add a new member to a Role interface then this should be seen as a breaking change (and hence a first-level version) - because any existing external implementations will need to add that member. But if I add a member to what I deem to be a 'Result' interface then it should only be my own code that is impacted - it is just a new feature (second-level version) for everyone else. But with no enforced distinction between the two types there's some risk that people are implementing the Result interfaces and hence their code would be broken.
Has anyone else encountered this dilemma? If so, how have you dealt with it? I look forward to your answers.
But please don't both to respond with either of the following arguments (which I have heard all too often):
My Result interfaces should be abstract classes rather than interfaces. This does not solve the problem, and potentially makes it worse, since external code can sub-class them.
I should be returning the concrete type and ensuring that anything I don't want accessible outside the API is marked 'internal'. There are lots of cases where I need things inside the API to be public, e.g. to be accessible to other frameworks (not going through the API).
I think what you're asking is it possible to expose an interface, but determine that a given instance is one you created?
If so, you could also create an internal private interface, and mark all your implementations as also implementing the private interface. Then upon being given an object from the outside world, verify it has the internal interface implementation as well.
public interface IPublic
{
...
}
internal interface ISecret { }
public class PublicImplementation : IPublic, ISecret
{
...
}
Only you can implement the ISecret, so even if someone implements the IPublic and passes it to you, it will fail the ISecret test.

Add a property to already created Type at runtime C# ASP.NET

I had a requirement of generating classes and its objects at runtime. Hence, looking at this article I created the same. (using )
I am storing all created types in a list.
But now the other requirement is to add properties to already created Types.
This is for the reason, if i want to use say Class A as a property Type in Class B and say Both in Class C.
I read a lot of articles on the same but have not yet come to a solution
Any Help will be appreciated.
Thanks
Actually, i am in process of developing a multitenant application like LitwareHR by Microsoft.
This will be a system where admin can make sub sites with same escalation management functionality (like MS sharepoint)
Everything is done except workflows!
For data to be stored in tables, i am storing it in XML format..
Eg:
<root tablename="UserInfo">
<column name=\"Name\">Miron</column>
<column name=\"Company\">IBM</column>
</root>"
Everything from controls on the page to events to validators to web parts gets created on runtime using XSLT.
Here, the challenge comes when i need to use expression evaluator to apply workflows to it.
Eg: If UserInfo.Name == "Miron"
Everything gets created on runtime, so have to retrieve table info as an object.
Let me know if i am not clear!
If the types exist then this gets very tricky; you can't add actual properties to an existing type, but if the code that *inspects *the values uses TypeDescriptor (which most data-binding does) then you can add properties sort of via custom PropertyDescriptors - either by implementing ICustomTypeDescriptor (which requires that you do something at build), or TypeDescriptionProvider.
Both are very complex, and both also demand that you have somewhere handy to put the extra data (a property-bag).
Note that in 4.0, dynamic may have some usefulness here.
If you want to avoid this, then just wrap the types in something that looks similar but with extra properties. It'll get the job done while retaining sanity.
Yes, you can use Composition as you described to do this, but classically one would use inheritence for adding functionality to an existing type.
It is difficult to answer your question without more detail about how these classes are to be used, what will be calling them and how.
I believe you will have to derive your classes from single base. Also, to be able to:
use say Class A as a property Type in
Class B and say Both in Class C.
you will have to prepare class A, in case of it being a property of B; and classes A and B ready for them to be a property in Class C.
It would be helpful if you can add more information to your question.

C# / Object oriented design - maintaining valid object state

When designing a class, should logic to maintain valid state be incorporated in the class or outside of it ? That is, should properties throw exceptions on invalid states (i.e. value out of range, etc.), or should this validation be performed when the instance of the class is being constructed/modified ?
It belongs in the class. Nothing but the class itself (and any helpers it delegates to) should know, or be concerned with, the rules that determine valid or invalid state.
Yes, properties should check on valid/invalid values when being set. That's what it's for.
It should be impossible to put a class into an invalid state, regardless of the code outside it. That should make it clear.
On the other hand, the code outside it is still responsible for using the class correctly, so frequently it will make sense to check twice. The class's methods may throw an ArgumentException if passed something they don't like, and the calling code should ensure that this doesn't happen by having the right logic in place to validate input, etc.
There are also more complex cases where there are different "levels" of client involved in a system. An example is an OS - an application runs in "User mode" and ought to be incapable of putting the OS into an invalid state. But a driver runs in "Kernel mode" and is perfectly capable of corrupting the OS state, because it is part of a team that is responsible for implementing the services used by the applications.
This kind of dual-level arrangement can occur in object models; there can be "exterior" clients of the model that only see valid states, and "interior" clients (plug-ins, extensions, add-ons) which have to be able to see what would otherwise be regarded as "invalid" states, because they have a role to play in implementing state transitions. The definition of invalid/valid is different depending on the role being played by the client.
Generally this belongs in the class itself, but to some extent it has to also depend on your definition of 'valid'. For example, consider the System.IO.FileInfo class. Is it valid if it refers to file that no longer exists? How would it know?
I would agree with #Joel. Typcially this would be found in the class. However, I would not have the property accessors implement the validation logic. Rather I'd recommend a validation method for the persistence layer to call when the object is being persisted. This allows you to localize the validation logic in a single place and make different choices for valid/invalid based on the persistence operation being performed. If, for example, you are planning to delete an object from the database, do you care that some of its properties are invalid? Probably not -- as long as the ID and row versions are the same as those in the database, you just go ahead and delete it. Likewise, you may have different rules for inserts and updates, e.g., some fields may be null on insert, but required on update.
It depends.
If the validation is simple, and can be checked using only information contained in the class, then most of the time it's worth while to add the state checks to the class.
There are sometimes, however, where it's not really possible or desirable to do so.
A great example is a compiler. Checking the state of abstract syntax trees (ASTs) to make sure a program is valid is usually not done by either property setters or constructors. Instead, the validation is usually done by a tree visitor, or a series of mutually recursive methods in some sort of "semantic analysis class". In either case, however, properties are validated long after their values are set.
Also, with objects used to old UI state it's usually a bad idea (from a usability perspective) to throw exceptions when invalid values are set. This is particularly true for apps that use WPF data binding. In that case you want to display some sort of modeless feedback to the customer rather than throwing an exception.
The class really should maintain valid values. It shouldn't matter if these are entered through the constructor or through properties. Both should reject invalid values. If both a constructor parameter and a property require the same validation, you can either use a common private method to validate the value for both the property and the constructor or you can do the validation in the property and use the property inside your constructor when setting the local variables. I would recommend using a common validation method, personally.
Your class should throw an exception if it receives invalid values. All in all, good design can help reduce the chances of this happening.
The valid state in a class is best express with the concept of class invariant. It is a boolean expression which must hold true for the objects of that class to be valid.
The Design by Contract approach suggests that you, as a developer of class C, should guarantee that the class invariant holds:
After construction
After a call to a public method
This will imply that, since the object is encapsulated (noone can modify it except via calls to public methods), the invariant will also be satisfied at entering any public method, or at entering the destructor (in languages with destructors), if any.
Each public method states preconditions that the caller must satisfy, and postconditions that will be satisfied by the class at the end of every public method. Violating a precondition effectively violates the contract of the class, so that it can still be correct but it doesn't have to behave in any particular way, nor maintain the invariant, if it is called with a precondition violation. A class that fulfills its contract in the absence of caller violations can be said to be correct.
A concept different from correct but complementary to it (and certainly belonging to the multiple factors of software quality) is that of robust. In our context, a robust class will detect when one of its methods is called without fulfilling the method preconditions. In such cases, an assertion violation exception will typically be thrown, so that the caller knows that he blew it.
So, answering your question, both the class and its caller have obligations as part of the class contract. A robust class will detect contract violations and spit. A correct caller will not violate the contract.
Classes belonging to the public interface of a code library should be compiled as robust, while inner classes could be tested as robust but then run in the released product as just correct, without the precondition checks on. This depends on a number of things and was discussed elsewhere.

What pattern(s) am I supposed to use for this situation?

For several applications I made for my current client I have shared user accounts. This means that each account in one application should exist in the other applications.
Each application has it's own set of settings.
The number of applications and the settings themselves will be the parts that really change over time so I want to separate them.
The data store is accessed through an IRepository class (XMLRepository, SQLRepository etc).
They abstract the actual data access logic away.
The SettingsService class should be able to get an ISetting class as followed
public T GetSetting<T>(IUser user) where T : ISetting
Since the fields of an ISettings class will be different for each type I would reckon that it's the actual Settings class that should know how to fill it's own fields, but it doesn't know how to get the values.
The repository however would know how to access the data, but it doesn't know where to put them.
The GetSetting is actually a factory method if I'm not mistaking. I have the feeling this problem is not something new and there is probably a good pattern to solve this.
What are my options?
You will need some sort of factory for each concrete type of ISetting that can create the concrete SomeSetting instance from data returned from a Repository.
How such a factory should work depends on how you envision the settings persistence schema. Do you have a custom schema for each type of ISetting, or do you simply serialize and deserialize settings in a BLOB/XML?
In the first case, you will need a custom Repository for each settings schema. This is the easy scenario, since each specialized Repository will simply act as the custom factory.
In the other case, you can save metadata together with the BLOB that either stores which custom factory to use to deserialize the BLOB, or alternatively simply the type of the serialized BLOB (and you can then use the serialization API of .NET to serialize and deserialize the object).

C# Console App Session/Storage

What would be the best way to implement a psuedo-session/local storage class in a console app? Basically, when the app starts I will take in some arguments that I want to make available to every class while the app is running. I was thinking I could just create a static class and init the values when the app starts, but is there a more elegant way?
I typically create a static class called 'ConfigurationCache' (or something of the sort) that can be used to provide application-wide configuration settings.
Keep in mind that you don't want to get too carried away with globals. I seriously recommend taking a look at your design and passing just what you need via method parameters. You're design should be such that each method receives a parameter for what is needed (see Code Complete 2 - Steve McConnell).
This isn't to say a static class is wrong but ask yourself why you need that over passing parameters into your various classes and methods.
If you want to take the command line arguments (or some other super-duper setting) and put them somewhere that your whole app can see, I don't know why you would consider it "inelegant" to put them in a static class when the app starts. That sounds exactly like what you want to do.
you could use the singleton design pattern if you need an object that you can pass around in your code but imo a static class is fine, too.
Frankly, I think the most elegant way would be to rethink your design to avoid "global" variables. Classes should be created or receive data they need to be constructed; methods should operate on those data. You violate encapsulation by making global variables that a class or classes need to do their jobs.
I would suggest possibly implementing a singleton class to manage your psuedo-session data. You'll have the ability to access the data globally while ensuring only one instance of the class exists and remains consistent while shared between your objects.
MSDN implementation of a singleton class
Think about your data as a configuration file required by all your classes. The file would be accessible from every class - so there is nothing really wrong with exposing the data through a static class.
But every class would have to know the path to the configuration file and a change of the path would affect many classes. (Of course, the path should better be a constant in only one class referenced by all classes riquiring the path.) So a better solution would be creating a class the encapsulates the access to the configuartion file. Now every class can create an instance of this class and access the configuartion data of the file. Because your data is not backed by a file, you would have to build something like a monostate.
Now you could start thinking about class coupling. Does it matter for you? Are you planning to write unit test and will you have to mock the configuration data? Yes? In this case you should start thinking about using dependency injection and accessing the data only through an interace.
So I suggest using dependency injection using an interface and I would implement the interface with the monostate pattern.

Categories