0

Given this field in an Oracle table:

ColumnName varchar(255 byte)

Given this string:

-- abcd abcdefghijkl mnokpqrstuvwxy abcd ab abcdefgh abc def abc
abcdef ab.* abcd
abcdefgh ij
abcd abcdefghijkl mn ab ab.cd = ef.abcdefghijk ab ab.cd = ab.cdabe
abcd abcdefghi.jklmnopqrstuvwxyzabc de ef ea.fd = ef.aezerfds
azere
fr.qsdfrtd = 1
fds ad.dfdsq

We insert this text into the specified column with a simple insert statement with the help of toad for oracle: that works fine.

However: if we insert this text with the help of nhibernate we will get an oracle error:

ORA-12899: value too large for column [**SNIP**] (actual: 262, maximum: 255)

This error is actually correct if you do a byte count of the given string, we will get a count of 262.

Why does nhibernate fail and why does toad for oracle succeed for the same action?

Has anyone any experience with this problem or something related to it?

Edit

Worth to mention here is that the string has been submitted in a html textarea. Possible problem here is that a return is counted as 1 character in the browser but it should be counted as more then 1 character since in .net it is represented by \r\n.

All this in a asp.net mvc scenario.

Tom B.
  • 2,892
  • 3
  • 13
  • 34
  • Partially similar: http://stackoverflow.com/questions/11241076/new-line-characters-in-text-area-increases-text-length-in-c-sharp – Tom B. Jan 20 '16 at 09:40
  • http://ashleyglee.com/maxlength-on-html-textarea-form-element/ – Tom B. Jan 20 '16 at 09:44
  • http://stackoverflow.com/questions/10030921/chrome-counts-characters-wrong-in-textarea-with-maxlength-attribute – Tom B. Jan 20 '16 at 10:04

1 Answers1

1

The actual problem:

It has nothing to do with nhibernate or oracle. When a textarea with newlines is posted to the "backend" of asp.net mvc we recieve those newlines as \r\n. It counts as 2 characters, which results in 2 bytes for the database save.

However in our situation we have a maxlength=255 html attribute. The browser counts a newline as 1 character. See the difference?

The solution

We solved it by replacing \r\n with \n.

public class NewLineModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (result != null && !string.IsNullOrEmpty(result.AttemptedValue) &&
                bindingContext.ModelType == typeof(string))
            {
                var value = result.AttemptedValue;
                var replacedValue = value.Replace("\r\n", "\n");

                return replacedValue;
            }
            return base.BindModel(controllerContext, bindingContext);
        }
    }
Tom B.
  • 2,892
  • 3
  • 13
  • 34