2008-11-01 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel / ServiceHostBase.cs
1 //
2 // ServiceHostBase.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2005-2006 Novell, Inc.  http://www.novell.com
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 using System;
29 using System.Collections.Generic;
30 using System.Collections.ObjectModel;
31 using System.ServiceModel.Channels;
32 using System.ServiceModel.Configuration;
33 using System.ServiceModel.Description;
34 using System.ServiceModel.Dispatcher;
35 using System.ServiceModel.Security;
36 using System.Reflection;
37
38 namespace System.ServiceModel
39 {
40         public abstract class ServiceHostBase
41                 : CommunicationObject, IExtensibleObject<ServiceHostBase>, IDisposable
42         {
43                 ServiceCredentials credentials;
44                 ServiceDescription description;
45                 UriSchemeKeyedCollection base_addresses;
46                 TimeSpan open_timeout, close_timeout, instance_idle_timeout;
47                 ServiceThrottle throttle;
48                 List<InstanceContext> contexts;
49                 ReadOnlyCollection<InstanceContext> exposed_contexts;
50                 ChannelDispatcherCollection channel_dispatchers;
51                 IDictionary<string,ContractDescription> contracts;
52                 int flow_limit = int.MaxValue;
53                 IExtensionCollection<ServiceHostBase> extensions;
54
55                 protected ServiceHostBase ()
56                 {
57                         open_timeout = DefaultOpenTimeout;
58                         close_timeout = DefaultCloseTimeout;
59
60                         credentials = new ServiceCredentials ();
61                         throttle = new ServiceThrottle ();
62                         contexts = new List<InstanceContext> ();
63                         exposed_contexts = new ReadOnlyCollection<InstanceContext> (contexts);
64                         channel_dispatchers = new ChannelDispatcherCollection (this);
65                 }
66
67                 public event EventHandler<UnknownMessageReceivedEventArgs>
68                         UnknownMessageReceived;
69
70                 public ReadOnlyCollection<Uri> BaseAddresses {
71                         get { return new ReadOnlyCollection<Uri> (base_addresses.InternalItems); }
72                 }
73
74                 internal Uri CreateUri (string sheme, Uri relatieUri) {
75                         Uri baseUri = base_addresses.Contains (sheme) ? base_addresses [sheme] : null;
76
77                         if (relatieUri == null)
78                                 return baseUri;
79                         if (relatieUri.IsAbsoluteUri)
80                                 return relatieUri;
81                         if (baseUri == null)
82                                 return null;
83                         return new Uri (baseUri, relatieUri);
84                 }
85
86                 [MonoTODO]
87                 public ChannelDispatcherCollection ChannelDispatchers {
88                         get { return channel_dispatchers; }
89                 }
90
91                 public ServiceAuthorizationBehavior Authorization {
92                         get;
93                         private set;
94                 }
95
96                 [MonoTODO]
97                 public ServiceCredentials Credentials {
98                         get { return credentials; }
99                 }
100
101                 public ServiceDescription Description {
102                         get { return description; }
103                 }
104
105                 protected IDictionary<string,ContractDescription> ImplementedContracts {
106                         get { return contracts; }
107                 }
108
109                 [MonoTODO]
110                 public IExtensionCollection<ServiceHostBase> Extensions {
111                         get {
112                                 if (extensions == null)
113                                         extensions = new ExtensionCollection<ServiceHostBase> (this);
114                                 return extensions;
115                         }
116                 }
117
118                 protected internal override TimeSpan DefaultCloseTimeout {
119                         get { return DefaultCommunicationTimeouts.Instance.CloseTimeout; }
120                 }
121
122                 protected internal override TimeSpan DefaultOpenTimeout {
123                         get { return DefaultCommunicationTimeouts.Instance.OpenTimeout; }
124                 }
125
126                 public TimeSpan CloseTimeout {
127                         get { return close_timeout; }
128                         set { close_timeout = value; }
129                 }
130
131                 public TimeSpan OpenTimeout {
132                         get { return open_timeout; }
133                         set { open_timeout = value; }
134                 }
135
136                 public int ManualFlowControlLimit {
137                         get { return flow_limit; }
138                         set { flow_limit = value; }
139                 }
140
141                 public ServiceEndpoint AddServiceEndpoint (
142                         string implementedContract, Binding binding, string address)
143                 {
144                         return AddServiceEndpoint (implementedContract,
145                                 binding,
146                                 new Uri (address, UriKind.RelativeOrAbsolute));
147                 }
148
149                 [MonoTODO]
150                 public ServiceEndpoint AddServiceEndpoint (
151                         string implementedContract, Binding binding,
152                         string address, Uri listenUri)
153                 {
154                         Uri uri = new Uri (address, UriKind.RelativeOrAbsolute);
155                         return AddServiceEndpoint (
156                                 implementedContract, binding, uri, uri);
157                 }
158
159                 [MonoTODO]
160                 public ServiceEndpoint AddServiceEndpoint (
161                         string implementedContract, Binding binding,
162                         Uri address)
163                 {
164                         return AddServiceEndpoint (implementedContract, binding, address, address);
165                 }
166
167                 [MonoTODO]
168                 public ServiceEndpoint AddServiceEndpoint (
169                         string implementedContract, Binding binding,
170                         Uri address, Uri listenUri)
171                 {
172                         EndpointAddress ea = BuildEndpointAddress (address, binding);
173                         ContractDescription cd = GetContract (implementedContract);
174                         if (cd == null)
175                                 throw new InvalidOperationException (String.Format ("Contract '{0}' was not found in the implemented contracts in this service host.", implementedContract));
176                         return AddServiceEndpointCore (cd, binding, ea, listenUri);
177                 }
178
179                 Type PopulateType (string typeName)
180                 {
181                         Type type = Type.GetType (typeName);
182                         if (type != null)
183                                 return type;
184                         foreach (ContractDescription cd in ImplementedContracts.Values) {
185                                 type = cd.ContractType.Assembly.GetType (typeName);
186                                 if (type != null)
187                                         return type;
188                         }
189                         return null;
190                 }
191
192                 ContractDescription GetContract (string typeName)
193                 {
194                         //FIXME: hack hack hack
195                         ImplementedContracts ["IHttpGetHelpPageAndMetadataContract"] =
196                                 ContractDescription.GetContract (typeof (IHttpGetHelpPageAndMetadataContract));
197
198                         // FIXME: As long as I tried, *only* IMetadataExchange
199                         // is the exception case that does not require full
200                         // type name. Hence I treat it as a special case.
201                         if (typeName == ServiceMetadataBehavior.MexContractName) {
202                                 if (!Description.Behaviors.Contains (typeof (ServiceMetadataBehavior)) && Array.IndexOf (Description.ServiceType.GetInterfaces (), typeof (IMetadataExchange)) < 0)
203                                         throw new InvalidOperationException (
204                                                 "Add ServiceMetadataBehavior to the ServiceHost to add a endpoint for IMetadataExchange contract.");
205                                         
206                                 ImplementedContracts [ServiceMetadataBehavior.MexContractName] =
207                                         ContractDescription.GetContract (typeof (IMetadataExchange));
208
209                                 foreach (ContractDescription cd in ImplementedContracts.Values)
210                                         if (cd.ContractType == typeof (IMetadataExchange))
211                                                 return cd;
212                                 return null;
213                         }
214
215                         Type type = PopulateType (typeName);
216                         if (type == null)
217                                 return null;
218
219                         foreach (ContractDescription cd in ImplementedContracts.Values) {
220                                 // FIXME: This check is a negative side effect 
221                                 // of the above hack.
222                                 if (cd.ContractType == typeof (IMetadataExchange))
223                                         continue;
224
225                                 if (cd.ContractType == type ||
226                                     cd.ContractType.IsSubclassOf (type) ||
227                                     type.IsInterface && cd.ContractType.GetInterface (type.FullName) == type)
228                                         return cd;
229                         }
230                         return null;
231                 }
232
233                 internal EndpointAddress BuildEndpointAddress (Uri address, Binding binding)
234                 {
235                         if (!address.IsAbsoluteUri) {
236                                 // Find a Base address with matching scheme,
237                                 // and build new absolute address
238                                 if (!base_addresses.Contains (binding.Scheme))
239                                         throw new InvalidOperationException (String.Format ("Could not find base address that matches Scheme {0} for endpoint {1}", binding.Scheme, binding.Name));
240
241                                 Uri baseaddr = base_addresses [binding.Scheme];
242
243                                 if (!baseaddr.AbsoluteUri.EndsWith ("/"))
244                                         baseaddr = new Uri (baseaddr.AbsoluteUri + "/");
245                                 address = new Uri (baseaddr, address);
246                         }
247                         return new EndpointAddress (address);
248                 }
249
250                 internal ServiceEndpoint AddServiceEndpointCore (
251                         ContractDescription cd, Binding binding, EndpointAddress address, Uri listenUri)
252                 {
253                         foreach (ServiceEndpoint e in Description.Endpoints)
254                                 if (e.Contract == cd)
255                                         return e;
256                         ServiceEndpoint se = new ServiceEndpoint (cd, binding, address);
257                         se.ListenUri = listenUri.IsAbsoluteUri ? listenUri : new Uri (address.Uri, listenUri);
258                         Description.Endpoints.Add (se);
259                         return se;
260                 }
261
262                 [MonoTODO]
263                 protected virtual void ApplyConfiguration ()
264                 {
265                         if (Description == null)
266                                 throw new InvalidOperationException ("ApplyConfiguration requires that the Description property be initialized. Either provide a valid ServiceDescription in the CreateDescription method or override the ApplyConfiguration method to provide an alternative implementation");
267
268                         ServiceElement service = GetServiceElement ();
269
270                         //TODO: Should we call here LoadServiceElement ?
271                         if (service != null) {
272                                 
273                                 //base addresses
274                                 HostElement host = service.Host;
275                                 foreach (BaseAddressElement baseAddress in host.BaseAddresses) {
276                                         this.base_addresses.Add (new Uri (baseAddress.BaseAddress));
277                                 }
278
279                                 // services
280                                 foreach (ServiceEndpointElement endpoint in service.Endpoints) {
281                                         // FIXME: consider BindingName as well
282                                         ServiceEndpoint se = AddServiceEndpoint (
283                                                 endpoint.Contract,
284                                                 ConfigUtil.CreateBinding (endpoint.Binding, endpoint.BindingConfiguration),
285                                                 endpoint.Address.ToString ());
286                                 }
287                                 // behaviors
288                                 // TODO: use EvaluationContext of ServiceElement.
289                                 ServiceBehaviorElement behavior = ConfigUtil.BehaviorsSection.ServiceBehaviors.Find (service.BehaviorConfiguration);
290                                 if (behavior != null) {
291                                         for (int i = 0; i < behavior.Count; i++) {
292                                                 BehaviorExtensionElement bxel = behavior [i];
293                                                 IServiceBehavior b = (IServiceBehavior) behavior [i].CreateBehavior ();
294                                                 if (b != null)
295                                                         Description.Behaviors.Add (b);
296                                         }
297                                 }
298                         }
299                         // TODO: consider commonBehaviors here
300
301                         // ensure ServiceAuthorizationBehavior
302                         Authorization = Description.Behaviors.Find<ServiceAuthorizationBehavior> ();
303                         if (Authorization == null) {
304                                 Authorization = new ServiceAuthorizationBehavior ();
305                                 Description.Behaviors.Add (Authorization);
306                         }
307
308                         // ensure ServiceDebugBehavior
309                         ServiceDebugBehavior debugBehavior = Description.Behaviors.Find<ServiceDebugBehavior> ();
310                         if (debugBehavior == null) {
311                                 debugBehavior = new ServiceDebugBehavior ();
312                                 Description.Behaviors.Add (debugBehavior);
313                         }
314                 }
315
316                 private ServiceElement GetServiceElement() {
317                         Type serviceType = Description.ServiceType;
318                         if (serviceType == null)
319                                 return null;
320
321                         return ConfigUtil.ServicesSection.Services [serviceType.FullName];                      
322                 }
323
324                 internal ContractDescription GetContract (string name, string ns)
325                 {
326                         foreach (ContractDescription d in ImplementedContracts.Values)
327                                 if (d.Name == name && d.Namespace == ns)
328                                         return d;
329                         return null;
330                 }
331
332                 protected abstract ServiceDescription CreateDescription (
333                         out IDictionary<string,ContractDescription> implementedContracts);
334
335                 [MonoTODO]
336                 protected void InitializeDescription (UriSchemeKeyedCollection baseAddresses)
337                 {
338                         this.base_addresses = baseAddresses;
339                         IDictionary<string,ContractDescription> retContracts;
340                         description = CreateDescription (out retContracts);
341                         contracts = retContracts;
342
343                         ApplyConfiguration ();
344                 }
345
346                 [MonoTODO]
347                 protected virtual void InitializeRuntime ()
348                 {
349                         //First validate the description, which should call all behaviors
350                         //'Validate' method.
351                         ValidateDescription ();
352                         
353                         //Build all ChannelDispatchers, one dispatcher per user configured EndPoint.
354                         //We must keep thet ServiceEndpoints as a seperate collection, since the user
355                         //can change the collection in the description during the behaviors events.
356                         Dictionary<ServiceEndpoint, ChannelDispatcher> endPointToDispatcher = new Dictionary<ServiceEndpoint,ChannelDispatcher>();
357                         ServiceEndpoint[] endPoints = new ServiceEndpoint[Description.Endpoints.Count];
358                         Description.Endpoints.CopyTo (endPoints, 0);
359                         foreach (ServiceEndpoint se in endPoints) {
360                                 //Let all behaviors add their binding parameters
361                                 BindingParameterCollection commonParams =
362                                         new BindingParameterCollection ();
363                                 AddBindingParameters (commonParams, se);
364                                 ChannelDispatcher channel = BuildChannelDispatcher (se, commonParams);
365                                 ChannelDispatchers.Add (channel);                               
366                                 endPointToDispatcher[se] = channel;                             
367                         }
368
369                         //After the ChannelDispatchers are created, and attached to the service host
370                         //Apply dispatching behaviors.
371                         foreach (IServiceBehavior b in Description.Behaviors)
372                                 b.ApplyDispatchBehavior (Description, this);
373
374                         foreach(KeyValuePair<ServiceEndpoint, ChannelDispatcher> val in endPointToDispatcher)
375                                 ApplyDispatchBehavior(val.Value, val.Key);                      
376                 }
377
378                 private void ValidateDescription () {
379                         foreach (IServiceBehavior b in Description.Behaviors)
380                                 b.Validate (Description, this);
381                         foreach (ServiceEndpoint endPoint in Description.Endpoints)
382                                 endPoint.Validate ();
383                 }               
384
385                 private void ApplyDispatchBehavior (ChannelDispatcher dispatcher, ServiceEndpoint endPoint) {                   
386                         foreach (IContractBehavior b in endPoint.Contract.Behaviors)
387                                 b.ApplyDispatchBehavior (endPoint.Contract, endPoint, dispatcher.Endpoints[0].DispatchRuntime);
388                         foreach (IEndpointBehavior b in endPoint.Behaviors)
389                                 b.ApplyDispatchBehavior (endPoint, dispatcher.Endpoints [0]);
390                         foreach (OperationDescription operation in endPoint.Contract.Operations) {
391                                 foreach (IOperationBehavior b in operation.Behaviors)
392                                         b.ApplyDispatchBehavior (operation, dispatcher.Endpoints [0].DispatchRuntime.Operations [operation.Name]);
393                         }
394
395                 }
396
397                 internal ChannelDispatcher BuildChannelDispatcher (ServiceEndpoint se, BindingParameterCollection commonParams) {
398
399                         //User the binding parameters to build the channel listener and Dispatcher
400                         IChannelListener lf = BuildListener (se, commonParams);
401                         ChannelDispatcher cd = new ChannelDispatcher (
402                                 lf, se.Binding.Name);
403                         cd.MessageVersion = se.Binding.MessageVersion;
404                         if (cd.MessageVersion == null)
405                                 cd.MessageVersion = MessageVersion.Default;
406
407                         //Attach one EndpointDispacher to the ChannelDispatcher
408                         EndpointDispatcher endpoint_dispatcher =
409                                 new EndpointDispatcher (se.Address, se.Contract.Name, se.Contract.Namespace);
410                         endpoint_dispatcher.ContractFilter = GetContractFilter (se.Contract);
411                         endpoint_dispatcher.ChannelDispatcher = cd;
412                         cd.Endpoints.Add (endpoint_dispatcher);
413                         
414                         //Build the dispatch operations
415                         DispatchRuntime db = endpoint_dispatcher.DispatchRuntime;
416                         foreach (OperationDescription od in se.Contract.Operations)
417                                 if (!db.Operations.Contains (od.Name))
418                                         PopulateDispatchOperation (db, od);
419
420                         return cd;
421                 }
422
423                 private MessageFilter GetContractFilter (ContractDescription contractDescription)
424                 {
425                         List<string> actions = new List<string> ();
426                         foreach (OperationDescription od in contractDescription.Operations)
427                                 foreach (MessageDescription md in od.Messages)
428                                         if (md.Direction == MessageDirection.Input)
429                                                 if (md.Action == "*")
430                                                         return new MatchAllMessageFilter ();
431                                                 else
432                                                         actions.Add (md.Action);
433
434                         return new ActionMessageFilter (actions.ToArray ());
435                 }
436
437                 private void AddBindingParameters (BindingParameterCollection commonParams, ServiceEndpoint endPoint) {
438
439                         commonParams.Add (ChannelProtectionRequirements.CreateFromContract (endPoint.Contract));
440                         foreach (IServiceBehavior b in Description.Behaviors)
441                                 b.AddBindingParameters (Description, this, Description.Endpoints, commonParams);
442
443                         foreach (IContractBehavior b in endPoint.Contract.Behaviors)
444                                 b.AddBindingParameters (endPoint.Contract, endPoint, commonParams);
445                         foreach (IEndpointBehavior b in endPoint.Behaviors)
446                                 b.AddBindingParameters (endPoint, commonParams);
447                         foreach (OperationDescription operation in endPoint.Contract.Operations) {
448                                 foreach (IOperationBehavior b in operation.Behaviors)
449                                         b.AddBindingParameters (operation, commonParams);
450                         }
451                 }
452
453                 void PopulateDispatchOperation (DispatchRuntime db, OperationDescription od) {
454                         string reqA = null, resA = null;
455                         foreach (MessageDescription m in od.Messages) {
456                                 if (m.Direction == MessageDirection.Input)
457                                         reqA = m.Action;
458                                 else
459                                         resA = m.Action;
460                         }
461                         DispatchOperation o =
462                                 od.IsOneWay ?
463                                 new DispatchOperation (db, od.Name, reqA) :
464                                 new DispatchOperation (db, od.Name, reqA, resA);
465                         bool has_void_reply = false;
466                         foreach (MessageDescription md in od.Messages) {
467                                 if (md.Direction == MessageDirection.Input &&
468                                         md.Body.Parts.Count == 1 &&
469                                         md.Body.Parts [0].Type == typeof (Message))
470                                         o.DeserializeRequest = false;
471                                 if (md.Direction == MessageDirection.Output &&
472                                         md.Body.ReturnValue != null) {
473                                         if (md.Body.ReturnValue.Type == typeof (Message))
474                                                 o.SerializeReply = false;
475                                         else if (md.Body.ReturnValue.Type == typeof (void))
476                                                 has_void_reply = true;
477                                 }
478                         }
479
480                         // Setup Invoker
481                         // FIXME: support async method
482                         if (od.SyncMethod != null)
483                                 o.Invoker = new SyncMethodInvoker (od.SyncMethod);
484                         else
485                                 o.Invoker = new AsyncMethodInvoker (od.BeginMethod, od.EndMethod);
486
487                         // Setup Formater
488                         o.Formatter = BaseMessagesFormatter.Create (od);
489
490                         if (o.Action == "*" && o.ReplyAction == "*") {
491                                 //Signature : Message  (Message)
492                                 //          : void  (Message)
493                                 //FIXME: void (IChannel)
494                                 if (!o.DeserializeRequest && (!o.SerializeReply || has_void_reply))
495                                         db.UnhandledDispatchOperation = o;
496                         }
497
498                         db.Operations.Add (o);
499                 }
500
501                 [MonoTODO]
502                 protected void LoadConfigurationSection (ServiceElement element)
503                 {
504                         ServicesSection services = ConfigUtil.ServicesSection;
505                 }
506
507                 void DoOpen (TimeSpan timeout)
508                 {
509                         for (int i = 0; i < ChannelDispatchers.Count; i++)
510                                 ChannelDispatchers [i].Open (timeout);
511                 }
512
513                 IChannelListener BuildListener (ServiceEndpoint se,
514                         BindingParameterCollection pl)
515                 {
516                         Binding b = se.Binding;
517                         if (b.CanBuildChannelListener<IReplySessionChannel> (pl))
518                                 return b.BuildChannelListener<IReplySessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
519                         if (b.CanBuildChannelListener<IReplyChannel> (pl))
520                                 return b.BuildChannelListener<IReplyChannel> (se.ListenUri, "", se.ListenUriMode, pl);
521                         if (b.CanBuildChannelListener<IInputSessionChannel> (pl))
522                                 return b.BuildChannelListener<IInputSessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
523                         if (b.CanBuildChannelListener<IInputChannel> (pl))
524                                 return b.BuildChannelListener<IInputChannel> (se.ListenUri, "", se.ListenUriMode, pl);
525                         throw new InvalidOperationException ("None of the listener channel types is supported");
526                 }
527
528                 [MonoTODO]
529                 protected override sealed void OnAbort ()
530                 {
531                 }
532
533                 [MonoTODO]
534                 protected override sealed IAsyncResult OnBeginClose (
535                         TimeSpan timeout, AsyncCallback callback, object state)
536                 {
537                         throw new NotImplementedException ();
538                 }
539
540                 [MonoTODO]
541                 protected override sealed IAsyncResult OnBeginOpen (
542                         TimeSpan timeout, AsyncCallback callback, object state)
543                 {
544                         throw new NotImplementedException ();
545                 }
546
547                 [MonoTODO]
548                 protected override void OnClose (TimeSpan timeout)
549                 {
550                         ReleasePerformanceCounters ();
551                         List<ChannelDispatcherBase> l = new List<ChannelDispatcherBase> (ChannelDispatchers);
552                         foreach (ChannelDispatcherBase e in l)
553                                 e.Close ();
554                 }
555
556                 protected override sealed void OnOpen (TimeSpan timeout)
557                 {
558                         InitializeRuntime ();
559                         DoOpen (timeout);
560                 }
561
562                 [MonoTODO]
563                 protected override void OnEndClose (IAsyncResult result)
564                 {
565                         throw new NotImplementedException ();
566                 }
567
568                 [MonoTODO]
569                 protected override sealed void OnEndOpen (IAsyncResult result)
570                 {
571                         throw new NotImplementedException ();
572                 }
573
574                 protected override void OnOpened ()
575                 {
576                 }
577
578                 [MonoTODO]
579                 protected void ReleasePerformanceCounters ()
580                 {
581                 }
582
583                 void IDisposable.Dispose ()
584                 {
585                         Close ();
586                 }
587
588                 class SyncMethodInvoker : IOperationInvoker
589                 {
590                         readonly MethodInfo _methodInfo;
591                         public SyncMethodInvoker (MethodInfo methodInfo) {
592                                 _methodInfo = methodInfo;
593                         }
594                         
595                         #region IOperationInvoker Members
596
597                         public bool IsSynchronous {
598                                 get { return true; }
599                         }
600
601                         public object [] AllocateParameters () {
602                                 return new object [_methodInfo.GetParameters ().Length];
603                         }
604
605                         public object Invoke (object instance, object [] parameters)
606             {
607                                 return _methodInfo.Invoke (instance, parameters);
608                         }
609
610                         public IAsyncResult InvokeBegin (object instance, object [] inputs, AsyncCallback callback, object state) {
611                                 throw new NotSupportedException ();
612                         }
613
614                         public object InvokeEnd (object instance, out object [] outputs, IAsyncResult result) {
615                                 throw new NotSupportedException ();
616                         }
617
618                         #endregion
619                 }
620
621                 class AsyncMethodInvoker : IOperationInvoker
622                 {
623                         readonly MethodInfo _beginMethodInfo, _endMethodInfo;
624                         public AsyncMethodInvoker (MethodInfo beginMethodInfo, MethodInfo endMethodInfo) {
625                                 _beginMethodInfo = beginMethodInfo;
626                                 _endMethodInfo = endMethodInfo;
627                         }
628
629                         #region IOperationInvoker Members
630
631                         public bool IsSynchronous {
632                                 get { return false; }
633                         }
634
635                         public object [] AllocateParameters () {
636                                 return new object [_beginMethodInfo.GetParameters ().Length - 2 + _endMethodInfo.GetParameters().Length-1];
637                         }
638
639                         public object Invoke (object instance, object [] parameters) {
640                                 throw new NotImplementedException ("Can't invoke async method synchronously");
641                                 //BUGBUG: need to differentiate between input and output parameters.
642                                 IAsyncResult asyncResult = InvokeBegin(instance, parameters, delegate(IAsyncResult ignore) { }, null);
643                                 asyncResult.AsyncWaitHandle.WaitOne();
644                                 return InvokeEnd(instance, out parameters, asyncResult);
645                         }
646
647                         public IAsyncResult InvokeBegin (object instance, object [] inputs, AsyncCallback callback, object state) {
648                                 if (inputs.Length + 2 != _beginMethodInfo.GetParameters ().Length)
649                                         throw new ArgumentException ("Wrong number of input parameters");
650                                 object [] fullargs = new object [_beginMethodInfo.GetParameters ().Length];
651                                 Array.Copy (inputs, fullargs, inputs.Length);
652                                 fullargs [inputs.Length] = callback;
653                                 fullargs [inputs.Length + 1] = state;
654                                 return (IAsyncResult) _beginMethodInfo.Invoke (instance, fullargs);
655                         }
656
657                         public object InvokeEnd (object instance, out object [] outputs, IAsyncResult asyncResult) {
658                                 outputs = new object [_endMethodInfo.GetParameters ().Length - 1];
659                                 object [] fullargs = new object [_endMethodInfo.GetParameters ().Length];
660                                 fullargs [outputs.Length] = asyncResult;
661                                 object result = _endMethodInfo.Invoke (instance, fullargs);
662                                 Array.Copy (fullargs, outputs, outputs.Length);
663                                 return result;
664                         }
665
666                         #endregion
667                 }
668         }
669 }