public static AmqpMap GetRuleDescriptionMap(RuleDescription description) { var ruleDescriptionMap = new AmqpMap(); switch (description.Filter) { case SqlFilter sqlFilter: var filterMap = GetSqlFilterMap(sqlFilter); ruleDescriptionMap[ManagementConstants.Properties.SqlFilter] = filterMap; break; case CorrelationFilter correlationFilter: var correlationFilterMap = GetCorrelationFilterMap(correlationFilter); ruleDescriptionMap[ManagementConstants.Properties.CorrelationFilter] = correlationFilterMap; break; default: throw new NotSupportedException( Resources.RuleFilterNotSupported.FormatForUser( description.Filter.GetType(), nameof(SqlFilter), nameof(CorrelationFilter))); } var amqpAction = GetRuleActionMap(description.Action as SqlRuleAction); ruleDescriptionMap[ManagementConstants.Properties.SqlRuleAction] = amqpAction; ruleDescriptionMap[ManagementConstants.Properties.RuleName] = description.Name; return(ruleDescriptionMap); }
static AmqpMap GetCorrelationFilterMap(CorrelationFilter correlationFilter) { var correlationFilterMap = new AmqpMap { [ManagementConstants.Properties.CorrelationId] = correlationFilter.CorrelationId, [ManagementConstants.Properties.MessageId] = correlationFilter.MessageId, [ManagementConstants.Properties.To] = correlationFilter.To, [ManagementConstants.Properties.ReplyTo] = correlationFilter.ReplyTo, [ManagementConstants.Properties.Label] = correlationFilter.Label, [ManagementConstants.Properties.SessionId] = correlationFilter.SessionId, [ManagementConstants.Properties.ReplyToSessionId] = correlationFilter.ReplyToSessionId, [ManagementConstants.Properties.ContentType] = correlationFilter.ContentType }; var propertiesMap = new AmqpMap(); foreach (var property in correlationFilter.Properties) { propertiesMap[new MapKey(property.Key)] = property.Value; } correlationFilterMap[ManagementConstants.Properties.CorrelationFilterProperties] = propertiesMap; return(correlationFilterMap); }
public static AmqpMap GetRuleDescriptionMap(RuleDescription description) { AmqpMap ruleDescriptionMap = new AmqpMap(); if (description.Filter is SqlFilter) { AmqpMap filterMap = GetSqlFilterMap(description.Filter as SqlFilter); ruleDescriptionMap[ManagementConstants.Properties.SqlFilter] = filterMap; } else if (description.Filter is CorrelationFilter) { AmqpMap correlationFilterMap = GetCorrelationFilterMap(description.Filter as CorrelationFilter); ruleDescriptionMap[ManagementConstants.Properties.CorrelationFilter] = correlationFilterMap; } else { throw new NotSupportedException( Resources.RuleFilterNotSupported.FormatForUser( description.Filter.GetType(), nameof(SqlFilter), nameof(CorrelationFilter))); } AmqpMap amqpAction = GetRuleActionMap(description.Action as SqlRuleAction); ruleDescriptionMap[ManagementConstants.Properties.SqlRuleAction] = amqpAction; return(ruleDescriptionMap); }
public static void ReadMapValue(ByteBuffer buffer, AmqpMap map, int size, int count) { for (; count > 0; count -= 2) { object key = AmqpEncoding.DecodeObject(buffer); object item = AmqpEncoding.DecodeObject(buffer); map[new MapKey(key)] = item; } }
static AmqpMap GetSqlFilterMap(SqlFilter sqlFilter) { var amqpFilterMap = new AmqpMap { [ManagementConstants.Properties.Expression] = sqlFilter.SqlExpression }; return(amqpFilterMap); }
public AmqpRequestMessage(string operation, TimeSpan timeout, string trackingId) { Map = new AmqpMap(); AmqpMessage = AmqpMessage.Create(new AmqpValue { Value = Map }); AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.Operation] = operation; AmqpMessage.ApplicationProperties.Map[ManagementConstants.Properties.ServerTimeout] = (uint)timeout.TotalMilliseconds; AmqpMessage.ApplicationProperties.Map[ManagementConstants.Properties.TrackingId] = trackingId ?? Guid.NewGuid().ToString(); }
static AmqpMap GetRuleActionMap(SqlRuleAction sqlRuleAction) { AmqpMap ruleActionMap = null; if (sqlRuleAction != null) { ruleActionMap = new AmqpMap { [ManagementConstants.Properties.Expression] = sqlRuleAction.SqlExpression }; } return(ruleActionMap); }
public static T DecodeMap <T>(ByteBuffer buffer) where T : RestrictedMap, new() { AmqpMap amqpMaps = MapEncoding.Decode(buffer, 0); T t = default(T); if (amqpMaps != null) { t = Activator.CreateInstance <T>(); t.SetMap(amqpMaps); } return(t); }
internal static T DecodeMap <T>(ByteBuffer buffer) where T : RestrictedMap, new() { AmqpMap map = MapEncoding.Decode(buffer, 0); T restrictedMap = null; if (map != null) { restrictedMap = new T(); restrictedMap.SetMap(map); } return(restrictedMap); }
public static int GetValueSize(AmqpMap value) { int size = 0; if (value.Count > 0) { foreach (KeyValuePair<MapKey, object> item in value) { size += AmqpEncoding.GetObjectEncodeSize(item.Key.Key); size += AmqpEncoding.GetObjectEncodeSize(item.Value); } } return size; }
public static AmqpMap Decode(ByteBuffer buffer, FormatCode formatCode) { if (formatCode == 0 && (formatCode = AmqpEncoding.ReadFormatCode(buffer)) == FormatCode.Null) { return null; } int size = 0; int count = 0; AmqpEncoding.ReadSizeAndCount(buffer, formatCode, FormatCode.Map8, FormatCode.Map32, out size, out count); AmqpMap map = new AmqpMap(); MapEncoding.ReadMapValue(buffer, map, size, count); return map; }
protected override async Task <long> OnScheduleMessageAsync(BrokeredMessage brokeredMessage) { // TODO: Ensure System.Transactions.Transaction.Current is null. Transactions are not supported by 1.0.0 version of dotnet core. using (AmqpMessage amqpMessage = AmqpMessageConverter.ClientGetMessage(brokeredMessage)) { var request = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.ScheduleMessageOperation, this.OperationTimeout, null); ArraySegment <byte>[] payload = amqpMessage.GetPayload(); BufferListStream buffer = new BufferListStream(payload); ArraySegment <byte> value = buffer.ReadBytes((int)buffer.Length); var entry = new AmqpMap(); { entry[ManagementConstants.Properties.Message] = value; entry[ManagementConstants.Properties.MessageId] = brokeredMessage.MessageId; if (!string.IsNullOrWhiteSpace(brokeredMessage.SessionId)) { entry[ManagementConstants.Properties.SessionId] = brokeredMessage.SessionId; } if (!string.IsNullOrWhiteSpace(brokeredMessage.PartitionKey)) { entry[ManagementConstants.Properties.PartitionKey] = brokeredMessage.PartitionKey; } } request.Map[ManagementConstants.Properties.Messages] = new List <AmqpMap> { entry }; IEnumerable <long> sequenceNumbers = null; var response = await this.ExecuteRequestResponseAsync(request); if (response.StatusCode == AmqpResponseStatusCode.OK) { sequenceNumbers = response.GetValue <long[]>(ManagementConstants.Properties.SequenceNumbers); } else { response.ToMessagingContractException(); } return(sequenceNumbers?.FirstOrDefault() ?? 0); } }
public static void Encode(AmqpMap value, ByteBuffer buffer) { if (value == null) { AmqpEncoding.EncodeNull(buffer); } else { int encodeWidth = MapEncoding.GetEncodeWidth(value); AmqpBitConverter.WriteUByte(buffer, encodeWidth == FixedWidth.UByte ? (byte)FormatCode.Map8 : (byte)FormatCode.Map32); int size = encodeWidth + value.ValueSize; MapEncoding.Encode(value, encodeWidth, size, buffer); } }
public static object FromAmqp(SerializableType serializable, object value) { if (value == null) { return(null); } if (serializable.AmqpType == AmqpType.Primitive) { var listType = serializable as SerializableType.List; if (listType != null && listType.ItemType.AmqpType != AmqpType.Primitive) { IList list = (IList)serializable.CreateInstance(); foreach (var item in (IEnumerable)value) { list.Add(FromAmqp(listType.ItemType, item)); } value = list; } return(value); } if (serializable.AmqpType == AmqpType.Described) { return(((SerializableType.Converted)serializable).GetSource(value)); } if (serializable.AmqpType == AmqpType.Composite) { object container = serializable.CreateInstance(); var composite = (SerializableType.Composite)serializable; AmqpMap map = (AmqpMap)value; foreach (var member in composite.Members) { object obj = map[new MapKey(member.Name)]; if (obj != null) { member.Accessor.Set(container, obj); } } return(container); } return(value); }
public async Task <EventHubPartitionRuntimeInformation> GetPartitionRuntimeInformationAsync(string partitionId) { RequestResponseAmqpLink requestLink = await link.GetOrCreateAsync( TimeSpan.FromSeconds(AmqpClientConstants.AmqpSessionTimeoutInSeconds)).ConfigureAwait(false); // Create request and attach token. AmqpMessage request = CreateGetPartitionRuntimeInformationRequest(partitionId); request.ApplicationProperties.Map[AmqpClientConstants.ManagementSecurityTokenKey] = await GetTokenString().ConfigureAwait(false); AmqpMessage response = await requestLink.RequestAsync(request, eventHubClient.ConnectionStringBuilder.OperationTimeout).ConfigureAwait(false); int statusCode = (int)response.ApplicationProperties.Map[AmqpClientConstants.ResponseStatusCode]; string statusDescription = (string)response.ApplicationProperties.Map[AmqpClientConstants.ResponseStatusDescription]; if (statusCode != (int)AmqpResponseStatusCode.Accepted && statusCode != (int)AmqpResponseStatusCode.OK) { AmqpSymbol errorCondition = AmqpExceptionHelper.GetResponseErrorCondition(response, (AmqpResponseStatusCode)statusCode); Error error = new Error { Condition = errorCondition, Description = statusDescription }; throw AmqpExceptionHelper.ToMessagingContract(error); } AmqpMap infoMap = null; if (response.ValueBody != null) { infoMap = response.ValueBody.Value as AmqpMap; } if (infoMap == null) { throw new InvalidOperationException($"Return type mismatch in GetPartitionRuntimeInformationAsync. Response returned NULL or response isn't AmqpMap."); } return(new EventHubPartitionRuntimeInformation() { Type = (string)infoMap[new MapKey(AmqpClientConstants.EntityTypeName)], Path = (string)infoMap[new MapKey(AmqpClientConstants.EntityNameKey)], PartitionId = (string)infoMap[new MapKey(AmqpClientConstants.PartitionNameKey)], BeginSequenceNumber = (long)infoMap[new MapKey(AmqpClientConstants.ManagementPartitionBeginSequenceNumber)], LastEnqueuedSequenceNumber = (long)infoMap[new MapKey(AmqpClientConstants.ManagementPartitionLastEnqueuedSequenceNumber)], LastEnqueuedOffset = (string)infoMap[new MapKey(AmqpClientConstants.ManagementPartitionLastEnqueuedOffset)], LastEnqueuedTimeUtc = (DateTime)infoMap[new MapKey(AmqpClientConstants.ManagementPartitionLastEnqueuedTimeUtc)], IsEmpty = (bool)infoMap[new MapKey(AmqpClientConstants.ManagementPartitionRuntimeInfoPartitionIsEmpty)] }); }
protected override void OnDecode(ByteBuffer buffer, int count) { if (count-- > 0) { CorrelationId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { MessageId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { To = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { ReplyTo = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { Subject = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { SessionId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { ReplyToSessionId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { ContentType = AmqpCodec.DecodeString(buffer); } if (count > 0) { properties = AmqpCodec.DecodeMap(buffer); } }
protected override void OnDecode(ByteBuffer buffer, int count) { if (count-- > 0) { this.CorrelationId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { this.MessageId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { this.To = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { this.ReplyTo = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { this.Label = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { this.SessionId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { this.ReplyToSessionId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { this.ContentType = AmqpCodec.DecodeString(buffer); } if (count > 0) { this.properties = AmqpCodec.DecodeMap(buffer); } }
public async Task <EventHubPartitionRuntimeInformation> GetPartitionRuntimeInformationAsync(string partitionId) { RequestResponseAmqpLink requestLink = await this.link.GetOrCreateAsync(TimeSpan.FromMinutes(1)).ConfigureAwait(false); // Create request and attach token. var request = this.CreateGetPartitionRuntimeInformationRequest(partitionId); request.ApplicationProperties.Map[AmqpClientConstants.ManagementSecurityTokenKey] = await GetTokenString().ConfigureAwait(false); var response = await requestLink.RequestAsync(request, TimeSpan.FromMinutes(1)).ConfigureAwait(false); int statusCode = (int)response.ApplicationProperties.Map[AmqpClientConstants.ResponseStatusCode]; string statusDescription = (string)response.ApplicationProperties.Map[AmqpClientConstants.ResponseStatusDescription]; if (statusCode != (int)AmqpResponseStatusCode.Accepted && statusCode != (int)AmqpResponseStatusCode.OK) { AmqpSymbol errorCondition = AmqpExceptionHelper.GetResponseErrorCondition(response, (AmqpResponseStatusCode)statusCode); Error error = new Error { Condition = errorCondition, Description = statusDescription }; throw AmqpExceptionHelper.ToMessagingContract(error); } AmqpMap infoMap = null; if (response.ValueBody != null) { infoMap = response.ValueBody.Value as AmqpMap; } if (infoMap == null) { throw new InvalidOperationException($"Return type mismatch in GetPartitionRuntimeInformationAsync. Response returned NULL or response isn't AmqpMap."); } return(new EventHubPartitionRuntimeInformation() { Type = (string)infoMap[new MapKey("type")], Path = (string)infoMap[new MapKey("name")], PartitionId = (string)infoMap[new MapKey("partition")], BeginSequenceNumber = (long)infoMap[new MapKey("begin_sequence_number")], LastEnqueuedSequenceNumber = (long)infoMap[new MapKey("last_enqueued_sequence_number")], LastEnqueuedOffset = (string)infoMap[new MapKey("last_enqueued_offset")], LastEnqueuedTimeUtc = (DateTime)infoMap[new MapKey("last_enqueued_time_utc")] }); }
public async Task <EventHubRuntimeInformation> GetRuntimeInformationAsync() { RequestResponseAmqpLink requestLink = await link.GetOrCreateAsync( TimeSpan.FromSeconds(AmqpClientConstants.AmqpSessionTimeoutInSeconds)).ConfigureAwait(false); // Create request and attach token. AmqpMessage request = CreateGetRuntimeInformationRequest(); request.ApplicationProperties.Map[AmqpClientConstants.ManagementSecurityTokenKey] = await GetTokenString().ConfigureAwait(false); AmqpMessage response = await requestLink.RequestAsync(request, eventHubClient.ConnectionStringBuilder.OperationTimeout).ConfigureAwait(false); int statusCode = (int)response.ApplicationProperties.Map[AmqpClientConstants.ResponseStatusCode]; string statusDescription = (string)response.ApplicationProperties.Map[AmqpClientConstants.ResponseStatusDescription]; if (statusCode != (int)AmqpResponseStatusCode.Accepted && statusCode != (int)AmqpResponseStatusCode.OK) { AmqpSymbol errorCondition = AmqpExceptionHelper.GetResponseErrorCondition(response, (AmqpResponseStatusCode)statusCode); Error error = new Error { Condition = errorCondition, Description = statusDescription }; throw AmqpExceptionHelper.ToMessagingContract(error); } AmqpMap infoMap = null; if (response.ValueBody != null) { infoMap = response.ValueBody.Value as AmqpMap; } if (infoMap == null) { throw new InvalidOperationException($"Return type mismatch in GetRuntimeInformationAsync. Response returned NULL or response isn't AmqpMap."); } return(new EventHubRuntimeInformation() { Type = (string)infoMap[new MapKey("type")], Path = (string)infoMap[new MapKey("name")], CreatedAt = (DateTime)infoMap[new MapKey("created_at")], PartitionCount = (int)infoMap[new MapKey("partition_count")], PartitionIds = (string[])infoMap[new MapKey("partition_ids")], }); }
public static object ToAmqp(SerializableType serializable, object value) { if (value == null) { return(null); } if (serializable.AmqpType == AmqpType.Primitive) { var listType = serializable as SerializableType.List; if (listType != null && listType.ItemType.AmqpType != AmqpType.Primitive) { List <object> list = new List <object>(); foreach (var item in (IEnumerable)value) { list.Add(ToAmqp(listType.ItemType, item)); } value = list; } return(value); } if (serializable.AmqpType == AmqpType.Described) { return(((SerializableType.Converted)serializable).GetTarget(value)); } if (serializable.AmqpType == AmqpType.Composite) { var composite = (SerializableType.Composite)serializable; AmqpMap map = new AmqpMap(); foreach (var member in composite.Members) { map[new MapKey(member.Name)] = member.Accessor.Get(value); } return(map); } return(value); }
/// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="timeout"></param> /// <param name="cancellationToken"></param> /// <returns></returns> internal async Task <long> ScheduleMessageInternalAsync( ServiceBusMessage message, TimeSpan timeout, CancellationToken cancellationToken = default) { var sendLink = default(SendingAmqpLink); try { using (AmqpMessage amqpMessage = AmqpMessageConverter.SBMessageToAmqpMessage(message)) { var request = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.ScheduleMessageOperation, timeout, null); if (_sendLink.TryGetOpenedObject(out sendLink)) { request.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = sendLink.Name; } ArraySegment <byte>[] payload = amqpMessage.GetPayload(); var buffer = new BufferListStream(payload); ArraySegment <byte> value = buffer.ReadBytes((int)buffer.Length); var entry = new AmqpMap(); { entry[ManagementConstants.Properties.Message] = value; entry[ManagementConstants.Properties.MessageId] = message.MessageId; if (!string.IsNullOrWhiteSpace(message.SessionId)) { entry[ManagementConstants.Properties.SessionId] = message.SessionId; } if (!string.IsNullOrWhiteSpace(message.PartitionKey)) { entry[ManagementConstants.Properties.PartitionKey] = message.PartitionKey; } if (!string.IsNullOrWhiteSpace(message.ViaPartitionKey)) { entry[ManagementConstants.Properties.ViaPartitionKey] = message.ViaPartitionKey; } } request.Map[ManagementConstants.Properties.Messages] = new List <AmqpMap> { entry }; AmqpResponseMessage amqpResponseMessage = await ManagementUtilities.ExecuteRequestResponseAsync( _connectionScope, _managementLink, request, timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); if (amqpResponseMessage.StatusCode == AmqpResponseStatusCode.OK) { var sequenceNumbers = amqpResponseMessage.GetValue <long[]>(ManagementConstants.Properties.SequenceNumbers); if (sequenceNumbers == null || sequenceNumbers.Length < 1) { throw new ServiceBusException(true, "Could not schedule message successfully."); } return(sequenceNumbers[0]); } else { throw amqpResponseMessage.ToMessagingContractException(); } } } catch (Exception exception) { ExceptionDispatchInfo.Capture(AmqpExceptionHelper.TranslateException( exception, sendLink?.GetTrackingId(), null, HasLinkCommunicationError(sendLink))) .Throw(); throw; // will never be reached } }
/// <summary> /// Encodes a map and appends the bytes to the buffer. /// </summary> /// <param name="data">The map.</param> /// <param name="buffer">The destination buffer.</param> public static void EncodeMap(AmqpMap data, ByteBuffer buffer) { MapEncoding.Encode(data, buffer); }
/// <summary> /// Gets the encode size of a map. /// </summary> /// <param name="value">The map.</param> /// <returns>Encode size in bytes of the map.</returns> public static int GetMapEncodeSize(AmqpMap value) { return(MapEncoding.GetEncodeSize(value)); }
public static bool TryGetNetObjectFromAmqpObject(object amqpObject, MappingType mappingType, out object netObject) { netObject = null; if (amqpObject == null) { return(false); } switch (SerializationUtilities.GetTypeId(amqpObject)) { case PropertyValueType.Byte: case PropertyValueType.SByte: case PropertyValueType.Int16: case PropertyValueType.Int32: case PropertyValueType.Int64: case PropertyValueType.UInt16: case PropertyValueType.UInt32: case PropertyValueType.UInt64: case PropertyValueType.Single: case PropertyValueType.Double: case PropertyValueType.Boolean: case PropertyValueType.Decimal: case PropertyValueType.Char: case PropertyValueType.Guid: case PropertyValueType.DateTime: case PropertyValueType.String: netObject = amqpObject; break; case PropertyValueType.Unknown: if (amqpObject is AmqpSymbol) { netObject = ((AmqpSymbol)amqpObject).Value; } else if (amqpObject is ArraySegment <byte> ) { ArraySegment <byte> binValue = (ArraySegment <byte>)amqpObject; if (binValue.Count == binValue.Array.Length) { netObject = binValue.Array; } else { byte[] buffer = new byte[binValue.Count]; Buffer.BlockCopy(binValue.Array, binValue.Offset, buffer, 0, binValue.Count); netObject = buffer; } } else if (amqpObject is DescribedType) { DescribedType describedType = (DescribedType)amqpObject; if (describedType.Descriptor is AmqpSymbol) { AmqpSymbol symbol = (AmqpSymbol)describedType.Descriptor; if (symbol.Equals((AmqpSymbol)UriName)) { netObject = new Uri((string)describedType.Value); } else if (symbol.Equals((AmqpSymbol)TimeSpanName)) { netObject = new TimeSpan((long)describedType.Value); } else if (symbol.Equals((AmqpSymbol)DateTimeOffsetName)) { netObject = new DateTimeOffset(new DateTime((long)describedType.Value, DateTimeKind.Utc)); } } } else if (mappingType == MappingType.ApplicationProperty) { throw FxTrace.Exception.AsError(new SerializationException(IotHubApiResources.GetString(ApiResources.FailedToSerializeUnsupportedType, amqpObject.GetType().FullName))); } else if (amqpObject is AmqpMap) { AmqpMap map = (AmqpMap)amqpObject; Dictionary <string, object> dictionary = new Dictionary <string, object>(); foreach (var pair in map) { dictionary.Add(pair.Key.ToString(), pair.Value); } netObject = dictionary; } else { netObject = amqpObject; } break; default: break; } return(netObject != null); }
internal void SetMap(AmqpMap map) { this.innerMap = map; }
static void Encode(AmqpMap value, int width, int size, ByteBuffer buffer) { if (width == FixedWidth.UByte) { AmqpBitConverter.WriteUByte(buffer, (byte)size); AmqpBitConverter.WriteUByte(buffer, (byte)(value.Count * 2)); } else { AmqpBitConverter.WriteUInt(buffer, (uint)size); AmqpBitConverter.WriteUInt(buffer, (uint)(value.Count * 2)); } if (value.Count > 0) { foreach (KeyValuePair<MapKey, object> item in value) { AmqpEncoding.EncodeObject(item.Key.Key, buffer); AmqpEncoding.EncodeObject(item.Value, buffer); } } }
public static int GetEncodeSize(AmqpMap value) { return value == null ? FixedWidth.NullEncoded : FixedWidth.FormatCode + (MapEncoding.GetEncodeWidth(value) * 2) + value.ValueSize; }
internal static bool TryGetAmqpObjectFromNetObject(object netObject, MappingType mappingType, out object amqpObject) { amqpObject = null; if (netObject == null) { return(true); } switch (SerializationUtilities.GetTypeId(netObject)) { case PropertyValueType.Byte: case PropertyValueType.SByte: case PropertyValueType.Int16: case PropertyValueType.Int32: case PropertyValueType.Int64: case PropertyValueType.UInt16: case PropertyValueType.UInt32: case PropertyValueType.UInt64: case PropertyValueType.Single: case PropertyValueType.Double: case PropertyValueType.Boolean: case PropertyValueType.Decimal: case PropertyValueType.Char: case PropertyValueType.Guid: case PropertyValueType.DateTime: case PropertyValueType.String: amqpObject = netObject; break; case PropertyValueType.Stream: if (mappingType == MappingType.ApplicationProperty) { amqpObject = StreamToBytes((Stream)netObject); } break; case PropertyValueType.Uri: amqpObject = new DescribedType((AmqpSymbol)UriName, ((Uri)netObject).AbsoluteUri); break; case PropertyValueType.DateTimeOffset: amqpObject = new DescribedType((AmqpSymbol)DateTimeOffsetName, ((DateTimeOffset)netObject).UtcTicks); break; case PropertyValueType.TimeSpan: amqpObject = new DescribedType((AmqpSymbol)TimeSpanName, ((TimeSpan)netObject).Ticks); break; case PropertyValueType.Unknown: if (netObject is Stream netObjectAsStream) { if (mappingType == MappingType.ApplicationProperty) { amqpObject = StreamToBytes(netObjectAsStream); } } else if (mappingType == MappingType.ApplicationProperty) { throw Fx.Exception.AsError(new SerializationException(Resources.FailedToSerializeUnsupportedType.FormatForUser(netObject.GetType().FullName))); } else if (netObject is byte[] netObjectAsByteArray) { amqpObject = new ArraySegment <byte>(netObjectAsByteArray); } else if (netObject is IList) { // Array is also an IList amqpObject = netObject; } else if (netObject is IDictionary netObjectAsDictionary) { amqpObject = new AmqpMap(netObjectAsDictionary); } break; } return(amqpObject != null); }
public DescribedMap(AmqpSymbol name, ulong code) : base(name, code) { this.innerMap = new AmqpMap(); }
public void SetMap(AmqpMap map) { this.innerMap = map; }
static int GetEncodeWidth(AmqpMap value) { return AmqpEncoding.GetEncodeWidthByCountAndSize(value.Count * 2, value.ValueSize); }
public override void DecodeValue(ByteBuffer buffer) { this.innerMap = MapEncoding.Decode(buffer, 0); }
public static bool TryGetAmqpObjectFromNetObject(object netObject, MappingType mappingType, out object amqpObject) { amqpObject = null; if (netObject == null) { return false; } switch (SerializationUtilities.GetTypeId(netObject)) { case PropertyValueType.Byte: case PropertyValueType.SByte: case PropertyValueType.Int16: case PropertyValueType.Int32: case PropertyValueType.Int64: case PropertyValueType.UInt16: case PropertyValueType.UInt32: case PropertyValueType.UInt64: case PropertyValueType.Single: case PropertyValueType.Double: case PropertyValueType.Boolean: case PropertyValueType.Decimal: case PropertyValueType.Char: case PropertyValueType.Guid: case PropertyValueType.DateTime: case PropertyValueType.String: amqpObject = netObject; break; case PropertyValueType.Stream: if (mappingType == MappingType.ApplicationProperty) { amqpObject = ReadStream((Stream)netObject); } break; case PropertyValueType.Uri: amqpObject = new DescribedType((AmqpSymbol)UriName, ((Uri)netObject).AbsoluteUri); break; case PropertyValueType.DateTimeOffset: amqpObject = new DescribedType((AmqpSymbol)DateTimeOffsetName, ((DateTimeOffset)netObject).UtcTicks); break; case PropertyValueType.TimeSpan: amqpObject = new DescribedType((AmqpSymbol)TimeSpanName, ((TimeSpan)netObject).Ticks); break; case PropertyValueType.Unknown: if (netObject is Stream) { if (mappingType == MappingType.ApplicationProperty) { amqpObject = ReadStream((Stream)netObject); } } else if (mappingType == MappingType.ApplicationProperty) { throw FxTrace.Exception.AsError(new SerializationException(IotHubApiResources.GetString(ApiResources.FailedToSerializeUnsupportedType, netObject.GetType().FullName))); } else if (netObject is byte[]) { amqpObject = new ArraySegment<byte>((byte[])netObject); } else if (netObject is IList) { // Array is also an IList amqpObject = netObject; } else if (netObject is IDictionary) { amqpObject = new AmqpMap((IDictionary)netObject); } break; default: break; } return amqpObject != null; }
public AmqpCorrelationRuleFilterCodec() : base(Name, Code) { properties = new AmqpMap(); }
static void DumpAmqpData(ByteBuffer buffer, int indent) { int offset = buffer.Offset; byte formatCode = buffer.Buffer[buffer.Offset]; if (formatCode == 0x40) { WriteAmqpValue(offset, indent, "Null"); } else if (formatCode == 0x41) { WriteAmqpValue(offset, indent, "Bool:True"); } else if (formatCode == 0x42) { WriteAmqpValue(offset, indent, "Bool:False"); } else if (formatCode == 0x50) { WriteAmqpValue(offset, indent, string.Format("UByte:{0}", (byte)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x60) { WriteAmqpValue(offset, indent, string.Format("UShort:{0}", (ushort)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x70) { WriteAmqpValue(offset, indent, string.Format("UInt:{0}", (uint)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x52) { WriteAmqpValue(offset, indent, string.Format("SmallUInt:{0}", (uint)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x80) { WriteAmqpValue(offset, indent, string.Format("ULong:{0}", (ulong)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x53) { WriteAmqpValue(offset, indent, string.Format("SmallULong:{0}", (ulong)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x51) { WriteAmqpValue(offset, indent, string.Format("Byte:{0}", (sbyte)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x61) { WriteAmqpValue(offset, indent, string.Format("Short:{0}", (short)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x71) { WriteAmqpValue(offset, indent, string.Format("Int:{0}", (int)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x54) { WriteAmqpValue(offset, indent, string.Format("SmallInt:{0}", (int)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x81) { WriteAmqpValue(offset, indent, string.Format("Long:{0}", (long)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x54) { WriteAmqpValue(offset, indent, string.Format("SmallLong:{0}", (long)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x72) { WriteAmqpValue(offset, indent, string.Format("Float:{0}", (float)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x82) { WriteAmqpValue(offset, indent, string.Format("Double:{0}", (double)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x73) { WriteAmqpValue(offset, indent, string.Format("Char:{0}", (char)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x83) { WriteAmqpValue(offset, indent, string.Format("TimeStamp:{0}", (DateTime)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0x98) { WriteAmqpValue(offset, indent, string.Format("Uuid:{0}", (Guid)AmqpEncoding.DecodeObject(buffer))); } else if (formatCode == 0xa0 || formatCode == 0xb0) { ArraySegment <byte> bin = (ArraySegment <byte>)AmqpEncoding.DecodeObject(buffer); WriteAmqpValue(offset, indent, string.Format("Binary{0}:{1}", formatCode == 0xa0 ? 8 : 32, bin.Array == null ? "Null" : bin.Count.ToString())); } else if (formatCode == 0xa1 || formatCode == 0xb1 || formatCode == 0xa2 || formatCode == 0xb2) { string str = (string)AmqpEncoding.DecodeObject(buffer); string toDisplay = "Null"; if (str != null) { toDisplay = str.Length > 20 ? str.Substring(0, 8) + "..." + str.Substring(str.Length - 8) : str; } WriteAmqpValue(offset, indent, string.Format("Utf{0}String{1}:{2}", (formatCode & 0x0F) == 0x01 ? 8 : 16, (formatCode & 0xF0) == 0xa0 ? 8 : 32, toDisplay)); } else if (formatCode == 0xa3 || formatCode == 0xb3) { AmqpSymbol sym = (AmqpSymbol)AmqpEncoding.DecodeObject(buffer); string toDisplay = "Null"; if (sym.Value != null) { toDisplay = sym.Value.Length > 16 ? sym.Value.Substring(0, 6) + "..." + sym.Value.Substring(sym.Value.Length - 6) : sym.Value; } WriteAmqpValue(offset, indent, string.Format("Symbol{0}:{1}", formatCode == 0xa3 ? 8 : 32, toDisplay)); } else if (formatCode == 0xc0 || formatCode == 0xd0) { IList <object> list = AmqpEncoding.DecodeObject(buffer) as List <object>; WriteAmqpValue(offset, indent, string.Format("List{0}:{1}", formatCode == 0xc0 ? 8 : 32, list.Count)); for (int i = 0; i < list.Count; ++i) { WriteAmqpValue(-1, indent + 1, list[i].ToString()); } } else if (formatCode == 0xe0 || formatCode == 0xf0) { Array array = (Array)AmqpEncoding.DecodeObject(buffer); WriteAmqpValue(offset, indent, string.Format("Array{0}:{1}", formatCode == 0xe0 ? 8 : 32, array.Length)); for (int i = 0; i < array.Length; ++i) { WriteAmqpValue(-1, indent + 1, array.GetValue(i).ToString()); } } else if (formatCode == 0xc1 || formatCode == 0xd1) { AmqpMap map = (AmqpMap)AmqpEncoding.DecodeObject(buffer); WriteAmqpValue(offset, indent, string.Format("Map{0}:{1}", formatCode == 0xc0 ? 8 : 32, map.Count)); foreach (var kvp in map) { WriteAmqpValue(-1, indent + 1, kvp.Key.ToString()); WriteAmqpValue(-1, indent + 1, kvp.Value?.ToString() ?? "Null"); } } else if (formatCode == 0x00) { WriteAmqpValue(offset, indent, "Described"); DumpAmqpData(buffer, indent + 1); DumpAmqpData(buffer, indent + 1); } }
public async Task <object> Start() { RequestResponseAmqpLink requestLink = await this.client.link.GetOrCreateAsync(TimeSpan.FromMinutes(1)); ApplicationProperties properties = new ApplicationProperties(); properties.Map[AmqpClientConstants.ManagementOperationKey] = this.md.Operation.Name; // generate message sections containing the arguments // convert custom-type parameters if needed object bodyValue = null; AmqpMap bodyMap = null; for (int i = 0; i < this.argCount; i++) { ManagementParamAttribute paramAttribute = this.md.Parameters[i]; object value = SerializationHelper.ToAmqp(this.md.ParameterTypes[i].Serializable, this.mcm.InArgs[i]); if (paramAttribute.Location == ManagementParamLocation.ApplicationProperties) { properties.Map[paramAttribute.Name] = value; } else if (paramAttribute.Location == ManagementParamLocation.MapBody) { if (bodyMap == null) { bodyMap = new AmqpMap(); } bodyMap[new MapKey(paramAttribute.Name)] = value; } else { bodyValue = value; } } // Upsert link RequestProperties to ApplicationProperties foreach (var requestProperty in requestLink.RequestProperties) { properties.Map[requestProperty.Key] = requestProperty.Value; } this.request = AmqpMessage.Create(new AmqpValue { Value = bodyMap ?? bodyValue }); this.request.ApplicationProperties = properties; this.response = await requestLink.RequestAsync(request, TimeSpan.FromMinutes(1)); int statusCode = (int)this.response.ApplicationProperties.Map[AmqpClientConstants.ResponseStatusCode]; string statusDescription = (string)this.response.ApplicationProperties.Map[AmqpClientConstants.ResponseStatusDescription]; if (statusCode != (int)AmqpResponseStatusCode.Accepted && statusCode != (int)AmqpResponseStatusCode.OK) { AmqpSymbol errorCondition = AmqpExceptionHelper.GetResponseErrorCondition(this.response, (AmqpResponseStatusCode)statusCode); Error error = new Error { Condition = errorCondition, Description = statusDescription }; throw new AmqpException(error); } object returnValue = null; if (this.response.ValueBody != null) { returnValue = this.response.ValueBody.Value; } if (md.ReturnType.HasValue && returnValue != null) { Type expected = md.ReturnType.Type; SerializableType serializable = md.ReturnType.Serializable; if (serializable == null) { // must be a generic parameter expected = mcm.GenericTypes[md.ReturnType.Type.GenericParameterPosition]; serializable = expected.GetSerializable(); } returnValue = SerializationHelper.FromAmqp(serializable, returnValue); if (!expected.IsAssignableFrom(returnValue.GetType())) { throw new InvalidOperationException($"Return type mismatch in {mcm.MethodBase.Name}. Expect {expected.Name} Actual {returnValue.GetType().Name}"); } } return(returnValue); }
public void AmqpCodecMapTest() { byte[] workBuffer = new byte[4096]; ByteBuffer buffer = new ByteBuffer(workBuffer); string strBig = new string('A', 512); AmqpMap map = new AmqpMap(); map.Add(new MapKey("boolTrue"), boolTrue); map.Add(new MapKey("boolFalse"), boolFalse); map.Add(new MapKey("ubyte"), ubyteValue); map.Add(new MapKey("ushort"), ushortValue); map.Add(new MapKey("uint"), uintValue); map.Add(new MapKey("ulong"), ulongValue); map.Add(new MapKey("byte"), byteValue); map.Add(new MapKey("short"), shortValue); map.Add(new MapKey("int"), intValue); map.Add(new MapKey("long"), longValue); map.Add(new MapKey("null"), null); map.Add(new MapKey("float"), floatValue); map.Add(new MapKey("double"), doubleValue); map.Add(new MapKey("decimal32"), decimal32Value); map.Add(new MapKey("decimal64"), decimal64Value); map.Add(new MapKey("decimal128"), decimal128Value); map.Add(new MapKey("char"), charValue); map.Add(new MapKey("datetime"), dtValue); map.Add(new MapKey("uuid"), uuidValue); map.Add(new MapKey("binaryNull"), new ArraySegment <byte>()); map.Add(new MapKey("binary8"), bin8Value); map.Add(new MapKey("binary32"), bin32Value); map.Add(new MapKey("symbolNull"), new AmqpSymbol()); map.Add(new MapKey("symbol8"), new AmqpSymbol(strValue)); map.Add(new MapKey("symbol32"), new AmqpSymbol(strBig)); map.Add(new MapKey("string8"), strValue); map.Add(new MapKey("string32"), strBig); map.Add(new MapKey("described1"), described1); AmqpCodec.EncodeMap(map, buffer); // make sure the size written is correct (it has to be Map32) // the first byte is FormatCode.Map32 int mapSize = (int)AmqpBitConverter.ReadUInt(workBuffer, 1, 4); Assert.Equal(buffer.Length - 5, mapSize); AmqpMap decMap = AmqpCodec.DecodeMap(buffer); Assert.True(decMap[new MapKey("boolTrue")].Equals(true), "Boolean true expected."); Assert.True(decMap[new MapKey("boolFalse")].Equals(false), "Boolean false expected."); Assert.True(decMap[new MapKey("ubyte")].Equals(ubyteValue), "UByte value not equal."); Assert.True(decMap[new MapKey("ushort")].Equals(ushortValue), "UShort value not equal."); Assert.True(decMap[new MapKey("uint")].Equals(uintValue), "UInt value not equal."); Assert.True(decMap[new MapKey("ulong")].Equals(ulongValue), "ULong value not equal."); Assert.True(decMap[new MapKey("byte")].Equals(byteValue), "Byte value not equal."); Assert.True(decMap[new MapKey("short")].Equals(shortValue), "Short value not equal."); Assert.True(decMap[new MapKey("int")].Equals(intValue), "Int value not equal."); Assert.True(decMap[new MapKey("long")].Equals(longValue), "Long value not equal."); Assert.True(decMap[new MapKey("null")] == null, "Null object expected."); Assert.True(decMap[new MapKey("float")].Equals(floatValue), "Float value not equal."); Assert.True(decMap[new MapKey("double")].Equals(doubleValue), "Double value not equal."); Assert.True(decMap[new MapKey("decimal32")].Equals(decimal32Value), "Decimal32 value not equal."); Assert.True(decMap[new MapKey("decimal64")].Equals(decimal64Value), "Decimal64 value not equal."); Assert.True(decMap[new MapKey("decimal128")].Equals(decimal128Value), "Decimal128 value not equal."); Assert.True(decMap[new MapKey("char")].Equals(charValue), "Char value not equal."); Assert.True(decMap[new MapKey("datetime")].Equals(dtValue), "TimeStamp value not equal."); Assert.True(decMap[new MapKey("uuid")].Equals(uuidValue), "Uuid value not equal."); Assert.True(decMap[new MapKey("binaryNull")] == null, "Null binary expected."); ArraySegment <byte> bin8 = (ArraySegment <byte>)decMap[new MapKey("binary8")]; EnsureEqual(bin8.Array, bin8.Offset, bin8.Count, bin8Value.Array, bin8Value.Offset, bin8Value.Count); ArraySegment <byte> bin32 = (ArraySegment <byte>)decMap[new MapKey("binary32")]; EnsureEqual(bin32.Array, bin32.Offset, bin32.Count, bin32Value.Array, bin32Value.Offset, bin32Value.Count); Assert.True(decMap[new MapKey("symbolNull")] == null, "Null symbol expected."); AmqpSymbol symDecode = (AmqpSymbol)decMap[new MapKey("symbol8")]; Assert.True(symDecode.Equals(strValue), "AmqpSymbol value not equal."); symDecode = (AmqpSymbol)decMap[new MapKey("symbol32")]; Assert.True(symDecode.Equals(strBig), "AmqpSymbol value (big) not equal."); string strDecode = (string)decMap[new MapKey("string8")]; Assert.True(strDecode.Equals(strValue), "string value not equal."); strDecode = (string)decMap[new MapKey("string32")]; Assert.True(strDecode.Equals(strBig), "string value (big) not equal."); DescribedType described = (DescribedType)decMap[new MapKey("described1")]; Assert.True(described.Descriptor.Equals(described1.Descriptor), "Described value 1 descriptor is different"); Assert.True(described.Value.Equals(described1.Value), "Described value 1 value is different"); }
/// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="timeout"></param> /// <param name="cancellationToken"></param> /// <returns></returns> internal async Task <long> ScheduleMessageInternalAsync( ServiceBusMessage message, TimeSpan timeout, CancellationToken cancellationToken = default) { var stopWatch = Stopwatch.StartNew(); using (AmqpMessage amqpMessage = AmqpMessageConverter.SBMessageToAmqpMessage(message)) { var request = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.ScheduleMessageOperation, timeout, null); if (_sendLink.TryGetOpenedObject(out SendingAmqpLink sendLink)) { request.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = sendLink.Name; } ArraySegment <byte>[] payload = amqpMessage.GetPayload(); var buffer = new BufferListStream(payload); ArraySegment <byte> value = buffer.ReadBytes((int)buffer.Length); var entry = new AmqpMap(); { entry[ManagementConstants.Properties.Message] = value; entry[ManagementConstants.Properties.MessageId] = message.MessageId; if (!string.IsNullOrWhiteSpace(message.SessionId)) { entry[ManagementConstants.Properties.SessionId] = message.SessionId; } if (!string.IsNullOrWhiteSpace(message.PartitionKey)) { entry[ManagementConstants.Properties.PartitionKey] = message.PartitionKey; } if (!string.IsNullOrWhiteSpace(message.ViaPartitionKey)) { entry[ManagementConstants.Properties.ViaPartitionKey] = message.ViaPartitionKey; } } request.Map[ManagementConstants.Properties.Messages] = new List <AmqpMap> { entry }; RequestResponseAmqpLink mgmtLink = await _managementLink.GetOrCreateAsync( UseMinimum(_connectionScope.SessionTimeout, timeout.CalculateRemaining(stopWatch.Elapsed))) .ConfigureAwait(false); using AmqpMessage response = await mgmtLink.RequestAsync( request.AmqpMessage, timeout.CalculateRemaining(stopWatch.Elapsed)) .ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); stopWatch.Stop(); AmqpResponseMessage amqpResponseMessage = AmqpResponseMessage.CreateResponse(response); if (amqpResponseMessage.StatusCode == AmqpResponseStatusCode.OK) { var sequenceNumbers = amqpResponseMessage.GetValue <long[]>(ManagementConstants.Properties.SequenceNumbers); if (sequenceNumbers == null || sequenceNumbers.Length < 1) { throw new ServiceBusException(true, "Could not schedule message successfully."); } return(sequenceNumbers[0]); } else { throw amqpResponseMessage.ToMessagingContractException(); } } }