Boolean return type confusion - return

public boolean equals(Object obj) {
return new Integer(id).equals(((Person)obj).getId());
As far as i know boolean return "true" or "false" how can i use this type for this code?

Related

How to access ModelState.AddModelError() from IsValid function of ValidationAttribute class

i try to add this line ModelState.AddModelError(string key, string errorMessage); in IsValid function of ValidationAttribute class but fail.
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class AtleastOneAttribute : ValidationAttribute, IClientValidatable
{
// For Server side
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
var oHobby=value as IEnumerable;
foreach (var _object in oHobby)
{
Hobby _oHobby = (Hobby)_object;
if (_oHobby.IsSelected)
{
return ValidationResult.Success;
}
}
}
ModelState.AddModelError("Hobbies", "Err message....");
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
tell me how to access ModelState.AddModelError from IsValid function of ValidationAttribute class ?
thanks
ModelState is not accessible in IsValid function. IsValid method adds an error to ModelState through it's return statement, so if you need to add an error just return it:
return new ValidationResult("Err message....");

JsonSerializer - serialize decimal places with 'N2' formatting

I'm serializing decimals using Newtonsoft.Json.JsonSerializer.
How can I set it to serialize decimal numbers with only 1 decimal place to use 0 at the end.
i.e. 3.5 serializes to "3.50"?
You'll have to write your own custom JsonConverter and use it to intercept the decimal type so you can change how it gets serialized. Here's an example:
public class DecimalFormatConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(decimal));
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
writer.WriteValue(string.Format("{0:N2}", value));
}
public override bool CanRead
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
To use it, simply pass in a new instance of this custom converter to the SerializeObject method:
var json = JsonConvert.SerializeObject(yourObject, new DecimalFormatConverter());
The accepted answer is correct, but expanding upon the comments on accepted answer:
If you want the decimals in your JSON to be numbers instead of strings, you need to use WriteRawValue and use :0.00 instead of :N2 for the string formatting (as N2 includes thousand separator commas and other culture specific number formatting that will break your JSON)
public class DecimalFormatConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(decimal);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue($"{value:0.00}");
}
public override bool CanRead => false;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
This is the difference in output compared to the accepted answer.
# writer.WriteRawValue($"{value:0.00}");
{
"MyDecimal": 3.50,
"MyBiggerDecimal": 12345.50
}
# writer.WriteValue($"{value:N2}");
{
"MyDecimal": "3.50",
"MyBiggerDecimal": "12,345.50"
}
Note - the accepted answer is correct for the OP's specific question i.e. serialize 3.5 to "3.50", but I got here wanting to serialize 3.5 to 3.50 (without the string quotes).
Hy!
The second answer is also correct, but not reflecting Cultures.
If you want to have really 0.00 (with .) you have to use:
public class DecimalFormatConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(decimal);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
FormattableString formattableString = $"{value:0.00}";
writer.WriteRawValue(formattableString.ToString(CultureInfo.InvariantCulture));
}
public override bool CanRead => false;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
With this it is garantueed to have dot as decimal separater.
The difference is:
FormattableString formattableString = $"{value:0.00}";
writer.WriteRawValue(formattableString.ToString(CultureInfo.InvariantCulture));

Globalization issue with decimal and Nancy model binding

I'm new to Nancy and I'm trying to bind a decimal property using the Nancy.ModelBinding namespace like this:
var model = this.Bind<AddPaymentModel>();
My app is using a non-US culture (pt-BR) where decimals are represented differently (4.50 would be 4,50) and the code above throws an error, even thought the CurrentCulture is correctly set to pt-BR. I'm posting JSON and I think it might be related to the JSON deserializer...
Part of my stacktrace:
Nancy.RequestExecutionException: Oh noes! ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: 450,00 is not a valid value for Decimal. ---> System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.Decimal.Parse(String s, NumberStyles style, IFormatProvider provider)
at System.ComponentModel.DecimalConverter.FromString(String value, NumberFormatInfo formatInfo)
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
--- End of inner exception stack trace ---
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.ComponentModel.TypeConverter.ConvertFromInvariantString(String text)
at Nancy.Json.JavaScriptSerializer.ConvertToType(Type type, Object obj)
at Nancy.Json.JavaScriptSerializer.ConvertToObject(IDictionary`2 dict, Type type)
at Nancy.Json.JavaScriptSerializer.ConvertToType(Type type, Object obj)
at Nancy.Json.JavaScriptSerializer.ConvertToType[T](Object obj)
at Nancy.Json.JavaScriptSerializer.Deserialize[T](String input)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Nancy.ModelBinding.DefaultBodyDeserializers.JsonBodyDeserializer.Deserialize(String contentType, Stream bodyStream, BindingContext context)
at Nancy.ModelBinding.DefaultBinder.DeserializeRequestBody(BindingContext context)
at Nancy.ModelBinding.DefaultBinder.Bind(NancyContext context, Type modelType, String[] blackList)
What am I missing?
you could try switcing to the Newtonsoft.JsonNet serializer for nancy instead.
http://nuget.org/packages/Nancy.Serialization.JsonNet
Here is a "catch all" example implementaion
using System;
using System.Collections.Generic;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Serialization.JsonNet;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Application
{
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override NancyInternalConfiguration InternalConfiguration
{
get
{
return NancyInternalConfiguration.WithOverrides(
c => c.Serializers.Insert(0, typeof(ModifiedJsonNetJsonSerializer)));
}
}
public class ModifiedJsonNetJsonSerializer : JsonNetSerializer
{
public ModifiedJsonNetJsonSerializer()
: base(new List<JsonConverter> { new FloatConverter() })
{ }
public class FloatConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var floatValue = (float)value;
writer.WriteValue(string.Format("{0:0.00}", floatValue));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jobject = JToken.Load(reader);
var str = jobject.Value<string>();
float number;
try
{
number = float.Parse(str);
}
catch (FormatException)
{
str = str.IndexOf(".", StringComparison.Ordinal) > -1 ? str.Replace('.', ',') : str.Replace(',', '.');
number = float.Parse(str);
}
return number;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(float) || objectType == typeof(Single);
}
}
}
}
}

I cannot access the KeyPressed function for when i press the ESCAPE key

The first problem is that the addKeyListener does is redlined wherever I place it. I've looked at various different examples online but it seems that Im missing something.
here is my code:
import net.rim.device.api.system.KeyListener;
import net.rim.device.api.ui.Keypad;
public class BBMIDLET extends javax.microedition.midlet.MIDlet implements KeyListener
public void startApp() {
Display.init(this);
addKeyListener(new TestKeyPadListener());
}
public class TestKeyPadListener implements KeyListener {
public boolean keyChar(char key, int status, int time) {
System.out.println("key: " + key);
return false;
}
public boolean keyDown(int keycode, int time) {
System.out.println("keycode: " + keycode);
if (Keypad.key(keycode) == Keypad.KEY_ESCAPE) {
System.out.println("Hi");
return false;
}
return true;
}
public boolean keyUp(int keycode, int time) {
throw new UnsupportedOperationException("Not supported yet.");
}
public boolean keyRepeat(int keycode, int time) {
throw new UnsupportedOperationException("Not supported yet.");
}
public boolean keyStatus(int keycode, int time) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
Thanks in advance
addKeyListener(KeyListener l) is not a method of javax.microedition.midlet.MIDlet or net.rim.device.api.system.KeyListener and you did not declare it anywhere else in your BBMIDLET class so it is undefined.

ModelMetadata: ShowForEdit property not appearing to work

Iv wrote an MetaDataProvider like the one below and am using it in conjunction with Editor templates. The DisplayName is working correctly, but for some reason the ShowForEdit value it not having any effect. Any ideas?
public class MyModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); I
metadata.DisplayName = "test";
metadata.ShowForEdit = false;
metadata.ShowForDisplay = false;
metadata.HideSurroundingHtml = true;
return metadata;
}
}
This seems similar to the question Why can't I set ShowForEdit model metadata with an attribute?, so I'll replicate my answer here:
What is the type of property you are applying it to? If we use Reflector, we can discover that the ShowForEdit and ShowForDisplay properties are used in the following functions:
ShowForEdit: System.Web.Mvc.Html.DefaultEditorTemplates.ShouldShow(...)
ShowForDisplay: System.Web.Mvc.Html.DefaultDisplayTemplates.ShouldShow(...)
The definition of those methods is:
private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)
{
return (((metadata.ShowForEdit && (metadata.ModelType != typeof(EntityState))) && !metadata.IsComplexType) && !templateInfo.Visited(metadata));
}
private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)
{
return (((metadata.ShowForDisplay && (metadata.ModelType != typeof(EntityState))) && !metadata.IsComplexType) && !templateInfo.Visited(metadata));
}
Ignoring the obvious property check (metadata.ShowForX), you can see that it is checking whether the model is an intstance of EntityState (probably isn't), and then a check for metadata.IsComplexType.
We can look at the IsComplexType property here:
public virtual bool IsComplexType
{
get
{
return !TypeDescriptor.GetConverter(this.ModelType).CanConvertFrom(typeof(string));
}
}
What that is saying is that it will return true if the model cannot be converted from a string, and in the ShouldShow() methods, it will show if it is not a complex type, i.e., the value CAN be converted from a string.
What you will need to do, is create a TypeConverter that can convert a string, to the model, e.g:
A model:
[TypeConverter(typeof(ItemConverter))]
public class Item
{
#region Properties
public string Text { get; set; }
#endregion
}
And a converter:
public class ItemConverter : TypeConverter
{
#region Methods
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value.GetType() == typeof(string))
{
return new Item { Text = (string)value };
}
return base.ConvertFrom(context, culture, value);
}
#endregion
}
With that in place, try it again and see if that helps.

Resources