2
0

ImmutableDispatchRuntime.cs 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel.Dispatcher
  5. {
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Collections.Specialized;
  9. using System.Diagnostics;
  10. using System.Runtime;
  11. using System.ServiceModel;
  12. using System.ServiceModel.Channels;
  13. using System.ServiceModel.Diagnostics;
  14. using System.Threading;
  15. using System.Transactions;
  16. using System.ServiceModel.Diagnostics.Application;
  17. using System.Runtime.Diagnostics;
  18. using System.Security;
  19. class ImmutableDispatchRuntime
  20. {
  21. readonly AuthenticationBehavior authenticationBehavior;
  22. readonly AuthorizationBehavior authorizationBehavior;
  23. readonly int correlationCount;
  24. readonly ConcurrencyBehavior concurrency;
  25. readonly IDemuxer demuxer;
  26. readonly ErrorBehavior error;
  27. readonly bool enableFaults;
  28. readonly bool ignoreTransactionFlow;
  29. readonly bool impersonateOnSerializingReply;
  30. readonly IInputSessionShutdown[] inputSessionShutdownHandlers;
  31. readonly InstanceBehavior instance;
  32. readonly bool isOnServer;
  33. readonly bool manualAddressing;
  34. readonly IDispatchMessageInspector[] messageInspectors;
  35. readonly int parameterInspectorCorrelationOffset;
  36. readonly IRequestReplyCorrelator requestReplyCorrelator;
  37. readonly SecurityImpersonationBehavior securityImpersonation;
  38. readonly TerminatingOperationBehavior terminate;
  39. readonly ThreadBehavior thread;
  40. readonly TransactionBehavior transaction;
  41. readonly bool validateMustUnderstand;
  42. readonly bool receiveContextEnabledChannel;
  43. readonly bool sendAsynchronously;
  44. readonly bool requireClaimsPrincipalOnOperationContext;
  45. readonly MessageRpcProcessor processMessage1;
  46. readonly MessageRpcProcessor processMessage11;
  47. readonly MessageRpcProcessor processMessage2;
  48. readonly MessageRpcProcessor processMessage3;
  49. readonly MessageRpcProcessor processMessage31;
  50. readonly MessageRpcProcessor processMessage4;
  51. readonly MessageRpcProcessor processMessage41;
  52. readonly MessageRpcProcessor processMessage5;
  53. readonly MessageRpcProcessor processMessage6;
  54. readonly MessageRpcProcessor processMessage7;
  55. readonly MessageRpcProcessor processMessage8;
  56. readonly MessageRpcProcessor processMessage9;
  57. readonly MessageRpcProcessor processMessageCleanup;
  58. readonly MessageRpcProcessor processMessageCleanupError;
  59. static AsyncCallback onFinalizeCorrelationCompleted =
  60. Fx.ThunkCallback(new AsyncCallback(OnFinalizeCorrelationCompletedCallback));
  61. static AsyncCallback onReplyCompleted =
  62. Fx.ThunkCallback(new AsyncCallback(OnReplyCompletedCallback));
  63. bool didTraceProcessMessage1 = false;
  64. bool didTraceProcessMessage2 = false;
  65. bool didTraceProcessMessage3 = false;
  66. bool didTraceProcessMessage31 = false;
  67. bool didTraceProcessMessage4 = false;
  68. bool didTraceProcessMessage41 = false;
  69. internal ImmutableDispatchRuntime(DispatchRuntime dispatch)
  70. {
  71. this.authenticationBehavior = AuthenticationBehavior.TryCreate(dispatch);
  72. this.authorizationBehavior = AuthorizationBehavior.TryCreate(dispatch);
  73. this.concurrency = new ConcurrencyBehavior(dispatch);
  74. this.error = new ErrorBehavior(dispatch.ChannelDispatcher);
  75. this.enableFaults = dispatch.EnableFaults;
  76. this.inputSessionShutdownHandlers = EmptyArray<IInputSessionShutdown>.ToArray(dispatch.InputSessionShutdownHandlers);
  77. this.instance = new InstanceBehavior(dispatch, this);
  78. this.isOnServer = dispatch.IsOnServer;
  79. this.manualAddressing = dispatch.ManualAddressing;
  80. this.messageInspectors = EmptyArray<IDispatchMessageInspector>.ToArray(dispatch.MessageInspectors);
  81. this.requestReplyCorrelator = new RequestReplyCorrelator();
  82. this.securityImpersonation = SecurityImpersonationBehavior.CreateIfNecessary(dispatch);
  83. this.requireClaimsPrincipalOnOperationContext = dispatch.RequireClaimsPrincipalOnOperationContext;
  84. this.impersonateOnSerializingReply = dispatch.ImpersonateOnSerializingReply;
  85. this.terminate = TerminatingOperationBehavior.CreateIfNecessary(dispatch);
  86. this.thread = new ThreadBehavior(dispatch);
  87. this.validateMustUnderstand = dispatch.ValidateMustUnderstand;
  88. this.ignoreTransactionFlow = dispatch.IgnoreTransactionMessageProperty;
  89. this.transaction = TransactionBehavior.CreateIfNeeded(dispatch);
  90. this.receiveContextEnabledChannel = dispatch.ChannelDispatcher.ReceiveContextEnabled;
  91. this.sendAsynchronously = dispatch.ChannelDispatcher.SendAsynchronously;
  92. this.parameterInspectorCorrelationOffset = (dispatch.MessageInspectors.Count +
  93. dispatch.MaxCallContextInitializers);
  94. this.correlationCount = this.parameterInspectorCorrelationOffset + dispatch.MaxParameterInspectors;
  95. DispatchOperationRuntime unhandled = new DispatchOperationRuntime(dispatch.UnhandledDispatchOperation, this);
  96. if (dispatch.OperationSelector == null)
  97. {
  98. ActionDemuxer demuxer = new ActionDemuxer();
  99. for (int i = 0; i < dispatch.Operations.Count; i++)
  100. {
  101. DispatchOperation operation = dispatch.Operations[i];
  102. DispatchOperationRuntime operationRuntime = new DispatchOperationRuntime(operation, this);
  103. demuxer.Add(operation.Action, operationRuntime);
  104. }
  105. demuxer.SetUnhandled(unhandled);
  106. this.demuxer = demuxer;
  107. }
  108. else
  109. {
  110. CustomDemuxer demuxer = new CustomDemuxer(dispatch.OperationSelector);
  111. for (int i = 0; i < dispatch.Operations.Count; i++)
  112. {
  113. DispatchOperation operation = dispatch.Operations[i];
  114. DispatchOperationRuntime operationRuntime = new DispatchOperationRuntime(operation, this);
  115. demuxer.Add(operation.Name, operationRuntime);
  116. }
  117. demuxer.SetUnhandled(unhandled);
  118. this.demuxer = demuxer;
  119. }
  120. this.processMessage1 = new MessageRpcProcessor(this.ProcessMessage1);
  121. this.processMessage11 = new MessageRpcProcessor(this.ProcessMessage11);
  122. this.processMessage2 = new MessageRpcProcessor(this.ProcessMessage2);
  123. this.processMessage3 = new MessageRpcProcessor(this.ProcessMessage3);
  124. this.processMessage31 = new MessageRpcProcessor(this.ProcessMessage31);
  125. this.processMessage4 = new MessageRpcProcessor(this.ProcessMessage4);
  126. this.processMessage41 = new MessageRpcProcessor(this.ProcessMessage41);
  127. this.processMessage5 = new MessageRpcProcessor(this.ProcessMessage5);
  128. this.processMessage6 = new MessageRpcProcessor(this.ProcessMessage6);
  129. this.processMessage7 = new MessageRpcProcessor(this.ProcessMessage7);
  130. this.processMessage8 = new MessageRpcProcessor(this.ProcessMessage8);
  131. this.processMessage9 = new MessageRpcProcessor(this.ProcessMessage9);
  132. this.processMessageCleanup = new MessageRpcProcessor(this.ProcessMessageCleanup);
  133. this.processMessageCleanupError = new MessageRpcProcessor(this.ProcessMessageCleanupError);
  134. }
  135. internal int CallContextCorrelationOffset
  136. {
  137. get { return this.messageInspectors.Length; }
  138. }
  139. internal int CorrelationCount
  140. {
  141. get { return this.correlationCount; }
  142. }
  143. internal bool EnableFaults
  144. {
  145. get { return this.enableFaults; }
  146. }
  147. internal InstanceBehavior InstanceBehavior
  148. {
  149. get { return this.instance; }
  150. }
  151. internal bool IsImpersonationEnabledOnSerializingReply
  152. {
  153. get { return this.impersonateOnSerializingReply; }
  154. }
  155. internal bool RequireClaimsPrincipalOnOperationContext
  156. {
  157. get { return this.requireClaimsPrincipalOnOperationContext; }
  158. }
  159. internal bool ManualAddressing
  160. {
  161. get { return this.manualAddressing; }
  162. }
  163. internal int MessageInspectorCorrelationOffset
  164. {
  165. get { return 0; }
  166. }
  167. internal int ParameterInspectorCorrelationOffset
  168. {
  169. get { return this.parameterInspectorCorrelationOffset; }
  170. }
  171. internal IRequestReplyCorrelator RequestReplyCorrelator
  172. {
  173. get { return this.requestReplyCorrelator; }
  174. }
  175. internal SecurityImpersonationBehavior SecurityImpersonation
  176. {
  177. get { return this.securityImpersonation; }
  178. }
  179. internal bool ValidateMustUnderstand
  180. {
  181. get { return validateMustUnderstand; }
  182. }
  183. internal ErrorBehavior ErrorBehavior
  184. {
  185. get { return this.error; }
  186. }
  187. bool AcquireDynamicInstanceContext(ref MessageRpc rpc)
  188. {
  189. if (rpc.InstanceContext.QuotaThrottle != null)
  190. {
  191. return AcquireDynamicInstanceContextCore(ref rpc);
  192. }
  193. else
  194. {
  195. return true;
  196. }
  197. }
  198. bool AcquireDynamicInstanceContextCore(ref MessageRpc rpc)
  199. {
  200. bool success = rpc.InstanceContext.QuotaThrottle.Acquire(rpc.Pause());
  201. if (success)
  202. {
  203. rpc.UnPause();
  204. }
  205. return success;
  206. }
  207. internal void AfterReceiveRequest(ref MessageRpc rpc)
  208. {
  209. if (this.messageInspectors.Length > 0)
  210. {
  211. AfterReceiveRequestCore(ref rpc);
  212. }
  213. }
  214. internal void AfterReceiveRequestCore(ref MessageRpc rpc)
  215. {
  216. int offset = this.MessageInspectorCorrelationOffset;
  217. try
  218. {
  219. for (int i = 0; i < this.messageInspectors.Length; i++)
  220. {
  221. rpc.Correlation[offset + i] = this.messageInspectors[i].AfterReceiveRequest(ref rpc.Request, (IClientChannel)rpc.Channel.Proxy, rpc.InstanceContext);
  222. if (TD.MessageInspectorAfterReceiveInvokedIsEnabled())
  223. {
  224. TD.MessageInspectorAfterReceiveInvoked(rpc.EventTraceActivity, this.messageInspectors[i].GetType().FullName);
  225. }
  226. }
  227. }
  228. catch (Exception e)
  229. {
  230. if (Fx.IsFatal(e))
  231. {
  232. throw;
  233. }
  234. if (ErrorBehavior.ShouldRethrowExceptionAsIs(e))
  235. {
  236. throw;
  237. }
  238. throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
  239. }
  240. }
  241. void BeforeSendReply(ref MessageRpc rpc, ref Exception exception, ref bool thereIsAnUnhandledException)
  242. {
  243. if (this.messageInspectors.Length > 0)
  244. {
  245. BeforeSendReplyCore(ref rpc, ref exception, ref thereIsAnUnhandledException);
  246. }
  247. }
  248. internal void BeforeSendReplyCore(ref MessageRpc rpc, ref Exception exception, ref bool thereIsAnUnhandledException)
  249. {
  250. int offset = this.MessageInspectorCorrelationOffset;
  251. for (int i = 0; i < this.messageInspectors.Length; i++)
  252. {
  253. try
  254. {
  255. Message originalReply = rpc.Reply;
  256. Message reply = originalReply;
  257. this.messageInspectors[i].BeforeSendReply(ref reply, rpc.Correlation[offset + i]);
  258. if (TD.MessageInspectorBeforeSendInvokedIsEnabled())
  259. {
  260. TD.MessageInspectorBeforeSendInvoked(rpc.EventTraceActivity, this.messageInspectors[i].GetType().FullName);
  261. }
  262. if ((reply == null) && (originalReply != null))
  263. {
  264. string message = SR.GetString(SR.SFxNullReplyFromExtension2, this.messageInspectors[i].GetType().ToString(), (rpc.Operation.Name ?? ""));
  265. ErrorBehavior.ThrowAndCatch(new InvalidOperationException(message));
  266. }
  267. rpc.Reply = reply;
  268. }
  269. catch (Exception e)
  270. {
  271. if (Fx.IsFatal(e))
  272. {
  273. throw;
  274. }
  275. if (!ErrorBehavior.ShouldRethrowExceptionAsIs(e))
  276. {
  277. throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
  278. }
  279. if (exception == null)
  280. {
  281. exception = e;
  282. }
  283. thereIsAnUnhandledException = (!this.error.HandleError(e)) || thereIsAnUnhandledException;
  284. }
  285. }
  286. }
  287. void FinalizeCorrelation(ref MessageRpc rpc)
  288. {
  289. Message reply = rpc.Reply;
  290. if (reply != null && rpc.Error == null)
  291. {
  292. if (rpc.transaction != null && rpc.transaction.Current != null &&
  293. rpc.transaction.Current.TransactionInformation.Status != TransactionStatus.Active)
  294. {
  295. return;
  296. }
  297. CorrelationCallbackMessageProperty callback;
  298. if (CorrelationCallbackMessageProperty.TryGet(reply, out callback))
  299. {
  300. if (callback.IsFullyDefined)
  301. {
  302. try
  303. {
  304. rpc.RequestContextThrewOnReply = true;
  305. rpc.CorrelationCallback = callback;
  306. rpc.Reply = rpc.CorrelationCallback.FinalizeCorrelation(reply,
  307. rpc.ReplyTimeoutHelper.RemainingTime());
  308. }
  309. catch (Exception e)
  310. {
  311. if (Fx.IsFatal(e))
  312. {
  313. throw;
  314. }
  315. if (!this.error.HandleError(e))
  316. {
  317. rpc.CorrelationCallback = null;
  318. rpc.CanSendReply = false;
  319. }
  320. }
  321. }
  322. else
  323. {
  324. rpc.CorrelationCallback = new RpcCorrelationCallbackMessageProperty(callback, this, ref rpc);
  325. reply.Properties[CorrelationCallbackMessageProperty.Name] = rpc.CorrelationCallback;
  326. }
  327. }
  328. }
  329. }
  330. void BeginFinalizeCorrelation(ref MessageRpc rpc)
  331. {
  332. Message reply = rpc.Reply;
  333. if (reply != null && rpc.Error == null)
  334. {
  335. if (rpc.transaction != null && rpc.transaction.Current != null &&
  336. rpc.transaction.Current.TransactionInformation.Status != TransactionStatus.Active)
  337. {
  338. return;
  339. }
  340. CorrelationCallbackMessageProperty callback;
  341. if (CorrelationCallbackMessageProperty.TryGet(reply, out callback))
  342. {
  343. if (callback.IsFullyDefined)
  344. {
  345. bool success = false;
  346. try
  347. {
  348. rpc.RequestContextThrewOnReply = true;
  349. rpc.CorrelationCallback = callback;
  350. IResumeMessageRpc resume = rpc.Pause();
  351. rpc.AsyncResult = rpc.CorrelationCallback.BeginFinalizeCorrelation(reply,
  352. rpc.ReplyTimeoutHelper.RemainingTime(), onFinalizeCorrelationCompleted, resume);
  353. success = true;
  354. if (rpc.AsyncResult.CompletedSynchronously)
  355. {
  356. rpc.UnPause();
  357. }
  358. }
  359. catch (Exception e)
  360. {
  361. if (Fx.IsFatal(e))
  362. {
  363. throw;
  364. }
  365. if (!this.error.HandleError(e))
  366. {
  367. rpc.CorrelationCallback = null;
  368. rpc.CanSendReply = false;
  369. }
  370. }
  371. finally
  372. {
  373. if (!success)
  374. {
  375. rpc.UnPause();
  376. }
  377. }
  378. }
  379. else
  380. {
  381. rpc.CorrelationCallback = new RpcCorrelationCallbackMessageProperty(callback, this, ref rpc);
  382. reply.Properties[CorrelationCallbackMessageProperty.Name] = rpc.CorrelationCallback;
  383. }
  384. }
  385. }
  386. }
  387. void Reply(ref MessageRpc rpc)
  388. {
  389. rpc.RequestContextThrewOnReply = true;
  390. rpc.SuccessfullySendReply = false;
  391. try
  392. {
  393. rpc.RequestContext.Reply(rpc.Reply, rpc.ReplyTimeoutHelper.RemainingTime());
  394. rpc.RequestContextThrewOnReply = false;
  395. rpc.SuccessfullySendReply = true;
  396. if (TD.DispatchMessageStopIsEnabled())
  397. {
  398. TD.DispatchMessageStop(rpc.EventTraceActivity);
  399. }
  400. }
  401. catch (CommunicationException e)
  402. {
  403. this.error.HandleError(e);
  404. }
  405. catch (TimeoutException e)
  406. {
  407. this.error.HandleError(e);
  408. }
  409. catch (Exception e)
  410. {
  411. if (Fx.IsFatal(e))
  412. {
  413. throw;
  414. }
  415. if (DiagnosticUtility.ShouldTraceError)
  416. {
  417. TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.ServiceOperationExceptionOnReply,
  418. SR.GetString(SR.TraceCodeServiceOperationExceptionOnReply),
  419. this, e);
  420. }
  421. if (!this.error.HandleError(e))
  422. {
  423. rpc.RequestContextThrewOnReply = true;
  424. rpc.CanSendReply = false;
  425. }
  426. }
  427. }
  428. void BeginReply(ref MessageRpc rpc)
  429. {
  430. bool success = false;
  431. try
  432. {
  433. IResumeMessageRpc resume = rpc.Pause();
  434. rpc.AsyncResult = rpc.RequestContext.BeginReply(rpc.Reply, rpc.ReplyTimeoutHelper.RemainingTime(),
  435. onReplyCompleted, resume);
  436. success = true;
  437. if (rpc.AsyncResult.CompletedSynchronously)
  438. {
  439. rpc.UnPause();
  440. }
  441. }
  442. catch (CommunicationException e)
  443. {
  444. this.error.HandleError(e);
  445. }
  446. catch (TimeoutException e)
  447. {
  448. this.error.HandleError(e);
  449. }
  450. catch (Exception e)
  451. {
  452. if (Fx.IsFatal(e))
  453. {
  454. throw;
  455. }
  456. if (DiagnosticUtility.ShouldTraceError)
  457. {
  458. TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Error,
  459. TraceCode.ServiceOperationExceptionOnReply,
  460. SR.GetString(SR.TraceCodeServiceOperationExceptionOnReply),
  461. this, e);
  462. }
  463. if (!this.error.HandleError(e))
  464. {
  465. rpc.RequestContextThrewOnReply = true;
  466. rpc.CanSendReply = false;
  467. }
  468. }
  469. finally
  470. {
  471. if (!success)
  472. {
  473. rpc.UnPause();
  474. }
  475. }
  476. }
  477. internal bool Dispatch(ref MessageRpc rpc, bool isOperationContextSet)
  478. {
  479. rpc.ErrorProcessor = this.processMessage8;
  480. rpc.NextProcessor = this.processMessage1;
  481. return rpc.Process(isOperationContextSet);
  482. }
  483. void EndFinalizeCorrelation(ref MessageRpc rpc)
  484. {
  485. try
  486. {
  487. rpc.Reply = rpc.CorrelationCallback.EndFinalizeCorrelation(rpc.AsyncResult);
  488. }
  489. catch (Exception e)
  490. {
  491. if (Fx.IsFatal(e))
  492. {
  493. throw;
  494. }
  495. if (!this.error.HandleError(e))
  496. {
  497. rpc.CanSendReply = false;
  498. }
  499. }
  500. }
  501. bool EndReply(ref MessageRpc rpc)
  502. {
  503. bool success = false;
  504. try
  505. {
  506. rpc.RequestContext.EndReply(rpc.AsyncResult);
  507. rpc.RequestContextThrewOnReply = false;
  508. success = true;
  509. if (TD.DispatchMessageStopIsEnabled())
  510. {
  511. TD.DispatchMessageStop(rpc.EventTraceActivity);
  512. }
  513. }
  514. catch (Exception e)
  515. {
  516. if (Fx.IsFatal(e))
  517. {
  518. throw;
  519. }
  520. this.error.HandleError(e);
  521. }
  522. return success;
  523. }
  524. internal void InputSessionDoneReceiving(ServiceChannel channel)
  525. {
  526. if (this.inputSessionShutdownHandlers.Length > 0)
  527. {
  528. this.InputSessionDoneReceivingCore(channel);
  529. }
  530. }
  531. void InputSessionDoneReceivingCore(ServiceChannel channel)
  532. {
  533. IDuplexContextChannel proxy = channel.Proxy as IDuplexContextChannel;
  534. if (proxy != null)
  535. {
  536. IInputSessionShutdown[] handlers = this.inputSessionShutdownHandlers;
  537. try
  538. {
  539. for (int i = 0; i < handlers.Length; i++)
  540. {
  541. handlers[i].DoneReceiving(proxy);
  542. }
  543. }
  544. catch (Exception e)
  545. {
  546. if (Fx.IsFatal(e))
  547. {
  548. throw;
  549. }
  550. if (!this.error.HandleError(e))
  551. {
  552. proxy.Abort();
  553. }
  554. }
  555. }
  556. }
  557. internal bool IsConcurrent(ref MessageRpc rpc)
  558. {
  559. return this.concurrency.IsConcurrent(ref rpc);
  560. }
  561. internal void InputSessionFaulted(ServiceChannel channel)
  562. {
  563. if (this.inputSessionShutdownHandlers.Length > 0)
  564. {
  565. this.InputSessionFaultedCore(channel);
  566. }
  567. }
  568. void InputSessionFaultedCore(ServiceChannel channel)
  569. {
  570. IDuplexContextChannel proxy = channel.Proxy as IDuplexContextChannel;
  571. if (proxy != null)
  572. {
  573. IInputSessionShutdown[] handlers = this.inputSessionShutdownHandlers;
  574. try
  575. {
  576. for (int i = 0; i < handlers.Length; i++)
  577. {
  578. handlers[i].ChannelFaulted(proxy);
  579. }
  580. }
  581. catch (Exception e)
  582. {
  583. if (Fx.IsFatal(e))
  584. {
  585. throw;
  586. }
  587. if (!this.error.HandleError(e))
  588. {
  589. proxy.Abort();
  590. }
  591. }
  592. }
  593. }
  594. static internal void GotDynamicInstanceContext(object state)
  595. {
  596. bool alreadyResumedNoLock;
  597. ((IResumeMessageRpc)state).Resume(out alreadyResumedNoLock);
  598. if (alreadyResumedNoLock)
  599. {
  600. Fx.Assert("GotDynamicInstanceContext more than once for same call.");
  601. }
  602. }
  603. void AddMessageProperties(Message message, OperationContext context, ServiceChannel replyChannel)
  604. {
  605. if (context.InternalServiceChannel == replyChannel)
  606. {
  607. if (context.HasOutgoingMessageHeaders)
  608. {
  609. message.Headers.CopyHeadersFrom(context.OutgoingMessageHeaders);
  610. }
  611. if (context.HasOutgoingMessageProperties)
  612. {
  613. message.Properties.MergeProperties(context.OutgoingMessageProperties);
  614. }
  615. }
  616. }
  617. static void OnFinalizeCorrelationCompletedCallback(IAsyncResult result)
  618. {
  619. if (result.CompletedSynchronously)
  620. {
  621. return;
  622. }
  623. IResumeMessageRpc resume = result.AsyncState as IResumeMessageRpc;
  624. if (resume == null)
  625. {
  626. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxInvalidAsyncResultState0));
  627. }
  628. resume.Resume(result);
  629. }
  630. static void OnReplyCompletedCallback(IAsyncResult result)
  631. {
  632. if (result.CompletedSynchronously)
  633. {
  634. return;
  635. }
  636. IResumeMessageRpc resume = result.AsyncState as IResumeMessageRpc;
  637. if (resume == null)
  638. {
  639. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxInvalidAsyncResultState0));
  640. }
  641. resume.Resume(result);
  642. }
  643. void PrepareReply(ref MessageRpc rpc)
  644. {
  645. RequestContext context = rpc.OperationContext.RequestContext;
  646. Exception exception = null;
  647. bool thereIsAnUnhandledException = false;
  648. if (!rpc.Operation.IsOneWay)
  649. {
  650. if (DiagnosticUtility.ShouldTraceWarning)
  651. {
  652. // If a service both returns null and sets RequestContext null, that
  653. // means they handled it (either by calling Close or Reply manually).
  654. // These traces catch accidents, where you accidentally return null,
  655. // or you accidentally close the context so we can't return your message.
  656. if ((rpc.Reply == null) && (context != null))
  657. {
  658. TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Warning,
  659. TraceCode.ServiceOperationMissingReply,
  660. SR.GetString(SR.TraceCodeServiceOperationMissingReply, rpc.Operation.Name ?? String.Empty),
  661. null, null);
  662. }
  663. else if ((context == null) && (rpc.Reply != null))
  664. {
  665. TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Warning,
  666. TraceCode.ServiceOperationMissingReplyContext,
  667. SR.GetString(SR.TraceCodeServiceOperationMissingReplyContext, rpc.Operation.Name ?? String.Empty),
  668. null, null);
  669. }
  670. }
  671. if ((context != null) && (rpc.Reply != null))
  672. {
  673. try
  674. {
  675. rpc.CanSendReply = PrepareAndAddressReply(ref rpc);
  676. }
  677. catch (Exception e)
  678. {
  679. if (Fx.IsFatal(e))
  680. {
  681. throw;
  682. }
  683. thereIsAnUnhandledException = (!this.error.HandleError(e)) || thereIsAnUnhandledException;
  684. exception = e;
  685. }
  686. }
  687. }
  688. this.BeforeSendReply(ref rpc, ref exception, ref thereIsAnUnhandledException);
  689. if (rpc.Operation.IsOneWay)
  690. {
  691. rpc.CanSendReply = false;
  692. }
  693. if (!rpc.Operation.IsOneWay && (context != null) && (rpc.Reply != null))
  694. {
  695. if (exception != null)
  696. {
  697. // We don't call ProvideFault again, since we have already passed the
  698. // point where SFx addresses the reply, and it is reasonable for
  699. // ProvideFault to expect that SFx will address the reply. Instead
  700. // we always just do 'internal server error' processing.
  701. rpc.Error = exception;
  702. this.error.ProvideOnlyFaultOfLastResort(ref rpc);
  703. try
  704. {
  705. rpc.CanSendReply = PrepareAndAddressReply(ref rpc);
  706. }
  707. catch (Exception e)
  708. {
  709. if (Fx.IsFatal(e))
  710. {
  711. throw;
  712. }
  713. this.error.HandleError(e);
  714. }
  715. }
  716. }
  717. else if ((exception != null) && thereIsAnUnhandledException)
  718. {
  719. rpc.Abort();
  720. }
  721. }
  722. bool PrepareAndAddressReply(ref MessageRpc rpc)
  723. {
  724. bool canSendReply = true;
  725. if (!this.manualAddressing)
  726. {
  727. if (!object.ReferenceEquals(rpc.RequestID, null))
  728. {
  729. System.ServiceModel.Channels.RequestReplyCorrelator.PrepareReply(rpc.Reply, rpc.RequestID);
  730. }
  731. if (!rpc.Channel.HasSession)
  732. {
  733. canSendReply = System.ServiceModel.Channels.RequestReplyCorrelator.AddressReply(rpc.Reply, rpc.ReplyToInfo);
  734. }
  735. }
  736. AddMessageProperties(rpc.Reply, rpc.OperationContext, rpc.Channel);
  737. if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && rpc.EventTraceActivity != null)
  738. {
  739. rpc.Reply.Properties[EventTraceActivity.Name] = rpc.EventTraceActivity;
  740. }
  741. return canSendReply;
  742. }
  743. internal DispatchOperationRuntime GetOperation(ref Message message)
  744. {
  745. return this.demuxer.GetOperation(ref message);
  746. }
  747. internal void ProcessMessage1(ref MessageRpc rpc)
  748. {
  749. rpc.NextProcessor = this.processMessage11;
  750. if (this.receiveContextEnabledChannel)
  751. {
  752. ReceiveContextRPCFacet.CreateIfRequired(this, ref rpc);
  753. }
  754. if (!rpc.IsPaused)
  755. {
  756. this.ProcessMessage11(ref rpc);
  757. }
  758. else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage1)
  759. {
  760. this.didTraceProcessMessage1 = true;
  761. TraceUtility.TraceEvent(
  762. TraceEventType.Information,
  763. TraceCode.MessageProcessingPaused,
  764. SR.GetString(SR.TraceCodeProcessMessage31Paused,
  765. rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
  766. rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
  767. }
  768. }
  769. internal void ProcessMessage11(ref MessageRpc rpc)
  770. {
  771. rpc.NextProcessor = this.processMessage2;
  772. if (rpc.Operation.IsOneWay)
  773. {
  774. rpc.RequestContext.Reply(null);
  775. rpc.OperationContext.RequestContext = null;
  776. }
  777. else
  778. {
  779. if (!rpc.Channel.IsReplyChannel &&
  780. ((object)rpc.RequestID == null) &&
  781. (rpc.Operation.Action != MessageHeaders.WildcardAction))
  782. {
  783. CommunicationException error = new CommunicationException(SR.GetString(SR.SFxOneWayMessageToTwoWayMethod0));
  784. throw TraceUtility.ThrowHelperError(error, rpc.Request);
  785. }
  786. if (!this.manualAddressing)
  787. {
  788. EndpointAddress replyTo = rpc.ReplyToInfo.ReplyTo;
  789. if (replyTo != null && replyTo.IsNone && rpc.Channel.IsReplyChannel)
  790. {
  791. CommunicationException error = new CommunicationException(SR.GetString(SR.SFxRequestReplyNone));
  792. throw TraceUtility.ThrowHelperError(error, rpc.Request);
  793. }
  794. if (this.isOnServer)
  795. {
  796. EndpointAddress remoteAddress = rpc.Channel.RemoteAddress;
  797. if ((remoteAddress != null) && !remoteAddress.IsAnonymous)
  798. {
  799. MessageHeaders headers = rpc.Request.Headers;
  800. Uri remoteUri = remoteAddress.Uri;
  801. if ((replyTo != null) && !replyTo.IsAnonymous && (remoteUri != replyTo.Uri))
  802. {
  803. string text = SR.GetString(SR.SFxRequestHasInvalidReplyToOnServer, replyTo.Uri, remoteUri);
  804. Exception error = new InvalidOperationException(text);
  805. throw TraceUtility.ThrowHelperError(error, rpc.Request);
  806. }
  807. EndpointAddress faultTo = headers.FaultTo;
  808. if ((faultTo != null) && !faultTo.IsAnonymous && (remoteUri != faultTo.Uri))
  809. {
  810. string text = SR.GetString(SR.SFxRequestHasInvalidFaultToOnServer, faultTo.Uri, remoteUri);
  811. Exception error = new InvalidOperationException(text);
  812. throw TraceUtility.ThrowHelperError(error, rpc.Request);
  813. }
  814. if (rpc.RequestVersion.Addressing == AddressingVersion.WSAddressingAugust2004)
  815. {
  816. EndpointAddress from = headers.From;
  817. if ((from != null) && !from.IsAnonymous && (remoteUri != from.Uri))
  818. {
  819. string text = SR.GetString(SR.SFxRequestHasInvalidFromOnServer, from.Uri, remoteUri);
  820. Exception error = new InvalidOperationException(text);
  821. throw TraceUtility.ThrowHelperError(error, rpc.Request);
  822. }
  823. }
  824. }
  825. }
  826. }
  827. }
  828. if (this.concurrency.IsConcurrent(ref rpc))
  829. {
  830. rpc.Channel.IncrementActivity();
  831. rpc.SuccessfullyIncrementedActivity = true;
  832. }
  833. if (this.authenticationBehavior != null)
  834. {
  835. this.authenticationBehavior.Authenticate(ref rpc);
  836. }
  837. if (this.authorizationBehavior != null)
  838. {
  839. this.authorizationBehavior.Authorize(ref rpc);
  840. }
  841. this.instance.EnsureInstanceContext(ref rpc);
  842. this.TransferChannelFromPendingList(ref rpc);
  843. this.AcquireDynamicInstanceContext(ref rpc);
  844. if (!rpc.IsPaused)
  845. {
  846. this.ProcessMessage2(ref rpc);
  847. }
  848. }
  849. void ProcessMessage2(ref MessageRpc rpc)
  850. {
  851. rpc.NextProcessor = this.processMessage3;
  852. this.AfterReceiveRequest(ref rpc);
  853. if (!this.ignoreTransactionFlow)
  854. {
  855. // Transactions need to have the context in the message
  856. rpc.TransactionMessageProperty = TransactionMessageProperty.TryGet(rpc.Request);
  857. }
  858. this.concurrency.LockInstance(ref rpc);
  859. if (!rpc.IsPaused)
  860. {
  861. this.ProcessMessage3(ref rpc);
  862. }
  863. else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage2)
  864. {
  865. this.didTraceProcessMessage2 = true;
  866. TraceUtility.TraceEvent(
  867. TraceEventType.Information,
  868. TraceCode.MessageProcessingPaused,
  869. SR.GetString(SR.TraceCodeProcessMessage2Paused,
  870. rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
  871. rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
  872. }
  873. }
  874. void ProcessMessage3(ref MessageRpc rpc)
  875. {
  876. rpc.NextProcessor = this.processMessage31;
  877. rpc.SuccessfullyLockedInstance = true;
  878. // This also needs to happen after LockInstance, in case
  879. // we are using an AutoComplete=false transaction.
  880. if (this.transaction != null)
  881. {
  882. this.transaction.ResolveTransaction(ref rpc);
  883. if (rpc.Operation.TransactionRequired)
  884. {
  885. this.transaction.SetCurrent(ref rpc);
  886. }
  887. }
  888. if (!rpc.IsPaused)
  889. {
  890. this.ProcessMessage31(ref rpc);
  891. }
  892. else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage3)
  893. {
  894. this.didTraceProcessMessage3 = true;
  895. TraceUtility.TraceEvent(
  896. TraceEventType.Information,
  897. TraceCode.MessageProcessingPaused,
  898. SR.GetString(SR.TraceCodeProcessMessage3Paused,
  899. rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
  900. rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
  901. }
  902. }
  903. void ProcessMessage31(ref MessageRpc rpc)
  904. {
  905. rpc.NextProcessor = this.ProcessMessage4;
  906. if (this.transaction != null)
  907. {
  908. if (rpc.Operation.TransactionRequired)
  909. {
  910. ReceiveContextRPCFacet receiveContext = rpc.ReceiveContext;
  911. if (receiveContext != null)
  912. {
  913. rpc.ReceiveContext = null;
  914. receiveContext.Complete(this, ref rpc, TimeSpan.MaxValue, rpc.Transaction.Current);
  915. }
  916. }
  917. }
  918. if (!rpc.IsPaused)
  919. {
  920. this.ProcessMessage4(ref rpc);
  921. }
  922. else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage31)
  923. {
  924. this.didTraceProcessMessage31 = true;
  925. TraceUtility.TraceEvent(
  926. TraceEventType.Information,
  927. TraceCode.MessageProcessingPaused,
  928. SR.GetString(SR.TraceCodeProcessMessage31Paused,
  929. rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
  930. rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
  931. }
  932. }
  933. void ProcessMessage4(ref MessageRpc rpc)
  934. {
  935. rpc.NextProcessor = this.processMessage41;
  936. try
  937. {
  938. this.thread.BindThread(ref rpc);
  939. }
  940. catch (Exception e)
  941. {
  942. if (Fx.IsFatal(e))
  943. {
  944. throw;
  945. }
  946. throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e);
  947. }
  948. if (!rpc.IsPaused)
  949. {
  950. this.ProcessMessage41(ref rpc);
  951. }
  952. else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage4)
  953. {
  954. this.didTraceProcessMessage4 = true;
  955. TraceUtility.TraceEvent(
  956. TraceEventType.Information,
  957. TraceCode.MessageProcessingPaused,
  958. SR.GetString(SR.TraceCodeProcessMessage4Paused,
  959. rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
  960. rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
  961. }
  962. }
  963. void ProcessMessage41(ref MessageRpc rpc)
  964. {
  965. rpc.NextProcessor = this.processMessage5;
  966. // This needs to happen after LockInstance--LockInstance guarantees
  967. // in-order delivery, so we can't receive the next message until we
  968. // have acquired the lock.
  969. //
  970. // This also needs to happen after BindThread, since EricZ believes
  971. // that running on UI thread should guarantee in-order delivery if
  972. // the SynchronizationContext is single threaded.
  973. // Note: for IManualConcurrencyOperationInvoker, the invoke assumes full control over pumping.
  974. if (this.concurrency.IsConcurrent(ref rpc) && !(rpc.Operation.Invoker is IManualConcurrencyOperationInvoker))
  975. {
  976. rpc.EnsureReceive();
  977. }
  978. this.instance.EnsureServiceInstance(ref rpc);
  979. if (!rpc.IsPaused)
  980. {
  981. this.ProcessMessage5(ref rpc);
  982. }
  983. else if (this.isOnServer && DiagnosticUtility.ShouldTraceInformation && !this.didTraceProcessMessage41)
  984. {
  985. this.didTraceProcessMessage41 = true;
  986. TraceUtility.TraceEvent(
  987. TraceEventType.Information,
  988. TraceCode.MessageProcessingPaused,
  989. SR.GetString(SR.TraceCodeProcessMessage4Paused,
  990. rpc.Channel.DispatchRuntime.EndpointDispatcher.ContractName,
  991. rpc.Channel.DispatchRuntime.EndpointDispatcher.EndpointAddress));
  992. }
  993. }
  994. void ProcessMessage5(ref MessageRpc rpc)
  995. {
  996. rpc.NextProcessor = this.processMessage6;
  997. try
  998. {
  999. bool success = false;
  1000. try
  1001. {
  1002. if (!rpc.Operation.IsSynchronous)
  1003. {
  1004. // If async call completes in [....], it tells us through the gate below
  1005. rpc.PrepareInvokeContinueGate();
  1006. }
  1007. if (this.transaction != null)
  1008. {
  1009. this.transaction.InitializeCallContext(ref rpc);
  1010. }
  1011. SetActivityIdOnThread(ref rpc);
  1012. rpc.Operation.InvokeBegin(ref rpc);
  1013. success = true;
  1014. }
  1015. finally
  1016. {
  1017. try
  1018. {
  1019. try
  1020. {
  1021. if (this.transaction != null)
  1022. {
  1023. this.transaction.ClearCallContext(ref rpc);
  1024. }
  1025. }
  1026. finally
  1027. {
  1028. if (!rpc.Operation.IsSynchronous && rpc.IsPaused)
  1029. {
  1030. // Check if the callback produced the async result and set it back on the RPC on this stack
  1031. // and proceed only if the gate was signaled by the callback and completed synchronously
  1032. if (rpc.UnlockInvokeContinueGate(out rpc.AsyncResult))
  1033. {
  1034. rpc.UnPause();
  1035. }
  1036. }
  1037. }
  1038. }
  1039. catch (Exception e)
  1040. {
  1041. if (Fx.IsFatal(e))
  1042. {
  1043. throw;
  1044. }
  1045. if (success && (rpc.Operation.IsSynchronous || !rpc.IsPaused))
  1046. {
  1047. throw;
  1048. }
  1049. this.error.HandleError(e);
  1050. }
  1051. }
  1052. }
  1053. catch
  1054. {
  1055. // This catch clause forces ClearCallContext to run prior to stackwalks exiting this frame.
  1056. throw;
  1057. }
  1058. // Proceed if rpc is unpaused and invoke begin was successful.
  1059. if (!rpc.IsPaused)
  1060. {
  1061. this.ProcessMessage6(ref rpc);
  1062. }
  1063. }
  1064. void ProcessMessage6(ref MessageRpc rpc)
  1065. {
  1066. rpc.NextProcessor = (rpc.Operation.IsSynchronous) ?
  1067. this.processMessage8 :
  1068. this.processMessage7;
  1069. try
  1070. {
  1071. this.thread.BindEndThread(ref rpc);
  1072. }
  1073. catch (Exception e)
  1074. {
  1075. if (Fx.IsFatal(e))
  1076. {
  1077. throw;
  1078. }
  1079. throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e);
  1080. }
  1081. if (!rpc.IsPaused)
  1082. {
  1083. if (rpc.Operation.IsSynchronous)
  1084. {
  1085. this.ProcessMessage8(ref rpc);
  1086. }
  1087. else
  1088. {
  1089. this.ProcessMessage7(ref rpc);
  1090. }
  1091. }
  1092. }
  1093. void ProcessMessage7(ref MessageRpc rpc)
  1094. {
  1095. rpc.NextProcessor = null;
  1096. try
  1097. {
  1098. bool success = false;
  1099. try
  1100. {
  1101. if (this.transaction != null)
  1102. {
  1103. this.transaction.InitializeCallContext(ref rpc);
  1104. }
  1105. rpc.Operation.InvokeEnd(ref rpc);
  1106. success = true;
  1107. }
  1108. finally
  1109. {
  1110. try
  1111. {
  1112. if (this.transaction != null)
  1113. {
  1114. this.transaction.ClearCallContext(ref rpc);
  1115. }
  1116. }
  1117. catch (Exception e)
  1118. {
  1119. if (Fx.IsFatal(e))
  1120. {
  1121. throw;
  1122. }
  1123. if (success)
  1124. {
  1125. // Throw the transaction.ClearContextException only if
  1126. // there isn't an exception on the thread already.
  1127. throw;
  1128. }
  1129. this.error.HandleError(e);
  1130. }
  1131. }
  1132. }
  1133. catch
  1134. {
  1135. // Make sure user Exception filters are not run with bad call context
  1136. throw;
  1137. }
  1138. // this never pauses
  1139. this.ProcessMessage8(ref rpc);
  1140. }
  1141. void ProcessMessage8(ref MessageRpc rpc)
  1142. {
  1143. rpc.NextProcessor = this.processMessage9;
  1144. try
  1145. {
  1146. this.error.ProvideMessageFault(ref rpc);
  1147. }
  1148. catch (Exception e)
  1149. {
  1150. if (Fx.IsFatal(e))
  1151. {
  1152. throw;
  1153. }
  1154. this.error.HandleError(e);
  1155. }
  1156. this.PrepareReply(ref rpc);
  1157. if (rpc.CanSendReply)
  1158. {
  1159. rpc.ReplyTimeoutHelper = new TimeoutHelper(rpc.Channel.OperationTimeout);
  1160. if (this.sendAsynchronously)
  1161. {
  1162. this.BeginFinalizeCorrelation(ref rpc);
  1163. }
  1164. else
  1165. {
  1166. this.FinalizeCorrelation(ref rpc);
  1167. }
  1168. }
  1169. if (!rpc.IsPaused)
  1170. {
  1171. this.ProcessMessage9(ref rpc);
  1172. }
  1173. }
  1174. void ProcessMessage9(ref MessageRpc rpc)
  1175. {
  1176. rpc.NextProcessor = this.processMessageCleanup;
  1177. if (rpc.FinalizeCorrelationImplicitly && this.sendAsynchronously)
  1178. {
  1179. this.EndFinalizeCorrelation(ref rpc);
  1180. }
  1181. if (rpc.CorrelationCallback == null || rpc.FinalizeCorrelationImplicitly)
  1182. {
  1183. this.ResolveTransactionOutcome(ref rpc);
  1184. }
  1185. if (rpc.CanSendReply)
  1186. {
  1187. if (rpc.Reply != null)
  1188. {
  1189. TraceUtility.MessageFlowAtMessageSent(rpc.Reply, rpc.EventTraceActivity);
  1190. }
  1191. if (this.sendAsynchronously)
  1192. {
  1193. this.BeginReply(ref rpc);
  1194. }
  1195. else
  1196. {
  1197. this.Reply(ref rpc);
  1198. }
  1199. }
  1200. if (!rpc.IsPaused)
  1201. {
  1202. this.ProcessMessageCleanup(ref rpc);
  1203. }
  1204. }
  1205. // Logic for knowing when to close stuff:
  1206. //
  1207. // ASSUMPTIONS:
  1208. // Closing a stream over a message also closes the message.
  1209. // Closing a message over a stream does not close the stream.
  1210. // (OperationStreamProvider.ReleaseStream is no-op)
  1211. //
  1212. // This is a table of what should be disposed in what cases.
  1213. // The rows represent the type of parameter to the method and
  1214. // whether we are disposing parameters or not. The columns
  1215. // are for the inputs vs. the outputs. The cells contain the
  1216. // values that need to be Disposed. M^P means that exactly
  1217. // one of the message and parameter needs to be disposed,
  1218. // since they refer to the same object.
  1219. //
  1220. // Request Reply
  1221. // Message | M or P | M or P
  1222. // Dispose Stream | P | M and P
  1223. // Params | M and P | M and P
  1224. // | |
  1225. // Message | none | none
  1226. // NoDispose Stream | none | M
  1227. // Params | M | M
  1228. //
  1229. // By choosing to dispose the parameter in both of the "M or P"
  1230. // cases, the logic needed to generate this table is:
  1231. //
  1232. // CloseRequestMessage = IsParams
  1233. // CloseRequestParams = rpc.Operation.DisposeParameters
  1234. // CloseReplyMessage = rpc.Operation.SerializeReply
  1235. // CloseReplyParams = rpc.Operation.DisposeParameters
  1236. //
  1237. // IsParams can be calculated based on whether the request
  1238. // message was consumed after deserializing but before calling
  1239. // the user. This is stored as rpc.DidDeserializeRequestBody.
  1240. //
  1241. void ProcessMessageCleanup(ref MessageRpc rpc)
  1242. {
  1243. Fx.Assert(
  1244. !object.ReferenceEquals(rpc.ErrorProcessor, this.processMessageCleanupError),
  1245. "ProcessMessageCleanup run twice on the same MessageRpc!");
  1246. rpc.ErrorProcessor = this.processMessageCleanupError;
  1247. bool replyWasSent = false;
  1248. if (rpc.CanSendReply)
  1249. {
  1250. if (this.sendAsynchronously)
  1251. {
  1252. replyWasSent = this.EndReply(ref rpc);
  1253. }
  1254. else
  1255. {
  1256. replyWasSent = rpc.SuccessfullySendReply;
  1257. }
  1258. }
  1259. try
  1260. {
  1261. try
  1262. {
  1263. if (rpc.DidDeserializeRequestBody)
  1264. {
  1265. rpc.Request.Close();
  1266. }
  1267. }
  1268. catch (Exception e)
  1269. {
  1270. if (Fx.IsFatal(e))
  1271. {
  1272. throw;
  1273. }
  1274. this.error.HandleError(e);
  1275. }
  1276. if (rpc.HostingProperty != null)
  1277. {
  1278. try
  1279. {
  1280. rpc.HostingProperty.Close();
  1281. }
  1282. catch (Exception e)
  1283. {
  1284. if (Fx.IsFatal(e))
  1285. {
  1286. throw;
  1287. }
  1288. throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e);
  1289. }
  1290. }
  1291. // for wf, wf owns the lifetime of the request message. So in that case, we should not dispose the inputs
  1292. IManualConcurrencyOperationInvoker manualInvoker = rpc.Operation.Invoker as IManualConcurrencyOperationInvoker;
  1293. rpc.DisposeParameters(manualInvoker != null && manualInvoker.OwnsFormatter); //Dispose all input/output/return parameters
  1294. if (rpc.FaultInfo.IsConsideredUnhandled)
  1295. {
  1296. if (!replyWasSent)
  1297. {
  1298. rpc.AbortRequestContext();
  1299. rpc.AbortChannel();
  1300. }
  1301. else
  1302. {
  1303. rpc.CloseRequestContext();
  1304. rpc.CloseChannel();
  1305. }
  1306. rpc.AbortInstanceContext();
  1307. }
  1308. else
  1309. {
  1310. if (rpc.RequestContextThrewOnReply)
  1311. {
  1312. rpc.AbortRequestContext();
  1313. }
  1314. else
  1315. {
  1316. rpc.CloseRequestContext();
  1317. }
  1318. }
  1319. if ((rpc.Reply != null) && (rpc.Reply != rpc.ReturnParameter))
  1320. {
  1321. try
  1322. {
  1323. rpc.Reply.Close();
  1324. }
  1325. catch (Exception e)
  1326. {
  1327. if (Fx.IsFatal(e))
  1328. {
  1329. throw;
  1330. }
  1331. this.error.HandleError(e);
  1332. }
  1333. }
  1334. if ((rpc.FaultInfo.Fault != null) && (rpc.FaultInfo.Fault.State != MessageState.Closed))
  1335. {
  1336. // maybe ProvideFault gave a Message, but then BeforeSendReply replaced it
  1337. // in that case, we need to close the one from ProvideFault
  1338. try
  1339. {
  1340. rpc.FaultInfo.Fault.Close();
  1341. }
  1342. catch (Exception e)
  1343. {
  1344. if (Fx.IsFatal(e))
  1345. {
  1346. throw;
  1347. }
  1348. this.error.HandleError(e);
  1349. }
  1350. }
  1351. try
  1352. {
  1353. rpc.OperationContext.FireOperationCompleted();
  1354. }
  1355. #pragma warning suppress 56500 // covered by FxCOP
  1356. catch (Exception e)
  1357. {
  1358. if (Fx.IsFatal(e))
  1359. {
  1360. throw;
  1361. }
  1362. throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
  1363. }
  1364. this.instance.AfterReply(ref rpc, this.error);
  1365. if (rpc.SuccessfullyLockedInstance)
  1366. {
  1367. try
  1368. {
  1369. this.concurrency.UnlockInstance(ref rpc);
  1370. }
  1371. catch (Exception e)
  1372. {
  1373. if (Fx.IsFatal(e))
  1374. {
  1375. throw;
  1376. }
  1377. Fx.Assert("Exceptions should be caught by callee");
  1378. rpc.InstanceContext.FaultInternal();
  1379. this.error.HandleError(e);
  1380. }
  1381. }
  1382. if (this.terminate != null)
  1383. {
  1384. try
  1385. {
  1386. this.terminate.AfterReply(ref rpc);
  1387. }
  1388. catch (Exception e)
  1389. {
  1390. if (Fx.IsFatal(e))
  1391. {
  1392. throw;
  1393. }
  1394. this.error.HandleError(e);
  1395. }
  1396. }
  1397. if (rpc.SuccessfullyIncrementedActivity)
  1398. {
  1399. try
  1400. {
  1401. rpc.Channel.DecrementActivity();
  1402. }
  1403. catch (Exception e)
  1404. {
  1405. if (Fx.IsFatal(e))
  1406. {
  1407. throw;
  1408. }
  1409. this.error.HandleError(e);
  1410. }
  1411. }
  1412. }
  1413. finally
  1414. {
  1415. if (rpc.MessageRpcOwnsInstanceContextThrottle && rpc.channelHandler.InstanceContextServiceThrottle != null)
  1416. {
  1417. rpc.channelHandler.InstanceContextServiceThrottle.DeactivateInstanceContext();
  1418. }
  1419. if (rpc.Activity != null && DiagnosticUtility.ShouldUseActivity)
  1420. {
  1421. rpc.Activity.Stop();
  1422. }
  1423. }
  1424. this.error.HandleError(ref rpc);
  1425. }
  1426. void ProcessMessageCleanupError(ref MessageRpc rpc)
  1427. {
  1428. this.error.HandleError(ref rpc);
  1429. }
  1430. void ResolveTransactionOutcome(ref MessageRpc rpc)
  1431. {
  1432. if (this.transaction != null)
  1433. {
  1434. try
  1435. {
  1436. bool hadError = (rpc.Error != null);
  1437. try
  1438. {
  1439. this.transaction.ResolveOutcome(ref rpc);
  1440. }
  1441. catch (FaultException e)
  1442. {
  1443. if (rpc.Error == null)
  1444. {
  1445. rpc.Error = e;
  1446. }
  1447. }
  1448. finally
  1449. {
  1450. if (!hadError && rpc.Error != null)
  1451. {
  1452. this.error.ProvideMessageFault(ref rpc);
  1453. this.PrepareAndAddressReply(ref rpc);
  1454. }
  1455. }
  1456. }
  1457. catch (Exception e)
  1458. {
  1459. if (Fx.IsFatal(e))
  1460. {
  1461. throw;
  1462. }
  1463. this.error.HandleError(e);
  1464. }
  1465. }
  1466. }
  1467. [Fx.Tag.SecurityNote(Critical = "Calls security critical method to set the ActivityId on the thread",
  1468. Safe = "Set the ActivityId only when MessageRpc is available")]
  1469. [SecuritySafeCritical]
  1470. void SetActivityIdOnThread(ref MessageRpc rpc)
  1471. {
  1472. if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && rpc.EventTraceActivity != null)
  1473. {
  1474. // Propogate the ActivityId to the service operation
  1475. EventTraceActivityHelper.SetOnThread(rpc.EventTraceActivity);
  1476. }
  1477. }
  1478. void TransferChannelFromPendingList(ref MessageRpc rpc)
  1479. {
  1480. if (rpc.Channel.IsPending)
  1481. {
  1482. rpc.Channel.IsPending = false;
  1483. ChannelDispatcher channelDispatcher = rpc.Channel.ChannelDispatcher;
  1484. IInstanceContextProvider provider = this.instance.InstanceContextProvider;
  1485. if (!InstanceContextProviderBase.IsProviderSessionful(provider) &&
  1486. !InstanceContextProviderBase.IsProviderSingleton(provider))
  1487. {
  1488. IChannel proxy = rpc.Channel.Proxy as IChannel;
  1489. if (!rpc.InstanceContext.IncomingChannels.Contains(proxy))
  1490. {
  1491. channelDispatcher.Channels.Add(proxy);
  1492. }
  1493. }
  1494. channelDispatcher.PendingChannels.Remove(rpc.Channel.Binder.Channel);
  1495. }
  1496. }
  1497. interface IDemuxer
  1498. {
  1499. DispatchOperationRuntime GetOperation(ref Message request);
  1500. }
  1501. class ActionDemuxer : IDemuxer
  1502. {
  1503. HybridDictionary map;
  1504. DispatchOperationRuntime unhandled;
  1505. internal ActionDemuxer()
  1506. {
  1507. this.map = new HybridDictionary();
  1508. }
  1509. internal void Add(string action, DispatchOperationRuntime operation)
  1510. {
  1511. if (map.Contains(action))
  1512. {
  1513. DispatchOperationRuntime existingOperation = (DispatchOperationRuntime)map[action];
  1514. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxActionDemuxerDuplicate, existingOperation.Name, operation.Name, action)));
  1515. }
  1516. this.map.Add(action, operation);
  1517. }
  1518. internal void SetUnhandled(DispatchOperationRuntime operation)
  1519. {
  1520. this.unhandled = operation;
  1521. }
  1522. public DispatchOperationRuntime GetOperation(ref Message request)
  1523. {
  1524. string action = request.Headers.Action;
  1525. if (action == null)
  1526. {
  1527. action = MessageHeaders.WildcardAction;
  1528. }
  1529. DispatchOperationRuntime operation = (DispatchOperationRuntime)this.map[action];
  1530. if (operation != null)
  1531. {
  1532. return operation;
  1533. }
  1534. return this.unhandled;
  1535. }
  1536. }
  1537. class CustomDemuxer : IDemuxer
  1538. {
  1539. Dictionary<string, DispatchOperationRuntime> map;
  1540. IDispatchOperationSelector selector;
  1541. DispatchOperationRuntime unhandled;
  1542. internal CustomDemuxer(IDispatchOperationSelector selector)
  1543. {
  1544. this.selector = selector;
  1545. this.map = new Dictionary<string, DispatchOperationRuntime>();
  1546. }
  1547. internal void Add(string name, DispatchOperationRuntime operation)
  1548. {
  1549. this.map.Add(name, operation);
  1550. }
  1551. internal void SetUnhandled(DispatchOperationRuntime operation)
  1552. {
  1553. this.unhandled = operation;
  1554. }
  1555. public DispatchOperationRuntime GetOperation(ref Message request)
  1556. {
  1557. string operationName = this.selector.SelectOperation(ref request);
  1558. DispatchOperationRuntime operation = null;
  1559. if (this.map.TryGetValue(operationName, out operation))
  1560. {
  1561. return operation;
  1562. }
  1563. else
  1564. {
  1565. return this.unhandled;
  1566. }
  1567. }
  1568. }
  1569. class RpcCorrelationCallbackMessageProperty : CorrelationCallbackMessageProperty
  1570. {
  1571. CorrelationCallbackMessageProperty innerCallback;
  1572. MessageRpc rpc;
  1573. ImmutableDispatchRuntime runtime;
  1574. TransactionScope scope;
  1575. // This constructor should be used when creating the RPCCorrelationMessageproperty the first time
  1576. // Here we copy the data & the needed data from the original callback
  1577. public RpcCorrelationCallbackMessageProperty(CorrelationCallbackMessageProperty innerCallback,
  1578. ImmutableDispatchRuntime runtime, ref MessageRpc rpc)
  1579. : base(innerCallback)
  1580. {
  1581. this.innerCallback = innerCallback;
  1582. this.runtime = runtime;
  1583. this.rpc = rpc;
  1584. }
  1585. // This constructor should be used when we are making a copy from the already initialized RPCCorrelationCallbackMessageProperty
  1586. public RpcCorrelationCallbackMessageProperty(RpcCorrelationCallbackMessageProperty rpcCallbackMessageProperty)
  1587. : base(rpcCallbackMessageProperty)
  1588. {
  1589. this.innerCallback = rpcCallbackMessageProperty.innerCallback;
  1590. this.runtime = rpcCallbackMessageProperty.runtime;
  1591. this.rpc = rpcCallbackMessageProperty.rpc;
  1592. }
  1593. public override IMessageProperty CreateCopy()
  1594. {
  1595. return new RpcCorrelationCallbackMessageProperty(this);
  1596. }
  1597. protected override IAsyncResult OnBeginFinalizeCorrelation(Message message, TimeSpan timeout,
  1598. AsyncCallback callback, object state)
  1599. {
  1600. bool success = false;
  1601. this.Enter();
  1602. try
  1603. {
  1604. IAsyncResult result = this.innerCallback.BeginFinalizeCorrelation(message, timeout, callback, state);
  1605. success = true;
  1606. return result;
  1607. }
  1608. finally
  1609. {
  1610. this.Leave(success);
  1611. }
  1612. }
  1613. protected override Message OnEndFinalizeCorrelation(IAsyncResult result)
  1614. {
  1615. bool success = false;
  1616. this.Enter();
  1617. try
  1618. {
  1619. Message message = this.innerCallback.EndFinalizeCorrelation(result);
  1620. success = true;
  1621. return message;
  1622. }
  1623. finally
  1624. {
  1625. this.Leave(success);
  1626. this.CompleteTransaction();
  1627. }
  1628. }
  1629. protected override Message OnFinalizeCorrelation(Message message, TimeSpan timeout)
  1630. {
  1631. bool success = false;
  1632. this.Enter();
  1633. try
  1634. {
  1635. Message newMessage = this.innerCallback.FinalizeCorrelation(message, timeout);
  1636. success = true;
  1637. return newMessage;
  1638. }
  1639. finally
  1640. {
  1641. this.Leave(success);
  1642. this.CompleteTransaction();
  1643. }
  1644. }
  1645. void CompleteTransaction()
  1646. {
  1647. this.runtime.ResolveTransactionOutcome(ref this.rpc);
  1648. }
  1649. void Enter()
  1650. {
  1651. if (this.rpc.transaction != null && this.rpc.transaction.Current != null)
  1652. {
  1653. this.scope = new TransactionScope(this.rpc.transaction.Current);
  1654. }
  1655. }
  1656. void Leave(bool complete)
  1657. {
  1658. if (this.scope != null)
  1659. {
  1660. if (complete)
  1661. {
  1662. scope.Complete();
  1663. }
  1664. scope.Dispose();
  1665. this.scope = null;
  1666. }
  1667. }
  1668. }
  1669. }
  1670. }