public void Deserialize_Stream_WithICustomObjectCreator_CreatesCustomObjects() { // Arrange var creator = new FakeCustomObjectCreator(); var settings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var serializer = new DefaultSerializer(settings, settings) { DeserializationOptions = new DeserializationOptions() { CustomObjectCreator = creator } }; var stream = new MemoryStream(Encoding.UTF8.GetBytes("{\"subNode\":{\"property\":\"value\"}}")); // Act var result = serializer.Deserialize<JsonDocument>(stream); // Assert Assert.NotNull(result); Assert.NotNull(result.SubNode); Assert.AreEqual(typeof(DocumentSubNodeInherited), result.SubNode.GetType()); Assert.AreEqual("value", result.SubNode.Property); }
public static IServiceSerializer CreateServiceSerializer(Type @type) { var defaultSerializer = new DefaultSerializer(); var jsonSerializer = new JsonSerializer(); defaultSerializer.SetSuccessor(jsonSerializer); return defaultSerializer; }
public virtual void PersistSelf(Type typeToBePersisted, object toBePersisted, ISerializer serializer) { if (serializer == null) { serializer = new DefaultSerializer(Pipe.ControlChannelEncoding); } var pathSegment = typeToBePersisted.FullName; this.WriteLineToSelf(serializer.GetString(serializer.GetBuffer(toBePersisted)), pathSegment); }
public void SampleMessageFieldParams() { var defaultSerializer = new DefaultSerializer<SampleMessage>(this.messageRegistry, this.typeRegistry); var d = new MessageDispatcher<SampleApiClass>(this.messageRegistry, this.typeRegistry); using (var buf = new ThreadSafeWriteQueue(1024)) { var orig = new SampleMessage { MessageId = defaultSerializer.MessageId, A = 10 }; defaultSerializer.Serialize(buf, orig); var pos = buf.ReadMessage(); Assert.IsTrue(d.Dispatch(buf, pos, defaultSerializer.MessageId, new SampleApiClass())); } }
public void BinarySerialization() { var reg = new MessageRegistry(); var ser = new DefaultSerializer<SubMessage>(reg, new TypeRegistry( new[] { TypeRegistry.StandartTypes, new[] { new VectorXYZBinarySerializer() }})); using (var buf = new ThreadSafeWriteQueue(1024)) { var src = new SubMessage { Vector3 = new Vector3(1.1f, 2.2f, 3.3f) }; ser.Serialize(buf, src); var dst = new SubMessage(); ser.Deserialize(buf, buf.ReadMessage(), dst); Assert.AreEqual(src.Vector3, dst.Vector3); } }
public void SerializeActorFactory() { using (var context = NetMQContext.Create()) using (var testActor = new Actor(context)) { var serializer = new DefaultSerializer(Pipe.ControlChannelEncoding); var customer = new Customer(testActor); customer.Firstname = "george"; var buffer = serializer.GetBuffer(customer); var result = serializer.Deserializer<Customer>(buffer); Assert.AreEqual(customer.Firstname, result.Firstname); } }
public void TestDynamicObject() { var reg = new MessageRegistry(); var typeRegistry = TypeRegistry.CreateDefault(); var ser = new DefaultSerializer<SubMessage>(reg, typeRegistry); var r = new DynamicSerializer(reg, typeRegistry); using (var buf = new ThreadSafeWriteQueue(1024)) { dynamic src = new SubMessage { MessageId = ser.MessageId, A = 1, B = 2 }; r.Serialize(buf, src); dynamic a = new { }; r.Deserialize(buf, buf.ReadMessage(), a); } }
public void EmptyString() { var r = new DefaultSerializer<SubMessage>(this.messageRegistry, this.typeRegistry); using (var buf = new ThreadSafeWriteQueue(1024)) { var orig = new SubMessage { Text = string.Empty, }; r.Serialize(buf, orig); SubMessage message = new SubMessage(); r.Deserialize(buf, buf.ReadMessage(), message); Assert.AreEqual(orig.MessageId, message.MessageId); Assert.IsTrue(string.IsNullOrEmpty(message.Text)); } }
public void TestVec4() { var r = new DefaultSerializer<SingleMessage<Vector4>>(this.messageRegistry, this.typeRegistry,4); using (var buf = new ThreadSafeWriteQueue(1024)) { var orig = new SingleMessage<Vector4> { MessageId = r.MessageId, A = new Vector4(1.1f, 2.2f, 3.3f,( 4.4f)) }; r.Serialize(buf, orig); SingleMessage<Vector4> message = new SingleMessage<Vector4>(); r.Deserialize(buf, buf.ReadMessage(), message); Assert.AreEqual(orig.MessageId, message.MessageId); Assert.AreEqual(orig.A, message.A); } }
public void JsonSettings_With_Null_ContractResolver_Defaults_To_DefaultContractResolver() { JsonConvert.DefaultSettings = null; // no default settings available // Arrange var deserializationSettings = new JsonSerializerSettings { ContractResolver = null }; var serializationSettings = new JsonSerializerSettings { ContractResolver = null }; // Act var serializer = new DefaultSerializer(deserializationSettings, serializationSettings); // Assert Assert.IsInstanceOf<DefaultContractResolver>(serializer.DeserializationSettings.ContractResolver); Assert.IsInstanceOf<DefaultContractResolver>(serializer.SerializerSettings.ContractResolver); }
public void TestTable() { var reg = new MessageRegistry(); var a = new LuaSerializer(reg, LuaTypeRegistry.CreateDefault()); var ser = new DefaultSerializer<SubMessage>(reg, TypeRegistry.CreateDefault()); using (var buf = new ThreadSafeWriteQueue(1024)) { var dictionary = new Dictionary<LuaObject, LuaObject> { }; dictionary.Add(LuaObject.FromString("MessageId"), LuaObject.FromNumber(ser.MessageId)); var table = LuaObject.FromTable(dictionary); table[LuaObject.FromString("Text")] = LuaObject.FromString("abc"); a.Send(buf, table); int pos = buf.ReadMessage(); var id = buf.ReadInt32(pos); Assert.AreEqual(ser.MessageId, id); var table2 = a.Receive(buf, pos); Assert.AreEqual(ser.MessageId, table2[LuaObject.FromString("MessageId")].AsNumber()); Assert.AreEqual(table[LuaObject.FromString("Text")].AsString(), table2[LuaObject.FromString("Text")].AsString()); } }
public static string Serialize(VCard vcard) { return(DefaultSerializer.GetVCardString("VERSION", vcard.Version.ToVCardString(), false, vcard.Version)); }
public EchoServerHandler() { this.serializable = new DefaultSerializer(); }
public DefaultSerializerFacts() { m_serializer = new DefaultSerializer(); }
public DefaultSerializerTests() { serializer = new DefaultSerializer(); }
public void StripBrackets_StringList_RemovesBrackets() { //arrange var serializer = new DefaultSerializer(); object values = new List<string> { "1", "2", "3", "4" }; //act var valuesBytes = serializer.Serialize(values); var actual = valuesBytes.StripBrackets(); //assert var expected = new byte[] {0x22, 0x31, 0x22, 0x2c, 0x22, 0x32, 0x22, 0x2c, 0x22, 0x33, 0x22, 0x2c, 0x22, 0x34, 0x22}; Assert.AreEqual(expected, actual); }
protected override void OnInitializePhysics() { // collision configuration contains default setup for memory, collision setup CollisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); Broadphase = new DbvtBroadphase(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf); World.Gravity = new Vector3(0, -10, 0); GImpactCollisionAlgorithm.RegisterAlgorithm(Dispatcher); string bulletFile; string[] args = Environment.GetCommandLineArgs(); if (args.Length == 1) { bulletFile = "testFile.bullet"; } else { bulletFile = args[1]; } fileLoader = new CustomBulletWorldImporter(World); if (!fileLoader.LoadFile(bulletFile)) { CollisionShape groundShape = new BoxShape(50); CollisionShapes.Add(groundShape); RigidBody ground = LocalCreateRigidBody(0, Matrix.Translation(0, -50, 0), groundShape); ground.UserObject = "Ground"; // create a few dynamic rigidbodies float mass = 1.0f; Vector3[] positions = new Vector3[2] { new Vector3(0.1f, 0.2f, 0.3f), new Vector3(0.4f, 0.5f, 0.6f) }; float[] radi = new float[2] { 0.3f, 0.4f }; CollisionShape colShape = new MultiSphereShape(positions, radi); //CollisionShape colShape = new CapsuleShapeZ(1, 1); //CollisionShape colShape = new CylinderShapeZ(1, 1, 1); //CollisionShape colShape = new BoxShape(1); //CollisionShape colShape = new SphereShape(1); CollisionShapes.Add(colShape); Vector3 localInertia = colShape.CalculateLocalInertia(mass); float start_x = StartPosX - ArraySizeX / 2; float start_y = StartPosY; float start_z = StartPosZ - ArraySizeZ / 2; int k, i, j; for (k = 0; k < ArraySizeY; k++) { for (i = 0; i < ArraySizeX; i++) { for (j = 0; j < ArraySizeZ; j++) { Matrix startTransform = Matrix.Translation( 2 * i + start_x, 2 * k + start_y, 2 * j + start_z ); // using motionstate is recommended, it provides interpolation capabilities // and only synchronizes 'active' objects DefaultMotionState myMotionState = new DefaultMotionState(startTransform); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia); RigidBody body = new RigidBody(rbInfo); rbInfo.Dispose(); // make it drop from a height body.Translate(new Vector3(0, 20, 0)); World.AddRigidBody(body); } } } DefaultSerializer serializer = new DefaultSerializer(); serializer.RegisterNameForObject(ground, "GroundName"); for (i = 0; i < CollisionShapes.Count; i++) { serializer.RegisterNameForObject(CollisionShapes[i], "name" + i.ToString()); } Point2PointConstraint p2p = new Point2PointConstraint((RigidBody)World.CollisionObjectArray[2], new Vector3(0, 1, 0)); World.AddConstraint(p2p); serializer.RegisterNameForObject(p2p, "constraintje"); World.Serialize(serializer); BulletSharp.DataStream data = serializer.LockBuffer(); byte[] dataBytes = new byte[data.Length]; data.Read(dataBytes, 0, dataBytes.Length); FileStream file = new FileStream("testFile.bullet", FileMode.Create); file.Write(dataBytes, 0, dataBytes.Length); file.Close(); } }
private static void WriteEntityContent(TableOperation operation, OperationContext ctx, JsonTextWriter jsonWriter) { ITableEntity entityToWrite = operation.Entity; Dictionary <string, object> propertyDictionary = new Dictionary <string, object>(); foreach (KeyValuePair <string, object> kvp in GetPropertiesWithKeys(entityToWrite, ctx, operation.OperationType)) { if (kvp.Value == null) { continue; } if (kvp.Value.GetType() == typeof(DateTime)) { propertyDictionary[kvp.Key] = ((DateTime)kvp.Value).ToUniversalTime().ToString("o", System.Globalization.CultureInfo.InvariantCulture); propertyDictionary[kvp.Key + Constants.OdataTypeString] = Constants.EdmDateTime; continue; } if (kvp.Value.GetType() == typeof(byte[])) { propertyDictionary[kvp.Key] = Convert.ToBase64String((byte[])kvp.Value); propertyDictionary[kvp.Key + Constants.OdataTypeString] = Constants.EdmBinary; continue; } if (kvp.Value.GetType() == typeof(Int64)) { propertyDictionary[kvp.Key] = kvp.Value.ToString(); propertyDictionary[kvp.Key + Constants.OdataTypeString] = Constants.EdmInt64; continue; } if (kvp.Value.GetType() == typeof(Guid)) { propertyDictionary[kvp.Key] = kvp.Value.ToString(); propertyDictionary[kvp.Key + Constants.OdataTypeString] = Constants.EdmGuid; continue; } if (kvp.Value.GetType() == typeof(Double)) { Double value = ((Double)kvp.Value); if (Double.IsNaN(value)) { propertyDictionary[kvp.Key] = "NaN"; } else if (Double.IsPositiveInfinity(value)) { propertyDictionary[kvp.Key] = "Infinity"; } else if (Double.IsNegativeInfinity(value)) { propertyDictionary[kvp.Key] = "-Infinity"; } else { propertyDictionary[kvp.Key] = Convert.ToString(kvp.Value, System.Globalization.CultureInfo.InvariantCulture); } propertyDictionary[kvp.Key + Constants.OdataTypeString] = Constants.EdmDouble; continue; } propertyDictionary[kvp.Key] = kvp.Value; } JObject json = JObject.FromObject(propertyDictionary, DefaultSerializer.Create()); json.WriteTo(jsonWriter); }
public string Serialize <T>(T body) { return(DefaultSerializer.Serialize(body)); }
public SerializeDemoSimulation() { CollisionConfiguration = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConfiguration); Broadphase = new DbvtBroadphase(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(Dispatcher); string bulletFile; string[] args = Environment.GetCommandLineArgs(); if (args.Length == 1) { bulletFile = "testFile.bullet"; } else { bulletFile = args[1]; } _fileLoader = new CustomBulletWorldImporter(World); if (!_fileLoader.LoadFile(bulletFile)) { var groundShape = new BoxShape(50); _collisionShapes.Add(groundShape); RigidBody ground = PhysicsHelper.CreateStaticBody(Matrix.Translation(0, -50, 0), groundShape, World); ground.UserObject = "Ground"; // create a few dynamic rigidbodies float mass = 1.0f; Vector3[] positions = new[] { new Vector3(0.1f, 0.2f, 0.3f), new Vector3(0.4f, 0.5f, 0.6f) }; float[] radi = new float[2] { 0.3f, 0.4f }; var colShape = new MultiSphereShape(positions, radi); //var colShape = new CapsuleShapeZ(1, 1); //var colShape = new CylinderShapeZ(1, 1, 1); //var colShape = new BoxShape(1); //var colShape = new SphereShape(1); _collisionShapes.Add(colShape); Vector3 localInertia = colShape.CalculateLocalInertia(mass); float startX = StartPosX - NumObjectsX / 2; float startY = StartPosY; float startZ = StartPosZ - NumObjectsZ / 2; for (int y = 0; y < NumObjectsY; y++) { for (int x = 0; x < NumObjectsX; x++) { for (int z = 0; z < NumObjectsZ; z++) { Matrix startTransform = Matrix.Translation( 2 * x + startX, 2 * y + startY, 2 * z + startZ ); // using motionstate is recommended, it provides interpolation capabilities // and only synchronizes 'active' objects DefaultMotionState myMotionState = new DefaultMotionState(startTransform); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia); RigidBody body = new RigidBody(rbInfo); rbInfo.Dispose(); // make it drop from a height body.Translate(new Vector3(0, 20, 0)); World.AddRigidBody(body); } } } using (var serializer = new DefaultSerializer()) { serializer.RegisterNameForObject(ground, "GroundName"); for (int i = 0; i < _collisionShapes.Count; i++) { serializer.RegisterNameForObject(_collisionShapes[i], "name" + i.ToString()); } var p2p = new Point2PointConstraint((RigidBody)World.CollisionObjectArray[2], new Vector3(0, 1, 0)); World.AddConstraint(p2p); serializer.RegisterNameForObject(p2p, "constraintje"); World.Serialize(serializer); byte[] dataBytes = new byte[serializer.CurrentBufferSize]; Marshal.Copy(serializer.BufferPointer, dataBytes, 0, dataBytes.Length); using (var file = new FileStream("testFile.bullet", FileMode.Create)) { file.Write(dataBytes, 0, dataBytes.Length); } } } }
public void JsonSettings_With_Null_ContractResolver_Uses_JsonConvert_Default_ContractResolver_If_Available() { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var deserializationSettings = new JsonSerializerSettings { ContractResolver = null }; var serializationSettings = new JsonSerializerSettings { ContractResolver = null }; var serializer = new DefaultSerializer(deserializationSettings, serializationSettings); Assert.IsInstanceOf<CamelCasePropertyNamesContractResolver>(serializer.DeserializationSettings.ContractResolver); Assert.IsInstanceOf<CamelCasePropertyNamesContractResolver>(serializer.SerializerSettings.ContractResolver); }
public void GetMemberName_IgnoredProperty_ReturnsNull() { // Arrange var settings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var serializer = new DefaultSerializer(settings, settings); // Act var result = serializer.GetMemberName(typeof(JsonDocument).GetTypeInfo().GetProperty("IgnoredProperty")); // Assert Assert.IsNull(result); }
public void GetMemberName_NamedProperty_ReturnsNameFromAttribute() { // Arrange var settings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var serializer = new DefaultSerializer(settings, settings); // Act var result = serializer.GetMemberName(typeof(JsonDocument).GetTypeInfo().GetProperty("NamedProperty")); // Assert Assert.AreEqual("useThisName", result); }
public static object FromJson( JsonValue json, Type typeScope, DeserializationContext context = default(DeserializationContext) ) { // === Handle null === if (json.IsNull) { return(null); } // === Parse and validate arguments === if (typeScope == null) { throw new ArgumentNullException(nameof(typeScope)); } // context cannot be null, no need to check // === Guard insecure deserialization === if (!context.suppressInsecureDeserializationException) { if (typeScope == typeof(object)) { throw new InsecureDeserializationException( "You cannot deserialize unknown data to an 'object' " + "or 'dynamic' variable, as it poses a security risk. " + "Read the security section of the serialization " + "documentation to learn more." ); } } // === Determine deserialization type (the "$type" argument) === Type deserializationType = GetDeserializationType(json, typeScope); // === Call static constructor of the deserialized type === RuntimeHelpers.RunClassConstructor(deserializationType.TypeHandle); // === Deserialize === // .NET primitives if (typeScope.IsPrimitive) { return(DotNetPrimitivesSerializer.FromJson(json, typeScope)); } // string if (typeScope == typeof(string)) { return(json.AsString); } // enums if (typeScope.IsEnum) { return(EnumSerializer.FromJson(json, typeScope)); } // arrays if (typeScope.IsArray) { // binary data if (typeScope == typeof(byte[])) { return(BinarySerializer.FromJson(json, typeScope, context)); } return(ArraySerializer.FromJson(json, typeScope, context)); } // by what type value to search through ITypeSerializers var searchType = typeScope.IsGenericType ? typeScope.GetGenericTypeDefinition() : typeScope; // exact type serializers if (exactTypeSerializers.TryGetValue(searchType, out ITypeSerializer serializer)) { return(serializer.FromJson(json, deserializationType, context)); } // assignable type serializers foreach (var pair in assignableTypeSerializers) { if (pair.Key.IsAssignableFrom(searchType)) { return(pair.Value.FromJson(json, deserializationType, context)); } } // unisave serializable if (typeof(IUnisaveSerializable).IsAssignableFrom(deserializationType)) { return(UnisaveSerializableTypeSerializer.FromJson( json, deserializationType, context )); } // serializable if (typeof(ISerializable).IsAssignableFrom(deserializationType)) { return(SerializableTypeSerializer.FromJson( json, deserializationType, context )); } // other return(DefaultSerializer.FromJson( json, deserializationType, context )); }
static IEnumerable <OutboxOperation> ConvertStringToObject(string data) { return(string.IsNullOrEmpty(data) ? Enumerable.Empty <OutboxOperation>() : DefaultSerializer.DeSerialize <IEnumerable <OutboxOperation> >(data)); }
public void GetErrorMessageFromFormValidationError() { #region response objects var responseWithErrorMessage = @"{ ""remediation"": { ""type"": ""array"", ""value"": [ { ""rel"": [ ""create-form"" ], ""name"": ""reset-authenticator"", ""relatesTo"": [ ""$.currentAuthenticator"" ], ""href"": "".................."", ""method"": ""POST"", ""produces"": ""application/ion+json; okta-version=1.0.0"", ""value"": [ { ""name"": ""credentials"", ""type"": ""object"", ""form"": { ""value"": [ { ""name"": ""passcode"", ""label"": ""New password"", ""secret"": true, ""messages"": { ""type"": ""array"", ""value"": [ { ""message"": ""Error Message"", ""i18n"": { ""key"": ""password.passwordRequirementsNotMet"", ""params"": [ ""Password requirements: at least 8 characters,"" ] }, ""class"": ""ERROR"" } ] } } ] }, ""required"": true } ], ""accepts"": ""application/json; okta-version=1.0.0"" } ] } }"; var responseWithNoErrors = @"{ ""remediation"": { ""type"": ""array"", ""value"": [ { ""rel"": [ ""create-form"" ], ""name"": ""reset-authenticator"", ""relatesTo"": [ ""$.currentAuthenticator"" ], ""value"": [ { ""form"": { ""value"": [ { ""name"": ""passcode"", ""label"": ""New password"", ""secret"": true, } ] }, ""required"": true } ], ""accepts"": ""application/json; okta-version=1.0.0"" } ] } }"; #endregion response objects var serializer = new DefaultSerializer(); var resourseFactory = new ResourceFactory(null, null, null); var errorData = serializer.Deserialize(responseWithErrorMessage); var errorObject = resourseFactory.CreateNew <IonApiError>(errorData); errorObject.ErrorSummary.Should().Be("Error Message"); errorData = serializer.Deserialize(responseWithNoErrors); errorObject = resourseFactory.CreateNew <IonApiError>(errorData); errorObject.ErrorSummary.Should().BeNullOrEmpty(); errorData = serializer.Deserialize("{ }"); errorObject = resourseFactory.CreateNew <IonApiError>(errorData); errorObject.ErrorSummary.Should().BeNullOrEmpty(); }
public virtual void OnHandleInput() { if (Input.KeysPressed.Count != 0) { switch (Input.KeysPressed[0]) { case Keys.Escape: case Keys.Q: Graphics.Form.Close(); return; case Keys.F1: MessageBox.Show( "Move using WASD + shift\n" + "Left click - point camera\n" + "Right click - pick up an object using a Point2PointConstraint\n" + "Right click + shift - pick up an object using a fixed Generic6DofConstraint\n" + "Space - shoot box\n" + "Q - quit\n" + Graphics.InfoText, "Help"); // Key release won't be captured Input.KeysDown.Remove(Keys.F1); break; case Keys.F3: IsDebugDrawEnabled = !IsDebugDrawEnabled; break; case Keys.F8: Input.ClearKeyCache(); GraphicsLibraryManager.ExitWithReload = true; Graphics.Form.Close(); break; case Keys.F11: Graphics.IsFullScreen = !Graphics.IsFullScreen; break; case (Keys.Control | Keys.F): const int maxSerializeBufferSize = 1024 * 1024 * 5; using (var serializer = new DefaultSerializer(maxSerializeBufferSize)) { World.Serialize(serializer); byte[] dataBytes = new byte[serializer.CurrentBufferSize]; System.Runtime.InteropServices.Marshal.Copy(serializer.BufferPointer, dataBytes, 0, dataBytes.Length); using (var file = new System.IO.FileStream("world.bullet", System.IO.FileMode.Create)) { file.Write(dataBytes, 0, dataBytes.Length); } } break; case Keys.G: //shadowsEnabled = !shadowsEnabled; break; case Keys.Space: ShootBox(Freelook.Eye, GetCameraRayTo()); break; case Keys.Return: ClientResetScene(); break; } } _bodyPicker.Update(); }
public HybridDbContractResolver(DefaultSerializer serializer) : base(shareCache: false) { this.serializer = serializer; }
public void GetMemberName_Null_ArgumentNullException() { // Arrange var serializer = new DefaultSerializer(); // Act/Assert Assert.Throws<ArgumentNullException>(() => serializer.GetMemberName(null)); }
private static Dictionary <string, object> ReadSingleItem(JToken token, out string etag) { Dictionary <string, object> properties = token.ToObject <Dictionary <string, object> >(DefaultSerializer.Create()); // Parse the etag, and remove all the "odata.*" properties we don't use. if (properties.ContainsKey(@"odata.etag")) { etag = (string)properties[@"odata.etag"]; } else { etag = null; } foreach (string odataPropName in properties.Keys.Where(key => key.StartsWith(@"odata.", StringComparison.Ordinal)).ToArray()) { properties.Remove(odataPropName); } // We have to special-case timestamp here, because in the 'minimalmetadata' case, // Timestamp doesn't have an "@odata.type" property - the assumption is that you know // the type. if (properties.ContainsKey(@"Timestamp") && properties[@"Timestamp"].GetType() == typeof(string)) { properties[@"Timestamp"] = DateTime.Parse((string)properties[@"Timestamp"], CultureInfo.InvariantCulture); } // In the full metadata case, this property will exist, and we need to remove it. if (properties.ContainsKey(@"*****@*****.**")) { properties.Remove(@"*****@*****.**"); } // Replace all the 'long's with 'int's (the JSON parser parses all integer types into longs, but the odata spec specifies that they're int's. foreach (KeyValuePair <string, object> odataProp in properties.Where(kvp => (kvp.Value != null) && (kvp.Value.GetType() == typeof(long))).ToArray()) { // We first have to unbox the value into a "long", then downcast into an "int". C# will not combine the operations. properties[odataProp.Key] = (int)(long)odataProp.Value; } foreach (KeyValuePair <string, object> typeAnnotation in properties.Where(kvp => kvp.Key.EndsWith(@"@odata.type", StringComparison.Ordinal)).ToArray()) { properties.Remove(typeAnnotation.Key); string propName = typeAnnotation.Key.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries)[0]; switch ((string)typeAnnotation.Value) { case Constants.EdmBinary: properties[propName] = Convert.FromBase64String((string)properties[propName]); break; case Constants.EdmBoolean: properties[propName] = Boolean.Parse((string)properties[propName]); break; case Constants.EdmDateTime: properties[propName] = DateTime.Parse((string)properties[propName], CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); break; case Constants.EdmDouble: properties[propName] = Double.Parse((string)properties[propName], CultureInfo.InvariantCulture); break; case Constants.EdmGuid: properties[propName] = Guid.Parse((string)properties[propName]); break; case Constants.EdmInt32: properties[propName] = Int32.Parse((string)properties[propName], CultureInfo.InvariantCulture); break; case Constants.EdmInt64: properties[propName] = Int64.Parse((string)properties[propName], CultureInfo.InvariantCulture); break; case Constants.EdmString: properties[propName] = (string)properties[propName]; break; default: throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.UnexpectedEDMType, typeAnnotation.Value)); } } return(properties); }
private async Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs) { if (!eventArgs.ApplicationMessage.Topic.Contains(GetRequestTopic(null, null))) { return; } var message = eventArgs.ApplicationMessage; var methodName = message.GetUserProperty("Method"); var id = message.GetUserProperty("Id"); var timeout = message.GetUserProperty <int?>("Timeout"); var broadcast = message.GetUserProperty <bool?>("Broadcast") ?? false; var noResponse = message.GetUserProperty <bool?>("NoResponse") ?? false; var clientId = GetSource(message.Topic); using var serviceScope = _serviceProvider.CreateScope(); using var cts = timeout.HasValue ? new CancellationTokenSource(timeout.Value * 1000) : new CancellationTokenSource(); var responseBuilder = new MqttApplicationMessageBuilder() .WithContentType(DefaultSerializer.ContentType) .WithTopic(GetResponseTopic(GetSource(message.Topic))) .WithAtLeastOnceQoS(); if (broadcast) { responseBuilder.WithUserProperty("Broadcast", true.ToString()); } if (timeout > 0) { responseBuilder.WithMessageExpiryInterval((uint)timeout.Value); } try { if (!RpcMethodResolver.Methods.TryGetValue(methodName, out var method)) { if (string.IsNullOrEmpty(id) || noResponse) { return; } throw new EntryPointNotFoundException($"Method '{methodName}' not found."); } var parameters = method.GetParameters(); object[] args; switch (parameters.Length) { case 0: args = null; break; case 1: var parameterInfo = parameters.First(); args = parameterInfo.ParameterType == typeof(byte[]) ? new[] { (object)message.Payload } : new[] { DefaultSerializer.Deserialize(message.Payload, parameterInfo.ParameterType) }; break; default: _logger.Error(new NotImplementedException(), "Multiple parameters resolving has not been supported yet, please use a key-value object."); return; } var rpcService = (IRpcService)serviceScope.ServiceProvider.GetService(method.DeclaringType); rpcService.CurrentContext = new RpcContext { Topic = message.Topic, RemoteClientId = clientId }; var task = Task.Run(async() => { var returnValue = method.Invoke(rpcService, args); if (returnValue is Task t) { await t.ConfigureAwait(false); if (t.GetType().IsGenericType) { var resultProperty = t.GetType().GetProperty("Result"); Debug.Assert(resultProperty != null); returnValue = resultProperty.GetValue(t); } } return(returnValue); }, cts.Token); if (!string.IsNullOrEmpty(id)) { if (!_waitingCalls.TryAdd(id, new CancellableTask(task, cts))) { throw new InvalidOperationException(); } } else { _noIdCalls.TryAdd(cts, task); } var result = await task.ConfigureAwait(false); responseBuilder.WithUserProperty("Success", true.ToString()); if (!noResponse) { responseBuilder.WithUserProperty("Id", id) .WithPayload(DefaultSerializer.Serialize(result)); } } catch (Exception ex) { responseBuilder.WithUserProperty("Success", false.ToString()) .WithUserProperty("ErrorCode", ex.HResult.ToString()) .WithUserProperty("ErrorMessage", ex.Message); } finally { if (!string.IsNullOrEmpty(id)) { _waitingCalls.TryRemove(id, out _); } else { _noIdCalls.TryRemove(cts, out _); } if (!noResponse) { await _mqttClient.PublishAsync(responseBuilder.Build()).ConfigureAwait(false); } } }
public void StripBrackets_WhenString_DoesNothing() { //arrange var serializer = new DefaultSerializer(); object values = "howdy pardner"; //act var valuesBytes = serializer.Serialize(values); var actual = valuesBytes.StripBrackets(); //assert var expected = new byte[] { 0x22, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x20, 0x70, 0x61, 0x72, 0x64, 0x6e, 0x65, 0x72, 0x22 }; Assert.AreEqual(expected, actual); }
public void SetDefault() { var serializer = new DefaultSerializer(); MimeSerializer.Default = serializer; Assert.Same(serializer, MimeSerializer.Default); }
public static string Serialize(VCard vcard) { return(DefaultSerializer.GetVCardString("FN", vcard.FormattedName, true, vcard.Version)); }
public void ThreeBytesString() { var r = new DefaultSerializer<SubMessage>(this.messageRegistry, this.typeRegistry); using (var buf = new ThreadSafeWriteQueue(1024)) { var orig = new SubMessage { Text = "aaa", }; r.Serialize(buf, orig); r.Serialize(buf, orig); SubMessage message = new SubMessage(); r.Deserialize(buf, buf.ReadMessage(), message); Assert.AreEqual(orig.MessageId, message.MessageId); Assert.AreEqual(orig.Text, message.Text); r.Deserialize(buf, buf.ReadMessage(), message); Assert.AreEqual(orig.MessageId, message.MessageId); Assert.AreEqual(orig.Text, message.Text); } }
static Config() { Serializer = new DefaultSerializer(); DataPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data"); }
public void TwoMessages() { var r = new DefaultSerializer<SubMessage>(this.messageRegistry, this.typeRegistry); using (var buf = new ThreadSafeWriteQueue(1024)) { var orig = new SubMessage { MessageId = int.MaxValue, A = int.MinValue, B = float.Epsilon, C = uint.MinValue, Byte = 1, Text = "aaaвпаав", }; var orig2 = new SubMessage { MessageId = int.MaxValue, A = int.MaxValue, B = float.MaxValue, C = uint.MaxValue, Byte = 255, Text = "впаавzz", }; r.Serialize(buf, orig); r.Serialize(buf, orig2); SubMessage message = new SubMessage(); r.Deserialize(buf, buf.ReadMessage(), message); Assert.AreEqual(orig.MessageId, message.MessageId); Assert.AreEqual(orig.A, message.A); Assert.AreEqual(orig.B, message.B); Assert.AreEqual(orig.C, message.C); Assert.AreEqual(orig.Text, message.Text); r.Deserialize(buf, buf.ReadMessage(), message); Assert.AreEqual(orig2.MessageId, message.MessageId); Assert.AreEqual(orig2.A, message.A); Assert.AreEqual(orig2.B, message.B); Assert.AreEqual(orig2.C, message.C); Assert.AreEqual(orig2.Text, message.Text); } }
private static JsonValue Serialize( object subject, Type typeScope, SerializationContext context ) { Type type = subject.GetType(); // .NET primitives if (type.IsPrimitive) { return(DotNetPrimitivesSerializer.ToJson(subject, type)); } // string if (type == typeof(string)) { return((string)subject); } // enums if (type.IsEnum) { return(EnumSerializer.ToJson(subject)); } // arrays if (type.IsArray) { // binary data if (type == typeof(byte[])) { return(BinarySerializer.ToJson(subject, typeScope, context)); } return(ArraySerializer.ToJson(subject, typeScope, context)); } // by what type value to search through ITypeSerializers var searchType = type.IsGenericType ? type.GetGenericTypeDefinition() : type; // exact type serializers if (exactTypeSerializers.TryGetValue(searchType, out ITypeSerializer serializer)) { return(serializer.ToJson(subject, typeScope, context)); } // assignable type serializers foreach (var pair in assignableTypeSerializers) { if (pair.Key.IsAssignableFrom(searchType)) { return(pair.Value.ToJson(subject, typeScope, context)); } } // unisave serializable if (typeof(IUnisaveSerializable).IsAssignableFrom(type)) { return(UnisaveSerializableTypeSerializer.ToJson( subject, typeScope, context )); } // serializable if (typeof(ISerializable).IsAssignableFrom(type)) { return(SerializableTypeSerializer.ToJson( subject, typeScope, context )); } // validate type scope if (!typeScope.IsAssignableFrom(type)) { throw new ArgumentException( $"Given subject is of type {type} that is not assignable " + $"to the given type scope {typeScope}" ); } // other return(DefaultSerializer.ToJson(subject, typeScope, context)); }
public DefaultGeneralTrieSettings() { IndexBuilder = new GeneralIndexBuilder <TK>(); TrieBuilder = () => new MvGeneralNode <TK, TV, char>(this); Serializer = new DefaultSerializer <TK, TV, char>(); }
public virtual void OnHandleInput() { if (Input.KeysPressed.Count != 0) { switch (Input.KeysPressed[0]) { case Keys.Escape: case Keys.Q: Graphics.Form.Close(); return; case Keys.F1: MessageBox.Show( "Move using WASD + shift\n" + "Left click - point camera\n" + "Right click - pick up an object using a Point2PointConstraint\n" + "Right click + shift - pick up an object using a fixed Generic6DofConstraint\n" + "Space - shoot box\n" + "Q - quit\n" + Graphics.InfoText, "Help"); // Key release won't be captured Input.KeysDown.Remove(Keys.F1); break; case Keys.F3: IsDebugDrawEnabled = !IsDebugDrawEnabled; break; case Keys.F8: Input.ClearKeyCache(); GraphicsLibraryManager.ExitWithReload = true; Graphics.Form.Close(); break; case Keys.F11: Graphics.IsFullScreen = !Graphics.IsFullScreen; break; case (Keys.Control | Keys.F): const int maxSerializeBufferSize = 1024 * 1024 * 5; using (var serializer = new DefaultSerializer(maxSerializeBufferSize)) { World.Serialize(serializer); byte[] dataBytes = new byte[serializer.CurrentBufferSize]; System.Runtime.InteropServices.Marshal.Copy(serializer.BufferPointer, dataBytes, 0, dataBytes.Length); using (var file = new System.IO.FileStream("world.bullet", System.IO.FileMode.Create)) { file.Write(dataBytes, 0, dataBytes.Length); } } break; case Keys.G: //shadowsEnabled = !shadowsEnabled; break; case Keys.Space: ShootBox(Freelook.Eye, GetRayTo(Input.MousePoint, Freelook.Eye, Freelook.Target, Graphics.FieldOfView)); break; case Keys.Return: ClientResetScene(); break; } } if (Input.MousePressed != MouseButtons.None) { Vector3 rayTo = GetRayTo(Input.MousePoint, Freelook.Eye, Freelook.Target, Graphics.FieldOfView); if (Input.MousePressed == MouseButtons.Right) { if (World != null) { Vector3 rayFrom = Freelook.Eye; ClosestRayResultCallback rayCallback = new ClosestRayResultCallback(ref rayFrom, ref rayTo); World.RayTest(ref rayFrom, ref rayTo, rayCallback); if (rayCallback.HasHit) { Vector3 pickPos = rayCallback.HitPointWorld; RigidBody body = rayCallback.CollisionObject as RigidBody; if (body != null) { if (!(body.IsStaticObject || body.IsKinematicObject)) { pickedBody = body; pickedBody.ActivationState = ActivationState.DisableDeactivation; Vector3 localPivot = Vector3.TransformCoordinate(pickPos, Matrix.Invert(body.CenterOfMassTransform)); if (Input.KeysDown.Contains(Keys.ShiftKey)) { Generic6DofConstraint dof6 = new Generic6DofConstraint(body, Matrix.Translation(localPivot), false) { LinearLowerLimit = Vector3.Zero, LinearUpperLimit = Vector3.Zero, AngularLowerLimit = Vector3.Zero, AngularUpperLimit = Vector3.Zero }; World.AddConstraint(dof6); pickConstraint = dof6; dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 0); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 1); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 2); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 3); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 4); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 5); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 0); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 1); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 2); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 3); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 4); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 5); } else { Point2PointConstraint p2p = new Point2PointConstraint(body, localPivot); World.AddConstraint(p2p); pickConstraint = p2p; p2p.Setting.ImpulseClamp = 30; //very weak constraint for picking p2p.Setting.Tau = 0.001f; /* * p2p.SetParam(ConstraintParams.Cfm, 0.8f, 0); * p2p.SetParam(ConstraintParams.Cfm, 0.8f, 1); * p2p.SetParam(ConstraintParams.Cfm, 0.8f, 2); * p2p.SetParam(ConstraintParams.Erp, 0.1f, 0); * p2p.SetParam(ConstraintParams.Erp, 0.1f, 1); * p2p.SetParam(ConstraintParams.Erp, 0.1f, 2); */ } } } else { MultiBodyLinkCollider multiCol = rayCallback.CollisionObject as MultiBodyLinkCollider; if (multiCol != null && multiCol.MultiBody != null) { MultiBody mb = multiCol.MultiBody; prevCanSleep = mb.CanSleep; mb.CanSleep = false; Vector3 pivotInA = mb.WorldPosToLocal(multiCol.Link, pickPos); MultiBodyPoint2Point p2p = new MultiBodyPoint2Point(mb, multiCol.Link, null, pivotInA, pickPos); p2p.MaxAppliedImpulse = 2; (World as MultiBodyDynamicsWorld).AddMultiBodyConstraint(p2p); pickingMultiBodyPoint2Point = p2p; } } oldPickingDist = (pickPos - rayFrom).Length; } rayCallback.Dispose(); } } } else if (Input.MouseReleased == MouseButtons.Right) { RemovePickingConstraint(); } // Mouse movement if (Input.MouseDown == MouseButtons.Right) { MovePickedBody(); } }
protected virtual void OnHandleInput() { if (Input.KeysPressed.Count != 0) { switch (Input.KeysPressed[0]) { case Keys.Escape: case Keys.Q: Form.Close(); return; case Keys.F1: MessageBox.Show( "Move using mouse and WASD + shift\n" + "Space - Shoot box\n" + "Q - Quit\n\n" + "G - Toggle shadows\n" + "L - Toggle deferred lighting\n", "Help"); return; case Keys.F3: //IsDebugDrawEnabled = !IsDebugDrawEnabled; break; case Keys.F11: //ToggleFullScreen(); break; case (Keys.Control | Keys.F): const int maxSerializeBufferSize = 1024 * 1024 * 5; using (var serializer = new DefaultSerializer(maxSerializeBufferSize)) { PhysicsContext.World.Serialize(serializer); byte[] dataBytes = new byte[serializer.CurrentBufferSize]; Marshal.Copy(serializer.BufferPointer, dataBytes, 0, dataBytes.Length); using (var file = new System.IO.FileStream("world.bullet", System.IO.FileMode.Create)) { file.Write(dataBytes, 0, dataBytes.Length); } } break; case Keys.G: shadowsEnabled = !shadowsEnabled; break; case Keys.L: deferredLightingEnabled = !deferredLightingEnabled; break; case Keys.Space: PhysicsContext.ShootBox(Freelook.Eye, GetRayTo(Input.MousePoint, Freelook.Eye, Freelook.Target, FieldOfView)); break; } } if (Input.MousePressed != MouseButtons.None) { Vector3 rayTo = GetRayTo(Input.MousePoint, Freelook.Eye, Freelook.Target, FieldOfView); if (Input.MousePressed == MouseButtons.Right) { if (PhysicsContext.World != null) { Vector3 rayFrom = Freelook.Eye; var rayCallback = new ClosestRayResultCallback(ref rayFrom, ref rayTo); PhysicsContext.World.RayTest(rayFrom, rayTo, rayCallback); if (rayCallback.HasHit) { RigidBody body = rayCallback.CollisionObject as RigidBody; if (body != null) { if (!(body.IsStaticObject || body.IsKinematicObject)) { pickedBody = body; pickedBody.ActivationState = ActivationState.DisableDeactivation; Vector3 pickPos = rayCallback.HitPointWorld; Vector3 localPivot = Vector3.TransformCoordinate(pickPos, Matrix.Invert(body.CenterOfMassTransform)); if (Input.KeysDown.Contains(Keys.ShiftKey)) { Generic6DofConstraint dof6 = new Generic6DofConstraint(body, Matrix.Translation(localPivot), false) { LinearLowerLimit = Vector3.Zero, LinearUpperLimit = Vector3.Zero, AngularLowerLimit = Vector3.Zero, AngularUpperLimit = Vector3.Zero }; pickConstraint = dof6; dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 0); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 1); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 2); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 3); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 4); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 5); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 0); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 1); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 2); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 3); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 4); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 5); } else { var p2p = new Point2PointConstraint(body, localPivot); pickConstraint = p2p; p2p.Setting.ImpulseClamp = 30; //very weak constraint for picking p2p.Setting.Tau = 0.001f; /* * p2p.SetParam(ConstraintParams.Cfm, 0.8f, 0); * p2p.SetParam(ConstraintParams.Cfm, 0.8f, 1); * p2p.SetParam(ConstraintParams.Cfm, 0.8f, 2); * p2p.SetParam(ConstraintParams.Erp, 0.1f, 0); * p2p.SetParam(ConstraintParams.Erp, 0.1f, 1); * p2p.SetParam(ConstraintParams.Erp, 0.1f, 2); */ } PhysicsContext.World.AddConstraint(pickConstraint); oldPickingDist = (pickPos - rayFrom).Length(); } } } rayCallback.Dispose(); } } } else if (Input.MouseReleased == MouseButtons.Right) { RemovePickingConstraint(); } // Mouse movement if (Input.MouseDown == MouseButtons.Right) { if (pickConstraint != null) { Vector3 newRayTo = GetRayTo(Input.MousePoint, Freelook.Eye, Freelook.Target, FieldOfView); if (pickConstraint.ConstraintType == TypedConstraintType.D6) { Generic6DofConstraint pickCon = pickConstraint as Generic6DofConstraint; //keep it at the same picking distance Vector3 rayFrom = Freelook.Eye; Vector3 dir = newRayTo - rayFrom; dir.Normalize(); dir *= oldPickingDist; Vector3 newPivotB = rayFrom + dir; Matrix tempFrameOffsetA = pickCon.FrameOffsetA; tempFrameOffsetA.M41 = newPivotB.X; tempFrameOffsetA.M42 = newPivotB.Y; tempFrameOffsetA.M43 = newPivotB.Z; pickCon.SetFrames(tempFrameOffsetA, pickCon.FrameOffsetB); } else { Point2PointConstraint pickCon = pickConstraint as Point2PointConstraint; //keep it at the same picking distance Vector3 rayFrom = Freelook.Eye; Vector3 dir = newRayTo - rayFrom; dir.Normalize(); dir *= oldPickingDist; pickCon.PivotInB = rayFrom + dir; } } } }
public EntitySerializationWithIlPropertyFactoryTests() { var entityReflector = new EntityReflector(new IlDynamicPropertyFactory()); SUT = new DefaultSerializer(CreateSerializationConfiguration(entityReflector)); }
public async Task Test() { var resolver = new MockResolveProxyIds(); var serializer = new DefaultSerializer(); await test(serializer, resolver, typeof(DateTime)).ConfigureAwait(false); await test(serializer, resolver, typeof(DateTime?)).ConfigureAwait(false); await test(serializer, resolver, typeof(DateTime[])).ConfigureAwait(false); await test(serializer, resolver, typeof(Guid)).ConfigureAwait(false); await test(serializer, resolver, typeof(Guid?)).ConfigureAwait(false); await test(serializer, resolver, typeof(Guid[])).ConfigureAwait(false); await test(serializer, resolver, typeof(SampleClassWithÑƑ)).ConfigureAwait(false); await test(serializer, resolver, typeof(SampleClassWithÑƑ[])).ConfigureAwait(false); await test(serializer, resolver, typeof(TimeSpan)).ConfigureAwait(false); await test(serializer, resolver, typeof(TimeSpan?)).ConfigureAwait(false); await test(serializer, resolver, typeof(TimeSpan[])).ConfigureAwait(false); await test(serializer, resolver, typeof(Type)).ConfigureAwait(false); await test(serializer, resolver, typeof(Type[])).ConfigureAwait(false); await test(serializer, resolver, typeof(bool)).ConfigureAwait(false); await test(serializer, resolver, typeof(bool?)).ConfigureAwait(false); await test(serializer, resolver, typeof(bool[])).ConfigureAwait(false); await test(serializer, resolver, typeof(byte)).ConfigureAwait(false); await test(serializer, resolver, typeof(byte?)).ConfigureAwait(false); await test(serializer, resolver, typeof(byte[])).ConfigureAwait(false); await test(serializer, resolver, typeof(char)).ConfigureAwait(false); await test(serializer, resolver, typeof(char?)).ConfigureAwait(false); await test(serializer, resolver, typeof(char[])).ConfigureAwait(false); await test(serializer, resolver, typeof(decimal)).ConfigureAwait(false); await test(serializer, resolver, typeof(decimal?)).ConfigureAwait(false); await test(serializer, resolver, typeof(decimal[])).ConfigureAwait(false); await test(serializer, resolver, typeof(double)).ConfigureAwait(false); await test(serializer, resolver, typeof(double?)).ConfigureAwait(false); await test(serializer, resolver, typeof(double[])).ConfigureAwait(false); await test(serializer, resolver, typeof(float)).ConfigureAwait(false); await test(serializer, resolver, typeof(float?)).ConfigureAwait(false); await test(serializer, resolver, typeof(float[])).ConfigureAwait(false); await test(serializer, resolver, typeof(int)).ConfigureAwait(false); await test(serializer, resolver, typeof(int?)).ConfigureAwait(false); await test(serializer, resolver, typeof(int[])).ConfigureAwait(false); await test(serializer, resolver, typeof(long)).ConfigureAwait(false); await test(serializer, resolver, typeof(long?)).ConfigureAwait(false); await test(serializer, resolver, typeof(long[])).ConfigureAwait(false); await test(serializer, resolver, typeof(object)).ConfigureAwait(false); await test(serializer, resolver, typeof(object[])).ConfigureAwait(false); await test(serializer, resolver, typeof(sbyte)).ConfigureAwait(false); await test(serializer, resolver, typeof(sbyte?)).ConfigureAwait(false); await test(serializer, resolver, typeof(sbyte[])).ConfigureAwait(false); await test(serializer, resolver, typeof(short)).ConfigureAwait(false); await test(serializer, resolver, typeof(short?)).ConfigureAwait(false); await test(serializer, resolver, typeof(short[])).ConfigureAwait(false); await test(serializer, resolver, typeof(string)).ConfigureAwait(false); await test(serializer, resolver, typeof(string[])).ConfigureAwait(false); await test(serializer, resolver, typeof(uint)).ConfigureAwait(false); await test(serializer, resolver, typeof(uint?)).ConfigureAwait(false); await test(serializer, resolver, typeof(uint[])).ConfigureAwait(false); await test(serializer, resolver, typeof(ulong)).ConfigureAwait(false); await test(serializer, resolver, typeof(ulong?)).ConfigureAwait(false); await test(serializer, resolver, typeof(ulong[])).ConfigureAwait(false); await test(serializer, resolver, typeof(ushort)).ConfigureAwait(false); await test(serializer, resolver, typeof(ushort?)).ConfigureAwait(false); await test(serializer, resolver, typeof(ushort[])).ConfigureAwait(false); }
public static string Serialize(DateTime?value, string key, VCardVersion version) { string serializedValue = value?.ToString("o") ?? string.Empty; return(string.IsNullOrWhiteSpace(serializedValue) ? string.Empty : DefaultSerializer.GetVCardString(key, serializedValue, false, version)); }
public void StripBrackets_EmptyList_RemovesBrackets() { //arrange var serializer = new DefaultSerializer(); object values = new List<int> { }; //act var valuesBytes = serializer.Serialize(values); var actual = valuesBytes.StripBrackets(); //assert var expected = new byte[] { }; Assert.AreEqual(expected, actual); }
public void CreatingAnActor() { Type generic = typeof(Actor<>); //Clown clown = null; //actor.Clowns.TryGetValue(addressAndNumber[0], out clown); //var type = Type.GetType(addressAndNumber[0]); Type[] typeArgs = { typeof(Order) }; var obj = Activator.CreateInstance(typeof(Order)); var constructed = generic.MakeGenericType(typeArgs); // Create a Type object representing the constructed generic // type. using (var context = NetMQContext.Create()) { using (var xchange = new Exchange(context)) { xchange.Start(); var serializer = new DefaultSerializer(Pipe.ControlChannelEncoding); var target = (Actor)Activator.CreateInstance(constructed, context, new BinarySerializer()); obj = target.ReadfromPersistence(@"TestHelpers.Order", typeof(Order)); target.Start(); xchange.Stop(true); } } }
/// <summary> /// allows to write Public fields of T Object separate by space and with '\r\n' as lines separator /// </summary> public DefaultWriter() { _serializer = new DefaultSerializer <T>(new DefaultBasicSerializer <T>()); }
public void TagHelper_Serialization() { using var stream = new MemoryStream(); using var writer = new StreamWriter(stream, Encoding.UTF8, bufferSize: 4096); DefaultSerializer.Serialize(writer, DefaultTagHelpers); }
public object FromJson( JsonValue json, Type deserializationType, DeserializationContext context ) { // legacy format if (json.IsJsonObject) { return(DefaultSerializer.FromJson( json, deserializationType, context )); } JsonArray jsonArray = json.AsJsonArray; if (jsonArray == null) { throw new UnisaveSerializationException( "Given JSON cannot be deserialized as a Tuple." ); } if (jsonArray.Count == 0) { throw new UnisaveSerializationException( "Empty JSON array cannot be deserialized as a Tuple." ); } Type[] typeArgs = deserializationType.GenericTypeArguments; ConstructorInfo ci = deserializationType.GetConstructor(typeArgs); if (ci == null) { throw new UnisaveSerializationException( $"Cannot construct type {deserializationType}" ); } object[] items = new object[typeArgs.Length]; for (int i = 0; i < items.Length; i++) { // handle long tuples (recursively) if (i == 7) { if (!typeArgs[i].IsGenericType || !IsTupleType(typeArgs[i].GetGenericTypeDefinition())) { throw new UnisaveSerializationException( "Eighth tuple value has to be another tuple." ); } items[7] = FromJson(jsonArray, typeArgs[7], context); break; } items[i] = Serializer.FromJson(jsonArray[0], typeArgs[i], context); jsonArray.Remove(0); } return(ci.Invoke(items)); }
private void HandleKeyboardInput() { if (Input.KeysPressed.Count == 0) { return; } switch (Input.KeysPressed[0]) { case Keys.Escape: case Keys.Q: Graphics.Form.Close(); return; case Keys.F1: MessageBox.Show( "WASD + Shift\tMove\n" + "Left click\t\tPoint camera\n" + "Right click\tPick up an object using a Point2PointConstraint\n" + "Shift + Right click\tPick up an object using a fixed constraint\n" + "Space\t\tShoot box\n" + "Return\t\tReset\n" + "F11\t\tFullscreen\n" + "Q\t\tQuit\n\n", "Help"); // Key release won't be captured Input.KeysDown.Remove(Keys.F1); break; case Keys.F3: IsDebugDrawEnabled = !IsDebugDrawEnabled; break; case Keys.F5: var debugForm = new DebugInfoForm(this); debugForm.Show(); break; case Keys.F8: Input.ClearKeyCache(); GraphicsLibraryManager.ExitWithReload = true; Graphics.Form.Close(); break; case Keys.F11: Graphics.IsFullScreen = !Graphics.IsFullScreen; break; case (Keys.Control | Keys.F): const int maxSerializeBufferSize = 1024 * 1024 * 5; using (var serializer = new DefaultSerializer(maxSerializeBufferSize)) { Simulation.World.Serialize(serializer); var dataBytes = new byte[serializer.CurrentBufferSize]; Marshal.Copy(serializer.BufferPointer, dataBytes, 0, dataBytes.Length); using (var file = new System.IO.FileStream("world.bullet", System.IO.FileMode.Create)) { file.Write(dataBytes, 0, dataBytes.Length); } } break; case Keys.G: //shadowsEnabled = !shadowsEnabled; break; case Keys.Space: Vector3 destination = GetCameraRayTo(); _boxShooter.Shoot(FreeLook.Eye, GetCameraRayTo()); break; case Keys.Return: ResetScene(); break; } }
public DefaultNumericTrieSettings() { IndexBuilder = new NumericIndexBuilder <TK>(); TrieBuilder = () => new MvNumericNode <TK, TV>(this); Serializer = new DefaultSerializer <TK, TV, int>(); }
public virtual void OnHandleInput() { if (Input.KeysPressed.Count != 0) { switch (Input.KeysPressed[0]) { case Keys.Escape: case Keys.Q: Graphics.Form.Close(); return; case Keys.F3: IsDebugDrawEnabled = !IsDebugDrawEnabled; break; case Keys.F8: Input.ClearKeyCache(); GraphicsLibraryManager.ExitWithReload = true; Graphics.Form.Close(); break; case Keys.F11: Graphics.IsFullScreen = !Graphics.IsFullScreen; break; case (Keys.Control | Keys.F): const int maxSerializeBufferSize = 1024 * 1024 * 5; DefaultSerializer serializer = new DefaultSerializer(maxSerializeBufferSize); World.Serialize(serializer); byte[] dataBytes = new byte[serializer.CurrentBufferSize]; Marshal.Copy(serializer.BufferPointer, dataBytes, 0, dataBytes.Length); System.IO.FileStream file = new System.IO.FileStream("world.bullet", System.IO.FileMode.Create); file.Write(dataBytes, 0, dataBytes.Length); file.Dispose(); break; case Keys.G: //shadowsEnabled = !shadowsEnabled; break; case Keys.Space: ShootBox(Freelook.Eye, GetRayTo(Input.MousePoint, Freelook.Eye, Freelook.Target, Graphics.FieldOfView)); break; case Keys.Return: ClientResetScene(); break; } } if (Input.MousePressed != MouseButtons.None) { Vector3 rayTo = GetRayTo(Input.MousePoint, Freelook.Eye, Freelook.Target, Graphics.FieldOfView); if (Input.MousePressed == MouseButtons.Right) { if (_world != null) { Vector3 rayFrom = Freelook.Eye; ClosestRayResultCallback rayCallback = new ClosestRayResultCallback(ref rayFrom, ref rayTo); _world.RayTestRef(ref rayFrom, ref rayTo, rayCallback); if (rayCallback.HasHit) { RigidBody body = rayCallback.CollisionObject as RigidBody; if (body != null) { if (!(body.IsStaticObject || body.IsKinematicObject)) { pickedBody = body; pickedBody.ActivationState = ActivationState.DisableDeactivation; Vector3 pickPos = rayCallback.HitPointWorld; Vector3 localPivot = Vector3.TransformCoordinate(pickPos, Matrix.Invert(body.CenterOfMassTransform)); if (Input.KeysDown.Contains(Keys.ShiftKey)) { Generic6DofConstraint dof6 = new Generic6DofConstraint(body, Matrix.Translation(localPivot), false) { LinearLowerLimit = Vector3.Zero, LinearUpperLimit = Vector3.Zero, AngularLowerLimit = Vector3.Zero, AngularUpperLimit = Vector3.Zero }; _world.AddConstraint(dof6); pickConstraint = dof6; dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 0); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 1); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 2); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 3); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 4); dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 5); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 0); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 1); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 2); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 3); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 4); dof6.SetParam(ConstraintParam.StopErp, 0.1f, 5); } else { Point2PointConstraint p2p = new Point2PointConstraint(body, localPivot); _world.AddConstraint(p2p); pickConstraint = p2p; p2p.Setting.ImpulseClamp = 30; //very weak constraint for picking p2p.Setting.Tau = 0.001f; /* * p2p.SetParam(ConstraintParams.Cfm, 0.8f, 0); * p2p.SetParam(ConstraintParams.Cfm, 0.8f, 1); * p2p.SetParam(ConstraintParams.Cfm, 0.8f, 2); * p2p.SetParam(ConstraintParams.Erp, 0.1f, 0); * p2p.SetParam(ConstraintParams.Erp, 0.1f, 1); * p2p.SetParam(ConstraintParams.Erp, 0.1f, 2); */ } oldPickingDist = (pickPos - rayFrom).Length; } } } rayCallback.Dispose(); } } } else if (Input.MouseReleased == MouseButtons.Right) { RemovePickingConstraint(); } // Mouse movement if (Input.MouseDown == MouseButtons.Right) { if (pickConstraint != null) { Vector3 newRayTo = GetRayTo(Input.MousePoint, Freelook.Eye, Freelook.Target, Graphics.FieldOfView); if (pickConstraint.ConstraintType == TypedConstraintType.D6) { Generic6DofConstraint pickCon = pickConstraint as Generic6DofConstraint; //keep it at the same picking distance Vector3 rayFrom = Freelook.Eye; Vector3 dir = newRayTo - rayFrom; dir.Normalize(); dir *= oldPickingDist; Vector3 newPivotB = rayFrom + dir; Matrix tempFrameOffsetA = pickCon.FrameOffsetA; tempFrameOffsetA.M41 = newPivotB.X; tempFrameOffsetA.M42 = newPivotB.Y; tempFrameOffsetA.M43 = newPivotB.Z; pickCon.SetFrames(tempFrameOffsetA, pickCon.FrameOffsetB); } else { Point2PointConstraint pickCon = pickConstraint as Point2PointConstraint; //keep it at the same picking distance Vector3 rayFrom = Freelook.Eye; Vector3 dir = newRayTo - rayFrom; dir.Normalize(); dir *= oldPickingDist; pickCon.PivotInB = rayFrom + dir; } } } }
/// <summary> /// allows to write fields define in your BasicSerializer implementation /// separate by 'string' define in BasicSerializer implementation /// and with by 'string' define in BasicSerializer implementation as lines separator /// </summary> /// <param name="serializer"></param> public DefaultWriter(IBasicSerializer <T> serializer) { _serializer = new DefaultSerializer <T>(serializer); }
/// <summary> /// Parses the error details from the stream. /// </summary> /// <param name="responseStream">The stream to parse.</param> /// <param name="cancellationToken">Cancellation token used to cancel the request.</param> /// <returns>The error details.</returns> public static async Task <StorageExtendedErrorInformation> ReadAndParseExtendedErrorAsync(Stream responseStream, CancellationToken cancellationToken) { try { StreamReader streamReader = new StreamReader(responseStream); using (JsonReader reader = new JsonTextReader(streamReader)) { reader.DateParseHandling = DateParseHandling.None; JObject dataSet = await JObject.LoadAsync(reader, cancellationToken).ConfigureAwait(false); Dictionary <string, object> properties = dataSet.ToObject <Dictionary <string, object> >(DefaultSerializer.Create()); StorageExtendedErrorInformation errorInformation = new StorageExtendedErrorInformation(); errorInformation.AdditionalDetails = new Dictionary <string, string>(); if (properties.ContainsKey(@"odata.error")) { Dictionary <string, object> errorProperties = ((JObject)properties[@"odata.error"]).ToObject <Dictionary <string, object> >(DefaultSerializer.Create()); if (errorProperties.ContainsKey(@"code")) { #pragma warning disable 618 errorInformation.ErrorCode = (string)errorProperties[@"code"]; #pragma warning restore 618 } if (errorProperties.ContainsKey(@"message")) { Dictionary <string, object> errorMessageProperties = ((JObject)errorProperties[@"message"]).ToObject <Dictionary <string, object> >(DefaultSerializer.Create()); if (errorMessageProperties.ContainsKey(@"value")) { errorInformation.ErrorMessage = (string)errorMessageProperties[@"value"]; } } if (errorProperties.ContainsKey(@"innererror")) { Dictionary <string, object> innerErrorDictionary = ((JObject)errorProperties[@"innererror"]).ToObject <Dictionary <string, object> >(DefaultSerializer.Create()); if (innerErrorDictionary.ContainsKey(@"message")) { errorInformation.AdditionalDetails[Constants.ErrorExceptionMessage] = (string)innerErrorDictionary[@"message"]; } if (innerErrorDictionary.ContainsKey(@"type")) { errorInformation.AdditionalDetails[Constants.ErrorException] = (string)innerErrorDictionary[@"type"]; } if (innerErrorDictionary.ContainsKey(@"stacktrace")) { errorInformation.AdditionalDetails[Constants.ErrorExceptionStackTrace] = (string)innerErrorDictionary[@"stacktrace"]; } } } return(errorInformation); } } catch (Exception) { // Exception cannot be parsed, better to throw the original exception than the error-parsing exception. return(null); } }
public void GetMemberName_BasicProperty_ReturnsPropertyName() { // Arrange var settings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var serializer = new DefaultSerializer(settings, settings); // Act var result = serializer.GetMemberName(typeof (JsonDocument).GetProperty("BasicProperty")); // Assert Assert.AreEqual("basicProperty", result); }