MemoryCache for Object - c#

I have various function classes that preform long calculation. Currently every access to the result of the functions means recalculating the functions. That's why I want to incorporate MemoryCache in my solution. But the problem is that I need a ChangeMonitor Class that monitors the function class for changes. I have seen examples that monitor a file. My question is: do I need to write a custom ChangeMonitor or am I missing a simple solution?
An example just to be clear:
class MyFunction
{
//I want to monitor changes to these parameters
private int param1;
private int param2;
//This result should be cached
public int GetResult()
{
return param1 * param2;
}
};

You could use a Factory class to have a single class for access and creation of the MyFunction objects.
The Factory can then manage and synchronize the internal dictionary containing the previous calculations.
The MyFunction class needs to implement then IEquals and provide a hash function. Inside myClass you need to add private nullable int result.

Thanks for all the answers.
I realized that if I want to use the ChangeMonitor class I would have to extend it to monitor memory segments. The better solution in my case would be to alert the cache that a function result has changed. I have done this by adding a method 'Reset' to MyFunction class. Every time a parameter changes I just call the Reset function which will invalidate the cache.

Related

Can I set private readonly instance variable?

I'd like to know if somehow it is possible to set private readonly class variable via reflection or something?
Consider the following class:
public class TestSevice
{
private readonly someClassType m_variable;
public TestService()
{
m_variable = //call to some processing function
}
private static int CalculateStuff(int x, int y)
{
//some processing and return
}
}
I'm writing a unit test for private static method CalculateStuff(int x, int y), which I'm able to call via reflection:
PrivateType pt = new PrivateType(typeof(AvatarService));
int actialRes = (int)pt.InvokeStatic("CalculateStuff", parameters);
The problem is that, for my unit test to work, I don't want to set m_variable or set it to null on invoking the static function.
So, is it possible with a constructor is parameterless ctor to not set m_variable or custom set to to something in the unit test?
Edit:
Some details on //call to some processing function
Here, a call is made to start the receiver of message queue.
The class TestService is instantiated on the start of worker role, and hence the queue receiver is started in the ctor. The message queue receiver then calls a wrapper function in TestSevice class, which in turn calls CalculateStuff. And since I just want to test the core business logic, I don't want to start queue receiver(which imposes certain dependencies).
If you are trying to test a class by modifying its behavior you have already missed the point.
If there is a way that class can get into a certain test then that's how you should test it. With read only the only way to do that is through a constructor.
If the property is read only it suggests you only want to instantiate it once for a specific instance of that class and know it can't change. If that's the case the you shouldn't want to change it but possibly instantiate another instance.
If it needs to be changed before each call on calculate and you are in a situation where you think you need the function to be static, then you should probably have it as an extra parameter. This means it can longer be read only. Doing it this way would disconnect it from the state of a given instance but if you are trying/need to change the value it shouldn't be read only.
Apparently the answer is yes. https://stackoverflow.com/a/934942/2540156 But that doesn't really sound like your issue. It sounds like you want an alternate constructor to call during unit testing that will prevent the code from running that sets your variable. For that you'll have to make a change to your constructor.

Securing property in a class library and requiring a only a certain method to set it

I have a class library (call it Lib1) that can be used in other project (call it Lib2).
Lib1 has a lot of static methods, but in order to be able to call them from Lib2 another method in Lib1: Configure() is required to run on the application start just once. This method should set a property (again, just once), and every time a static method from Lib1 is called, the property should be evaluated (lets say it needs to be equal to 5).
It is my understanding that the property needs to be static. However, the issue then is that this property can be hacked to be any value.
Instead the code that I require to run in Lib1:
Lib1.Configure() // sets property to 5
Someone could just write this:
(typeof(Lib1)).GetProperty("propertyName").SetValue((object)null, 5)
How can I assure that this hack would not fly?
I'm sure this is not the answer you are looking for, but it's the only correct answer: You cannot. Anything in the memory of a PC you do not control can be manipulated.
Create a static constructor and initialize your static read only field to the value (5 in your case) that you require.
public class YourClass{
private static readonly int yourCheckField;
static YourClass() { yourCheckField = 5 }
}

c#: (Static) Class-Level Variables

This is definitely a bit of a noob question, but my searches so afar haven't cleared the issue up for me.
A want a particular console app to store several class-level variables. In one case, I want to store a copy of my logging object, which I'll use in various places within the class. In another case, I want to store a simple type, a int value actually, which is only going to be used internally (doesn't need to be a property).
It appears that unless I specify these variables as static, I can't use them in Main() and beyond.
My understanding of static objects is that their values are shared across all instances of an object. Under normal operation, I'd expect their to be only one instance of my app, so this issue isn't a problem - but it has highlighted a lack of understanding on my part of something that is fairly fundamental.
In the case, of my logging object, I could see a case for making it static - sharing a log across multiple instances might be a benefit. However, it might not be the case... In the case of my int, I'd certainly never want this to be shared across instances.
So...
Am I misunderstanding the theory behind this?
Is there a different way I should be declaring and using my class-level variables?
Should I be avoiding using them? I could simply pass values as parameters from function to function, though it seems little a lot for work for no apparent gain.
EDIT: OK, the message is clear - my understanding of statics was largely correct, but the problem was one of structure and approach. Thanks for your replies.
Just encapsulate your application in another class, which you create and execute on the Main method:
class MyApp {
private MyLog lol = new MyLog();
private int myInt = 0;
public void Execute() {
// ...
}
}
class Program {
public static void Main() {
new MyApp().Execute();
}
}
You can still make the log field static if you want.
You should be creating a class outside of your Main function, and then creating an instance of that class from within Main.
EG
class MyConsoleApp
{
public static void Main()
{
MyClass mc = new MyClass();
}
}
Class MyClass
{
private MyLog lol as new MyLog();
private int myInt = 0;
}
The issue here is more or less purely syntactical: Because a static method can only access static fields, and the Main() method has to be static, this requires the used variables to be static. You never create an instance of the MyConsoleApp class.
Not really much theory here, only pragmatic requirements...
Thomas

A design for sending objects to be added to the appropriate data structure

I have a class called DataStructures where I have a set of public static data structures that store objects. To add an object to a data structures is an involved process requiring a number of checks to be carried out, processes to be remembered and data to be rearranged. In another class called Foo, I need to add objects to the data structures.
I was thinking I can do this by making a method called ObjectFeed which would take an object and the object's label as parameters. The label would tell the method which of the data structures the object should be added to. I would also have a method called addObject which would take the object to append and the appropriate target data structure as parameters:
Public Class DataStructures
{
public static List<obj> object1Storage = new List<obj>();
public static List<obj> object2Storage = new List<obj>();
...
}
Public Class Foo
{
public void ObjectFeed(/* PARAMETERS */)
{
//Code that generates an object called inspectionObject
//inspection object has an associated enum Type
if(objectType == Type.Type1)
{
addObject(inspectionObject, DataStructures.object1Storage);
}
if(objectType == Type.Type2)
{
addObject(inspectionObject, DataStructures.object2Storage);
}
...
}
private void addObject(obj inspectionObject, List<obj> objStorage)
{
objStorage.Add(inspectionObject);
//And a lot more code
}
}
Passing a public data structure as a parameter to a method that can just as well access that data structure directly doesn't feel correct. Is there a more clever and less intuitive way of doing this?
Edit:
In the example I originally contrived, the ObjectFeed method served no apparent purpose. I rewrote the method to look more like a method from the real world.
Where is the object type coming from? Passing a string value as a type of something is very rarely a good idea. Consider different options:
Create an enum for these values and use this. You can always parse it from string or print it to string if you need to.
Maybe it makes sense to have a couple of specific methods: FeedObjectType1(object obj), etc.? How often will these change?
Its really difficult to give you a definite answer without seeing the rest of the code.
Exposing public static lists from your DataStructures class is in most cases not a good design. To start with I would consider making them private and providing some methods to access the actual functionality that is needed. I would consider wrapping the lists with the addObject method, so that you don't have to pass the list as an argument. But again I am not sure if it makes sense in your case.
You seem to use DataStructures like some kind of global storage. I don't know what you store in there so I'm going to assume you have good reasons for this global storage.
If so, I would replace each list with a new kind of object, which deals with additions of data and does the checks relevant for it.
Something like:
interface IObjectStorage
{
void Add(object obj);
void Remove(object obj);
}
Each object storage type would derive from this and provide their own logic. Or it could derive from Collection<T> or something similar if collection-semantics makes sense. As your example is right now, I can't see the use for ObjectFeed, it serves as a fancy property accessor.
Selecting which property to access through a string sounds iffy to me. It is very prone to typos; I would rather use Type-objects available from any object in C# through the GetType-method or typeof() construct.
However. The whole setup feels a bit wrong to me, DataStructures et al.
First, testing your static class will be hard. I would pass around these stores to the types that need them instead. Replacing them with other stuff will also be hard, using interfaces will at least not tie you to a concrete implementation, but what if you want to use another location to store the objects in other code? Your static class is no longer relevant and you'll need to change a lot of code.
Maybe these things are out of your control, I don't know, the example code is a bit vague in that sense.
As pointed out in other answers:
The public static Lists are bad practice
Since the addObject method is the same for every data structure, it should be implemented as a data structure accessor.
To this end, I moved the instantiation of the data structures into Foo and moved the addObject method from Foo to a new class called StorageLibrary that more accurately represents the data structure architecture.
private class StorageLibrary
{
private List<obj> storedObjects = new List<obj>();
public void addObject(obj inspectionObject)
{
storedObjects.Add(inspectionObject);
//And a lot more code
}
}
public class Foo : StorageLibrary
{
//Declaration of libraries
public static StorageLibrary storage1 = new StorageLibrary();
public static StorageLibrary storage2 = new StorageLibrary();
...
private void ObjectFeed(/* PARAMATERS */)
{
//generate objects
if (objectType == Type.Type1)
{
storage1.addObject(inspectionObject);
}
if (objectType == Type.Type2)
{
storage2.addObject(inspectionObject);
}
...
}
}

Is it bad practice to have state in a static class?

I would like to do something like this:
public class Foo {
// Probably really a Guid, but I'm using a string here for simplicity's sake.
string Id { get; set; }
int Data { get; set; }
public Foo (int data) {
...
}
...
}
public static class FooManager {
Dictionary<string, Foo> foos = new Dictionary<string, Foo> ();
public static Foo Get (string id) {
return foos [id];
}
public static Foo Add (int data) {
Foo foo = new Foo (data);
foos.Add (foo.Id, foo);
return foo;
}
public static bool Remove (string id) {
return foos.Remove (id);
}
...
// Other members, perhaps events for when Foos are added or removed, etc.
}
This would allow me to manage the global collection of Foos from anywhere. However, I've been told that static classes should always be stateless--you shouldn't use them to store global data. Global data in general seems to be frowned upon. If I shouldn't use a static class, what is the right way to approach this problem?
Note: I did find a similar question, but the answer given doesn't really apply in my case.
Who stays that static classes should be stateless? Static means stated.
Just know how static classes work in the CLR:
You can't control the time when static constructors are called.
Static classes have a separate state for each calling program.
Also be aware of concurrency issues.
As a side note, it amazes me how often people say "Don't use X." It would be like someone walking into your toolshed and pointing to half a dozen tools and saying, "Those tools are bad practice." It doesn't make sense.
Global data is both powerful and a common source of problem, that's why techniques like dependency injection are used. You can think of it as a normal decoupling problem. Having global data that is referenced directly in a lot of places in your program makes a strong coupling between that global data and all those places.
In your example however you have isolated the access to the data into a class, which controls the exact details of the access of the global data. As some global data is often inevitable, I think that this is a good approach.
You can for example compare to how app.config and web.config are used through the .NET framework. They are accessed through a static class System.Configuration.ConfigurationManager with a static property AppSettings, which hides a away the details of how to reach the global data.
What you seem to be looking for here is a singleton class, not a static class. Static classes and methods should be referred for stateless routines. A singleton class gets instantiated once and only once per application run and has the full functionality of a class as such. Every time that you reference it in the future, you will get back the exact same instance with the exact same member properties.
The first google result for "C# singleton" seems to have a pretty decent explanation for implementation. http://www.yoda.arachsys.com/csharp/singleton.html
It's not generally bad. In some rare cases it's neccessary to do it that way than implementing something else with large overhead.
But it's recommended to watch for threadsafety.
You should lock every call to your dictionary so that only one thread can access it at one time.
private static readonly object LockStaticFields = new object();
public static Foo Add (int data) {
lock(LockStaticFields)
{
Foo foo = new Foo (data);
foos.Add (foo.Id, foo);
return foo;
}
}
Use a read only static property in your class, this property will be the same across all instances of the class. Increment it and decrement as needed from the constructor, etc.
I use lists in static classes all the time for things that will never (or extremely rarely) change - handy for for loading pick lists and such without hitting the db every time. Since I don't allow changes, I don't have to worry about locking/access control.
One other thing to take into consideration is the application itself and the budget for it. Is there really a need for something more complex than a static class?

Categories

Resources