Serialize a nullable int

333

Solution 1

XmlSerializer supports the ShouldSerialize{Foo}() pattern, so you can add a method:

public bool ShouldSerializeID() {return ID.HasValue;}

There is also the {Foo}Specified pattern - not sure if XmlSerializer supports that one.

Solution 2

I'm using this micro-pattern to implement Nullable serialization:

[XmlIgnore]
public double? SomeValue { get; set; }

[XmlAttribute("SomeValue")] // or [XmlElement("SomeValue")]
[EditorBrowsable(EditorBrowsableState.Never)]
public double XmlSomeValue { get { return SomeValue.Value; } set { SomeValue= value; } }  
[EditorBrowsable(EditorBrowsableState.Never)]
public bool XmlSomeValueSpecified { get { return SomeValue.HasValue; } }

This provides the right interface to the user without compromise and still does the right thing when serializing.

Solution 3

I figured out a workaround utilizing two properties. An int? property with an XmlIgnore attribute and an object property which gets serialized.

    /// <summary>
    /// Score db record
    /// </summary>        
    [System.Xml.Serialization.XmlIgnore()]
    public int? ID 
    { 
        get 
        { 
            return iID_m; 
        } 
        set 
        { 
            iID_m = value; 
        } 
    }

    /// <summary>
    /// Score db record
    /// </summary>        
    [System.Xml.Serialization.XmlElement("ID",IsNullable = false)]
    public object IDValue
    {
        get
        {
            return ID;
        }
        set
        {
            if (value == null)
            {
                ID = null;
            }
            else if (value is int || value is int?)
            {
                ID = (int)value;
            }
            else
            {
                ID = int.Parse(value.ToString());
            }
        }
    }

Solution 4

Wow thanks this question/answer really helped me out. I heart Stackoverflow.

I made what you are doing above a little more generic. All we're really looking for is to have Nullable with slightly different serialization behavior. I used Reflector to build my own Nullable, and added a few things here and there to make the XML serialization work the way we want. Seems to work pretty well:

public class Nullable<T>
{
    public Nullable(T value)
    {
        _value = value;
        _hasValue = true;
    }

    public Nullable()
    {
        _hasValue = false;
    }

    [XmlText]
    public T Value
    {
        get
        {
            if (!HasValue)
                throw new InvalidOperationException();
            return _value;
        }
        set
        {
            _value = value;
            _hasValue = true;
        }
    }

    [XmlIgnore]
    public bool HasValue
        { get { return _hasValue; } }

    public T GetValueOrDefault()
        { return _value; }
    public T GetValueOrDefault(T i_defaultValue)
        { return HasValue ? _value : i_defaultValue; }

    public static explicit operator T(Nullable<T> i_value)
        { return i_value.Value; }
    public static implicit operator Nullable<T>(T i_value)
        { return new Nullable<T>(i_value); }

    public override bool Equals(object i_other)
    {
        if (!HasValue)
            return (i_other == null);
        if (i_other == null)
            return false;
        return _value.Equals(i_other);
    }

    public override int GetHashCode()
    {
        if (!HasValue)
            return 0;
        return _value.GetHashCode();
    }

    public override string ToString()
    {
        if (!HasValue)
            return "";
        return _value.ToString();
    }

    bool _hasValue;
    T    _value;
}

You lose the ability to have your members as int? and so on (have to use Nullable<int> instead) but other than that all behavior stays the same.

Solution 5

Unfortunately, the behaviours you describe are accurately documented as such in the docs for XmlElementAttribute.IsNullable.

Share:
333
user3791176
Author by

user3791176

Updated on March 26, 2020

Comments

  • user3791176
    user3791176 about 4 years

    Say I want to create a Bitcoin exchange or an e-wallet service and make it as secure as possible. Assuming the nature of the service results in more Bitcoin deposits coming in then Bitcoin leaving the system out, yet the need to allow instant withdrawals of Bitcoins out of the service, I thought of the following scheme or scenario.

    Create on a separate computer a list of 1000 Bitcoin addresses using Multibit. Transfer those 1000 public keys to DB on web server using a USB, to a table holding a pool of free/non-used addresses. When a member creates an account I assign a free Bitcoin deposit address to make member account funding possible. Since the private key for these 1000 deposit addresses is not on the web server or DB (generated on another computer and only public keys were imported using USB) I am pretty much secure that all funds coming into the system as deposits are safe.

    When a member wishes to trade with another member, I simply maintain my own balance accounting system, by creating tables and logging transfers from one member account to another.

    When a member wishes to withdraw his Bitcoins, I will use a Hot wallet which would only accept requests from the web server IP address, check my internal accounting system to make sure member has enough balance left and make payments from the hot wallet to whatever external Bitcoin address withdrawal has been requested to. By making sure I keep no more than, say, 5% of overall balance on the hot wallet, any security breach will not result in 100% loss of site funds.

    How secure is this scheme? Would you suggest I do things otherwise?

    • KevinDTimm
      KevinDTimm almost 10 years
      What percentage of revenue do we get after designing your solution?
    • user3791176
      user3791176 almost 10 years
      designing my solution? Am just asking a question. You can answer if you want or you can skip. Simply am asking whether this solution is viable or not.
    • Chris Dodd
      Chris Dodd almost 10 years
      How do you verify member withdrawal requests as actually coming from the member? Why would anyone use your system rather than just maintaining their own bitcoin address?