1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
|
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using System.Text;
using System.Threading;
using System.Transactions;
enum MsmqTransactionMode
{
None, // do not use a transaction
Single, // create a single message transaction
CurrentOrSingle, // use Transaction.Current if set, Single otherwise
CurrentOrNone, // use Transaction.Current if set, None otherwise
CurrentOrThrow, // use Transaction.Current if set, throw otherwise
}
class MsmqQueue : IDisposable
{
MsmqQueueHandle handle;
bool isBoundToCompletionPort;
bool isAsyncEnabled;
protected int shareMode;
protected string formatName;
protected int accessMode;
public MsmqQueue(string formatName, int accessMode)
{
this.formatName = formatName;
this.accessMode = accessMode;
this.shareMode = UnsafeNativeMethods.MQ_DENY_NONE;
}
public MsmqQueue(string formatName, int accessMode, int shareMode)
{
this.formatName = formatName;
this.accessMode = accessMode;
this.shareMode = shareMode;
}
protected object ThisLock
{
get { return this; }
}
public string FormatName
{
get { return this.formatName; }
}
public override string ToString()
{
return this.formatName;
}
public void Dispose()
{
lock (this.ThisLock)
{
CloseQueue();
}
}
internal void EnsureOpen()
{
GetHandle();
}
MsmqQueueHandle GetHandleForAsync(out bool useCompletionPort)
{
lock (this.ThisLock)
{
if (this.handle == null)
{
this.handle = OpenQueue();
}
if (!this.isAsyncEnabled)
{
if (IsCompletionPortSupported(this.handle))
{
ThreadPool.BindHandle(this.handle);
this.isBoundToCompletionPort = true;
}
this.isAsyncEnabled = true;
}
useCompletionPort = this.isBoundToCompletionPort;
return this.handle;
}
}
protected MsmqQueueHandle GetHandle()
{
lock (this.ThisLock)
{
if (this.handle == null)
{
this.handle = OpenQueue();
}
return this.handle;
}
}
static bool IsCompletionPortSupported(MsmqQueueHandle handle)
{
// if it's a kernel handle, then it supports completion ports
int flags;
#pragma warning suppress 56523
return UnsafeNativeMethods.GetHandleInformation(handle, out flags) != 0;
}
[ResourceConsumption(ResourceScope.Machine)]
internal virtual MsmqQueueHandle OpenQueue()
{
MsmqQueueHandle handle;
int error = UnsafeNativeMethods.MQOpenQueue(this.formatName, this.accessMode,
this.shareMode, out handle);
if (error != 0)
{
Utility.CloseInvalidOutSafeHandle(handle);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqOpenError, MsmqError.GetErrorString(error)), error));
}
MsmqDiagnostics.QueueOpened(this.formatName);
return handle;
}
public virtual void CloseQueue()
{
if (this.handle != null)
{
CloseQueue(this.handle);
this.handle = null;
this.isBoundToCompletionPort = false;
this.isAsyncEnabled = false;
MsmqDiagnostics.QueueClosed(this.formatName);
}
}
void CloseQueue(MsmqQueueHandle handle)
{
handle.Dispose();
}
protected void HandleIsStale(MsmqQueueHandle handle)
{
lock (this.ThisLock)
{
if (this.handle == handle)
{
CloseQueue();
}
}
}
public static void GetMsmqInformation(ref Version version, ref bool activeDirectoryEnabled)
{
PrivateComputerProperties properties = new PrivateComputerProperties();
using (properties)
{
IntPtr nativePropertiesPointer = properties.Pin();
try
{
int error = UnsafeNativeMethods.MQGetPrivateComputerInformation(null,
nativePropertiesPointer);
if (error != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(
SR.MsmqGetPrivateComputerInformationError, MsmqError.GetErrorString(error)), error));
}
int packedVersion = properties.Version.Value;
version = new Version(
packedVersion >> 24,
(packedVersion & 0x00FF0000) >> 16,
packedVersion & 0xFFFF);
activeDirectoryEnabled = properties.ActiveDirectory.Value;
}
finally
{
properties.Unpin();
}
}
}
public static bool IsReadable(string formatName, out MsmqException ex)
{
return SupportsAccessMode(formatName, UnsafeNativeMethods.MQ_RECEIVE_ACCESS, out ex);
}
public static bool IsWriteable(string formatName)
{
MsmqException ex;
return SupportsAccessMode(formatName, UnsafeNativeMethods.MQ_SEND_ACCESS, out ex);
}
public static bool IsMoveable(string formatName)
{
MsmqException ex;
return SupportsAccessMode(formatName, UnsafeNativeMethods.MQ_MOVE_ACCESS, out ex);
}
internal static bool IsQueueOpenable(string formatName, int accessMode, int shareMode, out int error)
{
MsmqQueueHandle handle;
error = UnsafeNativeMethods.MQOpenQueue(formatName, accessMode,
shareMode, out handle);
if (error != 0)
{
Utility.CloseInvalidOutSafeHandle(handle);
return false;
}
handle.Dispose();
return true;
}
static bool SupportsAccessMode(string formatName, int accessType, out MsmqException msmqException)
{
msmqException = null;
try
{
using (MsmqQueue msmqQueue = new MsmqQueue(formatName, accessType))
{
msmqQueue.GetHandle();
}
}
catch (Exception ex)
{
msmqException = ex as MsmqException;
if (null != msmqException)
{
return false;
}
throw;
}
return true;
}
public static bool TryGetIsTransactional(string formatName, out bool isTransactional)
{
using (QueueTransactionProperties properties = new QueueTransactionProperties())
{
IntPtr nativePropertiesPointer = properties.Pin();
try
{
if (UnsafeNativeMethods.MQGetQueueProperties(formatName,
nativePropertiesPointer) == 0)
{
isTransactional = properties.Transaction.Value != UnsafeNativeMethods.MQ_TRANSACTIONAL_NONE;
return true;
}
else
{
isTransactional = false;
MsmqDiagnostics.QueueTransactionalStatusUnknown(formatName);
return false;
}
}
finally
{
properties.Unpin();
}
}
}
protected static bool IsErrorDueToStaleHandle(int error)
{
switch (error)
{
case UnsafeNativeMethods.MQ_ERROR_STALE_HANDLE:
case UnsafeNativeMethods.MQ_ERROR_INVALID_HANDLE:
case UnsafeNativeMethods.MQ_ERROR_INVALID_PARAMETER:
case UnsafeNativeMethods.MQ_ERROR_QUEUE_DELETED:
return true;
default:
return false;
}
}
protected static bool IsReceiveErrorDueToInsufficientBuffer(int error)
{
switch (error)
{
case UnsafeNativeMethods.MQ_ERROR_BUFFER_OVERFLOW:
case UnsafeNativeMethods.MQ_INFORMATION_FORMATNAME_BUFFER_TOO_SMALL:
case UnsafeNativeMethods.MQ_ERROR_FORMATNAME_BUFFER_TOO_SMALL:
case UnsafeNativeMethods.MQ_ERROR_SENDERID_BUFFER_TOO_SMALL:
case UnsafeNativeMethods.MQ_ERROR_SECURITY_DESCRIPTOR_TOO_SMALL:
case UnsafeNativeMethods.MQ_ERROR_USER_BUFFER_TOO_SMALL:
case UnsafeNativeMethods.MQ_ERROR_SENDER_CERT_BUFFER_TOO_SMALL:
case UnsafeNativeMethods.MQ_ERROR_RESULT_BUFFER_TOO_SMALL:
case UnsafeNativeMethods.MQ_ERROR_LABEL_BUFFER_TOO_SMALL:
case UnsafeNativeMethods.MQ_ERROR_SYMM_KEY_BUFFER_TOO_SMALL:
case UnsafeNativeMethods.MQ_ERROR_SIGNATURE_BUFFER_TOO_SMALL:
case UnsafeNativeMethods.MQ_ERROR_PROV_NAME_BUFFER_TOO_SMALL:
return true;
default:
return false;
}
}
public void MarkMessageRejected(long lookupId)
{
MsmqQueueHandle handle = GetHandle();
int error = 0;
try
{
error = UnsafeNativeMethods.MQMarkMessageRejected(handle, lookupId);
}
catch (ObjectDisposedException ex)
{
MsmqDiagnostics.ExpectedException(ex);
}
if (error != 0)
{
if (IsErrorDueToStaleHandle(error))
{
HandleIsStale(handle);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqSendError, MsmqError.GetErrorString(error)), error));
}
}
int TryMoveMessageDtcTransacted(long lookupId, MsmqQueueHandle sourceQueueHandle, MsmqQueueHandle destinationQueueHandle, MsmqTransactionMode transactionMode)
{
IDtcTransaction dtcTransaction = GetNativeTransaction(transactionMode);
if (dtcTransaction != null)
{
try
{
return UnsafeNativeMethods.MQMoveMessage(sourceQueueHandle, destinationQueueHandle,
lookupId, dtcTransaction);
}
finally
{
Marshal.ReleaseComObject(dtcTransaction);
}
}
else
{
return UnsafeNativeMethods.MQMoveMessage(sourceQueueHandle, destinationQueueHandle,
lookupId, (IntPtr)GetTransactionConstant(transactionMode));
}
}
public MoveReceiveResult TryMoveMessage(long lookupId, MsmqQueue destinationQueue, MsmqTransactionMode transactionMode)
{
MsmqQueueHandle sourceQueueHandle = GetHandle();
MsmqQueueHandle destinationQueueHandle = destinationQueue.GetHandle();
int error;
try
{
if (RequiresDtcTransaction(transactionMode))
{
error = TryMoveMessageDtcTransacted(lookupId, sourceQueueHandle, destinationQueueHandle, transactionMode);
}
else
{
error = UnsafeNativeMethods.MQMoveMessage(sourceQueueHandle, destinationQueueHandle,
lookupId, (IntPtr)GetTransactionConstant(transactionMode));
}
}
catch (ObjectDisposedException ex)
{
MsmqDiagnostics.ExpectedException(ex);
return MoveReceiveResult.Succeeded;
}
if (error != 0)
{
if (error == UnsafeNativeMethods.MQ_ERROR_MESSAGE_NOT_FOUND)
return MoveReceiveResult.MessageNotFound;
else if (error == UnsafeNativeMethods.MQ_ERROR_MESSAGE_LOCKED_UNDER_TRANSACTION)
return MoveReceiveResult.MessageLockedUnderTransaction;
else if (IsErrorDueToStaleHandle(error))
{
HandleIsStale(sourceQueueHandle);
destinationQueue.HandleIsStale(destinationQueueHandle);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqSendError,
MsmqError.GetErrorString(error)), error));
}
return MoveReceiveResult.Succeeded;
}
public virtual ReceiveResult TryReceive(NativeMsmqMessage message, TimeSpan timeout, MsmqTransactionMode transactionMode)
{
return TryReceiveInternal(message, timeout, transactionMode, UnsafeNativeMethods.MQ_ACTION_RECEIVE);
}
ReceiveResult TryReceiveInternal(NativeMsmqMessage message, TimeSpan timeout, MsmqTransactionMode transactionMode, int action)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
MsmqQueueHandle handle = GetHandle();
while (true)
{
int error = ReceiveCore(handle, message, timeoutHelper.RemainingTime(), transactionMode, action);
if (0 == error)
return ReceiveResult.MessageReceived;
if (IsReceiveErrorDueToInsufficientBuffer(error))
{
message.GrowBuffers();
continue;
}
else if (error == UnsafeNativeMethods.MQ_ERROR_IO_TIMEOUT)
{
return ReceiveResult.Timeout;
}
else if (error == UnsafeNativeMethods.MQ_ERROR_OPERATION_CANCELLED)
{
return ReceiveResult.OperationCancelled;
}
else if (error == UnsafeNativeMethods.MQ_ERROR_INVALID_HANDLE)
{
// should happen only if racing with Close
return ReceiveResult.OperationCancelled;
}
else if (IsErrorDueToStaleHandle(error))
{
HandleIsStale(handle);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqReceiveError, MsmqError.GetErrorString(error)), error));
}
}
public MoveReceiveResult TryReceiveByLookupId(long lookupId, NativeMsmqMessage message, MsmqTransactionMode transactionMode)
{
return this.TryReceiveByLookupId(lookupId, message, transactionMode, UnsafeNativeMethods.MQ_LOOKUP_RECEIVE_CURRENT);
}
public MoveReceiveResult TryReceiveByLookupId(long lookupId, NativeMsmqMessage message, MsmqTransactionMode transactionMode, int action)
{
MsmqQueueHandle handle = GetHandle();
int error = 0;
while (true)
{
try
{
error = ReceiveByLookupIdCore(handle, lookupId, message, transactionMode, action);
}
catch (ObjectDisposedException ex)
{
// ---- with Close
MsmqDiagnostics.ExpectedException(ex);
return MoveReceiveResult.Succeeded;
}
if (0 == error)
{
return MoveReceiveResult.Succeeded;
}
if (IsReceiveErrorDueToInsufficientBuffer(error))
{
message.GrowBuffers();
continue;
}
else if (UnsafeNativeMethods.MQ_ERROR_MESSAGE_NOT_FOUND == error)
{
return MoveReceiveResult.MessageNotFound;
}
else if (UnsafeNativeMethods.MQ_ERROR_MESSAGE_LOCKED_UNDER_TRANSACTION == error)
{
return MoveReceiveResult.MessageLockedUnderTransaction;
}
else if (IsErrorDueToStaleHandle(error))
{
HandleIsStale(handle);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqReceiveError, MsmqError.GetErrorString(error)), error));
}
}
[PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
protected unsafe int ReceiveByLookupIdCoreDtcTransacted(MsmqQueueHandle handle, long lookupId, NativeMsmqMessage message, MsmqTransactionMode transactionMode, int action)
{
IDtcTransaction dtcTransaction = GetNativeTransaction(transactionMode);
IntPtr nativePropertiesPointer = message.Pin();
try
{
if (dtcTransaction != null)
{
try
{
return UnsafeNativeMethods.MQReceiveMessageByLookupId(handle, lookupId, action, nativePropertiesPointer, null, IntPtr.Zero, dtcTransaction);
}
finally
{
Marshal.ReleaseComObject(dtcTransaction);
}
}
else
{
return UnsafeNativeMethods.MQReceiveMessageByLookupId(handle, lookupId, action, nativePropertiesPointer, null, IntPtr.Zero, (IntPtr)GetTransactionConstant(transactionMode));
}
}
finally
{
message.Unpin();
}
}
[PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
unsafe int ReceiveByLookupIdCore(MsmqQueueHandle handle, long lookupId, NativeMsmqMessage message, MsmqTransactionMode transactionMode, int action)
{
if (RequiresDtcTransaction(transactionMode))
{
return ReceiveByLookupIdCoreDtcTransacted(handle, lookupId, message, transactionMode, action);
}
else
{
IntPtr nativePropertiesPointer = message.Pin();
try
{
return UnsafeNativeMethods.MQReceiveMessageByLookupId(handle, lookupId, action, nativePropertiesPointer, null, IntPtr.Zero, (IntPtr)GetTransactionConstant(transactionMode));
}
finally
{
message.Unpin();
}
}
}
[PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
unsafe int ReceiveCoreDtcTransacted(MsmqQueueHandle handle, NativeMsmqMessage message, TimeSpan timeout, MsmqTransactionMode transactionMode, int action)
{
IDtcTransaction dtcTransaction = GetNativeTransaction(transactionMode);
int timeoutInMilliseconds = TimeoutHelper.ToMilliseconds(timeout);
IntPtr nativePropertiesPointer = message.Pin();
try
{
if (dtcTransaction != null)
{
try
{
return UnsafeNativeMethods.MQReceiveMessage(handle.DangerousGetHandle(), timeoutInMilliseconds,
action, nativePropertiesPointer, null, IntPtr.Zero, IntPtr.Zero, dtcTransaction);
}
finally
{
Marshal.ReleaseComObject(dtcTransaction);
}
}
else
{
return UnsafeNativeMethods.MQReceiveMessage(handle.DangerousGetHandle(), timeoutInMilliseconds,
action, nativePropertiesPointer, null, IntPtr.Zero, IntPtr.Zero, (IntPtr)GetTransactionConstant(transactionMode));
}
}
finally
{
message.Unpin();
}
}
[PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
unsafe int ReceiveCore(MsmqQueueHandle handle, NativeMsmqMessage message, TimeSpan timeout, MsmqTransactionMode transactionMode, int action)
{
if (RequiresDtcTransaction(transactionMode))
{
return ReceiveCoreDtcTransacted(handle, message, timeout, transactionMode, action);
}
else
{
int timeoutInMilliseconds = TimeoutHelper.ToMilliseconds(timeout);
IntPtr nativePropertiesPointer = message.Pin();
try
{
return UnsafeNativeMethods.MQReceiveMessage(handle.DangerousGetHandle(), timeoutInMilliseconds,
action, nativePropertiesPointer, null, IntPtr.Zero, IntPtr.Zero, (IntPtr)GetTransactionConstant(transactionMode));
}
finally
{
message.Unpin();
}
}
}
protected IDtcTransaction GetNativeTransaction(MsmqTransactionMode transactionMode)
{
Transaction transaction = Transaction.Current;
if (transaction != null)
{
return TransactionInterop.GetDtcTransaction(transaction);
}
if (transactionMode == MsmqTransactionMode.CurrentOrThrow)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MsmqTransactionRequired)));
}
return null;
}
public ReceiveResult TryPeek(NativeMsmqMessage message, TimeSpan timeout)
{
return TryReceiveInternal(message, timeout, MsmqTransactionMode.None,
UnsafeNativeMethods.MQ_ACTION_PEEK_CURRENT);
}
bool RequiresDtcTransaction(MsmqTransactionMode transactionMode)
{
switch (transactionMode)
{
case MsmqTransactionMode.None:
case MsmqTransactionMode.Single:
return false;
case MsmqTransactionMode.CurrentOrSingle:
case MsmqTransactionMode.CurrentOrNone:
case MsmqTransactionMode.CurrentOrThrow:
return true;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("transactionMode"));
}
}
int GetTransactionConstant(MsmqTransactionMode transactionMode)
{
switch (transactionMode)
{
case MsmqTransactionMode.CurrentOrNone:
case MsmqTransactionMode.None:
return UnsafeNativeMethods.MQ_NO_TRANSACTION;
case MsmqTransactionMode.Single:
case MsmqTransactionMode.CurrentOrSingle:
return UnsafeNativeMethods.MQ_SINGLE_MESSAGE;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("transactionMode"));
}
}
int SendDtcTransacted(NativeMsmqMessage message, MsmqTransactionMode transactionMode)
{
IDtcTransaction dtcTransaction = GetNativeTransaction(transactionMode);
MsmqQueueHandle handle = GetHandle();
IntPtr nativePropertiesPointer = message.Pin();
try
{
if (dtcTransaction != null)
{
try
{
return UnsafeNativeMethods.MQSendMessage(handle, nativePropertiesPointer,
dtcTransaction);
}
finally
{
Marshal.ReleaseComObject(dtcTransaction);
}
}
else
{
return UnsafeNativeMethods.MQSendMessage(handle, nativePropertiesPointer,
(IntPtr)GetTransactionConstant(transactionMode));
}
}
finally
{
message.Unpin();
}
}
public void Send(NativeMsmqMessage message, MsmqTransactionMode transactionMode)
{
int error = 0;
if (RequiresDtcTransaction(transactionMode))
{
error = SendDtcTransacted(message, transactionMode);
}
else
{
MsmqQueueHandle handle = GetHandle();
IntPtr nativePropertiesPointer = message.Pin();
try
{
error = UnsafeNativeMethods.MQSendMessage(handle, nativePropertiesPointer,
(IntPtr)GetTransactionConstant(transactionMode));
}
finally
{
message.Unpin();
}
}
if (error != 0)
{
if (IsErrorDueToStaleHandle(error))
{
HandleIsStale(handle);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqSendError, MsmqError.GetErrorString(error)), error));
}
}
[PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
unsafe int ReceiveCoreAsync(MsmqQueueHandle handle, IntPtr nativePropertiesPointer, TimeSpan timeout,
int action, NativeOverlapped* nativeOverlapped,
UnsafeNativeMethods.MQReceiveCallback receiveCallback)
{
int timeoutInMilliseconds = TimeoutHelper.ToMilliseconds(timeout);
return UnsafeNativeMethods.MQReceiveMessage(handle, timeoutInMilliseconds, action,
nativePropertiesPointer, nativeOverlapped, receiveCallback,
IntPtr.Zero, (IntPtr)UnsafeNativeMethods.MQ_NO_TRANSACTION);
}
public IAsyncResult BeginTryReceive(NativeMsmqMessage message, TimeSpan timeout,
AsyncCallback callback, object state)
{
return new TryReceiveAsyncResult(this, message, timeout,
UnsafeNativeMethods.MQ_ACTION_RECEIVE, callback, state);
}
public ReceiveResult EndTryReceive(IAsyncResult result)
{
return TryReceiveAsyncResult.End(result);
}
public IAsyncResult BeginPeek(NativeMsmqMessage message, TimeSpan timeout,
AsyncCallback callback, object state)
{
return new TryReceiveAsyncResult(this, message, timeout,
UnsafeNativeMethods.MQ_ACTION_PEEK_CURRENT, callback, state);
}
public ReceiveResult EndPeek(IAsyncResult result)
{
return TryReceiveAsyncResult.End(result);
}
class TryReceiveAsyncResult : AsyncResult
{
MsmqQueue msmqQueue;
int action;
TimeoutHelper timeoutHelper;
NativeMsmqMessage message;
unsafe NativeOverlapped* nativeOverlapped = null;
MsmqQueueHandle handle;
ReceiveResult receiveResult;
unsafe static IOCompletionCallback onPortedCompletion = Fx.ThunkCallback(new IOCompletionCallback(OnPortedCompletion));
unsafe static UnsafeNativeMethods.MQReceiveCallback onNonPortedCompletion;
[PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
public TryReceiveAsyncResult(MsmqQueue msmqQueue, NativeMsmqMessage message, TimeSpan timeout,
int action, AsyncCallback callback, object state)
: base(callback, state)
{
this.msmqQueue = msmqQueue;
this.message = message;
this.action = action;
this.timeoutHelper = new TimeoutHelper(timeout);
StartReceive(true);
}
[PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
unsafe ~TryReceiveAsyncResult()
{
if (null != this.nativeOverlapped
&& ! Environment.HasShutdownStarted
&& ! AppDomain.CurrentDomain.IsFinalizingForUnload())
{
Overlapped.Free(this.nativeOverlapped);
}
}
[PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
unsafe void StartReceive(bool synchronously)
{
bool useCompletionPort;
try
{
this.handle = this.msmqQueue.GetHandleForAsync(out useCompletionPort);
}
catch (MsmqException ex)
{
OnCompletion(ex.ErrorCode, synchronously);
return;
}
if (null != nativeOverlapped)
{
Fx.Assert("---- in StartReceive");
}
IntPtr nativePropertiesPointer = this.message.Pin();
nativeOverlapped = new Overlapped(0, 0, IntPtr.Zero, this).UnsafePack(onPortedCompletion, this.message.GetBuffersForAsync());
int error;
try
{
if (useCompletionPort)
{
error = msmqQueue.ReceiveCoreAsync(this.handle, nativePropertiesPointer, this.timeoutHelper.RemainingTime(),
this.action, nativeOverlapped, null);
}
else
{
if (onNonPortedCompletion == null)
{
onNonPortedCompletion = new UnsafeNativeMethods.MQReceiveCallback(OnNonPortedCompletion);
}
error = msmqQueue.ReceiveCoreAsync(this.handle, nativePropertiesPointer, this.timeoutHelper.RemainingTime(),
this.action, nativeOverlapped, onNonPortedCompletion);
}
}
catch (ObjectDisposedException ex)
{
// if Close ----s with the async Receive, it is possible that SafeHandle will throw ObjectDisposedException
// the behavior should be same as if operation was just cancelled (the channel will return no message)
MsmqDiagnostics.ExpectedException(ex);
error = UnsafeNativeMethods.MQ_ERROR_OPERATION_CANCELLED;
}
if (error != 0)
{
if (error != UnsafeNativeMethods.MQ_INFORMATION_OPERATION_PENDING)
{
Overlapped.Free(nativeOverlapped);
nativeOverlapped = null;
GC.SuppressFinalize(this);
OnCompletion(error, synchronously);
}
}
}
[PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
unsafe static void OnNonPortedCompletion(int error, IntPtr handle, int timeout,
int action, IntPtr props, NativeOverlapped* nativeOverlapped, IntPtr cursor)
{
ThreadPool.UnsafeQueueNativeOverlapped(nativeOverlapped);
}
[PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
unsafe static void OnPortedCompletion(uint error, uint numBytes, NativeOverlapped* nativeOverlapped)
{
Overlapped overlapped = Overlapped.Unpack(nativeOverlapped);
TryReceiveAsyncResult result = (TryReceiveAsyncResult)overlapped.AsyncResult;
if (error != 0)
{
error = (uint)UnsafeNativeMethods.MQGetOverlappedResult(nativeOverlapped);
}
Overlapped.Free(nativeOverlapped);
result.nativeOverlapped = null;
#pragma warning suppress 56508 // Suppression justified. Presharp warning concerns different scenario.
GC.SuppressFinalize(result);
result.OnCompletion((int)error, false);
}
void OnCompletion(int error, bool completedSynchronously)
{
Exception completionException = null;
this.receiveResult = ReceiveResult.MessageReceived;
try
{
if (error != 0)
{
if (error == UnsafeNativeMethods.MQ_ERROR_IO_TIMEOUT)
{
this.receiveResult = ReceiveResult.Timeout;
}
else if (error == UnsafeNativeMethods.MQ_ERROR_OPERATION_CANCELLED)
{
this.receiveResult = ReceiveResult.OperationCancelled;
}
else
{
if (IsReceiveErrorDueToInsufficientBuffer(error))
{
this.message.Unpin();
message.GrowBuffers();
StartReceive(completedSynchronously);
return;
}
else if (IsErrorDueToStaleHandle(error))
{
this.msmqQueue.HandleIsStale(this.handle);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqReceiveError, MsmqError.GetErrorString(error)), error));
}
}
}
catch (Exception e)
{
if (e is NullReferenceException || e is SEHException)
throw;
completionException = e;
}
this.message.Unpin();
Complete(completedSynchronously, completionException);
}
public static ReceiveResult End(IAsyncResult result)
{
TryReceiveAsyncResult thisPtr = AsyncResult.End<TryReceiveAsyncResult>(result);
return thisPtr.receiveResult;
}
}
class QueueTransactionProperties : NativeMsmqMessage
{
ByteProperty transaction;
public QueueTransactionProperties() : base(1)
{
this.transaction = new ByteProperty(this, UnsafeNativeMethods.PROPID_Q_TRANSACTION);
}
public ByteProperty Transaction
{
get { return this.transaction; }
}
}
class PrivateComputerProperties : NativeMsmqMessage
{
IntProperty version;
BooleanProperty activeDirectory;
public PrivateComputerProperties()
: base(2)
{
this.version = new IntProperty(this, UnsafeNativeMethods.PROPID_PC_VERSION);
this.activeDirectory = new BooleanProperty(this, UnsafeNativeMethods.PROPID_PC_DS_ENABLED);
}
public IntProperty Version
{
get { return this.version; }
}
public BooleanProperty ActiveDirectory
{
get { return this.activeDirectory; }
}
}
public enum MoveReceiveResult
{
Unknown,
Succeeded,
MessageNotFound,
MessageLockedUnderTransaction
}
internal enum ReceiveResult
{
Unknown,
MessageReceived,
Timeout,
OperationCancelled
}
}
static class MsmqFormatName
{
const string systemMessagingLabelPrefix = "LABEL:";
const string systemMessagingFormatNamePrefix = "FORMATNAME:";
public static string ToSystemMessagingQueueName(string formatName)
{
return systemMessagingFormatNamePrefix + formatName;
}
public static string FromQueuePath(string queuePath)
{
int len = 256;
StringBuilder buffer = new StringBuilder(len);
int error = UnsafeNativeMethods.MQPathNameToFormatName(queuePath, buffer, ref len);
if (UnsafeNativeMethods.MQ_ERROR_FORMATNAME_BUFFER_TOO_SMALL == error)
{
buffer = new StringBuilder(len);
error = UnsafeNativeMethods.MQPathNameToFormatName(queuePath, buffer, ref len);
}
if (0 != error)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new MsmqException(SR.GetString(SR.MsmqPathLookupError, queuePath, MsmqError.GetErrorString(error)), error));
}
return buffer.ToString();
}
}
}
|