public void CamelCaseListTest() { //setup var model = new List <CamelModel> { new CamelModel { FirstName = "first", DateOfBirth = new DateTime(1980, 4, 1), Gender = Gender.Male }, new CamelModel { FirstName = "second", DateOfBirth = new DateTime(1981, 4, 1), Gender = Gender.Female } }; var serializer = new CustomJsonSerializer(); serializer.JsonContractResolver = new CamelCasePropertyNamesContractResolver(); var st = serializer.Serialize(model); //act var deserializer = new CustomJsonDeserializer(GraphClient.DefaultJsonConverters, resolver: (DefaultContractResolver)serializer.JsonContractResolver); var output = deserializer.Deserialize <List <CamelModel> >(st); //assert AssertCamelModel(model[0], output[0]); AssertCamelModel(model[1], output[1]); }
//[Description("https://bitbucket.org/Readify/neo4jclient/issue/89")] public void ShouldSerializeCustomTypeThatHasTypeConverterUsingTypeConverterBasedJsonConverter() { //Arrange var serializer = new CustomJsonSerializer { JsonConverters = new[] { new TypeConverterBasedJsonConverter() } }; var model = new TestModelB { CustomValue = new TestValueB { A = 'o', B = 'p' } }; //Act var rawResult = serializer.Serialize(model); //Assert const string expectedRawOutput = "{\r\n \"CustomValue\": \"op\"\r\n}"; Assert.Equal(expectedRawOutput, rawResult); }
public void ShouldSerializeCustomValueWithCustomJsonConverter() { //Arrange var serializer = new CustomJsonSerializer { JsonConverters = new [] { new TestValueAConverter() } }; var model = new TestModelA { CustomValue = new TestValueA { A = 'o', B = 'p' } }; //Act var rawResult = serializer.Serialize(model); //Assert const string expectedRawOutput = "{\r\n \"CustomValue\": \"op\"\r\n}"; Assert.AreEqual(expectedRawOutput, rawResult); }
public void CamelCaseListTest() { //setup var model = new List<CamelModel> { new CamelModel { FirstName = "first", DateOfBirth = new DateTime(1980, 4, 1), Gender = Gender.Male }, new CamelModel { FirstName = "second", DateOfBirth = new DateTime(1981, 4, 1), Gender = Gender.Female } }; var serializer = new CustomJsonSerializer(); serializer.JsonContractResolver = new CamelCasePropertyNamesContractResolver(); var st = serializer.Serialize(model); //act var deserializer = new CustomJsonDeserializer(GraphClient.DefaultJsonConverters, resolver: (DefaultContractResolver)serializer.JsonContractResolver); var output = deserializer.Deserialize<List<CamelModel>>(st); //assert AssertCamelModel(model[0], output[0]); AssertCamelModel(model[1], output[1]); }
public void JsonSerializerWithEnumConverterShouldConvertEnumToStringValues() { // Arrange var testClass = new TestFoo { Gender = Gender.Female, GenderNullable = Gender.Male }; var serializer = new CustomJsonSerializer { JsonConverters = new JsonConverter[] { new EnumValueConverter(), new NullableEnumValueConverter() } }; const string expected = "{\r\n \"Gender\": \"Female\",\r\n \"GenderNullable\": \"Male\"\r\n}"; // Act var result = serializer.Serialize(testClass); // Assert Assert.Equal(expected, result); }
//[Description("https://bitbucket.org/Readify/neo4jclient/issue/89")] public void ShouldSerializeCustomValueWithCustomJsonConverter() { //Arrange var serializer = new CustomJsonSerializer { JsonConverters = new [] { new TestValueAConverter() } }; var model = new TestModelA { CustomValue = new TestValueA { A = 'o', B = 'p' } }; //Act var rawResult = serializer.Serialize(model); //Assert string expectedRawOutput = $"{{{Environment.NewLine} \"CustomValue\": \"op\"{Environment.NewLine}}}"; Assert.Equal(expectedRawOutput, rawResult); }
/// <summary> /// Invoke a synchronous service with the specified payload. The method call block until the method return. /// </summary> /// <typeparam name="TI">The payload type.</typeparam> /// <typeparam name="TO">The return type.</typeparam> /// <param name="serviceName">The name of the service, as configured in Argilla.Node.ServiceName.</param> /// <param name="payload">The payload used for invoke the service.</param> /// <returns></returns> public static TO Invoke <TI, TO>(string serviceName, TI payload) { TO outputValue = default; PayloadSync payloadSync = new PayloadSync() { Payload = payload }; string json = CustomJsonSerializer.Serialize(payloadSync); Exception lastException = null; try { Endpoint endpoint = GetFreeEndpoint(serviceName); string jsonResult = HttpHelper.Post(endpoint.EndpointSync, json); outputValue = CustomJsonSerializer.Deserialize <TO>(jsonResult); lastException = null; } catch (Exception ex) { logger.Error(ex.Message); ResolveResponse resolveResponse = Resolve(serviceName); foreach (Endpoint endpoint in resolveResponse.Endpoints) { try { string jsonResult = HttpHelper.Post(endpoint.EndpointSync, json); outputValue = CustomJsonSerializer.Deserialize <TO>(jsonResult); lastException = null; break; } catch (Exception e) { lastException = e; } } } if (lastException != null) { logger.Error(lastException, lastException.Message); throw lastException; } logger.Debug(String.Format("Output value: {0}", outputValue)); return(outputValue); }
public override async Task Write(BaseObject item) { await _serializer.Serialize(item, _stream); _stream.WriteByte(10); await _stream.FlushAsync(); _position++; }
public RegisterResponse Unregister(RegisterRequest registerRequest) { string resolverBaseAddress = ArgillaSettings.Current.Resolver.BaseAddress.EndsWith("/") ? ArgillaSettings.Current.Resolver.BaseAddress : ArgillaSettings.Current.Resolver.BaseAddress + "/"; string resolverAddress = resolverBaseAddress + "unregister"; string json = CustomJsonSerializer.Serialize(registerRequest); logger.Debug(String.Format("Registration request: {0}", json)); string result = HttpHelper.Post(resolverAddress, json); return(CustomJsonSerializer.Deserialize <RegisterResponse>(result)); }
public ActionResult Resolve([FromBody] ResolveRequest resolveRequest) { securityManager.Verify(new SecurityAssertion() { Payload = resolveRequest }); logger.Info("Resolve: " + CustomJsonSerializer.Serialize(resolveRequest)); ResolveResponse resolveResponse = new ResolveResponse(); resolveResponse.Endpoints = storageManager.Resolve(resolveRequest); return(new JsonResult(resolveResponse)); }
public ResolveResponse Resolve(string serviceName) { string resolverBaseAddress = ArgillaSettings.Current.Resolver.BaseAddress.EndsWith("/") ? ArgillaSettings.Current.Resolver.BaseAddress : ArgillaSettings.Current.Resolver.BaseAddress + "/"; string resolverAddress = resolverBaseAddress + "resolve"; logger.Info(String.Format("Resolve service {0} on {1}", serviceName, resolverAddress)); string result = HttpHelper.Post(resolverAddress, CustomJsonSerializer.Serialize(new ResolveRequest() { ServiceName = serviceName })); logger.Debug(String.Format("Resove result: {0}", result)); return(CustomJsonSerializer.Deserialize <ResolveResponse>(result)); }
public void SerializeTimeSpan() { // Arrange var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters }; var value = new TimeSpan(400, 13, 3, 2,10); var model = new TimeSpanModel { Foo = value }; // Act var result = serializer.Serialize(model.Foo); // Assert Assert.AreEqual("400.13:03:02.0100000", result.Replace("\"", "")); }
public void DeserializeGuidWithDefaultJsonConverters() { //Arrage var myGuid = Guid.NewGuid(); var foo = new EnumerableModel { Guids = new List<Guid> { myGuid } }; // Act var customSerializer = new CustomJsonSerializer{JsonConverters = GraphClient.DefaultJsonConverters}; var testStr = customSerializer.Serialize(foo); var customDeserializer = new CustomJsonDeserializer(GraphClient.DefaultJsonConverters); var result = customDeserializer.Deserialize<EnumerableModel>(testStr); // Assert Assert.AreEqual(myGuid, result.Guids.First()); }
public ActionResult Unregister([FromBody] Endpoint endpoint) { securityManager.Verify(new SecurityAssertion() { Payload = endpoint }); logger.Info("Unregister: " + CustomJsonSerializer.Serialize(endpoint)); storageManager.Unregister(endpoint); return(new JsonResult(new RegisterResponse() { Success = true })); }
public void JsonSerializerShouldSerializeTimeZoneInfo() { // Arrange var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters }; const string ausEasternStandardTime = "AUS Eastern Standard Time"; var timeZoneData = TimeZoneInfo.FindSystemTimeZoneById(ausEasternStandardTime); // Act var result = serializer.Serialize(timeZoneData); // Assert Assert.Equal(ausEasternStandardTime, result.Replace("\"", "")); }
public void JsonSerializerShouldSerializeAllProperties() { // Arrange var testNode = new TestNode { Foo = "foo", Bar = "bar" }; var serializer = new CustomJsonSerializer { NullHandling = NullValueHandling.Ignore, JsonConverters = GraphClient.DefaultJsonConverters }; // Act var result = serializer.Serialize(testNode); const string expectedValue = "{\r\n \"Foo\": \"foo\",\r\n \"Bar\": \"bar\"\r\n}"; // Assert Assert.AreEqual(expectedValue, result); }
public void JsonSerializerShouldSerializeTimeZoneInfo() { // Arrange var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters }; const string ausEasternStandardTime = "AUS Eastern Standard Time"; var timeZoneData = TimeZoneInfo.FindSystemTimeZoneById(ausEasternStandardTime); // Act var result = serializer.Serialize(timeZoneData); // Assert Assert.AreEqual(ausEasternStandardTime, result.Replace("\"","")); }
public void JsonSerializerShouldSerializeEnumToString() { // Arrange var testNode = new TestNodeWithEnum { Status = TestEnum.Value1 }; var serializer = new CustomJsonSerializer { NullHandling = NullValueHandling.Ignore, JsonConverters = new []{new EnumValueConverter()} }; // Act var result = serializer.Serialize(testNode); const string expectedValue = "{\r\n \"Status\": \"Value1\"\r\n}"; // Assert Assert.AreEqual(expectedValue, result); }
public void SerializeTimeSpan() { // Arrange var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters }; var value = new TimeSpan(400, 13, 3, 2, 10); var model = new TimeSpanModel { Foo = value }; // Act var result = serializer.Serialize(model.Foo); // Assert Assert.AreEqual("400.13:03:02.0100000", result.Replace("\"", "")); }
public void ShouldSerializeDateTimeOffsetInCorrectStringFormat() { //Arrange var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters }; var model = new DateOffsetModel { DateTime = DateTimeOffset.Parse("2012-08-31T00:11:00.3642578+10:00"), DateTimeNullable = DateTimeOffset.Parse("2012-08-31T00:11:00.3642578+10:00") }; //Act var actual = serializer.Serialize(model); //Assert const string expected = "{\r\n \"DateTime\": \"2012-08-31T00:11:00.3642578+10:00\",\r\n \"DateTimeNullable\": \"2012-08-31T00:11:00.3642578+10:00\"\r\n}"; Assert.AreEqual(expected, actual); }
public void ShouldSerializeDateTimeInCorrectStringFormat(string dateTimeStr) { //Arrange var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters }; var model = new DateModel { DateTime = DateTime.Parse(dateTimeStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal), DateTimeNullable = DateTime.Parse(dateTimeStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal) }; //Act var actual = serializer.Serialize(model); //Assert var expected = "{\r\n \"DateTime\": \"" + dateTimeStr + "\",\r\n \"DateTimeNullable\": \"" + dateTimeStr + "\"\r\n}"; Assert.AreEqual(expected, actual); }
public void ShouldSerializeNullableInt32ToJsonNumberUsingDefaultJsonConverters() { // Arrange var testNode = new NodeWithBuiltInTypes { Foo = 123 }; var serializer = new CustomJsonSerializer { NullHandling = NullValueHandling.Ignore, JsonConverters = GraphClient.DefaultJsonConverters }; // Act var result = serializer.Serialize(testNode); const string expectedValue = "{\r\n \"Foo\": 123\r\n}"; // Assert Assert.Equal(expectedValue, result); }
public void ShouldSerializeNullableBoolToJsonBooleanUsingDefaultJsonConverters() { // Arrange var testNode = new NodeWithBuiltInTypes { Bar = true }; var serializer = new CustomJsonSerializer { NullHandling = NullValueHandling.Ignore, JsonConverters = GraphClient.DefaultJsonConverters }; // Act var result = serializer.Serialize(testNode); const string expectedValue = "{\r\n \"Bar\": true\r\n}"; // Assert Assert.Equal(expectedValue, result); }
public void JsonSerializerShouldSerializeAllProperties() { // Arrange var testNode = new TestNode { Foo = "foo", Bar = "bar" }; var serializer = new CustomJsonSerializer { NullHandling = NullValueHandling.Ignore, JsonConverters = GraphClient.DefaultJsonConverters }; // Act var result = serializer.Serialize(testNode); const string expectedValue = "{\r\n \"Foo\": \"foo\",\r\n \"Bar\": \"bar\"\r\n}"; // Assert Assert.Equal(expectedValue, result); }
public void SerializeTimeSpan() { // Arrange var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters }; var value = new TimeSpan(400, 13, 3, 2, 10); var model = new TimeSpanModel { Foo = value }; // Act var result = serializer.Serialize(model); const string expected = "{\r\n \"Foo\": \"400.13:03:02.0100000\"\r\n}"; result.Should().Be(expected); }
private static object Serialize(object value, IList <JsonConverter> converters, IGraphClient gc, IEnumerable <CustomAttributeData> customAttributes = null) { if (value == null) { return(null); } var type = value.GetType(); var typeInfo = type.GetTypeInfo(); var converter = converters.FirstOrDefault(c => c.CanConvert(type) && c.CanWrite); if (converter != null) { var serializer = new CustomJsonSerializer { JsonConverters = converters, JsonContractResolver = ((IRawGraphClient)gc).JsonContractResolver }; return(JsonConvert.DeserializeObject <CustomJsonConverterHelper>(serializer.Serialize(new { value })).Value); } if (customAttributes != null && customAttributes.Any(x => x.AttributeType == typeof(Neo4jDateTimeAttribute))) { return(value); } if (typeInfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary <,>)) { return(SerializeDictionary(type, value, converters, gc)); } if (typeInfo.IsClass && type != typeof(string)) { if (typeInfo.IsArray || typeInfo.ImplementedInterfaces.Contains(typeof(IEnumerable))) { return(SerializeCollection((IEnumerable)value, converters, gc)); } return(SerializeObject(type, value, converters, gc)); } return(SerializePrimitive(type, typeInfo, value)); }
public void JsonSerializerShouldNotSerializeNullProperties() { // Arrange var testNode = new TestNode { Foo = "foo", Bar = null }; var serializer = new CustomJsonSerializer { NullHandling = NullValueHandling.Ignore, JsonConverters = GraphClient.DefaultJsonConverters }; // Act var result = serializer.Serialize(testNode); string expectedValue = $"{{{Environment.NewLine} \"Foo\": \"foo\"{Environment.NewLine}}}"; // Assert Assert.Equal(expectedValue, result); }
public void JsonSerializerShouldSerializeEnumToString() { // Arrange var testNode = new TestNodeWithEnum { Status = TestEnum.Value1 }; var serializer = new CustomJsonSerializer { NullHandling = NullValueHandling.Ignore, JsonConverters = new [] { new EnumValueConverter() } }; // Act var result = serializer.Serialize(testNode); const string expectedValue = "{\r\n \"Status\": \"Value1\"\r\n}"; // Assert Assert.Equal(expectedValue, result); }
//[Description("test https part of https://github.com/Readify/Neo4jClient/issues/336 https://github.com/Readify/Neo4jClient/pull/337 - see BoltGraphClientTests for bolt part")] public void JsonSerializerShouldNotSerializeNeo4JIgnoreAttribute() { // Arrange var testNode = new TestNodeWithSomeNeo4jIgnoreAttributes { Text = "foo", TextIgnore = "fooignore", TestInt = 42, TestNeo4jIntIgnore = 42, TestJsonIntIgnore = 42 }; var serializer = new CustomJsonSerializer { NullHandling = NullValueHandling.Ignore, JsonConverters = GraphClient.DefaultJsonConverters }; // Act var result = serializer.Serialize(testNode); const string expectedValue = "{\r\n \"Text\": \"foo\",\r\n \"TestInt\": 42\r\n}"; // Assert Assert.Equal(expectedValue, result); }
public ActionResult Callback([FromBody] PayloadSync payload) { string content = CustomJsonSerializer.Serialize(payload.Payload); MethodInfo methodInfo = ArgillaSettings.Current.MessageReceivedHandler; ParameterInfo[] pis = methodInfo.GetParameters(); ParameterInfo argumentPI = pis[0]; Type t = pis[0].ParameterType; object o = CustomJsonSerializer.Deserialize(content, t); object a = ArgillaSettings.Current.MessageReceivedHandler.Invoke(null, new[] { o }); string result = CustomJsonSerializer.Serialize(a); return(new ContentResult() { Content = result, ContentType = "application/json", StatusCode = 200 }); }
public void JsonSerializerShouldSerializeTimeZoneInfo() { // Arrange var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters }; var chosenTimeZone = new [] { "AUS Eastern Standard Time", "Australia/Perth" } .Where(s => TimeZoneInfo.GetSystemTimeZones().Any(tz => tz.Id.Equals(s))) .FirstOrDefault(tz => tz != null); Assert.NotNull(chosenTimeZone); // if this fails try adding a timezone that your platform has to the list above var timeZoneData = TimeZoneInfo.FindSystemTimeZoneById(chosenTimeZone); // Act var result = serializer.Serialize(timeZoneData); // Assert Assert.Equal(chosenTimeZone, result.Replace("\"", "")); }
public void ShouldSerializeDateTimeOffsetInCorrectStringFormat() { //Arrange var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters }; var model = new DateOffsetModel { DateTime = DateTimeOffset.Parse("2012-08-31T00:11:00.3642578+10:00"), DateTimeNullable = DateTimeOffset.Parse("2012-08-31T00:11:00.3642578+10:00") }; //Act var actual = serializer.Serialize(model); //Assert const string expected = "{\r\n \"DateTime\": \"2012-08-31T00:11:00.3642578+10:00\",\r\n \"DateTimeNullable\": \"2012-08-31T00:11:00.3642578+10:00\"\r\n}"; Assert.Equal(expected, actual); }
public void CamelCaseTest() { //setup var model = new CamelModel { FirstName = "first", DateOfBirth = new DateTime(1980, 4, 1), Gender = Gender.Male, S = "short property" }; var serializer = new CustomJsonSerializer(); serializer.JsonContractResolver = new CamelCasePropertyNamesContractResolver(); var st = serializer.Serialize(model); //act var deserializer = new CustomJsonDeserializer(GraphClient.DefaultJsonConverters, resolver: (DefaultContractResolver)serializer.JsonContractResolver); var output = deserializer.Deserialize<CamelModel>(st); //assert AssertCamelModel(model, output); }
public void ShouldSerializeDateTimeInCorrectStringFormat(string dateTimeStr) { //Arrange var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters }; var model = new DateModel { DateTime = DateTime.Parse(dateTimeStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal), DateTimeNullable = DateTime.Parse(dateTimeStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal) }; //Act var actual = serializer.Serialize(model); //Assert var expected = "{\r\n \"DateTime\": \"" + dateTimeStr + "\",\r\n \"DateTimeNullable\": \"" + dateTimeStr + "\"\r\n}"; Assert.Equal(expected, actual); }
//[Description("https://bitbucket.org/Readify/neo4jclient/issue/89")] public void ShouldSerializeBuiltInTypeThatHasTypeConverterUsingTypeConverterBasedJsonConverter() { //Arrange var serializer = new CustomJsonSerializer { JsonConverters = new[] { new TypeConverterBasedJsonConverter() } }; var model = new TestModelC { MyPoint = new System.Drawing.Point(100, 200) }; //Act var rawResult = serializer.Serialize(model); //Assert string expectedRawOutput = $"{{{Environment.NewLine} \"MyPoint\": \"100, 200\"{Environment.NewLine}}}"; Assert.Equal(expectedRawOutput, rawResult); }
internal static void Process(Object o) { PayloadAsync payload = o as PayloadAsync; if (payload == null) { throw new PayloadNullException(); } if (ArgillaSettings.Current.MessageReceivedHandler == null) { throw new CallbackNullException(); } string jsonArgument = CustomJsonSerializer.Serialize(payload.Payload); logger.Info(String.Format("Json argument: {0}", jsonArgument)); MethodInfo methodInfo = ArgillaSettings.Current.MessageReceivedHandler; ParameterInfo[] pis = methodInfo.GetParameters(); ParameterInfo argumentPI = pis[0]; Type t = pis[0].ParameterType; object argument = CustomJsonSerializer.Deserialize(jsonArgument, t); object a = ArgillaSettings.Current.MessageReceivedHandler.Invoke(null, new[] { argument }); payload.Payload = a; string json = CustomJsonSerializer.Serialize(payload); logger.Info(String.Format("Json: {0}", json)); string result = HttpHelper.Post(payload.UrlCallback, json); logger.Info(String.Format("Result: {0}", result)); }
public void CamelCaseTest() { //setup var model = new CamelModel { FirstName = "first", DateOfBirth = new DateTime(1980, 4, 1), Gender = Gender.Male, S = "short property" }; var serializer = new CustomJsonSerializer(); serializer.JsonContractResolver = new CamelCasePropertyNamesContractResolver(); var st = serializer.Serialize(model); //act var deserializer = new CustomJsonDeserializer(GraphClient.DefaultJsonConverters, resolver: (DefaultContractResolver)serializer.JsonContractResolver); var output = deserializer.Deserialize <CamelModel>(st); //assert AssertCamelModel(model, output); }
public void DeserializeGuidWithDefaultJsonConverters() { //Arrage var myGuid = Guid.NewGuid(); var foo = new EnumerableModel { Guids = new List <Guid> { myGuid } }; // Act var customSerializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters }; var testStr = customSerializer.Serialize(foo); var customDeserializer = new CustomJsonDeserializer(GraphClient.DefaultJsonConverters); var result = customDeserializer.Deserialize <EnumerableModel>(testStr); // Assert Assert.Equal(myGuid, result.Guids.First()); }
public void ShouldSerializeBuiltInTypeThatHasTypeConverterUsingTypeConverterBasedJsonConverter() { //Arrange var serializer = new CustomJsonSerializer { JsonConverters = new[] { new TypeConverterBasedJsonConverter() } }; var model = new TestModelC { MyPoint = new System.Drawing.Point(100, 200) }; //Act var rawResult = serializer.Serialize(model); //Assert const string expectedRawOutput = "{\r\n \"MyPoint\": \"100, 200\"\r\n}"; Assert.AreEqual(expectedRawOutput, rawResult); }
public void ShouldSerializeCustomValueWithCustomJsonConverter() { //Arrange var serializer = new CustomJsonSerializer { JsonConverters = new []{new TestValueAConverter()} }; var model = new TestModelA { CustomValue = new TestValueA { A = 'o', B = 'p' } }; //Act var rawResult = serializer.Serialize(model); //Assert const string expectedRawOutput = "{\r\n \"CustomValue\": \"op\"\r\n}"; Assert.AreEqual(expectedRawOutput, rawResult); }
public void SerializeOperationId() { var data = _serializer.Serialize(OperationId.From(5)); data.Should().Be("{\"$type\":\"OperationId\",\"Value\":5}"); }
public void JsonSerializerWithEnumConverterShouldConvertEnumToStringValues() { // Arrange var testClass = new TestFoo { Gender = Gender.Female, GenderNullable = Gender.Male }; var serializer = new CustomJsonSerializer { JsonConverters = new JsonConverter[] { new EnumValueConverter(), new NullableEnumValueConverter() } }; const string expected = "{\r\n \"Gender\": \"Female\",\r\n \"GenderNullable\": \"Male\"\r\n}"; // Act var result = serializer.Serialize(testClass); // Assert Assert.AreEqual(expected, result); }
public void ShouldSerializeNullableBoolToJsonBooleanUsingDefaultJsonConverters() { // Arrange var testNode = new NodeWithBuiltInTypes { Bar = true }; var serializer = new CustomJsonSerializer { NullHandling = NullValueHandling.Ignore, JsonConverters = GraphClient.DefaultJsonConverters }; // Act var result = serializer.Serialize(testNode); const string expectedValue = "{\r\n \"Bar\": true\r\n}"; // Assert Assert.AreEqual(expectedValue, result); }
public void ShouldSerializeNullableInt32ToJsonNumberUsingDefaultJsonConverters() { // Arrange var testNode = new NodeWithBuiltInTypes { Foo = 123 }; var serializer = new CustomJsonSerializer { NullHandling = NullValueHandling.Ignore, JsonConverters = GraphClient.DefaultJsonConverters }; // Act var result = serializer.Serialize(testNode); const string expectedValue = "{\r\n \"Foo\": 123\r\n}"; // Assert Assert.AreEqual(expectedValue, result); }
/// <summary> /// Most of the work happens here for generating the hook up script code /// </summary> /// <param name="e"></param> protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); // MS AJAX aware script management ClientScriptProxy scriptProxy = ClientScriptProxy.Current; // Register resources RegisterResources(scriptProxy); string dateFormat = DateFormat; if (string.IsNullOrEmpty(dateFormat) || dateFormat == "Auto") { // Try to create a data format string from culture settings // this code will fail if culture can't be mapped on server hence the empty try/catch try { dateFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern; } catch { } } dateFormat = dateFormat.ToLower().Replace("yyyy", "yy"); // Capture and map the various option parameters StringBuilder sbOptions = new StringBuilder(512); sbOptions.Append("{"); string onSelect = OnClientSelect; if (DisplayMode == DatePickerDisplayModes.Button) sbOptions.Append("showOn: 'button',"); else if (DisplayMode == DatePickerDisplayModes.ImageButton) { string img = ButtonImage; if (img == "WebResource") img = scriptProxy.GetWebResourceUrl(this, typeof(ControlResources), ControlResources.CALENDAR_ICON_RESOURCE); else img = ResolveUrl(ButtonImage); sbOptions.Append("showOn: 'button', buttonImageOnly: true, buttonImage: '" + img + "',buttonText: 'Select date',"); } else if (DisplayMode == DatePickerDisplayModes.Inline) { // need to store selection in the page somehow for inline since it's // not tied to a textbox scriptProxy.RegisterHiddenField(this, ClientID, Text); onSelect = ClientID + "OnSelect"; } if (!string.IsNullOrEmpty(onSelect)) sbOptions.Append("onSelect: " + onSelect + ","); if (DisplayMode != DatePickerDisplayModes.Inline) { if (!string.IsNullOrEmpty(OnClientBeforeShow)) sbOptions.Append("beforeShow: function(y,z) { $('#ui-datepicker-div').maxZIndex(); " + OnClientBeforeShow + "(y,z); },"); else sbOptions.Append("beforeShow: function() { $('#ui-datepicker-div').maxZIndex(); },"); } if (MaxDate.HasValue) sbOptions.Append("maxDate: " + UrlUtils.EncodeJsDate(MaxDate.Value) + ","); if (MinDate.HasValue) sbOptions.Append("minDate: " + UrlUtils.EncodeJsDate(MinDate.Value) + ","); if (ShowButtonPanel) sbOptions.Append("showButtonPanel: true,"); sbOptions.Append("dateFormat: '" + dateFormat + "'}"); // Write out initilization code for calendar StringBuilder sbStartupScript = new StringBuilder(400); sbStartupScript.AppendLine("$( function() {"); if (DisplayMode != DatePickerDisplayModes.Inline) { scriptProxy.RegisterClientScriptBlock(Page, typeof(ControlResources), "__attachDatePickerInputKeys", AttachDatePickerKeysScript, true); sbStartupScript.AppendFormat("var cal = jQuery('#{0}').datepicker({1}).attachDatepickerInputKeys();\r\n", ClientID, sbOptions); } else { sbStartupScript.AppendLine("var cal = jQuery('#" + ClientID + "Div').datepicker(" + sbOptions.ToString() + ")"); if (SelectedDate.HasValue && SelectedDate.Value > new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)) { CustomJsonSerializer ser = new CustomJsonSerializer(); ser.DateSerializationMode = JsonDateEncodingModes.NewDateExpression; string jsDate = ser.Serialize(SelectedDate); sbStartupScript.AppendLine("cal.datepicker('setDate'," + jsDate + ");"); } else sbStartupScript.AppendLine("cal.datepicker('setDate',new Date());"); // Assign value to hidden form var on selection scriptProxy.RegisterStartupScript(this, typeof(ControlResources), UniqueID + "OnSelect", "function " + ClientID + "OnSelect(dateStr) {\r\n" + ((!string.IsNullOrEmpty(OnClientSelect)) ? OnClientSelect + "(dateStr);\r\n" : "") + "jQuery('#" + ClientID + "')[0].value = dateStr;\r\n}\r\n", true); } sbStartupScript.AppendLine("} );"); scriptProxy.RegisterStartupScript(Page, typeof(ControlResources), "_cal" + UniqueID, sbStartupScript.ToString(), true); }