How to I declare to Ocean that my custom domain object can free memory? - ocean

I'd like to link my custom domain object into the Petrel free memory command. My domain object caches data while visualised and this cache could be cleared when the user wants to free memory.
I have found the IMemorySaver interface and tried declaring this on my custom domain object but the FreeMemory method is not called when the user choose to free memory in Petrel.
Any ideas?
Neal

In Ocean 2013.1 a new API has been introduced that allows custom domain objects and ToggleWindows from a plug-in to be told when the user has invoked the ‘Free memory’ feature (this will also work for programmatic calls to PetrelSystem.ForceFreeMemory()).
The API follows a similar pattern to the existing INameInfoFactory and IImageInfoFactory APIs.
In order to use the API you need to create a factory object for your custom domain object (or ToggleWindow) that implements the new IResourceSaverFactory interface.
This interface requires that you implement a single method called GetResourceSaver(). This
method will return a ResourceSaver object that is associated with your custom domain object (or ToggleWindow).
ResourceSaver is an abstract class and you should implement the FreeResources() method on your derived class.
When the ‘Free memory’ feature is invoked the system will use your ResourceSaverFactory to obtain a ResourceSaver object for each of your custom domain object (or ToggleWindow) instances.
The FreeResources() method will be called on your ResouceSaver
objects.
Regards,
Chippy

Neal, the IMemorySaver is declared as a service interface, which you should not re-implement.
Having said that, participation in Petrel's controlled resource management is a fair requirement.

Related

Facade in Object Oriented Programming

In OOP, should a Facade be an object or just a class? Which is better?
Most of the examples in Wikipedia creates Facade as an object which should be instantiated before use.
CarFacade cf = new CarFacade();
cf.start();
Can it be designed to be like this instead?
CarFacade.start();
UPDATE
Can a Facade facilitate a singleton?
A facade
represents a high level API for a complex subsystem (module).
reduces client code dependencies.
This means that your client code only uses the facade and does
not have a lot of dependencies to classes behind that facade.
It is better to use an instance of an interface, because
you can replace it for tests. E.g. mock the subsystem the facade represents.
you can replace it at runtime.
When you use a static methods, your client code is bound to that method implementations at compile-time. This is usually the opposite of the open/close principle.
I said "usually the opposite", because there are examples when static methods are used, but the system is still open for extension. E.g.
ServiceLoader
The static load methods only scan the classpath and lookup service implementations. Thus adding classes and META-INF/services descriptions to the classpath will add other available services without changing the ServiceLoader's code.
Spring's AuthenticationFacade for example uses a ThreadLocal internally. This makes it possible to replace the behavior of the AuthenticationFacade. Thus it is open for extension too.
Finally I think it is better to use an instance and interface like I would use for most of the other classes.
It's two fold. You can use it as a static method. Say for instance in spring security I use AuthenticationFacade to access currently logged in user Principal details like so. AuthenticationFacade.getName()
There are other instances, in which mostly people create an instance of Facade and use it. In my opinion neither approach is superior over the other. Rather it depends on your context.
Finally Facade can use Singleton pattern to make sure that it creates only one instance and provides a global point of access to it.
This question is highly subjective. The only reason I am responding is because I reviewed some of my own code and found where I had written a Façade in one application as a singleton and written almost the same Façade in a different application requiring an instance. I'm going to discuss why I chose each of those routes in their respective applications so that I can evaluate if I made the correct choice.
A façade vs the open/close principle is already explained by #Rene Link. In my personal experience, you have to think of it this way: Does the object hold the state of itself?
Let's say I have a façade that wraps the Azure Storage API for .NET (https://learn.microsoft.com/en-us/azure/storage/common/storage-samples-dotnet)
This facade holds information about how to authenticate against the storage API so that it the client can do something like this:
Azure.Authenticate(username, password);
Azure.CreateFile("My New Text File", "\\FILELOCATION");
As you can see in this example, I have not created an instance and i'm using static methods, therefore following the singleton pattern. While this makes for code that is more concise, I now have an issue if I need to authenticate to a given path with a different credential than the one already provided, I would have to do something like this:
Azure.Authenticate(username, password)
Azure.CreateFile("My New Text File", "\\FILELOCATION");
Azure.Authenticate(username2, password2);
Azure.CreateFile("My Restrictied Text File", "\\RESTRTICTEDFILELOCATION");
While this would work, it can be hard to determine why authentication failed when I call Azure.ReadFile, as I have no idea what username and password may have been passed into the singleton from thread4 on form2 (which is no where to found) This is a prime example of where you should be using an instance. It would make much more since to do something like this:
Using (AzureFacade myAzure = Azure.Authenticate(username, password))
{
Azure.CreateFile("My New Text File", "\\FILELOCATION"); // I will always know the username and password.
}
With that said, what happens if the developer needs to create a file in Azure in a method that has no idea what the username and password to Azure may be. A good example of this would be an application that periodically connects to Azure and performs some multi-threaded tasks. In said application, the user setups a connection string to azure and all mulit-threaded tasks are performed using that connection string. Therefore, there is no need to create an instance for each thread (as the state of the object will always be the same) However, in order to maintain thread safety, you don't want to share the same instance across all the threads. This is where a singleton, thread-safe pattern may come into play. (Spring's AuthenticationFacade according to #Rene Link) So that I could do something like this (psudocode)
Thread[] allTask = // Create 5 threads
Azure.Authenticate(username, password) // Authenticate for all 5 threads.
allTask.start(myfunction)
void myFunction()
{
Azure.CreateFile("x");
}
Therefore, the choice between an instance of a façade v. a singleton façade is completely dependent on the intended application of the facade, however both can definitely exist.

Where to put methods that interact with multiple classes

I have a class called Contact and one called Account
and I have a method called public static Account GetAccount(Contact c) {...}
Where is the best place to put this method? What design patterns should I be looking at?
A) With the Contact class
B) With the Account class
C) Have the method accessible in both classes
D) Somewhere else?
There are probably many good answers to your question. I'll take a stab at an answer, but it will have my personal biases baked in it.
In OOP, you generally don't see globally accessible) functions, disconnected from, but available to all classes. (Static methods might be globally available, but they are still tied to a particular class). To follow up on dkatzel's answer, a common pattern is in OOP is instance manager. You have a class or instance that provides access to a a database, file store, REST service, or some other place where Contact or Account objects are saved for future use.
You might be using a persistence framework with your Python project. Maybe something like this: https://docs.djangoproject.com/en/dev/topics/db/managers/
Some persistence frameworks create handy methods instance methods like Contact.getAccount() -- send the getAccount message to a contact and the method return the associated Account object. ...Or developers can add these sorts of convenience methods themselves.
Another kind of convenience method can live on the static side of a class. For example, the Account class could have a static getAccountForContact() method that returns a particular account for a given Contact object. This method would access the instance manager and use the information in the contact object to look up the correct account.
Usually you would not add a static method to the Contact class called getAccountForContact(). Instead, you would create an instance method on Contact called getAccount(). This method could then call Account.getAccountForContact() and pass "self" in as the parameter. (Or talk to an instance manager directly).
My guiding principle is typically DRY - do not repeat yourself. I pick the option that eliminates the most copy-and-paste code.
If you define your method in this way, it's not really connected with either of your classes. You can as well put it in a Util class:
public class AccountUtil{
public static Account getAccount(Contact c){ ... }
// you can put other methods here, e.g.
public static Contact getContact(Account a){ ... }
}
This follows the pattern of grouping static functions in utility classes like Math in Java / C#.
If you would like to bound the function to a class in a clear way, consider designing your class like this:
public class Contact{
public Account getAccount(){ ... } // returns the Account of this Contact
// other methods
}
In OOP it is generally recommended that you avoid using global functions when possible. If you want a static function anyways, I'd put it in a separate class.
It depends on how the lookup from Contact to Account happens but I would vote for putting it in a new class that uses the Repository pattern.
Repository repo = ...
Account account = repo.getAccount(contact);
That way you can have multiple Repository implemtations that look up the info from a database, or an HTTP request or internal mapping etc. and you don't have to modify the code that uses the repositories.
My vote is for a new class, especially if the function returns an existing account object. That is, if you have a collection of instances of Contact and a collection of instances of Account and this function maps one to the other, use a new class to encapsulate this mapping.
Otherwise, it probably makes sense as a method on Contact if GetAccount returns a new account filled in from a template. This would hold if GetAccount is something like a factory method for the Account class, or if the Account class is just a record type (instances of which have lifetimes which are bound to instances of Contact).
The only way I see this making sense as part of Account is if it makes sense as a constructor.

Passing client context using Unity in WCF service application

I have a WCF service application (actually, it uses WCF Web API preview 5) that intercepts each request and extracts several header values passed from the client. The idea is that the 'interceptor' will extract these values and setup a ClientContext object that is then globally available within the application for the duration of the request. The server is stateless, so the context is per-call.
My problem is that the application uses IoC (Unity) for dependency injection so there is no use of singleton's, etc. Any class that needs to use the context receives it via DI.
So, how do I 'dynamically' create a new context object for each request and make sure that it is used by the container for the duration of that request? I also need to be sure that it is completely thread-safe in that each request is truly using the correct instance.
UPDATE
So I realize as I look into the suggestions below that part of my problem is encapsulation. The idea is that the interface used for the context (IClientContext) contains only read-only properties so that the rest of the application code doesn't have the ability to make changes. (And in a team development environment, if the code allows it, someone will inevitably do it.)
As a result, in my message handler that intercepts the request, I can get an instance of the type implementing the interface from the container but I can't make use of it. I still want to only expose a read-only interface to all other code but need a way to set the property values. Any ideas?
I'm considering implementing two interfaces, one that provides read-only access and one that allows me to initialize the instance. Or casting the resolved object to a type that allows me to set the values. Unfortunately, this isn't fool-proof either but unless someone has a better idea, it might be the best I can do.
Read Andrew Oakley's Blog on WCF specific lifetime managers. He creates a UnityOperationContextLifetimeManager:
we came up with the idea to build a Unity lifetime manager tied to
WCF's OperationContext. That way, our container objects would live
only for the lifetime of the request...
Configure your context class with that lifetime manager and then just resolve it. It should give you an "operation singleton".
Sounds like you need a Unity LifetimeManager. See this SO question or this MSDN article.

How can I set additional properties when an object is persisted from a database using NHibernate?

I'm creating an application that creates a Catalog of files. The data of the catalog will be stored in a database through NHibernate, but the actual files are just stored on a file system. I've abstracted the interface to the file system into an interface called IFileSystemAdaptor.
When an object is persisted from the database I need to set its IFileSystemAdaptor FileSystemAdaptor property so that its methods and properties can access the file system.
For example a user may later call AddAttachment(string filename, Stream data) on the persisted object. This will cause it to write the stream to the specified file name through its IFileSystemAdaptor, and add the new file name to its AttachmenFileNames property which will later be saved to the database.
Where can I insert code to set the the FileSystemAdaptor property for objects that are persisted from the database? Should I add a layer of abstraction between the Session/SessionFactory that sets the FileSystemAdaptor property before returning objects? Or is there someway I can inject this functinality into the SessionFactory so it returns objects with the FileSystemAdaptor already set?
You could write a IPostLoadEventListener to set up your property after getting the entity from the database. Or use a custom bytecode provider to inject your entity with the IFileSystemAdaptor implementation.
I would treat that as an infrastructure concern. Your business logic could interact with the IFileSystemAdaptor and you could use Inversion of Control to pass concrete instances of FileSystemAdaptor to your business logic (the mapping between interface and concrete instance would be defined in web.config or app.config). This would allow you to create unit tests that pass in a mock instance of FileSystemAdaptor so your business logic would not have a dependency on the file system.
I would suggest implementing that class in a layer / project dedicated to infrastructure concerns or possibly an "Application Services" layer intended for application logic that is not necessarily business logic.
Another (potentially unpopular?) option might be to simply use service location for this. I've found this an acceptable way to provide limited services to entities without getting into the complexity of using a custom bytecode provider, etc.

Can a custom UserNamePasswordValidator add things to the WCF session?

Related to this question, I'm instantiating a connection to our internal API inside my custom UserNamePasswordValidator. Can I stash this somewhere so that I can use it in future calls in that user's session?
This is similar to this question, but I'm not using IIS, so I can't use HttpContext.Current (or can I?).
Update: Some context: our internal API is exposed via a COM object, which exposes a Login method. Rather than have a Login method in my service interface, I've got a custom UserNamePasswordValidator, which calls the Login method on the COM object.
Because instantiating the COM object and logging in is expensive, I'd like to re-use the now-logged-in COM object in my service methods.
Yes, it can. You'll need:
a custom ServiceCredentials implementation that returns a custom SecurityTokenManager.
a custom SecurityTokenManager implementation that returns a custom CustomUserNameSecurityTokenAuthenticator.
your custom CustomUserNameSecurityTokenAuthenticator needs to override ValidateUserNamePasswordCore, and should add a custom implementation of IAuthorizationPolicy.
your implementation of IAuthorizationPolicy should implement Evaluate, at which point it can start putting things in the WCF context.
replace the evaluationContext["PrimaryIdentity"] value with a PasswordIdentity or a custom IIdentity.
replace the evaluationContext["Principal"] value with a PasswordPrincipal or a custom IPrincipal.
update the evaluationContext["Identities"] collection to replace the GenericIdentity instance with your custom instance.
By doing this, you can have a custom IPrincipal implementation with some extra information in it.
For more details, see this.
UserNamePasswordValidator is absolutely out of all WCF contexts. It is only used to validate user name and password. Can you futher explain your problem?
Edit:
I guess COM object is instantiated for each session, isn't it? Otherwise wrapping COM into singleton should solve your problem. If you need to have per session COM object shared between validator and service instance you will need some cache or registry - something which is outside both validator and service and can be called from both of them.