I'm creating a class that will house election results. I have a results class that has a static method that will parse a file and return a results class with the results from the file.
I want to make sure that only the static method can modify the results, so i've been using the internal modifier (Precinct.InternalCandidates) (The prevents instances of my class outside of the dll from accessing the methods, right?).
Anyway, I need to expose the candidates as a read only list to the instantiated version of my class, but I'll obviously need to be able to add candidates during the population process. So, I've created another parameter in the Precinct Class called Precinct.Candidates that exposes a read only version of InternalCandidates
Here's how I'd envision it to work:
Results r = Results.ParseResultsFile("PathToFile.txt");
r.Candidates.Add(new Candidate) // Should error here
Console.WriteLine(r.Candidates[0].Name) // Should work
Here's what I have for my class stubs:
public class Results {
private List<Precinct> precincts = new List<Precinct>();
public ReadOnlyCollection<Precinct> Precincts {
get { return this.precincts.AsReadOnly(); }
}
public Results() {}
public static Results ParseResultsFile(string filePath) { ... }
}
public class Precinct {
internal List<Contest> InternalContests { get; set; }
public ReadOnlyCollection<Contest> Contests {
get { return this.InternalContests.AsReadOnly(); }
}
public Precinct {
this.InternalContests = new List<Contest>();
}
}
Is there a better way to accomplish this?
I'm afraid I have a little bit of bad news Rob... using Reflection, one can completely circumvent access modifiers. They help to protect a team from themselves, but are not suited to providing security.
You will need to ensure the physical security of the code and ensure that nobody can load your DLL into an app domain of their own creation.
UPDATE:
I stand corrected by myself. You can set an attribute that prevents reflection UNLESS THE CALLER HAS FULL TRUST (update from Leppie). See how.
You can prevent callers without full trust from accessing your private/internal methods and fields but a full trust caller cannot be prevented from using reflection.
Again. Cleaning up my old questions... I ended up just rolling my own Collection.
Worked out wonderfully..
Related
So say we have loaded a function F that take in/out a set of args and returns a result. How to check at runtime if this F does not act on anything other than args members and functions? Meaning no Console.Writeline, Singletons (or other stuff not presented in args). Is it possible with CodeContracts library or some other solution?
Say we know that [Pure] attribute was presented in the function definition. This sucks for many cases when we have a lambda, yet at least it would be something
Why I do not see how [Pure] can help - this code compiles:
class Test {
public struct Message {
public string Data;
}
public struct Package {
public int Size;
}
[Pure]
public static List<Package> Decomposse(Message m) {
Console.WriteLine("rrrr"); // This sould not happen
var mtu = 1400;
Package p = new Package{Size = mtu};
return Enumerable.Repeat(p, m.Data.Length / mtu).ToList();
}
}
And I want to eliminate (or at least detect that function calls stuff like Console.WriteLine("rrrr"))
It doesn't matter if the function has inputs or a result. Too many things can happen in a code body, e.g. instantiated object constructors. The problem is the modern language.
What about safe API calls which just retrieve data like DateTime.Now()? Are you going to build a list of API calls which mutate state and keep it updated for the rest of us over time, for all applications in your organization or on earth? Are you going to document what processes the compiler inlines? Then by reducing this approach to absurdity, can we accept it is not feasible?
My architecture models machines which should only change "Product" data points, but even I admit this is an unenforceable rule. I have other rules as well to try to enforce determinism. However, these modules must make API calls at some point to do the meaningful work already organized in APIs today. Otherwise we would rewrite them all.
class Machine1Product
{
public Cvar<int> Y { get; set; }
}
class Machine1 : Producer<Machine1Product>, IMachine
{
public Cvar<int> X { get; set; }
public void M()
{
// work which changes only product data points (Y)
}
}
Until a minimalist language is developed for functions, there is no observing or preventing side effects.
I've inherited a codebase, and found some code that I can't figure out why (and if) it's needed.
It's a custom ViewPage, but we have the exact same code repeated twice - once for ViewPage and once for ViewPage<T>.
Basically:
public class MyPageBase : WebViewPage
{
//A whole bunch of properties intended to be accessible on every page
}
public class MyPageBase<T> : WebViewPage<T>
{
//The exact same properties. Doesn't actually use T anywhere. The code is literally identical.
}
Having so much repeated code is far from ideal. Worse, I don't understand why it's needed. A few tests have shown that the top one doesn't seem to do anything, but I'm unable to do a comprehensive search of all views (this MyPageBase is used dozens of apps).
So my question is: Does/why does WebViewPage need to be inherited from twice, for generic+non-generic?
first of all it's not inherited twice you have two implementation of the same
class one is generic and other non generic.
you haven't provided us the inner code so here goes an example, say you have something like this..
public class MyPageBase<T> : WebViewPage<T>
{
//The exact same properties
private DbContext db;
public MyPageBase()
{
db = new MPContext();
}
public List<T> Fill()
{
return db.Set<T>().ToList();
}
public T FillBy(object id)
{
return db.Set<T>().Find(id);
}
}
So why do you need a generic page?
if there are some tasks that are common in all pages you just make a generic method to do the job. below is a very sample usage.
say you have USERS AND ORDERS tables in your dbcontext
public class UsersPage<USERS>:MyPageBase<USERS>{
public void Index()
{
var filledData = Fill<USERS>();
}
}
public class UsersPage<ORDERS >:MyPageBase<ORDERS >{
public void Index()
{
var filledData = Fill<ORDERS>();
}
}
ofcourse you could easily do this by
var filledData = db.USERS.ToList();
and you can ask why all the fuss? to implement the generic methods but some times there will happen to be more complex scenarios than fetching all the records etc.
say you have 20+ tables and you decide to fill only 5 records from each table. without a generic implementation
you know have to go all over 20+ pages and change your code
from
var filledData = db.TABLE_TYPE.ToList();
to
var filledData = db.TABLE_TYPE.Take(5).ToList()
however with generics you could just fix it in the below method, you could even make it parametric
public List<T> Fill()
{
return db.Set<T>().Take(5).ToList();
}
and you are safe..
now If you were to use the non generic implementation of MyPageBase
all these stuff you needed to do you had to write them over and over again.
ofcourse writing more and more code gives you experience but after a while when working in a program especially on a large scale you want to keep things simple, understandable and maintable as possible..
I'm sorry for my bad english,
I hope I was clear and this helped you!
The general reason I want to do this is:
class MovieApiController : ApiController
{
public string CurrentUser {get;set;}
// ...
public string Index()
{
return Resources.GetText("Color");
}
}
class Resources
{
static string GetText(string id)
{
var caller = ??? as MovieApiController;
if (caller && caller.CurrentUser == "Bob")
{
return "Red";
}
else
{
return "Blue";
}
}
}
I don't need this to be 100% dependable. It seems like the callstack should have this information, but StackFrame doesn't seem to expose any information about the specific object on which each frame executes.
It is generally a bad idea for a method to try to "sniff" its surroundings, and produce different results based on who is making the call.
A better approach is to make your Resources class aware of whatever it needs to know in order to make its decision, and configure it in a place where all relevant information is known, for example
class MovieApiController : ApiController {
private string currentUser;
private Resources resources;
public string CurrentUser {
get {
return currentUser;
}
set {
currentUser = value;
resources = new Resources(currentUser);
}
}
// ...
public string Index() {
return resources.GetText("Color");
}
}
class Resources {
private string currentUser;
public Resources(string currentUser) {
this.currentUser = currentUser;
}
public string GetText(string id) {
if (currentUser == "Bob") {
return "Red";
} else {
return "Blue";
}
}
}
CurrentUser should be available at HttpContext.Current.User and you can leave your controller out of the resource class.
It seems like the callstack should have this information,
Why? The call stack indicated what methods are called to get where you are at - it does not have any information about instances.
Rethink your parameters be deciding what information does the method need to do its job. Reaching outside of the class (e.g. by using the callstack or taking advantage of static methods like HttpContext.Current) limit the re-usability of your code.
From what you've shown, all you need is the current user name (you don't even show where you use the id value. If you want to return different things based on what's passed in then maybe you need separate methods?
As a side note, the optimizer has a great deal of latitude in reorganizing code to make it more efficient, so there are no guarantees that the call stack even contains what you think it should from the source code.
Short answer - you can't, short of creating a custom controller factory that stores the current controller as a property of the current HttpContext, and even that could prove unpredictable.
But it's really not good for a class to behave differently by attempting to inspect its caller. When a method depends on another class it needs to get the correct behavior by depending on the right class, calling the right method, and passing the right parameters.
So in this case you could
have a parameter that you pass to GetResources that tells it what it needs to know in order to return the correct string.
Create a more specific version of the Resources class that does what you need
declare
public interface IResources
{
string GetText(string id);
}
And have multiple classes that implement IResources, use dependency injection to provide the correct implementation to this controller. Ideally that's the best scenario. MovieApiController doesn't know anything about the implementation of IResources. It just knows that there's an instance of IResources that will do what it needs. And the Resource class doesn't know anything about what is calling it. It behaves the same no matter what calls it.
That would look like this:
public class MovieApiController : ApiController
{
private readonly IResources _resources;
public MovieApiController(IResources resources)
{
_resources = resources;
}
public string Index()
{
return _resources.GetText("Color");
}
}
Notice how the controller doesn't know anything about the Resources class. It just knows that it has something that implements IResources and it uses it.
If you're using ASP.NET Core then dependency injection is built in. (There's some good reading in there on the general concept.) If you're using anything older then you can still add it in.
http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection - This has a picture that is worth 1000 words for describing the concept.
http://www.c-sharpcorner.com/UploadFile/dacca2/implement-ioc-using-unity-in-mvc-5/
Some of these recommend understanding "inversion of control" first. You might find it easier to just implement something according to the example without trying to understand it first. The understanding comes when you see what it does.
I have a class from a third-party assembly (so I can't edit it):
public class MyClass
{
private bool _loggedIn;
public void Login() {_loggedIn = true;}
public void Logout() {
if (!_loggedIn) throw new InvalidOperationException();
_loggedIn = false;
}
}
Now, suppose I have an instance of MyClass (for which I don't know _loggedIn), and I need call LogOut. Which of the following methods of avoiding a fatal exception will generally be faster? (any other method would be fine too):
To call LogOut, and if _loggedIn == false, just catch the exception
To use reflection to check that _loggedIn == true, and only call LogOut if so
It depends on the invariants you expect to see in your application.
1. If you expect to have a lot of MyClass having different state(logged in, logged off), then it is better to avoid overhead of exception (because exception is Exceptional situation) and use some specific public IsLoggedIn property (obviously to avoid Reflection) or some TryXxxxx-like methods.
And even if you can't modify the original code no one stops you from wrapping it:
public class MyWrappedClass
{
public Boolean IsLoggedIn {get; private set;}
private MyClass m_Log;
public MyWrappedClass ()
{
this.m_Log = new MyClass();
this.IsLoggedIn = false;
}
public void Log()
{
try
{
this.m_Log.LogIn();
this.IsLoggedIn = true;
}
catch
{
this.IsLoggedIn = false;
}
}
public void LogOut()
{
try
{
this.m_Log.LogOut();
this.IsLoggedIn = false;
}
catch
{
this.IsLoggedIn = true;
}
}
}
You could even go further and implement IDisposable interface with it to avoid manual LogIn-LogOut management:
public class MyWrappedClass
{
private class LogSessionToken : IDisposable
{
private MyWrappedClass parent;
public LogSessionToken (MyWrappedClass parent)
{
parent.LogIn();
}
public void Dispose()
{
parent.LogOut();
}
}
public IDisposable LogSession()
{
return new LogSessionToken (this);
}
// ...
}
And use it like
using (var logToken = wrappedInstance.LogSession)
{
// do the work.
} // No need to worry about manual LogOut
2. If you expect to use only few of MyClass in a proper fashion, then it would be a better idea to not handle exception at all - if something wrong happened then it is some programming error thus the program shall be terminated.
First, if your class doesn't expose at least a read-only property for LoggedIn, there sounds like a fairly large design flaw.
For speed, using reflection will generally be faster, particularly if you cache the FieldInfo or build a Func<bool> using System.Linq.Expressions. This is because Exceptions collect lots of debug information when thrown, including a StackTrace, which can be expensive.
As with anything, though, it is often best to test such operations, as there are sometime optimizations or other factors that may surprise you.
If the pattern if (CanFoo) Foo(); appears very much, that tends to imply very strongly that either:
A properly-written client would know when it can or cannot call Foo. The fact that a client doesn't know suggest that it's probably deficient in other ways.
The class exposing CanFoo and Foo should also expose a method which will Foo if possible and appropriate (the method should throw if unable to establish expected post-conditions, but should return silently if the post-conditions were established before the call)
In cases where a class one does not control should provide such a method but doesn't, the cleanest approach may be to write one's own wrapper method whose semantics mirror those the missing method should have had. If a later version of the class implements the missing method, changing one's code to use that implementation may be easier than refactoring lots of if (CanFoo) constructs.
BTW, I would suggest that a properly-designed class should allow calling code to indicate whether it is expecting a transition from logged-in state to logged-out state, or whether it wants to end up in logged-out state but it doesn't care how it gets there. Both kinds of semantics have perfectly legitimate uses; in cases where the first kind would be appropriate, having a LogOut method throw an exception if called on a closed session would be a good thing, but in cases where client code merely wants to ensure that it is logged out, having an EnsureLoggedOut method that could be invoked unconditionally would be cleaner than having to add extra client-side code for that purpose.
FYI: the verbose preamble is to help explain why I am using Activator.CreateInstance. I have a number of entities (objects corresponding to database column information) that are "contained" in multiple databases, each of which has a different table/column setup. So I am able to retrieve an entity from each database, but the way I retrieve it is different per database. The database type is not known till runtime and could vary throughout execution. I have created the following setup:
First define the query operations each entity should support and each entity reader should support these operations.
public abstract class Operations<T> {
public delegate T findDelegate(int id);
public findDelegate find;
}
// there are many of these N=1,2,..., but here is one
// use abstract class since implementation of queries should be done by handlers
public class EntityNReader : Operations<EntityN> {
public Reader();
}
Define an interface for "Handler" classes, i.e. these classes implement the query operations listed above.
public interface IHandler<T> {
public string find(int id);
}
// there are many of these N,M=1,2..., but here is one
// use of interface is to force handlers to implement all query types
public class EntityNHandlerForDbTypeM : IHandler<EntityN> {
public string find(int id) {/*whatever*/}
}
This allows the developers to create a single class for handling EntityN query operations for DbTypeM. Now, create a Database class that contains the reader objects and binds the handler methods to the reader delegates.
public class Database {
// there are many of these, but here is one
public EntityNReader EntitiesN;
public Database(string dbType) {
// this is called for each EntityNReader
bindHandlers<Reader, TypeN>(MyReader, dbType);
// ...
// nullreferenceexception
EntitiesN.find(0);
}
// this is a factory that also performs late binding
private void bindHandlers<T,K>(T reader, string dbTypeM)
where T: Operations<K>, new()
{
// create instance of EntityNReader
r = (T)Activator.CreateInstance(typeof(T));
// r != null
// create instance of handler
IHandler<K> h = (IHandler<K>)(Activator.CreateInstance(
Type.GetType("namespace.to.EntityNHandlerForDbTypeM"),
new object[] { this }
));
// bind delegates
r.find = h.find;
}
}
As you can see in Databases constructor, the way the code is written now, I get a NullReferenceException even though instance r of EntityNReader is created and (verified to be) not null.
However, if I instantiate EntitiesN where it is declared in Database instead of within bindHandlers, the code compiles and everything works. The reason I don't just do this is that (subsequently) I would like to conditionally create readers/handlers inside of bindHandlers at the time the Database class is instantiated.
What is happening here? Link to actual code if necessary.
P.S. I am relatively new to programming, so I am open to hearing how an experience developer might design this component (especially if I am heading down the wrong path).
I realize your code was just samples, but I spotted this right off the bat...
if (supports[typeof(Entity1).Name]) { bindHandlers<Entity1Reader, Entity1>(Entities1, CamaDbType); }
if (supports[typeof(Entity2).Name]) { bindHandlers<Entity1Reader, Entity1>(Entities1, CamaDbType); }
Is it possible that you have a simple copy/paste mistake? Notice that Entities1 is passed in for both bindHandlers calls.