public void ReplaceInstructionWithSimpleGraph() { var intType = new DescribedType(new SimpleName("Int32").Qualify(), null); // Create a flow graph that consists of a single block that contains three // instructions. var graph = new FlowGraphBuilder(); var first = graph.EntryPoint.AppendInstruction( IntrinsicPrototype.Create("test-intrinsic", intType, EmptyArray <IType> .Value) .Instantiate(EmptyArray <ValueTag> .Value)); var second = graph.EntryPoint.AppendInstruction( IntrinsicPrototype.Create("test-intrinsic", intType, EmptyArray <IType> .Value) .Instantiate(EmptyArray <ValueTag> .Value)); var third = graph.EntryPoint.AppendInstruction( IntrinsicPrototype.Create("test-intrinsic", intType, EmptyArray <IType> .Value) .Instantiate(EmptyArray <ValueTag> .Value)); Assert.IsInstanceOf(typeof(IntrinsicPrototype), second.Instruction.Prototype); // Now replace the second instruction with a CFG that copies the first instruction's // result. var miniGraph = new FlowGraphBuilder(); miniGraph.EntryPoint.Flow = new ReturnFlow(Instruction.CreateCopy(first.ResultType, first)); second.ReplaceInstruction(miniGraph.ToImmutable()); // Test that the instruction was indeed replaced. Assert.IsInstanceOf(typeof(CopyPrototype), second.Instruction.Prototype); }
/// <summary> /// Установить список с автоподсказами для свойства данного объекта /// </summary> /// <returns></returns> public new GenericUserInterfaceBlockBuilderForCollectionType <TItem> SetAutoCompleteFor <TDataProvider>() where TDataProvider : DataProviderForAutoCompletion <TItem> { var key = typeof(TDataProvider).FullName; if (!Bag.AutoCompletionDataProviders.ContainsKey(key)) { throw new InvalidOperationException(string.Format(ExceptionTexts.DataProviderForAutoCompletionNotRegisteredFormat, key)); } var mainDesc = DescribedType.GetMainTypeDescription(); if (mainDesc.ArrayDescription.IsArray && !DescribedType.GetTypeDescription(mainDesc.ArrayDescription.ElementDiplayFullTypeName).IsPrimitive) { throw new InvalidOperationException( $"Вы не можете установить для свойства {Block.PropertyName} тип блока 'Автозаполнение'. " + "Так как данное свойство является массивом из непримитивов. " + "Необходим тип, который будет являтся массивом из примитивов."); } Block.InterfaceType = UserInterfaceType.AutoCompleteForMultiple; Block.AutoCompleteData = new AutoCompleteData { DataProviderTypeFullName = typeof(TDataProvider).FullName }; return(this); }
static void EncodeIfNotNull(DescribedType section, ByteBuffer buffer) { if (section != null) { section.Encode(buffer); } }
public void StraightforwardAnalysis() { var intType = new DescribedType(new SimpleName("Int32").Qualify(), null); var zeroInstruction = Instruction.CreateConstant( new IntegerConstant(0), intType); // Create an empty control flow graph. var graph = new FlowGraphBuilder(); graph.AddAnalysis(ValueUseAnalysis.Instance); // Modify the control flow graph. var entryBlock = graph.GetBasicBlock(graph.EntryPointTag); var zeroConstant = entryBlock.AppendInstruction(zeroInstruction); var exitBlock = graph.AddBasicBlock("exit"); var exitParam = new BlockParameter(intType); exitBlock.AppendParameter(exitParam); var copyInstruction = entryBlock.AppendInstruction( Instruction.CreateCopy(intType, zeroConstant.Tag)); entryBlock.Flow = new JumpFlow(exitBlock.Tag, new[] { zeroConstant.Tag }); // Analyze the graph. var uses = graph.GetAnalysisResult <ValueUses>(); // Check that the analysis looks alright. Assert.IsFalse(uses.GetInstructionUses(zeroConstant.Tag).Contains(exitParam.Tag)); Assert.IsFalse(uses.GetInstructionUses(exitParam.Tag).Contains(zeroConstant.Tag)); Assert.IsTrue(uses.GetFlowUses(zeroConstant.Tag).Contains(entryBlock.Tag)); Assert.IsFalse(uses.GetFlowUses(zeroConstant.Tag).Contains(exitBlock.Tag)); Assert.IsTrue(uses.GetInstructionUses(zeroConstant.Tag).Contains(copyInstruction.Tag)); Assert.IsFalse(uses.GetInstructionUses(copyInstruction.Tag).Contains(zeroConstant.Tag)); }
/// <summary> /// Attempts to create an AMQP property value for a given event property. /// </summary> /// /// <param name="eventPropertyValue">The value of the event property to create an AMQP property value for.</param> /// <param name="amqpPropertyValue">The AMQP property value that was created.</param> /// /// <returns><c>true</c> if an AMQP property value was able to be created; otherwise, <c>false</c>.</returns> /// private static bool TryCreateAmqpPropertyValueForEventProperty(object eventPropertyValue, out object amqpPropertyValue) { amqpPropertyValue = null; if (eventPropertyValue == null) { return(true); } switch (GetTypeIdentifier(eventPropertyValue)) { case AmqpProperty.Type.Byte: case AmqpProperty.Type.SByte: case AmqpProperty.Type.Int16: case AmqpProperty.Type.Int32: case AmqpProperty.Type.Int64: case AmqpProperty.Type.UInt16: case AmqpProperty.Type.UInt32: case AmqpProperty.Type.UInt64: case AmqpProperty.Type.Single: case AmqpProperty.Type.Double: case AmqpProperty.Type.Boolean: case AmqpProperty.Type.Decimal: case AmqpProperty.Type.Char: case AmqpProperty.Type.Guid: case AmqpProperty.Type.DateTime: case AmqpProperty.Type.String: amqpPropertyValue = eventPropertyValue; break; case AmqpProperty.Type.Stream: case AmqpProperty.Type.Unknown when eventPropertyValue is Stream: amqpPropertyValue = ReadStreamToArraySegment((Stream)eventPropertyValue); break; case AmqpProperty.Type.Uri: amqpPropertyValue = new DescribedType(AmqpProperty.Descriptor.Uri, ((Uri)eventPropertyValue).AbsoluteUri); break; case AmqpProperty.Type.DateTimeOffset: amqpPropertyValue = new DescribedType(AmqpProperty.Descriptor.DateTimeOffset, ((DateTimeOffset)eventPropertyValue).UtcTicks); break; case AmqpProperty.Type.TimeSpan: amqpPropertyValue = new DescribedType(AmqpProperty.Descriptor.TimeSpan, ((TimeSpan)eventPropertyValue).Ticks); break; case AmqpProperty.Type.Unknown: var exception = new SerializationException(string.Format(CultureInfo.CurrentCulture, Resources.FailedToSerializeUnsupportedType, eventPropertyValue.GetType().FullName)); EventHubsEventSource.Log.UnexpectedException(exception.Message); throw exception; } return(amqpPropertyValue != null); }
static void EncodeDescribedList(ByteBuffer buffer, object descriptor, params object[] values) { object descriptor2 = descriptor is string?(AmqpSymbol)(string)descriptor : descriptor; object[] values2 = values ?? new object[] { null }; DescribedType describedType = new DescribedType(descriptor2, new List <object>(values2)); AmqpEncoding.EncodeObject(describedType, buffer); }
public static void Encode(DescribedType value, ByteBuffer buffer) { if (value == null) { AmqpEncoding.EncodeNull(buffer); } else { AmqpBitConverter.WriteUByte(buffer, FormatCode.Described); AmqpEncoding.EncodeObject(value.Descriptor, buffer); AmqpEncoding.EncodeObject(value.Value, buffer); } }
public static void Encode(DescribedType value, ByteBuffer buffer) { if (value.Value == null) { AmqpEncoding.EncodeNull(buffer); } else { AmqpBitConverter.WriteUByte(buffer, (byte)FormatCode.Described); AmqpEncoding.EncodeObject(value.Descriptor, buffer); AmqpEncoding.EncodeObject(value.Value, buffer); } }
private void ValidateForMultipleDropDownList() { var main = DescribedType.GetMainTypeDescription(); if (!main.ArrayDescription.IsArray) { throw new InvalidOperationException(ExceptionTexts.CantImplementMultipleDropDownForToNotEnumerableProperty); } var enumerated = DescribedType.GetTypeDescription(main.ArrayDescription.ElementDiplayFullTypeName); if (!enumerated.IsPrimitive) { throw new InvalidOperationException(string.Format(ExceptionTexts.CantSetMultipleDropListNotOnPrimitivesFormat, Block.PropertyName, typeof(TItem).FullName)); } }
public void AmqpCodecDescribedArrayTest() { int size = AmqpCodec.GetObjectEncodeSize(described5); ByteBuffer buffer = new ByteBuffer(new byte[size]); AmqpCodec.EncodeObject(described5, buffer); DescribedType decoded = (DescribedType)AmqpCodec.DecodeObject(buffer); Assert.True(decoded.Descriptor.Equals(described5.Descriptor), "Descriptor value not equal"); string[] original = (string[])described5.Value; string[] array = (string[])decoded.Value; Assert.True(original.Length == array.Length, string.Format("length not equal {0} != {1}", original.Length, array.Length)); for (int i = 0; i < original.Length; ++i) { Assert.True(original[i] == array[i], string.Format("index {0}: {1} != {2}", i, original[i], array[i])); } }
protected DescribedType( AmqpContractSerializer serializer, Type type, SerializableType baseType, string descriptorName, ulong?descriptorCode, SerialiableMember[] members, Dictionary <Type, SerializableType> knownTypes, MethodAccessor onDesrialized) : base(serializer, type) { this.baseType = (DescribedType)baseType; this.descriptorName = descriptorName; this.descriptorCode = descriptorCode; this.members = members; this.onDeserialized = onDesrialized; this.knownTypes = GetKnownTypes(knownTypes); }
public void CreateEventFromMessageDoesNotIncludeUnknownApplicationPropertyType() { using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); var typeDescriptor = (AmqpSymbol)"INVALID"; var describedProperty = new DescribedType(typeDescriptor, 1234); message.ApplicationProperties.Map.Add(typeDescriptor.ToString(), describedProperty); var converter = new AmqpMessageConverter(); var eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Properties.Any(), Is.False, "The event should not have a set of application properties."); var containsValue = eventData.Properties.TryGetValue(typeDescriptor.ToString(), out var _); Assert.That(containsValue, Is.False, $"The event properties should not contain the described property."); }
public void RemoveDeadArgument() { var intType = new DescribedType(new SimpleName("Int32").Qualify(), null); // Create a flow graph that consists of a single block with two parameters. var graph = new FlowGraphBuilder(); graph.EntryPoint.AppendParameter(new BlockParameter(intType)); graph.EntryPoint.AppendParameter(new BlockParameter(intType)); graph.EntryPoint.Flow = new JumpFlow( graph.EntryPoint, graph.EntryPoint.ParameterTags.ToArray()); // Delete the first parameter. graph.RemoveDefinitions(new[] { graph.EntryPoint.ParameterTags.First() }); // Check that the argument to that parameter has been deleted as well. Assert.AreEqual(1, graph.EntryPoint.Flow.Branches[0].Arguments.Count); Assert.AreEqual( graph.EntryPoint.ParameterTags.First(), graph.EntryPoint.Flow.Branches[0].Arguments[0].ValueOrNull); }
public void CreateEventFromMessagePopulateDescribedApplicationProperties(object typeDescriptor, object propertyValueRaw, Func <object, object> propertyValueAccessor) { using var bodyStream = new MemoryStream(new byte[] { 0x11, 0x22, 0x33 }, false); using var message = AmqpMessage.Create(bodyStream, true); var describedProperty = new DescribedType(typeDescriptor, propertyValueAccessor(propertyValueRaw)); message.ApplicationProperties.Map.Add(typeDescriptor.ToString(), describedProperty); var converter = new AmqpMessageConverter(); var eventData = converter.CreateEventFromMessage(message); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.Body, Is.Not.Null, "The event should have a body."); Assert.That(eventData.Properties.Any(), Is.True, "The event should have a set of application properties."); var containsValue = eventData.Properties.TryGetValue(typeDescriptor.ToString(), out object value); Assert.That(containsValue, Is.True, $"The event properties did not contain the described property."); Assert.That(value, Is.EqualTo(propertyValueRaw), $"The property value did not match."); }
public void StraightforwardAnalysis() { var intType = new DescribedType(new SimpleName("Int32").Qualify(), null); var zeroInstruction = Instruction.CreateConstant( new IntegerConstant(0), intType); // Create an empty control flow graph. var graph = new FlowGraphBuilder(); graph.AddAnalysis(PredecessorAnalysis.Instance); graph.AddAnalysis(LivenessAnalysis.Instance); graph.AddAnalysis(InterferenceGraphAnalysis.Instance); // Modify the control flow graph. var entryBlock = graph.GetBasicBlock(graph.EntryPointTag); var zeroConstant = entryBlock.AppendInstruction(zeroInstruction, "zero"); var copyInstruction = entryBlock.AppendInstruction( Instruction.CreateCopy(intType, zeroConstant.Tag), "copy"); var exitBlock = graph.AddBasicBlock("exit"); var exitParam = new BlockParameter(intType, "param"); exitBlock.AppendParameter(exitParam); entryBlock.Flow = new JumpFlow(exitBlock.Tag, new[] { zeroConstant.Tag }); exitBlock.Flow = new ReturnFlow(Instruction.CreateCopy(intType, copyInstruction.Tag)); // Analyze the graph. var interference = graph.GetAnalysisResult <InterferenceGraph>(); // Check that the analysis looks alright. Assert.IsTrue(interference.InterferesWith(zeroConstant.Tag, copyInstruction.Tag)); Assert.IsFalse(interference.InterferesWith(zeroConstant.Tag, exitParam.Tag)); Assert.IsFalse(interference.InterferesWith(exitParam.Tag, copyInstruction.Tag)); }
/// <summary> /// Creates a new test assembly and wraps it in a container. /// </summary> public TestAssemblyContainer() { var testAsm = new DescribedAssembly(new SimpleName("TestAsm").Qualify()); this.Assembly = testAsm; var simpleType = new DescribedType(new SimpleName("SimpleType").Qualify(), testAsm); testAsm.AddType(simpleType); this.SimpleType = simpleType; var nestedType = new DescribedType(new SimpleName("NestedType"), simpleType); simpleType.AddNestedType(nestedType); this.NestedType = nestedType; var genericType1 = new DescribedType(new SimpleName("GenericType", 1).Qualify(), testAsm); genericType1.AddGenericParameter(new DescribedGenericParameter(genericType1, new SimpleName("T"))); testAsm.AddType(genericType1); this.GenericType1 = genericType1; var genericType2 = new DescribedType(new SimpleName("GenericType", 2).Qualify(), testAsm); genericType2.AddGenericParameter(new DescribedGenericParameter(genericType2, new SimpleName("T1"))); genericType2.AddGenericParameter(new DescribedGenericParameter(genericType2, new SimpleName("T2"))); testAsm.AddType(genericType2); this.GenericType2 = genericType2; var namespaceType = new DescribedType( new SimpleName("NamespaceType").Qualify(new SimpleName("TestNamespace")), testAsm); testAsm.AddType(namespaceType); this.NamespaceType = namespaceType; }
public void ReadDescribedString8() { string value = "ABC"; var descriptor = new DescribedType("GHI", "DEF"); var describedValue = new DescribedType(descriptor, value); _scratchByteBuffer.Reset(); AmqpCodec.EncodeObject(describedValue, _scratchByteBuffer); var encoded = _scratchByteBuffer.Buffer.AsMemory(0, _scratchByteBuffer.WritePos).ToArray(); var encodedBuffer = new ByteBuffer(encoded, 0, encoded.Length); var decoded = (DescribedType)AmqpCodec.DecodeObject(encodedBuffer); Assert.AreEqual(value, decoded.Value); var decodedDescriptor = (DescribedType)decoded.Descriptor; Assert.AreEqual(descriptor.Value, decodedDescriptor.Value); Assert.AreEqual(descriptor.Descriptor, decodedDescriptor.Descriptor); var reader = new AmqpReader(encoded); Assert.AreEqual(AmqpToken.Descriptor, reader.MoveNext()); // let's see what's the type of the descriptor. Oh, it's another descriptor Assert.AreEqual(AmqpToken.Descriptor, reader.MoveNext()); Assert.AreEqual(AmqpToken.String, reader.MoveNext()); var d1 = Encoding.UTF8.GetString(reader.Bytes); Assert.AreEqual(AmqpToken.String, reader.MoveNext()); var d2 = Encoding.UTF8.GetString(reader.Bytes); Assert.AreEqual(AmqpToken.String, reader.MoveNext()); var v1 = Encoding.UTF8.GetString(reader.Bytes); }
/// <inheritdoc/> protected override Tuple <IAssembly, IEnumerable <IAssembly> > RewriteAssemblies( Tuple <IAssembly, IEnumerable <IAssembly> > MainAndOtherAssemblies, IBinder Binder, ICompilerLog Log) { // In addition to emitting LLVM IR from managed code, flame-llvm must also // set up an environment in which managed code can run. Part of this // environment is the 'main' function: managed code expects an entry point // to look like this: `void|int Main(|string[])`, whereas a C 'main' function // must have the following signature: `int main(int, byte**)`. // // To bridge this divide, we'll generate a 'main' function and use that to // call the entry point. var originalAsm = MainAndOtherAssemblies.Item1; var originalEntryPoint = originalAsm.GetEntryPoint(); if (originalEntryPoint == null) { // We can't rewrite the entry point of an assembly that doesn't // have an entry point. return(MainAndOtherAssemblies); } // Generate the following class: // // public static class __entry_point // { // [#builtin_abi("C")] // [#builtin_llvm_linkage(external)] // public static int main(int argc, byte** argv) // { // try // { // var parsedArgs = Environment.Initialize(argc, argv); // return actual_entry_point(...); // // --or-- // actual_entry_point(...); // return 0; // } // catch (Exception ex) // { // Environment.HandleFatalException(ex); // return 1; // } // } // } var mainAsm = new DescribedAssembly( originalAsm.Name, originalAsm.AssemblyVersion, Binder.Environment); var epType = new DescribedType(new SimpleName("__entry_point"), mainAsm); epType.AddAttribute(PrimitiveAttributes.Instance.StaticTypeAttribute); var mainThunk = new DescribedBodyMethod( new SimpleName("main"), epType, PrimitiveTypes.Int32, true); mainThunk.AddAttribute(new LLVMLinkageAttribute(LLVMLinkage.LLVMExternalLinkage)); mainThunk.AddAttribute(LLVMAttributes.CreateAbiAttribute("C")); mainThunk.AddParameter(new DescribedParameter("argc", PrimitiveTypes.Int32)); mainThunk.AddParameter( new DescribedParameter( "argv", PrimitiveTypes.UInt8 .MakePointerType(PointerKind.TransientPointer) .MakePointerType(PointerKind.TransientPointer))); if (originalEntryPoint.HasSameSignature(mainThunk)) { // We don't have to rewrite the entry point if the existing entry point // already has the expected form. return(MainAndOtherAssemblies); } var epCall = CreateEntryPointCall(originalEntryPoint, mainThunk, Binder); mainThunk.Body = epCall.Type.GetIsInteger() ? (IStatement) new ReturnStatement( new StaticCastExpression(epCall, PrimitiveTypes.Int32).Simplify()) : new BlockStatement(new IStatement[] { new ExpressionStatement(epCall), new ReturnStatement(new IntegerExpression(0)) }); var handleExceptionMethod = BindEnvironmentHandleFatalExceptionMethod(Binder); if (handleExceptionMethod != null) { var exceptionParam = handleExceptionMethod.Parameters.Single <IParameter>(); var catchClause = new CatchClause( new DescribedVariableMember( exceptionParam.Name, exceptionParam.ParameterType)); catchClause.Body = new BlockStatement(new IStatement[] { new ExpressionStatement( new InvocationExpression( handleExceptionMethod, null, new IExpression[] { catchClause.ExceptionVariable.CreateGetExpression() })), new ReturnStatement(new IntegerExpression(1)) }); mainThunk.Body = new TryStatement( mainThunk.Body, new CatchClause[] { catchClause }); } epType.AddMethod(mainThunk); mainAsm.AddType(epType); mainAsm.EntryPoint = mainThunk; return(new Tuple <IAssembly, IEnumerable <IAssembly> >( mainAsm, new IAssembly[] { originalAsm }.Concat <IAssembly>(MainAndOtherAssemblies.Item2))); }
public static int GetEncodeSize(DescribedType value) { return(value == null ? FixedWidth.NullEncoded : FixedWidth.FormatCode + AmqpEncoding.GetObjectEncodeSize(value.Descriptor) + AmqpEncoding.GetObjectEncodeSize(value.Value)); }
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 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.Char: case PropertyValueType.Int16: case PropertyValueType.UInt16: case PropertyValueType.Int32: case PropertyValueType.UInt32: case PropertyValueType.Int64: case PropertyValueType.UInt64: case PropertyValueType.Single: case PropertyValueType.Double: case PropertyValueType.Decimal: case PropertyValueType.Boolean: case PropertyValueType.Guid: case PropertyValueType.String: case PropertyValueType.DateTime: { amqpObject = netObject; break; } case PropertyValueType.Uri: { amqpObject = new DescribedType((object)"com.microsoft:uri", ((Uri)netObject).AbsoluteUri); break; } case PropertyValueType.DateTimeOffset: { object obj = "com.microsoft:datetime-offset"; DateTimeOffset dateTimeOffset = (DateTimeOffset)netObject; amqpObject = new DescribedType(obj, (object)dateTimeOffset.UtcTicks); break; } case PropertyValueType.TimeSpan: { object obj1 = "com.microsoft:timespan"; TimeSpan timeSpan = (TimeSpan)netObject; amqpObject = new DescribedType(obj1, (object)timeSpan.Ticks); break; } case PropertyValueType.Stream: { if (mappingType != MappingType.ApplicationProperty) { break; } amqpObject = MessageConverter.ReadStream((Stream)netObject); break; } case PropertyValueType.Unknown: { if (!(netObject is Stream)) { if (mappingType == MappingType.ApplicationProperty) { throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.AsError(new SerializationException(SRClient.FailedToSerializeUnsupportedType(netObject.GetType().FullName)), null); } if (netObject is byte[]) { amqpObject = new ArraySegment <byte>((byte[])netObject); break; } else if (!(netObject is IList)) { if (!(netObject is IDictionary)) { break; } amqpObject = new AmqpMap((IDictionary)netObject); break; } else { amqpObject = netObject; break; } } else { if (mappingType != MappingType.ApplicationProperty) { break; } amqpObject = MessageConverter.ReadStream((Stream)netObject); break; } } } return(amqpObject != null); }
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); }
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.Char: case PropertyValueType.Int16: case PropertyValueType.UInt16: case PropertyValueType.Int32: case PropertyValueType.UInt32: case PropertyValueType.Int64: case PropertyValueType.UInt64: case PropertyValueType.Single: case PropertyValueType.Double: case PropertyValueType.Decimal: case PropertyValueType.Boolean: case PropertyValueType.Guid: case PropertyValueType.String: case PropertyValueType.DateTime: { netObject = amqpObject; return(netObject != null); } case PropertyValueType.Uri: case PropertyValueType.DateTimeOffset: case PropertyValueType.TimeSpan: case PropertyValueType.Stream: { return(netObject != null); } case PropertyValueType.Unknown: { if (amqpObject is AmqpSymbol) { netObject = ((AmqpSymbol)amqpObject).Value; return(netObject != null); } else if (amqpObject is ArraySegment <byte> ) { ArraySegment <byte> nums = (ArraySegment <byte>)amqpObject; if (nums.Count != (int)nums.Array.Length) { byte[] numArray = new byte[nums.Count]; Buffer.BlockCopy(nums.Array, nums.Offset, numArray, 0, nums.Count); netObject = numArray; return(netObject != null); } else { netObject = nums.Array; return(netObject != null); } } else if (!(amqpObject is DescribedType)) { if (mappingType == MappingType.ApplicationProperty) { throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.AsError(new SerializationException(SRClient.FailedToSerializeUnsupportedType(amqpObject.GetType().FullName)), null); } if (!(amqpObject is AmqpMap)) { netObject = amqpObject; return(netObject != null); } else { AmqpMap amqpMaps = (AmqpMap)amqpObject; Dictionary <string, object> strs = new Dictionary <string, object>(); foreach (KeyValuePair <MapKey, object> keyValuePair in (IEnumerable <KeyValuePair <MapKey, object> >)amqpMaps) { strs.Add(keyValuePair.Key.ToString(), keyValuePair.Value); } netObject = strs; return(netObject != null); } } else { DescribedType describedType = (DescribedType)amqpObject; if (!(describedType.Descriptor is AmqpSymbol)) { return(netObject != null); } AmqpSymbol descriptor = (AmqpSymbol)describedType.Descriptor; if (descriptor.Equals("com.microsoft:uri")) { netObject = new Uri((string)describedType.Value); return(netObject != null); } else if (!descriptor.Equals("com.microsoft:timespan")) { if (!descriptor.Equals("com.microsoft:datetime-offset")) { return(netObject != null); } netObject = new DateTimeOffset(new DateTime((long)describedType.Value, DateTimeKind.Utc)); return(netObject != null); } else { netObject = new TimeSpan((long)describedType.Value); return(netObject != null); } } } default: { return(netObject != null); } } }
public void AmqpSerializerListEncodingTest() { Action <Person, Person> personValidator = (p1, p2) => { Assert.NotNull(p2); Assert.True(21 == p2.Age, "Age should be increased by OnDeserialized"); Assert.Equal(p1.GetType().Name, p2.GetType().Name); Assert.Equal(p1.DateOfBirth.Value, p2.DateOfBirth.Value); Assert.Equal(p1.Properties.Count, p2.Properties.Count); foreach (var k in p1.Properties.Keys) { Assert.Equal(p1.Properties[k], p2.Properties[k]); } }; Action <List <int>, List <int> > gradesValidator = (l1, l2) => { if (l1 == null || l2 == null) { Assert.True(l1 == null && l2 == null); return; } Assert.Equal(l1.Count, l2.Count); for (int i = 0; i < l1.Count; ++i) { Assert.Equal(l1[i], l2[i]); } }; // Create an object to be serialized Person p = new Student("Tom") { Address = new Address() { FullAddress = new string('B', 1024) }, Grades = new List <int>() { 1, 2, 3, 4, 5 } }; p.Age = 20; p.DateOfBirth = new DateTime(1980, 5, 12, 10, 2, 45, DateTimeKind.Utc); p.Properties.Add("height", 6.1); p.Properties.Add("male", true); p.Properties.Add("nick-name", "big foot"); var stream = new MemoryStream(new byte[4096], 0, 4096, true, true); AmqpContractSerializer.WriteObject(stream, p); stream.Flush(); // Deserialize and verify stream.Seek(0, SeekOrigin.Begin); Person p3 = AmqpContractSerializer.ReadObject <Person>(stream); personValidator(p, p3); Assert.Equal(((Student)p).Address.FullAddress, ((Student)p3).Address.FullAddress); gradesValidator(((Student)p).Grades, ((Student)p3).Grades); // Inter-op: it should be an AMQP described list as other clients see it stream.Seek(0, SeekOrigin.Begin); DescribedType dl1 = (DescribedType)AmqpEncoding.DecodeObject(new ByteBuffer(stream.ToArray(), 0, (int)stream.Length)); Assert.Equal(1ul, dl1.Descriptor); List <object> lv = dl1.Value as List <object>; Assert.NotNull(lv); Assert.Equal(p.Name, lv[0]); Assert.Equal(p.Age, lv[1]); Assert.Equal(p.DateOfBirth.Value, lv[2]); Assert.True(lv[3] is DescribedType, "Address is decribed type"); Assert.Equal(3ul, ((DescribedType)lv[3]).Descriptor); Assert.Equal(((List <object>)((DescribedType)lv[3]).Value)[0], ((Student)p).Address.FullAddress); Assert.True(lv[4] is AmqpMap, "Properties should be map"); Assert.Equal(((AmqpMap)lv[4])[new MapKey("height")], p.Properties["height"]); Assert.Equal(((AmqpMap)lv[4])[new MapKey("male")], p.Properties["male"]); Assert.Equal(((AmqpMap)lv[4])[new MapKey("nick-name")], p.Properties["nick-name"]); Assert.True(lv[5] is List <object>); // Non-default serializer AmqpContractSerializer serializer = new AmqpContractSerializer(); ByteBuffer bf1 = new ByteBuffer(1024, true); serializer.WriteObjectInternal(bf1, p); Person p4 = serializer.ReadObjectInternal <Person, Person>(bf1); personValidator(p, p4); // Extensible: more items in the payload should not break DescribedType dl2 = new DescribedType( new AmqpSymbol("teacher"), new List <object>() { "Jerry", 40, null, 50000, lv[4], null, null, "unknown-string", true, new AmqpSymbol("unknown-symbol") }); ByteBuffer bf2 = new ByteBuffer(1024, true); AmqpEncoding.EncodeObject(dl2, bf2); AmqpCodec.EncodeULong(100ul, bf2); Person p5 = serializer.ReadObjectInternal <Person, Person>(bf2); Assert.True(p5 is Teacher); Assert.Equal(100ul, AmqpCodec.DecodeULong(bf2)); // unknowns should be skipped Assert.Equal(0, bf2.Length); // teacher Teacher teacher = new Teacher("Han"); teacher.Age = 30; teacher.Sallary = 60000; teacher.Classes = new Dictionary <int, string>() { { 101, "CS" }, { 102, "Math" }, { 205, "Project" } }; ByteBuffer bf3 = new ByteBuffer(1024, true); serializer.WriteObjectInternal(bf3, teacher); Person p6 = serializer.ReadObjectInternal <Person, Person>(bf3); Assert.True(p6 is Teacher); Assert.Equal(teacher.Age + 1, p6.Age); Assert.Equal(teacher.Sallary * 2, ((Teacher)p6).Sallary); Assert.Equal(teacher.Id, ((Teacher)p6).Id); Assert.Equal(teacher.Classes[101], ((Teacher)p6).Classes[101]); Assert.Equal(teacher.Classes[102], ((Teacher)p6).Classes[102]); Assert.Equal(teacher.Classes[205], ((Teacher)p6).Classes[205]); }
protected override void Initialize(ByteBuffer buffer, FormatCode formatCode, out int size, out int count, out int encodeWidth, out CollectionType effectiveType) { if (formatCode != FormatCode.Described) { throw new AmqpException(AmqpErrorCode.InvalidField, AmqpResources.GetString(AmqpResources.AmqpInvalidFormatCode, formatCode, buffer.Offset)); } effectiveType = null; formatCode = AmqpEncoding.ReadFormatCode(buffer); ulong? code = null; AmqpSymbol symbol = default(AmqpSymbol); if (formatCode == FormatCode.ULong0) { code = 0; } else if (formatCode == FormatCode.ULong || formatCode == FormatCode.SmallULong) { code = ULongEncoding.Decode(buffer, formatCode); } else if (formatCode == FormatCode.Symbol8 || formatCode == FormatCode.Symbol32) { symbol = SymbolEncoding.Decode(buffer, formatCode); } if (this.AreEqual(this.descriptorCode, this.descriptorName, code, symbol)) { effectiveType = this; } else if (this.knownTypes != null) { for (int i = 0; i < this.knownTypes.Length; ++i) { var kvp = this.knownTypes[i]; if (kvp.Value == null) { SerializableType knownType = this.serializer.GetType(kvp.Key); this.knownTypes[i] = kvp = new KeyValuePair <Type, SerializableType>(kvp.Key, knownType); } DescribedType describedKnownType = (DescribedType)kvp.Value; if (this.AreEqual(describedKnownType.descriptorCode, describedKnownType.descriptorName, code, symbol)) { effectiveType = describedKnownType; break; } } } if (effectiveType == null) { throw new SerializationException(AmqpResources.GetString(AmqpResources.AmqpUnknownDescriptor, code ?? (object)symbol.Value, this.type.Name)); } formatCode = AmqpEncoding.ReadFormatCode(buffer); if (this.Code == FormatCode.List32) { if (formatCode == FormatCode.List0) { size = count = encodeWidth = 0; } else { encodeWidth = formatCode == FormatCode.List8 ? FixedWidth.UByte : FixedWidth.UInt; AmqpEncoding.ReadSizeAndCount(buffer, formatCode, FormatCode.List8, FormatCode.List32, out size, out count); } } else { encodeWidth = formatCode == FormatCode.Map8 ? FixedWidth.UByte : FixedWidth.UInt; AmqpEncoding.ReadSizeAndCount(buffer, formatCode, FormatCode.Map8, FormatCode.Map32, out size, out count); } }
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"); }
public void AmqpCodecListTest() { byte[] workBuffer = new byte[4096]; ByteBuffer buffer = new ByteBuffer(workBuffer); string strBig = new string('A', 512); List <object> list = new List <object>(); list.Add(boolTrue); list.Add(boolFalse); list.Add(ubyteValue); list.Add(ushortValue); list.Add(uintValue); list.Add(ulongValue); list.Add(byteValue); list.Add(shortValue); list.Add(intValue); list.Add(longValue); list.Add(null); list.Add(floatValue); list.Add(doubleValue); list.Add(decimal32Value); list.Add(decimal64Value); list.Add(decimal128Value); list.Add(charValue); list.Add(dtValue); list.Add(uuidValue); list.Add(new ArraySegment <byte>()); list.Add(bin8Value); list.Add(bin32Value); list.Add(new AmqpSymbol()); list.Add(new AmqpSymbol(strValue)); list.Add(new AmqpSymbol(strBig)); list.Add(strValue); list.Add(strBig); list.Add(described1); list.Add(described2); list.Add(described3); list.Add(described4); AmqpCodec.EncodeList(list, buffer); // make sure the size written is correct (it has to be List32) // the first byte is FormatCode.List32 int listSize = (int)AmqpBitConverter.ReadUInt(workBuffer, 1, 4); Assert.Equal(buffer.Length - 5, listSize); IList decList = AmqpCodec.DecodeList(buffer); int index = 0; Assert.True(decList[index++].Equals(true), "Boolean true expected."); Assert.True(decList[index++].Equals(false), "Boolean false expected."); Assert.True(decList[index++].Equals(ubyteValue), "UByte value not equal."); Assert.True(decList[index++].Equals(ushortValue), "UShort value not equal."); Assert.True(decList[index++].Equals(uintValue), "UInt value not equal."); Assert.True(decList[index++].Equals(ulongValue), "ULong value not equal."); Assert.True(decList[index++].Equals(byteValue), "Byte value not equal."); Assert.True(decList[index++].Equals(shortValue), "Short value not equal."); Assert.True(decList[index++].Equals(intValue), "Int value not equal."); Assert.True(decList[index++].Equals(longValue), "Long value not equal."); Assert.True(decList[index++] == null, "Null object expected."); Assert.True(decList[index++].Equals(floatValue), "Float value not equal."); Assert.True(decList[index++].Equals(doubleValue), "Double value not equal."); Assert.True(decList[index++].Equals(decimal32Value), "Decimal32 value not equal."); Assert.True(decList[index++].Equals(decimal64Value), "Decimal64 value not equal."); Assert.True(decList[index++].Equals(decimal128Value), "Decimal128 value not equal."); Assert.True(decList[index++].Equals(charValue), "Char value not equal."); Assert.True(decList[index++].Equals(dtValue), "TimeStamp value not equal."); Assert.True(decList[index++].Equals(uuidValue), "Uuid value not equal."); Assert.True(decList[index++] == null, "Null binary expected."); ArraySegment <byte> bin8 = (ArraySegment <byte>)decList[index++]; EnsureEqual(bin8.Array, bin8.Offset, bin8.Count, bin8Value.Array, bin8Value.Offset, bin8Value.Count); ArraySegment <byte> bin32 = (ArraySegment <byte>)decList[index++]; EnsureEqual(bin32.Array, bin32.Offset, bin32.Count, bin32Value.Array, bin32Value.Offset, bin32Value.Count); Assert.True(decList[index++] == null, "Null symbol expected."); AmqpSymbol symDecode = (AmqpSymbol)decList[index++]; Assert.True(symDecode.Equals(strValue), "AmqpSymbol value not equal."); symDecode = (AmqpSymbol)decList[index++]; Assert.True(symDecode.Equals(strBig), "AmqpSymbol value (big) not equal."); string strDecode = (string)decList[index++]; Assert.True(strDecode.Equals(strValue), "string value not equal."); strDecode = (string)decList[index++]; Assert.True(strDecode.Equals(strBig), "string value (big) not equal."); DescribedType described = (DescribedType)decList[index++]; 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"); described = (DescribedType)decList[index++]; Assert.True(described.Descriptor.Equals(described2.Descriptor), "Described value 2 descriptor is different"); Assert.True(described.Value.Equals(described2.Value), "Described value 2 value is different"); described = (DescribedType)decList[index++]; Assert.True(described.Descriptor.Equals(described3.Descriptor), "Described value 3 descriptor is different"); Assert.True(described.Value.Equals(described3.Value), "Described value 3 value is different"); described = (DescribedType)decList[index++]; EnsureEqual((DateTime)described4.Descriptor, (DateTime)described.Descriptor); EnsureEqual((IList)described.Value, (IList)described4.Value); }
public static int GetEncodeSize(DescribedType value) { return value == null ? FixedWidth.NullEncoded : FixedWidth.FormatCode + AmqpEncoding.GetObjectEncodeSize(value.Descriptor) + AmqpEncoding.GetObjectEncodeSize(value.Value); }