I am trying to get a better understanding of some of the inner workings of WCF. I have done a fair amount of looking around, but I have not been able to find a clear explanation of what ChannelFactory.Open() does compared to IClientChannel.Open(). What is the purpose of opening the factory? If the channel is being used for communication, what part does the factory play in the process after the channel has been created and opened?
The question was asked here, among other questions, but never answered directly.
EDIT:
After de-compiling the source code, I found some of the specific reasons why Open needs to be called on ChannelFactory, which is documented below.
What I'm still having trouble understanding is why this work is being done through mechanisms provided by the ICommunicationObject, when the factory isn't actually communicating with anything (as far as I know). Why not just handle these things when the object is constructed or disposed of?
I think I'm probably far enough in the weeds that such an answer may not be publicly available. Thank you to those who weighed in on the original question.
Open needs to be called in the factory, since it's an ICommunicationObject - before you use one of those, it needs to be opened. But in most cases the factory is opened automatically for you when you call things such as CreateChannel, for example, so you seldom need to worry about explicitly opening the factory.
Regarding Close, it really depends on which binding the factory is using. In most cases you're correct, the resource is mostly associated with the channel. But it's possible that a certain binding would multiplex multiple channels in the same underlying connection, so closing the channel would simply remove the channel from the list to be multiplexed. Only when the factory is closed is that the underlying connection is actually released.
After de-compiling a bunch of the related classes in System.ServiceModel, I was able to get a little more information.
The Open call appears to make its way down the inheritance tree to the CommunicationObject, where its Open method is called. All this seems to do is provide a bunch of diagnostic information and raise a number of events.
The ChannelFactory class uses the Open events do a number of things, including creating its inner channel factory:
protected override void OnOpening()
{
base.OnOpening();
this.innerFactory = this.CreateFactory();
if (this.innerFactory == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString("InnerChannelFactoryWasNotSet")));
}
}
As has been mentioned by others here, the Close events are also used to do things like close all of the underlying channels, (by way of it's internal channel factory):
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
while (true)
{
IChannel channel;
lock (base.ThisLock)
{
if (this.channelsList.Count == 0)
{
break;
}
channel = this.channelsList[0];
}
channel.Close(timeoutHelper.RemainingTime());
}
}
Opening ChannelFactory or the innerchannel just change the state of the object, when is instantiated is starts in the Created state, the object can be configured but it is not usable to send or receive message, in the Opened state, the communicationObject is usable but it is no longer configurable
So the purpose of opening the factory is just a design choice and it is indeed done automatically when you create the first channel, it does not to much under the hood, the factory is responsible to create the channel that will actually bring messages from the transport layer and send them to you application.
Channel factories are responsible for creating channels. Channels
created by channel factories are used for sending messages. These
channels are responsible for getting the message from the layer above,
performing whatever processing is necessary, then sending the message
to the layer below. The following graphic illustrates this process
http://msdn.microsoft.com/en-us/library/ms789050.aspx
Hope this helps
Related
Reading IntroToRx website, it discourages using of Subject in favour of Observable.Create helper method.
As I can see, the OnNext method can be called only into subscribe method, because it's the only part I have access Observer object.
What if I would like to push new values after it's creation?
Am I "forced" to use a Subject?
If you are just exploring Rx, go for it - use Subjects, go nuts, see how they work, discover their pros and cons for yourself, then come back here and read the questions discussing why Subject is frowned upon.
Subjects offer a much easier way of "quickly bootstrapping" ideas and complicated Rx scenarios without needing to replicate the actual source conditions.
That said, they do inject state into what is kinda-sorta-supposed-to-be a stateless chain of operations, so be careful not to rely on them.
So, to sum up: if you are trying to generate sequences to test/learn how rx works or how you might make query X, use those subjects. If you find yourself using them intra-query, there is a CHANCE there is a better way.
Edit: realized I missed something:
Also, you ask if there is another way of raising stream events post-creation...the answer is yes; you might declare a stream via Create or Return or Generate that returns any old IObservable-based object that you define, which can also expose methods to inject events...or heck, have a lambda that spins a thread that checks a shared list that is routed to the return stream....I guess what I'm saying is that the possibilities are endless. There are something like a dozen "create a sequence of events" methods declared on Observable - try them all!
EDIT 2:
An example? Sure, let's throw something together using Observable.Create that mimics a really inefficient Subject:
var running = true;
var values = new ConcurrentQueue<int>();
var query = Observable.Create<int>(obs =>
{
var body = Task.Factory.StartNew(()=>
{
while(running)
{
int nextValue;
if(values.TryDequeue(out nextValue))
{
obs.OnNext(nextValue);
}
Thread.Yield();
}
});
return Disposable.Create(() =>
{
try
{
running = false;
body.Wait();
obs.OnCompleted();
}
catch(Exception ex)
{
obs.OnError(ex);
}
});
});
using(query.Subscribe(Console.WriteLine))
{
values.Enqueue(1);
values.Enqueue(2);
values.Enqueue(3);
values.Enqueue(4);
Console.ReadLine();
}
Note that this is just quick-and-extremely-dirty example code. :)
It depends on what you are trying to do. There are cases for Subjects, but just not as many as one thinks when they first start out with Rx.
How will the new data enter your sequence? Will it be from another event? Perhaps a message from a communications framework? Maybe polling a file?
Depending on these answers you will normally find that you already have some sort of event source, and you are just converting to Rx from another pattern (Events, Polling, Callbacks etc...)
You also don't just have to use Observable.Create. You could use Observable.Timer/Interval to set up a polling sequence, Observable.FromEventPattern to leverage an existing Event, Observable.Start for a one off async task style calculation etc...
As Rx (or even Linq) can be quite abstract, asking abstract questions can often lead to very broad answers. If you give an indication of a problem you are trying to solve, that might help provide you with an even better answer.
If you are receiving data from external device, you have no intention of signaling errors with IObserver.OnError (you assume your stream is endless and/or any problems with communications are within message itself), you poll at some rate, the only problem with Subject is that you will probably start polling this device even before anyone subscribes (but added benefit is that handling your state is pretty obvious, you created one object, it opened COM port, it communicates and publishes values)
Using Observable.Create or Observable.Timer/Interval might be better - but laziness is main reason, you will manage state anyway. And you will probably need to use Publish().RefCount() to prevent second subscription from opening port.
Hi I am using the Simple Injector DI library and have been following some really interesting material about an architectural model designed around the command pattern:
Meanwhile... on the command side of my architecture
Meanwhile... on the query side of my architecture
The container will manage the lifetime of the UnitOfWork, and I am using commands to perform specific functions to the database.
My question is if I have a command, for example an AddNewCustomerCommand, which in turn performs another call to another service (i.e. sends a text message), from a design standpoint is this acceptable or should this be done at a higher level and if so how best to do this?
Example code is below:
public class AddNewBusinessUnitHandler
: ICommandHandler<AddBusinessUnitCommand>
{
private IUnitOfWork uow;
private ICommandHandler<OtherServiceCommand> otherHandler;
AddNewBusinessUnitHandler(IUnitOfWork uow,
ICommandHandler<OtherServiceCommand> otherHandler)
{
this.uow = uow;
this.otherHandler = otherHandler;
}
public void Handle(AddBusinessUnitCommand command)
{
var businessUnit = new BusinessUnit()
{
Name = command.BusinessUnitName,
Address = command.BusinessUnitAddress
};
var otherCommand = new OtherServiceCommand()
{
welcomePostTo = command.BusinessUnitName
};
uow.BusinessUnitRepository.Add(businessUnit);
this.otherHandler.Handle(otherCommand);
}
}
It depends on your architectural view of (business) commands, but it is quite natural to have a one to one mapping between a Use Case and a command. In that case, the presentation layer should (during a single user action, such as a button click) do nothing more than create the command and execute it. Furthermore, it should do nothing more than execute that single command, never more. Everything needed to perform that use case, should be done by that command.
That said, sending text messages, writing to the database, doing complex calculations, communicating with web services, and everything else you need to operate the business' needs should be done during the context of that command (or perhaps queued to happen later). Not before, not after, since it is that command that represents the requirements, in a presentation agnostic way.
This doesn't mean that the command handler itself should do all this. It will be quite naturally to move much logic to other services where the handler depends on. So I can imagine your handler depending on a ITextMessageSender interface, for instance.
Another discussion is if command handlers should depend on other depend command handlers. When you look at use cases, it is not unlikely that big use cases consist of multiple smaller sub use cases, so in that sense it isn't strange. Again, there will be a one to one mapping between commands and use cases.
However, note that having a deep dependency graph of nested command handlers depending on each other, can complicate navigating through the code, so take a good look at this. It might be better to inject an ITextSessageSender instead of using an ICommandHandler<SendTextMessageCommand>, for instance.
Another downside of allowing handlers to nest, is that it makes doing infrastructural stuff a bit more complex. For instance, when wrapping command handlers with a decorator that add transactional behavior, you need to make sure that the nested handlers run in the same transaction as the outer most handler. I happened to help a client of me with this today. It's not incredibly hard, but takes a little time to figure out. The same holds for things like deadlock detection, since this also runs at the boundary of the transaction.
Besides, deadlock detection is an great example to show case the power of this command/handler pattern, since almost every other architectural style will make it impossible to plug-in this behavior. Take a look at the DeadlockRetryCommandHandlerDecorator class in this article) to see an example.
I'm trying to design a client / server solution. Currently it contains three projects. The client, the server, and a library that each use (because they both require a lot of the same stuff).
For example, both the client and the server (in this case) read incoming data in the exact same way. Because of this, both the client and the server have their own MessageReader object. The MessageReader will first read the first 4 bytes of incoming stream data to determine the length of the data and then read the rest. This is all performed asynchronously. When all the data is read the class raises its own MessageRead event or if there was an IOException while reading it raises its own ConnectionLost event.
So this all works fine. What's the problem? Well, the client and the server are a bit different. For example, while they may read data in the same way, they do not write data in the same way. The server has a Dictionary of clients and has a Broadcast method to write to all clients. The client only has a single TcpClient and can only Write to the server. Currently all this behavior is within each respective WinForm and I want to move it to a Client and Server class but I'm having some problems.
For example, remember earlier when I was talking about the MessageReader and how it can raise both a MessageRead event and a ConnectionLost event? Well, now there's a bit of a problem because in designing the Client class I have to capture these two events and re-raise them because the client form should not have access to the MessageReader class. It's a bit ugly and looks like this:
class Client
{
private MessageReader messageReader = new MessageReader();
public delegate void MessageReceivedHandler(string message);
public delegate void ConnectionLostHandler(string message);
public event ConnectionLostHandler ConnectionLost;
public event MessageReceivedHandler MessageReceived;
public Client()
{
messageReader.ConnectionLost += messageReader_ConnectionLost;
messageReader.MessageReceived += messageReader_MessageReceived;
}
private void messageReader_MessageReceived(string message)
{
if (ConnectionLost != null)
{
ConnectionLost(message);
}
}
private void messageReader_ConnectionLost(string message)
{
if (MessageReceived != null)
{
MessageReceived(message);
}
}
}
This code is ugly because its basically duplicate code. When the MessageReader raises the MessageReceieved handler the Client has to capture it and basically re-raise its own version (duplicate code) because the client form should not have access to the message reader.
Not really of a good way to solve it. I suppose both Client and Server could derive from an abstract DataReader but I don't think a client is a data reader, nor is the server. I feel like composition makes more logical sense but I can't figure out a way to do this without a lot of code duplication and confusing event handlers.
Ouch, this question is getting a bit long.. I hope I don't scare anyone away with the length. It's probably a simple question but I'm not really sure what to do.
Thanks for reading.
Composition.
I didn't even read your code or text. I find that the average developer (almost) never needs inheritance but they like to use it quite a bit.
Inheritance is fragile. Inheritance is hard to get correct. It's harder to keep it in check with SOLID.
Composition is easy to understand, easy to change, and easy to DI, Mock, and test.
SOLID
I ended up using inheritance for this even though the relationship wasn't strong. The code duplication it got rid of was worth it. Was able to place all the events both classes shared in to the base class.
I'm currently assigned to a task to develop a software module to communicate with a stepper motor controller. The project is written in C#, I have a C++ dll to communicate with the controller. The communication runs via the Serial port. I'm planning to write the whole piece in C# by importing the necessary methods by DllImport. The key method looks something like :
ComSendReceive(pHandle, bufferIn,sizeBufferIn,bufferOut,ref bufferOut)
There are several types of messages :
You send message and expect confirmation (not the same for every message, sometimes it's OK, sometimes it's COMPLETE etc..
You send message and receive message - you can receive an error or data (for instance GET_CONTROLLER_ID)
Several other types
Of course I need to control the communication for time-outs.
My question is: Is there any "design pattern" to use for that kind of problem? I'm sure this is quite a common problem many developers have solved already.
To contribute a little - I dealt with similar problem in my last job and I solved it this way :
I had a class to communicate with the Com port and a class AT_message with bunch of overloaded constructors :
class AT_Message
{
public bool DoResponseCheck;
public string ExpectedResponse;
public AT_COMMAND command;
public string data;
public bool AddCarriageReturn;
...
//Plenty of ctors
}
class UnfriendlyInterface
{
Response SendMessage(AT_Message msg)
{
//Communicates directly with C++ dll, send message, check timeouts etc....
}
}
And I had a class the main application was communicating with, it had human friendly methods like
class FriendlyInterface
{
bool AutodetectPortAndOpenComm();
Result AnalyzeSignal(byte[] buffer)
{
Response response = UnfriendlyInterface.SendMessage(new Message(AT_Command.PrepareForSignal, (doResponseCheck)true, ExpectedResponse.Ok,Timeout.short);
Response response = UnfriendlyInterface.SendMessage(new Message(buffer,(doResponseCheck)false,Timeout.long);
//.... Other steps
}
//... other methods
}
Since last time I was really in a big hurry, I implemented first solution that came to my mind. But is there a way to do it better? Now the device I'm communicate with is more complex than the previous one so if there's a way how to do it better, I'd like to do it that way.
This seems like a textbook facade pattern. The answer to all of this is to encapsulate your variation. For example, try to create a generic interface for commands that give an acknowledgement, and write client code to use that interface. Then concrete types can decide how to interpret various acknowledgements into a uniform signal (Ok = Complete = Good, or whatever)
Here's a good article on the facade pattern. Also see the wikipedia article.
Whenever i feel hungry i will publish i am hungry.This will be notified to the service providers say (MealsService,FruitService,JuiceService ).(These service providers know what to serve).
But the serving priority is the concern. Priority here means my first choice is MealsService when there are enough meal is available my need is end with MealsService.To verify the enough meal is availabe the MealsService raises the event "updateMeTheStockStatus" to the "MealsServiceStockUpdateListener" .
The "MealsServiceStockUpdateListener" will only reply back to "MealsService" . No other Service providers ( FruitService,JuiceService ) will be notified by the "MealsServiceStockUpdateListener" .If there is no sufficient stock then only the MealsService passes notification to the JuiceService (as it is the second priority).As usual it checks the stock.If stock is not sufficient it passes message to FruitService,so the flow continues like this.
How can i technically implement this?
Any implemention like priority based delagates and delegate chaining make sense ?
(Somebody! Please reframe it for good readability ).
Update : In this model there is no direct communication between "StackUpdateListener" and "me".Only The "Service Providers" will communicate me.
Like other answerers, I'm not entirely convinced that an event is the way forward, but let's go along with it for the moment.
It seems to me that the business with the MealsServiceStockUpdateListener is a red herring really - you're just trying to execute some event handlers but not others. This sort of thing crops up elsewhere when you have a "BeforeXXX" event which allows cancellation, or perhaps some sort of exception handling event.
Basically you need to get at each of your handlers separately. There are two different ways of doing that - either you can use a normal multicast delegate and call GetInvocationList() or you can change your event declaration to explicitly keep a list of handlers:
private List<EventHandler> handlers = new List<EventHandler>();
public event EventHandler MealRequired
{
add { handlers.Add(value); }
remove
{
int index = handlers.LastIndexOf(value);
if (index != -1)
{
handlers.RemoveAt(index);
}
}
}
These two approaches are not quite equivalent - if you subscribe with a delegate instance which is already a compound delegate, GetInvocationList will flatten it but the List approach won't. I'd probably go with GetInvocationList myself.
Now, the second issue is how to detect when the meal has provided. Again, there are two approaches. The first is to use the normal event handler pattern, making the EventArgs subclass in question mutable. This is the approach that HandledEventArgs takes. The second is to break the normal event pattern, and use a delegate that returns a value which can be used to indicate success or failure (and possibly other information). This is the approach that ResolveEventHandler takes. Either way, you execute the delegates in turn until one of them satistfies your requirements. Here's a short example (not using events per se, but using a compound delegate):
using System;
public class Test
{
static void Main(string[] args)
{
Func<bool> x = FirstProvider;
x += SecondProvider;
x += ThirdProvider;
Execute(x);
}
static void Execute(Func<bool> providers)
{
foreach (Func<bool> provider in providers.GetInvocationList())
{
if (provider())
{
Console.WriteLine("Done!");
return;
}
}
Console.WriteLine("No provider succeeded");
}
static bool FirstProvider()
{
Console.WriteLine("First provider returning false");
return false;
}
static bool SecondProvider()
{
Console.WriteLine("Second provider returning true");
return true;
}
static bool ThirdProvider()
{
Console.WriteLine("Third provider returning false");
return false;
}
}
Rather than publish a message "I'm hungry" to the providers, publish "I need to know current stock available". Then listen until you have enough information to make a request to the correct food service for what you need. This way the logic of what-makes-me-full is not spread amongst the food services... It seems cleaner to me.
Message passing isn't baked into .NET directly, you need to implement your own message forwarding by hand. Fortunately, the "chain of responsiblity design pattern" is designed specifically for the problem you're trying to solve, namely forwarding a message down a chain until someone can handle it.
Useful resources:
Chain of Responsibility on Wikipedia
C# implementation on DoFactory.com
I'm not sure if you really need a priority event. Anyways, let's suppose we want to code that just for fun.
The .NET Framework has no support for such a peculiar construct. Let me show one possible approach to implement it.
The first step would be to create custom store for event delegates (like described here);
Internally, the custom event store could work like a priority queue;
The specific EventArgs used would be HandledEventArgs (or a subclass of it). This would allow the event provider to stop calling handlers after one of them sets the event as Handled;
The next step is the hardest. How to say to tell the event provider what is the priority of the event handler that is being added?
Let me clarify the problem. Usually, the adding of a handler is like this:
eater.GotHungry += mealsService.Someone_GotHungry;
eater.GotHungry += juiceService.Someone_GotHungry;
eater.GotHungry += fruitService.Someone_GotHungry;
The += operator will only receive an delegate. It's not possible to pass a second priority parameter. There might be several possible solutions for this problem. One would be to define the priority in a custom attribute set at the event handler method. A scond approach is discussed in the question.
Compared to the chain of responsibility implementation at dofactory.com, this approach has some advantages. First, the handlers (your food services) do not need to know each other. Also, handlers can be added and remove at any time dynamically. Of course, you could implement a variation of a chain of responsibility that has this advantages too.
I don't think delegates are the proper solution to your problem. Delegates are a low-level service provided by C# for relatively tightly coupled events between components. If I understand your question properly (It is worded a little oddly, so I am not sure I clearly understand your problem), then I think what you need is a mediated consumer/provider.
Rather than having your consumers directly consume the meal, juice, and fruit providers, have them request a food item from a central mediator. The mediator would then be responsible for determining what is available and what should be provided to the consumer. The mediator would be a subscriber to events published by all three services. Whenever stock is added/updated in the Meal, Juice, or Fruit services, they would publish their current stock to all subscribers. The mediator, being a subscriber, would track current stock reductions on its own, and be able to determine for itself whether to send a meal, juice, or fruit to a food consumer when a get food request is made.
For example:
|---------- (GetFoodResponse) ----------------
V |
FoodConsumer ---- (GetFoodRequest) ------> FoodProvider <-----> [ Local Stock Data ]
^
|
|
MealService ---- (PublishStockMessage) ----------|
^
JuiceService --- (PublishStockMessage) ----------|
^
FruitService --- (PublishStockMessage) ----------|
The benefits of such a solution are that you reduce coupling, properly segregate responsibility, and solve your problem. For one, your consumers only need to consume a single service...the FoodProvider. The FoodProvider subscribes to publications from the other three services, and is responsible for determining what food to provide to a consumer. The three food services are not responsible for anything related to the hunger of your food consumers, they are only responsible for providing food and tracking the stock of the food they provide. You also gain the ability to distribute the various components. Your consumers, the food provider, and each of the three food services can all be hosted on different physical machines if required.
However, to achieve the above benefits, your solution becomes more complex. You have more parts, and they need to be connected to each other properly. You have to publish and subscribe to messages, which requires some kind of supporting infrastructure (WCF, MSMQ, some third party ESB, custom solution, etc.) You also have duplication of data, since the food provider tracks stock on its own in addition to each of the food services, which could lead to discontinuity in available stock. This can be mitigated if you manage stock updated properly, but that would also increase complexity.
If you can handle the additional complexity, ultimately, a solution like this would more flexible and adaptable than a more tightly connected solution that uses components and C# events in a local-deployment-only scenario (as in your original example.)
I am having a bit of trouble understanding your analogy here, which sounds like you're obscuring the actual intent of the software, but I think I have done something like what you are describing.
In my case the software was telemarketing software and each of the telemarketers had a calling queue. When that queue raises the event signifying that it is nearing empty, the program will grab a list of available people to call, and then pass them through a chain of responsibility which pushes the available call into the telemarketer's queue like so:
Each element in the chain acts as a priority filter: the first link in the chain will grab all of the people who have never been called before, and if it finishes (ie. went through all of the people who have never been called) without filling up the queue, it will pass the remaining list of people to call to the next link in the chain - which will apply another filter/search. This continues until the last link in the chain which just fires off an e-mail to an administrator indicating that there are no available people to be called and a human needs to intervene quickly before the telemarketers have no work to do.