I am using SignalR in version 2.1.2. I have noticed there are two public hub classes for me to use, Hub and Hub<T>. The former has an MSDN page which appears to be outdated and the latter lacks any MSDN page at all. I believe the MSDN documentation is not up to date with the latest version of SignalR from Nuget (which I'm using), because sources decompiled with the help of ReSharper show both of the classes inherit from HubBase base class. The MSDN page's Inheritance Hierarchy section shows the Hub class as inheriting from Object and implementing IHub and IDisposable interfaces, however the decompiled sources reveal the aforementioned HubBase base class, implementing the IHub interface which in turn implements IDisposable.
The difference between the non-generic and generic variant of the classes is that the non-generic one's Clients property returns IHubCallerConnectionContext<dynamic> while the generic variant returns typed IHubCallerConnectionContext<T>.
I'd like to have my clients typed, so when I call the client methods from the hub, I'd have proper Intellisense support and strongly-typed arguments. What I struggle with, though, is how to let the Hub know that my client model's method is actually to be invoked in the browser.
This is my TestModel class:
public sealed class TestModel
{
public String Name { get; set; }
public void Notify() {}
public void NotifyComplex(TestModel model) {}
}
With the non-generic hub, I'd just call .Notify() or .Notify(new TestModel() { Name = "sth" }) on the dynamicly bound this.Context.Clients.Client(…) or this.Context.Caller, but with the generic class, when I call these empty methods in similar manner, the browser is not notified at all.
How do you use the generic hub class the way it's supposed to be used?
I've found the answer. The MSDN documentation is not up-to-date as of yet, but the ASP .NET site offers nice SignalR tutorials and one of them covers the typed hubs:
http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-server#stronglytypedhubs
As the example in the article shows, if you use an interface for the type argument, everything works and you get strongly-typed hub clients whose methods are correctly translated to RPCs. Here's a piece of code I tested this with:
public sealed class TestHub
: Hub<ITestClient>
{
public override Task OnConnected()
{
this.Clients.Caller.SayHello("Hello from OnConnected!");
return base.OnConnected();
}
public void Hi()
{
// Say hello back to the client when client greets the server.
this.Clients.Caller.SayHello("Well, hello there!");
}
}
public interface ITestClient
{
void SayHello(String greeting);
}
Related
I have been using a lot of APIs where to listen to some event I just need to implement an interface, but it doesn't require me to subscribe, how they do that?
To explain it better here is how I usually do my listeners
interface IListener
{
void OnEventHappen();
}
public class EventClass
{
public static Action onEvent;
}
public class ListenerClass : IListener
{
//constructor
public ListenerClass()
{
EventClass.onEvent += OnEventHappen;
}
//function from IListener interface
public void OnEventHappen() { //something... }
}
but in those APIs it is not necessary to subscribe anywhere, I just need to implement the interface like this: (I removed the EventClass because in those APIs I have no access to the classes who trigger the events)
interface IListener
{
void OnEventHappen();
}
public class ListenerClass : IListener
{
//function from IListener interface
public void OnEventHappen() { //something... }
}
In c# such behavior can be achieved using reflection.
One example in comments mentions Unity and it's methods like OnBeginDrag or Update. Those are not called using c# events. Unity is mostly written in c++ and after your c# code is compiled Unity looks for all classes implementing certain interfaces or inheriting from certain classes (like MonoBehaviour) and checks if they have matching methods (like Update()) so it can call them later when necessary.
Another comment mentions Photon, a networking engine commonly used with Unity. In this case there is no "magic" or even reflection. To receive Photon's callbacks you have to call PhotonNetwork.AddCallbackTarget method and pass instance of your class as an argument. Only confusing thing in case of Photon is fact, that you don't have to do that directly. Instead of calling this method yourself, you can just inherit from MonoBehaviourPunCallbacks class which implements all Photon's callback interfaces and calls PhotonNetwork.AddCallbackTarget in it's OnEnable method. That method is in turn called by Unity like I explained earlier.
I'm building a program that will be processing messages from various topics. Since the data on each topic is different, I need dedicated classes that consumes data from any given topic. I want to do so using a base class that handles the communicates with the messaging system, and derived classes that implement the handling of the message:
public abstract class MessageConsumer<T>
{
public void Start(){/*omitted*/}
/* Other abstract properties and methods here to support template pattern*/
}
The Start method will tell the MessageConsumer to start pulling in new message. Examples of derived classes are:
public class CreatedMessageConsumer : MessageConsumer<CreatedMessage>
{
/*Implementation omitted*/
}
public class DeletedMessageConsumer : MessageConsumer<DeletedMessage>{}
In the code snippet above, I omitted the required constructor arguments, but it's easy to imagine how a DiContainer can be useful here. I use Autofac. The registration of CreatedMessageConsumer and DeletedMessageConsumer using Autofac works well.
My problem is how to resolve all classes that derives from MessageConsumer<>.
This SO post discusses how to resolve a given derived type, but I want to resolve all types that derive from MessageConsumer. Subsequently I want to call the Start method on all of them, e.g. something like
foreach(var consumer in container.Resolve<IEnumerable<MessageConsumer<??>>())
{
consumer.Start();
}
However, because I cannot provide the generic argument, it will not compile. Any idea how to do this? I'm using Autofac 4.2.1.
If you do not care about the generic argument, (which you don't otherwise you would have specified a generic argument in your last code block), then:
Define an interface (with method Start)
Implement that on your type(s)
Add it to the As chain where you define your Autofac registrations
Resolve the new interface
Updated code:
public interface IStartable {
void Start();
}
public abstract class MessageConsumer<T> : IStartable
{
public void Start(){/*omitted*/}
/* Other abstract properties and methods here to support template pattern*/
}
Caling code:
foreach(var consumer in container.Resolve<IEnumerable<IStartable>>())
{
consumer.Start();
}
I have the following abstract class for some plugin:
public abstract class BasePlugin
{
public void SomeMethod(){..defaultBehaviour}.
}
This base class is going to be inherited from several (may be hundreds) of implementations.
I know that for sure, later I am going to change "in a small way" (but still changing) the behaviour of SomeMethod.
I would like the existing implementation of BasePlugin to continue behaving the same and the new one to use the new Feature.
Is there some pattern that allow me to do that ?
NB : I have the lead on all the implementations but I can not check for the hundreds of implementation if the new behaviour will be fine
Many patterns woud fit, but I'd say template method pattern is reasonable option assuming you want to keep main part of default behavior intact:
public abstract class BasePlugin
{
public void SomeMethod(){
// default code before/after one or many variations
// to be provided by derived classes
...
Variation(....);
...
}
public virtual Variation(....) {} // nothing by default
}
You don't want to do that. If you are writing a plugin system you have another option. And that's to expose a number of contracts to the plugins. Each contract represents a type of feature in your application that the plugin can extend.
In your plugin base class you'll define a register method:
public abstract class PluginBase
{
public abstract void Register(IFeatureRepository repos);
}
..which the plugins use to register their extensions:
public class TextProcessingFilter : PluginBase, ITextProcessor
{
public void Register(IFeatureRepository repos)
{
repos.Get<ITextEditor>().Subscribe(this);
}
void ITextProcessor.Process(TextEditorContext ctx)
{
}
}
The upside with that new features do not break backwards compatibility which is really important if you are going to have a lot of plugins. Simply introduce new interfaces in new versions of the base plugin dll.
I would go with the Strategy pattern (due to among other things, "Prefer composition over inheritance" - especially for clients who might already be inheriting from another class):
public interface IPluginStrategy
{
void SomeMethod();
}
public class OldPluginStrategy : IPluginStrategy
{
public void SomeMethod()
{
// old plugin code
}
}
public class NewPluginStrategy : IPluginStrategy
{
public void SomeMethod()
{
// new plugin code which might be using OldPuginStrategy
// through inheritance or composition
}
}
and for the clients:
public class Client
{
public Client(IPluginStrategy pluginStrategy)
{
...
}
// use pluginStrategy's SomeMethod
}
Here it is in action:
var oldClient = new Client(new OldPluginStrategy());
...
var newClient = new Client(new NewPluginStrategy());
you can control which clients use which strategy so old clients can keep using the old plugin code while other (new?) clients will get the new plugin.
You do need access to the clients' code or at least a way to make sure they choose the plugin you want them to use.
A word of caution - if your different plugins are essentially doing the same thing, and you only want to keep different versions in order to avoid the risk of breaking existing clients, please consider the following:
This is symptomatic of bad design of your plugin - your clients should not be aware of your plugin internals.
This will most likely be extremely hard to maintain in the long run - What happens after 30 changes you've made to the plugin? Will you have 30 different versions of the plugin running in 30 different clients?
Program to an interface, not an implementation.
When using a common interface (Plugin) for all abstract skeletal implementation classes, you can add a new abstract class (BasePluginNew) for implementing new (default) behavior.
New implementations inherit from this new abstract class BasePluginNew.
Old implementations continue behaving the same.
Clients refer to the common Plugin interface and are independent of how it is implemented.
For further discussion see the GoF Design Patterns Memory (Design Principles / Interface Design) at http://w3sdesign.com.
i have the following problem.
The 1st step is to implement a program, which follows a specific protocol on startup.
Therefore, functions as onInit, onConfigRequest, etc. will be necessary.
(These are triggered e.g. by incoming message on a TCP Port)
My goal is to generate a class for example abstract one, which has abstract functions as onInit(), etc.
A programmer should just inherit from this base class and should merely override these abstract functions of the base class.
The rest as of the protocol e.g. should be simply handled in the background (using the code of the base class) and should not need to appear in the programmers code.
What is the correct design strategy for such tasks? and how do I deal with, that the static main method is not inheritable? What are the key-tags for this problem? (I have problem searching for a solution since I lack clear statements on this problem)
Goal is to create some sort of library/class, which - included in ones code - results in executables following the protocol.
EDIT (new explanation):
Okay let me try to explain more detailled:
In this case programs should be clients within a client server architecture.
We have a client server connection via TCP/IP. Each program needs to follow a specific protocol upon program start:
As soon as my program starts and gets connected to the server it will receive an Init Message (TcpClient), when this happens it should trigger the function onInit().
(Should this be implemented by an event system?) After onInit() a acknowledgement message should be sent to the server. Afterwards there are some other steps as e.g. a config message from the server which triggers an onConfig and so on. Let's concentrate on the onInit function.
The idea is, that onInit (and onConfig and so on) should be the only functions the programmer should edit while the overall protocol messaging is hidden for him.
Therefore, I thought using an abstract class with the abstract methods onInit(), onConfig() in it should be the right thing. The static Main class I would like to hide, since within it e.g. there will be some part which connects to the tcp port, which reacts on the Init Message and which will call the onInit function.
2 problems here:
1. the static main class cant be inherited, isn it?
2. I cannot call abstract functions from the main class in the abstract master class.
Let me give an Pseudo-example for my ideas:
public abstract class MasterClass
{
static void Main(string[] args){
1. open TCP connection
2. waiting for Init Message from server
3. onInit();
4. Send Acknowledgement, that Init Routine has ended successfully
5. waiting for Config message from server
6.....
}
public abstract void onInit();
public abstract void onConfig();
}
I hope you get the idea now!
The programmer should afterwards inherit from this masterclass and merely need to edit the functions onInit and so on.
Is this way possible? How?
What else do you recommend for solving this?
EDIT:
The strategy ideo provided below is a good one! Check out my comment on that.
Take a look at this, Strategy design pattern, it may help. A short code example below:
class MainClass {
static void Main(string[] args) {
// Where ProcessingStrategy is your abstract class.
// SpecificProcessingStrategy is someone else's implementation.
//
ProcessingStrategy strategy = new SpecificProcessingStrategy();
// Processor is implemented and provided by you and calls the appropriate methods on the
// ProcessingStrategy..
//
Processor processor = new Processor( strategy );
processor.Process();
}
}
If you wanted to provide the Main also, then take a look at having the name of the concrete ProcessingStrategy (SpecificProcessingStrategy in this example) passed in on the command line and load it dynamically (I'm not sure how to do this in C# but I'm sure many examples on the web).
What you are describing is the Template design pattern. Your abstract client contains the protocol details, and delegates to subclasses via protected template/hook methods to allow a conceret client to customize the behavior.
// In your provided library
public abstract class Client
{
public void Run()
{
OpenConnection();
WaitForInitMsg();
OnInit(); // notify subclass
SendInitAckMsg();
WaitForConfigMsg();
OnConfig(); // notify subclass
SendConfigAckMsg();
// etc, etc
}
protected abstract void OnInit() {}
protected abstract void OnConfig() {}
}
// customer/client uses the functionality like this
public class ConsoleClient : Client
{
protected void OnInit()
{
Console.WriteLine("Initialized");
}
protected void OnConfig()
{
Console.WriteLine("Configured");
}
}
public class MainClass
{
static void Main(string[] args)
{
ConsoleClient client = new ConsoleClient();
client.Run();
}
}
The customer never has access to any internals of your Clinet object that you don't explicitly expose.
Well, you are already made a good decision in choosinhg abstract class. Good in it is that you can define abstract methods which consumer (who inherited from it) must override, and have also "normal" methods with code in it. In this way you create a constrains for derived type to implement several set of the functions and plus, provide it with a common set of the functions that any derived type will have by default.
I am a developer who works primarily with embedded devices (programmed with C and assembly). My C# and OOP knowledge is very limited (although I can fake my way through it when necessary). I have five devices that interface with a PC via USB. The PC does some calculations and sends a result to the device. The same calculations are performed for each device, but the calculations are done differently. For each device, I have a C# Windows Forms application that does some work and sends data back and forth to the device. Currently, I'm trying to get the five different applications merged into one so we can easily make changes, add new devices easily, and have a standard user interface. My problem is that I don't exactly know the best way to do it since I don't know which device will be used until run time. I'm trying to avoid a bunch of if statements and I would like to be able to put each device in a separate file. Here is some psudo-code of what I'm talking about.
class Device //This is what EVERY device can do
{
...
DoWork1();
DoWork2();
DoWork3();
...
}
class Device1
{
...
DoWork1(); //This is how the work is done for this device
DoWork2();
DoWork3();
...
}
class Device2
{
...
DoWork1(); //This is how the work is done for this device (not the same way as Device1)
DoWork2();
DoWork3();
}
public partial class frmMain : Form
{
private (some kind of object or something) CurrentDevice;
public frmMain()
{
...
//Determine what device (could be one of five) is currently being used
CurrentDevice = (which device is currently being used)
//Could be CurrentDevice = new Device1();
}
}
private void Button1_Click()
{
CurrentDevice.DoWork1(); //But this could be Device1.DoWork1() or Device2.DoWork1(), depending on what device is currently being used (which was determined in the frmMain constructor)
}
I'm not really sure, but I'm thinking I could use an interface or maybe inherit the Device1 class for the Device class and override the methods...But I don't know how I would have one generic way of saying CurrentDevice.DoWork1() since CurrentDevice could be Device1 or Device2.
Any ideas would be greatly appreciated. I'm using Visual Studio 2008 with .NET 3.5 on Windows XP SP3 and Windows 7.
I hope I described the problem well enough. If not, or if I didn't mention something that I should, please let me know. I'm new to stackoverflow and C#.
Thank you,
Michael
In your case, you're basically defining a inheritance hierarchy that can either consist of an abstract base class and two derived types or an interface with two implementors of it. For example
public abstract class BaseDevice
{
public abstract void DoWork1();
}
public class Device1 : BaseDevice
{
public override void DoWork1()
{
// provide implementation here
}
}
// also create Device2 : BaseDevice and implement
OR you could utilize an interface definition
public interface IDevice
{
void DoWork1();
}
public class Device1 : IDevice
{
public void DoWork1()
{
// provide implementation
}
}
Which methodology you pick is up to you. You would perhaps favor an abstract base class if, for example, you wanted to define some behavior or properties with implementations that were common throughout the hierarchy. With an abstract class, you can provide implementations. An interface is an empty contract, you cannot provide any common behaviors, only a definition for what behaviors or properties may be present.
Either way you go, you would refer to instances of the more derived type via the abstract or interface base. In this manner, you don't care what the implementing type is, only what it can do (it's methods or properties).
Example:
BaseDevice device1 = new Device1();
BaseDevice device2 = new Device2();
// maybe you have a list?
List<BaseDevice> devices = new List<BaseDevice> { device1, device2 };
foreach (BaseDevice device in devices)
{
device.DoWork1(); // notice you don't care about the actual type, just the behavior
}
I was a little confused at first because in this case the pc does calculations the devices only receive the result. So as I understand it you need different implementations of something on the PC, not the devices themselves.
The real trick here is not about using an interface or inheritance - you already figured that out. The trick is getting the right implementation type, and you use a factory for that part.
But you do have to decide on inheritance vs interface as well.
Use inheritance only if that "something" is truly part of a common, but also meaningful family. Inheritance should have a very strong "is a" element.
OTOH many objects could exist that might do a calculation but that you might not want to make a family. This is where composition is useful. To get that by inheritance you would need to have them share a common base class. Here you can use composition to allow each object to use a common interface to allow the pc to perform the calculation.
I suggest this approach.
You should have a reference to a common, generic interface, IDoCalculation, or some such, that defines a method signature that will be called in the same way for any device.
Next you have to get the device specific implementation for that interface, this is where each device can have a different implementation. Create a class for each device type/implementation.
Now the trick is to get the class you need without having to know what it is. To once again keep the details hidden and make the method calls generic, you can create a parameterized Factory. This factory accepts a parameter that describes what device the pc needs a calculation for. It then interprets that parameter and based on that creates a specific class that implements IDoCalculation. This is returned and you are done.
I leave it to you to figure out how these objects need to be organized into different assemblies...
//Common interface
public interface IDoCalculation
{
//Use whatever method signatures you need
int DoCalculation();
}
public class DeviceImplementation1 : IDoCalculation
{
#region IDoCalculation Members
public int DoCalculation()
{
//Device 1 Specific code goes here
}
#endregion
}
public class DeviceImplementation2 : IDoCalculation
{
#region IDoCalculation Members
public int DoCalculation()
{
//Device 2 Specific code goes here
}
#endregion
}
// A simple factory that does not require a lot of OOP understanding.
public class DeviceCalculationFactory
{
//Return a correct implementor based on the device type passed in
public IDoCalculation GetCalculationImplementationInstance(string devicetype)
{
switch (devicetype)
{
case "Device1":
return new DeviceImplementation1();
case "Device2":
return new DeviceImplementation2();
default:
//TODO ???
return null;
}
}
}
// A simple client that calls the methods and then send the results
public class DeviceManager
{
//To do the calculation, get an implementor for the correct device type from the factory - Presumably the PC knows the device of interest, example "Device1"
public void DoTheCalculationThing(string deviceType)
{
DeviceCalculationFactory factory = new DeviceCalculationFactory();
IDoCalculation calculation = factory.GetCalculationImplementationInstance(deviceType);
int result = calculation.DoCalculation();
// now send the result to the device
}
}
You might be interested in looking at some design patterns for this.
http://www.oodesign.com/
Specifically Abstract Factory and Template Method. I think one of those might be what you're looking for.
http://www.oodesign.com/abstract-factory-pattern.html
http://www.oodesign.com/template-method-pattern.html
As I understand it, you want to be able to have a base class, then inherit the base class functions and define them in subclasses. One of those patterns would probably work for your scenario.
Anthony Pegram's answer is excellent but you may want to take it a step further. It is conceivable that although it appears that all your devices are performing the same tasks you may find that some do not, in fact, perform all the tasks and yet others perform even more.
In such cases you may be tempted to alter the interface to add another DoWork5 or DoWork6 method and simply raise NotImplemented exceptions on types that do not have the particular behaviour.
This is troublesome for many reasons. I would suggest (should you find yourself in this position) to take a look at making your roles explicit. You do this by creating interfaces that represent a particular role (or set of behaviours --- ties in with the interface segregation principle).
So you could have IMediaPlayer with Play, Pause, Rewind and another IMediaRecorder with a Record method. In this way you implement the relevant roles on your concrete classes.
HTH