I have classes with properties implemented in dll (I can not change implementation because i do not have huge source code). I can not replace using of property Name with inherited class because project have thousands lines of code where it used(Ctrl+h does not help). Somebody told that my problem can be solved by Dynamic property interception across Castle and Unity. But i cannot find any workable small examples. Can you show how to implement it? I read that Castle dynamic proxy intercepts only virtual methods. Is it possible to intercepts non virtual methods with interface?
namespace DynamicInterception
{
// Placed int first dll
public class Cargo
{
public string Name { get; set; }
}
//Placed in second dll
public class Wagon
{
public Cargo Cargo { get; set; }
}
class Program
{
static void Main(string[] args)
{
Wagon wagon = new Wagon();
wagon.Cargo = new Cargo() { Name = "Test" };
}
}
}
Yes, with Castle Dynamic Proxy you can intercept non-virtual members of a class if the member is part of an interface. Look at the documentation (specifically the section on IInterceptor) and if you're having problems, start a new question with some sample code showing the issue you're having.
Related
I created the ObservableCollection, which works with bindings, etc. Now I have a problem, I can't access it from other classes. Tried most things but probably missing some obvious things.
public MyFavorites()
{
ObservableServers = new ObservableCollection<Server>();
}
private ObservableCollection<Server> _myListOfServersObjects;
public ObservableCollection<Server> ObservableServers
{
get => _myListOfServersObjects;
set
{
if (_myListOfServersObjects != value)
{
_myListOfServersObjects = value;
OnPropertyChanged("ObservableServers");
}
}
}
full code: https://pastebin.com/KLFHwhKg
so i`m trying to add: https://pastebin.com/p7dBDcXq
This may get flagged because it's a very broad topic and not related to a specific issue. The general way you solve this is to create an interface such as the following:
public interface IServerCollection
{
IList<Server> ObservableServers { get; }
}
Notice that I've changed ObservableServers from an ObservableCollection<> to an IList<>. From the perspective of the other parts of your application the actual implementation doesn't matter, so choose the most basic interface object that will fulfill their needs. The actual implementation class fills in the details:
public class ServerCollection : IServerCollection
{
private IList<Server> _myListOfServersObjects = new ObservableCollection<Server>();
public IList<Server> ObservableServers {get => _myListOfServersObjects;}
}
So somewhere in your application something creates an instance of type ServerCollection, and it then gets passed in as an IList to whatever needs it e.g.:
public IServerCollection ServerCollection {get; private set;}
public MyFavorites(IServerCollection serverCollection)
{
ServerCollection = serverCollection;
}
This is known broadly as "Inversion of Control", and the actual passing of the interface instance into your class is known as "Dependency Injection". There are heaps of resources about both of these around the net, they're well worth reading up on. They solve a lot of problems but they also create a new one: you find yourself passing lots of these interface references around and storing them at multiple levels of your application. Thus, in a real application you typically use a dependency injection framework to largely automate the work for you, and in the case of .NET the package of choice 9 times out of 10 is Ninject.
I haven't done this for a while and I need to find out if this is the best OO way to go. I am having trouble assigning (Setting) the protected properties in a base class in the derived class. I have a solution but I like to know if this is the best design pattern to use or is there a better way?
My Base class
public abstract class EmailBase
{
protected string Subject { get; set; }
protected string To { get; set; }
protected string From { get; set; }
protected virtual void Send()
{
using (MailMessage mail = new MailMessage())
{
// Ok send message here...
}
}
}
I have two different email templates that I need to send so I thought it would be a good idea to have two derived classes, however I will post the code for one derived class for the problem at hand.
public class DerivedOne: EmailBase
{
private const string emailTemplate = "some static text for the body...";
public DerivedOne()
{
}
// This is how I want to set the base class properties,
// but it feels I am just duplicating properties...
public string To
{
set
{
base.To = value;
}
}
And in the controller...
// A send email button was pressed by the user
private bool SendEmail(Model)
{
DerivedOne eMail = new DerivedOne()
{
To = Model.To;
};
}
I tend to not send the properties through the derived constructor as I believe setting up properties tends to be cleaner. However, I know in the derived constructor you can set the base properties : base()
So this is why I have asked, am I wrong to create the same properties in the derived class so the controller can see it? (as the protected properties cannot be seen outside of inheritance of course)
Yes, I think that you right with your doubts. We should tend to avoid duplication wherever possible and use the full power of OOP.
Plus, you could avoid a lot of problems by making your classes immutable and providing dependencies via constructor. If class needs dependency to be consistent, this dependency should be provided via constructor. Doing this could guarantee yourself(and other programmers) that you can't create instance of class without providing this dependency. For example, in your case I believe you can't send Email without providing To information, so it's better to provide To via constructor. The same reasoning could be applied for other dependencies.
Plus, assigning protected properties in derived classes in itself could be a problem and could lead to violations of Liskov-substitution, Open-close and other SOLID principles. But, of course, sometimes it could be useful, and there is no general rule of not doing this.
I'm working on a game that uses MVCS and has, so far, clearly separated the business logic from the view.
However, I've been having trouble with one particular piece of the puzzle.
In the game we have command classes (IPlayerCommand) that execute a specific business logic. Each command class returns a result class (PlayerCommandResult). For each PlayerCommand we have a respected visual command class (IVisualPlayerCommand) that takes the PlayerCommandResult and updates the view accordingly.
I'd like the IVisualPlayerCommand to use specific classes that inherit PlayerCommandResult in order to get the information it needs (as opposed to using object). I'd also like to make it compile-time safe (as opposed to casting it before using it). For these two reasons I made the classes use generics.
Here are the declaration of the classes:
public class PlayerCommandResult
{}
public interface IPlayerCommand<T> where T : PlayerCommandResult
{
T Execute(GameWorld world);
}
public interface IVisualPlayerComamnd<T> where T : PlayerCommandResult
{
void Play(T commandResult);
}
Here is the Move Unit command as an example:
public class MoveUnitPlayerCommand : IPlayerCommand<MoveUnitPlayerCommandResult>
{
private Unit unitToMove;
public MoveUnitPlayerCommand(Unit unit)
{
this.unitToMove = unit;
}
public MoveUnitPlayerCommandResult Execute(GameWorld world)
{
MoveUnitPlayerCommand result = new MoveUnitPlayerCommand();
// Do some changes to the world and store any information needed to the result
return result;
}
}
public class MoveUnitVisualPlayerCommand : IVisualPlayerCommand<MoveUnitPlayerCommandResult>
{
void Play(MoveUnitPlayerCommandResult commandResult)
{
// Do something visual
}
}
public class MoveUnitPlayerCommandResult : PlayerCommandResult
{
public Unit TargetUnit { get; private set; }
public Path MovePath { get; private set; }
}
So far, so good. However, I'm having a really hard time tying a IPlayerCommand to a IVisualPlayerCommand because of the use of generics:
public class CommandExecutorService
{
public void ExecuteCommand<T>(IPlayerCommand<T> command) where T : PlayerCommandResult
{
T result = command.Execute(world);
IVisualPlayerCommand<T> visualCommand = GetVisualPlayerCommand(command);
visualCommand.Play(result);
}
public IVisualPlayerCommand<T> GetVisualPlayerCommand<T>(IPlayerCommand<T> command) where T : PlayerCommandResult
{
// ?!?!?!?!?!??!?!?!??!?!
}
}
I have a feeling that what I'm trying to do is not even possible because of the way generics work in C# (as opposed to Java where I could say IVisualPlayerCommand<?>).
Could you help me figure out a way?
Any feedback for the design is welcome.
P.S. Sorry if the title doesn't reflect the question. I wasn't sure how to boil down the question in one line.
P.P.S. Which is why I also don't know if this question has been asked and answered before.
You two command classes, are served as service. To me, for this case, I would use the service locator pattern. As how to implement this pattern, you can check this link
The drawback of using template, is that, if something changes, you have to compiled it again.
Here's link which provides an example of the service locator pattern.
So for you code, you want find the corresponding instance of IVisualPlayerCommand to IPlayerCommand, so the concrete service can inherit from both interface, which it actually implements the IVisualPlayerCommand interface, while the IPlayerCommand just severs as a tag.
so the code will like this:
class MoveUnitVisualPlayerCommand: IVisualPlayerCommand, IPlayerCommand {}
services = new Dictionary<object, object>();
this.services.Add(typeof(IPlayerCommand ), new MoveUnitVisualPlayerCommand());
as how to get the service, you can refer the example.
Hope this helps.
Needs -
To declare shared exports of the same interface. The exports are marked by unique export names so consumers may import a particular flavor of the export.
To inject a common instance of the class into a set of objects but to not share a common instance across sets of objects [This makes me use shared exports using different keys - one set of objects can use a single key to get satisfy their shared import need]
Here is the export class
public interface IMyExport
{
void Display();
}
public class MyExport : IMyExport
{
private Guid _id = Guid.NewGuid();
public void Display()
{
Console.WriteLine("Instance ID = "+_id);
}
}
and here is how I export instances of the class
public static class ExportInitialization
{
[Export("Type A", typeof(IMyExport)),
Export("Type B", typeof(IMyExport))]
public static IMyExport IceCreamExport
{
get
{
return new MyExport();
}
}
}
Consumers may import specific instances in the following manner
[Export]
public class ImporterA
{
private readonly IMyExport _myExport;
[ImportingConstructor]
public ImporterA([Import("Type A")]IMyExport myExport)
{
_myExport = myExport;
}
public void Display()
{
_myExport.Display();
}
}
[Export]
public class ImporterB
{
private readonly IMyExport _myExport;
[ImportingConstructor]
public ImporterB([Import("Type B")]IMyExport myExport)
{
_myExport = myExport;
}
public void Display()
{
_myExport.Display();
}
}
class Program
{
[Import]
public ImporterA ImporterA { get; set; }
[Import]
public ImporterB ImporterB { get; set; }
static void Main(string[] args)
{
new Program().Run();
}
public void Run()
{
var container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
container.ComposeParts(this);
ImporterA.Display();
ImporterB.Display();
Console.ReadKey();
}
}
This used to work fine with .Net 4.0 but when .Net 4.5 is installed - I get the following ouptut
Instance ID = 78bba41a-0c48-44fc-ae69-f0ead96371f9
Instance ID = 78bba41a-0c48-44fc-ae69-f0ead96371f9
Notice that the same instance of the object is returned for both imports. Am I breaking some undocumented rule regarding exporting via static properties?
I found that exporting the specific instances from two distinct static properties ensures that 2 distinct instances are returned.
[Export("Type A", typeof(IMyExport))]
public static IMyExport ExportA
{
get
{
return new MyExport();
}
}
[Export("Type B", typeof(IMyExport))]
public static IMyExport ExportB
{
get
{
return new MyExport();
}
}
This is puzzling since in the unmodified version the static getter was creating a new instance on every get. Not sure if this is the result of some C#/.Net optimization introduced with 4.5 or if this is a MEF issue
This is related to the MEF parts lifetime.
The default for MEF attributes is that components do not say whether they care to get a new instance each time or not.
Meaning that:
Your ExportAttribute does not specify whether exported instances can or should be shared;
Both of the ImportAttributes do not specify whether their import should be shared or not;
The default behavior of MEF is that, if it is not forbidden from sharing instances, it will. Meaning that, according to the documentation, the behavior of .NET 4.5 is the correct one: the instance of MyExport is shared, given that no-one on either side explicitly forbade sharing.
I think that .NET 4.0 had a bug/discrepancy where the static property was called every time, which resulted in what you observed, that is, non shared instances. And you were relying on that bug. I think that the bug finds its origin in a fundamental, framework-wide expectation for properties - it is very unusual to have a static property create a new, semantically distinct, instance for each property call.
I believe you should:
Replace your static property export with a static method export;
Specify the creation policy to non-shared, on either the Export side or the Import side;
I've seen this problem come up a lot, but never adequately handled, and I haven't seen it on Stack Overflow, so here goes. I wish there were a way to put this shortly and succinctly without lacking clarity, but I can't seem to shorten it, so bear with me...
A good case-study (my current case, of course) to illustrate the problem follows:
I write code for many locations, a Parent Compary (parentco), and several satellite locations (centers). I have two 'Managers', one designed for the parentco, and one designed for the centers (deployed many times). I also have two libraries, one for the centers, and one generic library (that is used at the centers and the parentco), that programs can include to communicate to the appropriate Manager (via TCP). The library for the centers has several classes designed to wrap database tables and other 'Messages' to do other things, and the generic library has a few 'Messages,' too, such as 'end connection,' 'invoke a process,' and others.
The Question:
When the Manager recieves a Message that is defined in the 'generic' library, how can it know which type of message it is? The first-blush solution would be something like this:
namespace generic_library
{
public interface IMessage_Creator
{
public IMessage Create_Message(short id);
}
public interface IMessage
{
short Message_ID { get; }
}
/// <summary>Perhaps a message to kill the current connection</summary>
public class Generic_Message1 : IMessage
{
public short Message_ID { get { return ID; } }
internal const short ID = 1;
}
public static class Message_Handler
{
private static readonly System.Collections.Generic.List<IMessage_Creator> _creators =
new System.Collections.Generic.List<IMessage_Creator>();
public static void Add_Creator(IMessage_Creator creator)
{
_creators.Add(creator);
}
public static IMessage Get_Message(short id)
{
switch (id)
{//the Generic library knows about the generic messages...
case Generic_Message1.ID:
return new Generic_Message1();
}
//no generic message found, search the registered creators.
IMessage ret = null;
foreach (IMessage_Creator creator in _creators)
{
ret = creator.Create_Message(id);
if (ret != null)
{
return ret;
}
}
//null if no creator was found.
return ret;
}
}
}
namespace center
{
public class Center_Creator : generic_library.IMessage_Creator
{
static Center_Creator()
{
generic_library.Message_Handler.Add_Creator(new Center_Creator());
}
public generic_library.IMessage Create_Message(short id)
{
switch (id)
{//The center library knows about center-specific messages
case center_message1.ID:
return new center_message1();
}
//we return null to say, "I don't know about that message id."
return null;
}
}
public class center_message1 : generic_library.IMessage
{
public short Message_ID
{
get { return ID; }
}
internal const short ID = 2;
}
}
A little explanation. As you can see, the center and generic library have their own messages they can handle. The center interface (here represented by namespace center) registers his creator, Center_Creator, in the static constructor so when the Message_Handler gets a message of his type, the creator will be called on to generate the correct message.
The problem with this approach:
You may have already seen the problem here, and that is:
If the class Center_Creator is never accessed at all (one is never created, and a static method is never invoked) by code, which should be the case until a message of that type is recieved, the static constructor, static Center_Creator() is never invoked, so the Message_Handler never knows about this creator.
That's all fine and dandy, but I don't know how to fix it. Many people have suggested using reflection to invoke the Center_Creator Type Initializer, but I don't want to put that burden on every program that uses this library!
What is the Stack Overflow community's suggestion? Please let me know if I can simplify this to help make it more accessible for the community.
EDIT:
The code is for the generic library and the Center Library. As you can see, I will have the same issues with the Parent Company library.
A diagram of the architecture. http://cid-0676bb3c1f8d6777.office.live.com/self.aspx/Public/Manager.jpg
Image.
Let's break this down:
You have an application which is to send & receive certain types of messages.
A message type must be registered before it can be read, however,
You do not register the type until you send a message, but
You want to be able to read a message before you write one.
Clearly the answer is that you are registering your message types at the wrong time.
I would suggest an explicitly called Init() method for message types. This could be done by using reflection to scan the libraries to see would types are defined, or by manually listing them.
your message handlers can be seen as plugins which makes your problem a potential fit for the Managed Extensibility Framework. Since .Net 4 it's also shipped with the .Net framework.
You can find sample introductions to MEF here and here.
I've put together a litte example to show that it's quite simple to use basic MEF functionality (although there is much more you can do with it). First there is a PluginHost class which will host the plugins in its Plugins collection. Then there's a simple interface containing just the property Description and an example implementation of a plugin called ExamplePlugin.
The Plugins collection will be filled by the container.ComposeParts(..) method called in the constructor. All that's required to make that magic happen are the [Export] and [ImportMany] attributes.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace Playground
{
public class Program
{
static void Main(string[] args)
{
PluginHost host = new PluginHost();
host.PrintListOfPlugins();
Console.ReadKey();
}
}
public class PluginHost
{
[ImportMany]
public IEnumerable<IPlugin> Plugins { get; set; }
public PluginHost()
{
var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
public void PrintListOfPlugins()
{
foreach (IPlugin plugin in Plugins)
Console.WriteLine(plugin.Description);
}
}
public interface IPlugin
{
string Description { get; }
}
[Export(typeof(IPlugin))]
public class ExamplePlugin : IPlugin
{
#region IPlugin Members
public string Description
{
get { return "I'm an example plugin!"; }
}
#endregion
}
}
UPDATE: You can use so called Catalogs to discover plugins in more than one assembly. For example there is a DirectoryCatalog which gives you all exports found in all assemblies in a given directory.
AppDomain.CurrentDomain.GetAssemblies(); returns an array of all assemblies loaded into the current AppDomain. You could then iterate over that array to create an AggregateCatalog containing an AssemblyCatalog per loaded assembly.
Some ideas:
Use .NET serialization to serialize/deserialize your messages and put them in a class library used by both ends (or even use WCF to handle communication).
Add a custom attribute to your creator classes and populate the creator list using reflection at the first time Get_Message is called ("if (!initialized) FindAndAddCreators();").
Introduce some initialization method in your library that registers all the creator classes.
Try using a factory pattern.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace SO
{
class Program
{
static void Main(string[] args)
{
MessageFactory factory = new MessageFactory();
IMessage msg = factory.CreateObject(1);
IMessage msg2 = factory.CreateObject(2);
}
}
public interface IMessage
{
short Message_ID { get; }
}
public class Generic_Message1 : IMessage
{
public short Message_ID { get { return ID; } }
internal const short ID = 1;
}
public class center_message1 : IMessage
{
public short Message_ID { get { return ID; } }
internal const short ID = 2;
}
public class MessageFactory
{
private Dictionary<short, Type> messageMap = new Dictionary<short, Type>();
public MessageFactory()
{
Type[] messageTypes = Assembly.GetAssembly(typeof(IMessage)).GetTypes();
foreach (Type messageType in messageTypes)
{
if (!typeof(IMessage).IsAssignableFrom(messageType) || messageType == typeof(IMessage))
{
// messageType is not derived from IMessage
continue;
}
IMessage message = (IMessage)Activator.CreateInstance(messageType);
messageMap.Add(message.Message_ID, messageType);
}
}
public IMessage CreateObject(short Message_ID, params object[] args)
{
return (IMessage)Activator.CreateInstance(messageMap[Message_ID], args);
}
}
}
EDIT to answer comment:
If the "generic" library is the one processing the messages, and it has no knowledge of the types of message is is processing, you obviously have to change that.
Either move to a "plug-in" model where your custom message dlls will be loaded from a specific directory on startup of the generic library, or read the custom message dlls from a config file at startup for the generic library.
// Read customMessageDllName and customMessageClassName from your config file
Assembly assembly = Assembly.Load(customMessageDllName);
IMessage customMessage = (IMessage)assembly.CreateInstance(customMessageClassName);
Why not simply use WCF? You'll get ease of development, great support, as well as interoperability with Java.
Gallactic Jello is on the right path. The part he left out is overcoming the problem of the generic library knowing about classes in the center library, which I have further addressed. I've created a sample solution with three projects, the full contents of which I'll spare you. Here is the gist.
Class Library: Generic lib
Contains a Message_Handler, his own IMessage_Creator, definitions of the interfaces, and an IMessage type of his own.
Class Library: Center Lib
Contains an IMessage_Creator, and his own IMessage type.
Application: Application
has a SVM (static void Main()) containing the following lines of code:
Generic_lib.IMessage msg = Generic_lib.Message_Handler.get_message(2); //a Center Message
if (msg is Center_lib.Center_Message)
{
System.Console.WriteLine("got center message");
}
You will be amazed how important the if statement is!!! I'll explain later
Here's the code in the Type Initializer for Generic_lib.Message_Handler:
static Message_Handler()
{
//here, do the registration.
int registered = 0;
System.Reflection.Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
foreach (System.Reflection.Assembly asm in assemblies)
{
System.Type[] types = asm.GetTypes();
foreach (System.Type t in types)
{
System.Type[] interfaces = t.GetInterfaces();
foreach (System.Type i in interfaces)
{
if (i == typeof(IMessage_Creator))
{
System.Reflection.ConstructorInfo[] constructors = t.GetConstructors();
foreach (System.Reflection.ConstructorInfo ctor in constructors)
{
if (ctor.GetParameters().Length == 0)
{
Add_Creator(ctor.Invoke(new object[0]) as IMessage_Creator);
registered++;
}
}
}
}
}
}
System.Diagnostics.Debug.WriteLine("registered " + registered.ToString() + " message creators.");
}
Horrific, isn't it? First, we get all the assemblies in the current domain, and here's where the if statement comes in. If there was no reference to the 'Center__lib' anywhere in the program, the array of Assemblies won't contain Center_lib. You need to be sure that your reference to it is good. Creating a method that is never called that references it is not enough, a using statement is not good enough,
if (msg is Center_lib.Center_Message) ;
is not enough. It has to be a reference that can't be optimized away. The above are all optimized away (even in Debug mode, specifying `don't optimize.'
I hope someone can come up with an even more elegant solution, but this will have to do for now.
Aaron