Exemplo n.º 1
0
 internal static string FlagEnumToString(object value, NetJSONSettings settings)
 {
     if (settings.UseEnumString)
     {
         return ((Enum)value).ToString();
     }
     var eType = value.GetType().GetTypeInfo().GetEnumUnderlyingType();
     if (eType == NetJSON._intType)
         return IntToStr((int)value);
     else if (eType == NetJSON._longType)
         return LongToStr((long)value);
     else if (eType == typeof(ulong))
         return LongToStr((long)((ulong)value));
     else if (eType == typeof(uint))
         return IntUtility.uitoa((uint)value);
     else if (eType == typeof(byte))
     {
         return IntToStr((int)((byte)value));
     }
     else if (eType == typeof(ushort))
     {
         return IntToStr((int)((ushort)value));
     }
     else if (eType == typeof(short))
     {
         return IntToStr((int)((short)value));
     }
     return IntToStr((int)value);
 }
Exemplo n.º 2
0
        private static string DateToStringWithOffset(DateTime date, NetJSONSettings settings, TimeSpan offset) {
			return 
                settings._hasDateStringFormat ? date.ToString(settings._dateStringFormat) :
                settings.DateFormat == NetJSONDateFormat.Default ? DateToString(date, settings, offset) :
				settings.DateFormat == NetJSONDateFormat.EpochTime ? DateToEpochTime(date) :
				DateToISOFormat(date, settings, offset);
		}
Exemplo n.º 3
0
        private static string DateToString(DateTime date, NetJSONSettings settings, TimeSpan offset)
        {
            if (date == DateTime.MinValue)
            {
                return("\\/Date(-62135596800)\\/");
            }
            else if (date == DateTime.MaxValue)
            {
                return("\\/Date(253402300800)\\/");
            }

            var timeZoneFormat = settings.TimeZoneFormat;
            var hours          = Math.Abs(offset.Hours);
            var minutes        = Math.Abs(offset.Minutes);
            var offsetText     = timeZoneFormat == NetJSONTimeZoneFormat.Local ? (string.Concat(offset.Ticks >= 0 ? "+" : "-", hours < 10 ? "0" : string.Empty,
                                                                                                hours, minutes < 10 ? "0" : string.Empty, minutes)) : string.Empty;

            if (date.Kind == DateTimeKind.Utc && timeZoneFormat == NetJSONTimeZoneFormat.Utc)
            {
                offset =
#if NET_CORE
                    TimeZoneInfo.Local.GetUtcOffset(DateTime.Now);
#else
                    TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
#endif
                hours   = Math.Abs(offset.Hours);
                minutes = Math.Abs(offset.Minutes);
                date    = date.AddHours(hours).AddMinutes(minutes);
            }

            return(string.Concat("\\/Date(", DateToEpochTime(date), offsetText, ")\\/"));
        }
Exemplo n.º 4
0
        public static DateTimeOffset FastStringToDateTimeoffset(string value, NetJSONSettings settings)
        {
            TimeSpan offset;
            var      date = StringToDate(value, settings, out offset, isDateTimeOffset: true);

            return(new DateTimeOffset(date.Ticks, offset));
        }
Exemplo n.º 5
0
        public unsafe static string GetStringBasedValue(char *ptr, ref int index, NetJSONSettings settings)
        {
            char   current = '\0', prev = '\0';
            int    count = 0, startIndex = 0;
            string value = string.Empty;

            while (true)
            {
                current = ptr[index];
                if (count == 0 && current == settings._quoteChar)
                {
                    startIndex = index + 1;
                    ++count;
                }
                else if (count > 0 && current == settings._quoteChar && prev != '\\')
                {
                    value = new string(ptr, startIndex, index - startIndex);
                    ++index;
                    break;
                }
                else if (count == 0 && current == 'n')
                {
                    index += 3;
                    return(null);
                }

                prev = current;
                ++index;
            }

            return(value);
        }
Exemplo n.º 6
0
        private static string DateToISOFormat(DateTime date, NetJSONSettings settings, TimeSpan offset)
        {
            var timeZoneFormat = settings.TimeZoneFormat;
            var minute         = date.Minute;
            var hour           = date.Hour;
            var second         = date.Second;
            var timeOfDay      = date.TimeOfDay;
            int totalSeconds   = (int)(date.Ticks - (Math.Floor((decimal)date.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond));
            var day            = date.Day;
            var month          = date.Month;
            var year           = date.Year;

            var value = (_cachedDateStringBuilder ?? (_cachedDateStringBuilder = new StringBuilder(25)))
                        .Clear().Append(IntToStr(year)).Append('-')
                        .Append(month < 10 ? "0" : string.Empty)
                        .Append(IntToStr(month))
                        .Append('-').Append(day < 10 ? "0" : string.Empty).Append(IntToStr(day)).Append('T').Append(hour < 10 ? "0" : string.Empty).Append(IntToStr(hour)).Append(':')
                        .Append(minute < 10 ? "0" : string.Empty).Append(IntToStr(minute)).Append(':')
                        .Append(second < 10 ? "0" : string.Empty).Append(IntToStr(second)).Append('.')
                        .Append(IntToStr(totalSeconds));

            if (timeZoneFormat == NetJSONTimeZoneFormat.Utc)
            {
                value.Append('Z');
            }
            else if (timeZoneFormat == NetJSONTimeZoneFormat.Local)
            {
                //var offset = TimeZone.CurrentTimeZone.GetUtcOffset(date);
                var hours   = Math.Abs(offset.Hours);
                var minutes = Math.Abs(offset.Minutes);
                value.Append(offset.Ticks >= 0 ? '+' : '-').Append(hours < 10 ? "0" : string.Empty).Append(IntToStr(hours)).Append(minutes < 10 ? "0" : string.Empty).Append(IntToStr(minutes));
            }

            return(value.ToString());
        }
Exemplo n.º 7
0
 public static string CustomEnumToStr(Enum @enum, NetJSONSettings settings)
 {
     if (settings.UseEnumString)
     {
         return(@enum.ToString());
     }
     return(IntToStr((int)((object)@enum)));
 }
Exemplo n.º 8
0
		internal static string AllDateToString(DateTime date, NetJSONSettings settings) {
			var offset =
#if NET_STANDARD
                    TimeZoneInfo.Local.GetUtcOffset(date);
#else
					TimeZone.CurrentTimeZone.GetUtcOffset(date);
#endif
			return DateToStringWithOffset(date, settings, offset);
		}
Exemplo n.º 9
0
        public static string AllDateToString(DateTime date, NetJSONSettings settings)
        {
            var offset =
#if NET_CORE
                TimeZoneInfo.Local.GetUtcOffset(date);
#else
                TimeZone.CurrentTimeZone.GetUtcOffset(date);
#endif
            return(DateToStringWithOffset(date, settings, offset));
        }
Exemplo n.º 10
0
        public void SerializeDateTimeOffSet()
        {
            var settings = new NetJSONSettings {
                TimeZoneFormat = NetJSONTimeZoneFormat.Local, DateFormat = NetJSONDateFormat.ISO
            };
            var dateTimeOffset = new DateTimeOffset(DateTime.Now);
            var json           = NetJSON.Serialize(dateTimeOffset, settings);

            var dateTimeOffset2 = NetJSON.Deserialize <DateTimeOffset>(json, settings);

            Assert.AreEqual(dateTimeOffset, dateTimeOffset2);
        }
Exemplo n.º 11
0
        internal unsafe static string ToStringIfString(object value, NetJSONSettings settings)
        {
            var str = value as string;
            if(str != null)
            {
                StringBuilder sb = new StringBuilder();
                NetJSON.EncodedJSONString(sb, str, settings);
                return sb.ToString();
            }

            return str;
        }
Exemplo n.º 12
0
		internal static bool IsCurrentAQuot(char current, NetJSONSettings settings) {
			if (settings.HasOverrideQuoteChar)
				return current == settings._quoteChar;
			var quote = settings._quoteChar;
			var isQuote = current == QuotSingleChar || current == QuotDoubleChar;
			if (isQuote) {
				if (quote != current)
					settings._quoteCharString = (settings._quoteChar = current).ToString();
				settings.HasOverrideQuoteChar = true;
			}
			return isQuote;
		}
Exemplo n.º 13
0
        protected string SerializaMeasure(Entity entity)
        {
            NetJSONSettings formatsettings = new NetJSONSettings()
            {
                DateFormat     = NetJSONDateFormat.ISO,
                TimeZoneFormat = NetJSONTimeZoneFormat.Utc,
                CaseSensitive  = false
            };

            MeasureViewModels.EntityViewModel entityView = new MeasureViewModels.EntityViewModel(entity, 0, 3);
            string json = NetJSON.NetJSON.Serialize(entityView, formatsettings);

            return(json);
        }
Exemplo n.º 14
0
        public void SerializeDateTimeOffSetWithDifferentOffset()
        {
            var settings = new NetJSONSettings {
                TimeZoneFormat = NetJSONTimeZoneFormat.Local, DateFormat = NetJSONDateFormat.ISO
            };

            var now            = DateTime.Now;
            var dateTimeOffset = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, new TimeSpan(2, 0, 0));


            var json = NetJSON.Serialize(dateTimeOffset, settings);

            var dateTimeOffset2 = NetJSON.Deserialize <DateTimeOffset>(json, settings);

            Assert.AreEqual(dateTimeOffset, dateTimeOffset2);
        }
Exemplo n.º 15
0
        internal unsafe static object ToStringIfStringObject(object value, NetJSONSettings settings)
        {
            var str = value as string;
            if (str != null)
            {
                str = string.Concat('"', str, '"');
                fixed (char* p = str)
                {
                    char* ptr = p;
                    int index = 0;
                    return NetJSON.DecodeJSONString(ptr, ref index, settings, fromObject: true);
                }
            }

            return value;
        }
Exemplo n.º 16
0
		internal static unsafe void SkipProperty(char* ptr, ref int index, NetJSONSettings settings) {
			var currentIndex = index;
			char current = '\0';
			char bchar = '\0';
			char echar = '\0';
			bool isStringType = false;
			bool isNonStringType = false;
			int counter = 0;
			bool hasChar = false;
			var currentQuote = settings._quoteChar;

			while (true) {
				current = *(ptr + index);
				if (current != ' ' && current != ':' && current != '\n' && current != '\r' && current != '\t') {
					if (!hasChar) {
						isStringType = current == currentQuote;
						if (!isStringType)
							isNonStringType = current != '{' && current != '[';
						if (isStringType || isNonStringType)
							break;
						bchar = current;
						echar = current == '{' ? '}' :
							current == '[' ? ']' : '\0';
						counter = 1;
						hasChar = true;
					}
					else {
						if ((current == '{' && bchar == '{') || (current == '[' && bchar == '['))
							counter++;
						else if ((current == '}' && echar == '}') || (current == ']' && echar == ']'))
							counter--;
					}
				}
				index++;
				if (hasChar && counter == 0)
					break;
			}

			if (isStringType || isNonStringType) {
				index = currentIndex;
				if (isStringType)
					GetStringBasedValue(ptr, ref index, settings);
				else if (isNonStringType)
					GetNonStringValue(ptr, ref index);
			}
		}
Exemplo n.º 17
0
        public static bool IsCurrentAQuot(char current, NetJSONSettings settings)
        {
            if (settings.HasOverrideQuoteChar)
            {
                return(current == settings._quoteChar);
            }
            var quote   = settings._quoteChar;
            var isQuote = current == QuotSingleChar || current == QuotDoubleChar;

            if (isQuote)
            {
                if (quote != current)
                {
                    settings._quoteCharString = (settings._quoteChar = current).ToString();
                }
                settings.HasOverrideQuoteChar = true;
            }
            return(isQuote);
        }
Exemplo n.º 18
0
        public static DateTime FastStringToDate(string value, NetJSONSettings settings)
        {
            TimeSpan offset;

            return(StringToDate(value, settings, out offset, isDateTimeOffset: false));
        }
Exemplo n.º 19
0
        public unsafe static bool IsInRange(char *ptr, ref int index, int offset, string key, NetJSONSettings settings)
        {
            var inRangeChr = *(ptr + index + offset + 2);

            fixed(char *kPtr = key)
            {
                return((*(ptr + index) == settings._quoteChar &&
                        (inRangeChr == ':' || inRangeChr == ' ' ||
                         inRangeChr == '\t' || inRangeChr == '\n' || inRangeChr == '\r')) &&
                       *(ptr + index + 1) == *kPtr);
            }
        }
Exemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetJSONCacheSerializer"/> class
 /// with custom settings for serialization/deserialization
 /// </summary>
 /// <param name="settings">The settings to used during serialization/deserialization.</param>
 public GzNetJSONCacheSerializer(NetJSONSettings settings) : base(settings)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="NetJSONCacheSerializer"/> class
 /// with custom settings for serialization/deserialization
 /// </summary>
 /// <param name="settings">The settings to used during serialization/deserialization.</param>
 public NetJSONCacheSerializer(NetJSONSettings settings)
 {
     NotNull(settings, nameof(settings));
     this.settings = settings;
 }
Exemplo n.º 22
0
		internal static string CustomEnumToStr(Enum @enum, NetJSONSettings settings) {
			if (settings.UseEnumString)
				return @enum.ToString();
			return IntToStr((int)((object)@enum));
		}
Exemplo n.º 23
0
 public static bool NeedQuotes(Type type, NetJSONSettings settings)
 {
     return(NetJSON.NeedQuotes(type, settings));
 }
Exemplo n.º 24
0
        private static DateTime StringToDate(string value, NetJSONSettings settings, out TimeSpan offset, bool isDateTimeOffset)
        {
            offset = TimeSpan.Zero;

            if (settings._hasDateStringFormat)
            {
                return(DateTime.ParseExact(value, settings.DateStringFormat, CultureInfo.CurrentCulture));
            }

            if (settings.DateFormat == NetJSONDateFormat.EpochTime)
            {
                var unixTimeStamp = FastStringToLong(value);
                var date          = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                return(date.AddTicks(unixTimeStamp).ToLocalTime());
            }

            DateTime dt;

            string[] tokens           = null;
            bool     negative         = false;
            string   offsetText       = null;
            int      tickMilliseconds = 0;
            bool     noOffSetValue    = false;
            var      timeZoneFormat   = settings.TimeZoneFormat;

            if (value == "\\/Date(-62135596800)\\/")
            {
                return(DateTime.MinValue);
            }
            else if (value == "\\/Date(253402300800)\\/")
            {
                return(DateTime.MaxValue);
            }
            else if (value[0] == '\\')
            {
                var dateText = value.Substring(7, value.IndexOf(')', 7) - 7);
                negative = dateText.IndexOf('-') >= 0;
                tokens   = negative ? dateText.Split(_dateNegChars, StringSplitOptions.RemoveEmptyEntries)
                                        : dateText.Split(_datePosChars, StringSplitOptions.RemoveEmptyEntries);
                dateText = tokens[0];

                var ticks = FastStringToLong(dateText);

                dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                dt = dt.AddTicks(ticks);

                if (timeZoneFormat == NetJSONTimeZoneFormat.Unspecified || timeZoneFormat == NetJSONTimeZoneFormat.Utc)
                {
                    dt = dt.ToLocalTime();
                }

                var kind = timeZoneFormat == NetJSONTimeZoneFormat.Local ? DateTimeKind.Local :
                           timeZoneFormat == NetJSONTimeZoneFormat.Utc ? DateTimeKind.Utc :
                           DateTimeKind.Unspecified;

                dt = new DateTime(dt.Ticks, kind);

                offsetText = tokens.Length > 1 ? tokens[1] : offsetText;
            }
            else
            {
                var dateText      = value.Substring(0, 19);
                var diff          = value.Length - dateText.Length;
                var hasOffset     = diff > 0;
                var utcOffsetText = hasOffset ? value.Substring(dateText.Length, diff) : string.Empty;
                var firstChar     = utcOffsetText.Length > 0 ? utcOffsetText[0] : '\0';
                negative = diff > 0 && firstChar == '-';
                if (hasOffset)
                {
                    noOffSetValue = timeZoneFormat == NetJSONTimeZoneFormat.Utc || timeZoneFormat == NetJSONTimeZoneFormat.Unspecified;
                    offsetText    = utcOffsetText.Substring(1, utcOffsetText.Length - 1).Replace(":", string.Empty).Replace("Z", string.Empty);
                    if (timeZoneFormat == NetJSONTimeZoneFormat.Local)
                    {
                        int indexOfSign = offsetText.IndexOf('-');
                        negative = indexOfSign >= 0;
                        if (!negative)
                        {
                            indexOfSign = offsetText.IndexOf('+');
                        }
                        tickMilliseconds = FastStringToInt(offsetText.Substring(0, indexOfSign));
                        offsetText       = offsetText.Substring(indexOfSign + 1, offsetText.Length - indexOfSign - 1);
                        if (negative)
                        {
                            offsetText = offsetText.Replace("-", string.Empty);
                        }
                        else
                        {
                            offsetText = offsetText.Replace("+", string.Empty);
                        }
                    }
                    else
                    {
                        tickMilliseconds = FastStringToInt(offsetText);
                    }
                }
                dt = DateTime.Parse(dateText, CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal);
                if (timeZoneFormat == NetJSONTimeZoneFormat.Local)
                {
                    if (!isDateTimeOffset)
                    {
                        dt = dt.ToUniversalTime();
                    }
                    dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond, DateTimeKind.Local);
                }
                else if (timeZoneFormat == NetJSONTimeZoneFormat.Utc)
                {
                    dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond, DateTimeKind.Utc);
                }
            }

            var isNullOrWhiteSpace = false;

#if NET_35
            isNullOrWhiteSpace = offsetText.IsNullOrWhiteSpace();
#else
            isNullOrWhiteSpace = string.IsNullOrWhiteSpace(offsetText);
#endif

            if (!isNullOrWhiteSpace)
            {
                var hours   = noOffSetValue ? 0 : FastStringToInt(offsetText.Substring(0, 2));
                var minutes = noOffSetValue ? 0 : (offsetText.Length > 2 ? FastStringToInt(offsetText.Substring(2, 2)) : 0);
                if (negative)
                {
                    hours *= -1;
                }
                offset = new TimeSpan(hours, minutes, 0);
                if (!isDateTimeOffset)
                {
                    dt = dt.AddHours(hours).AddMinutes(minutes);
                }
                dt = dt.AddTicks(tickMilliseconds);
            }

            return(dt);
        }
Exemplo n.º 25
0
 public static string AllDateOffsetToString(DateTimeOffset offset, NetJSONSettings settings)
 {
     return(DateToStringWithOffset(offset.DateTime, settings, offset.Offset));
 }
Exemplo n.º 26
0
        /// <summary>
        /// Configures the cache manager to use the <code>NetJSON</code> based cache serializer with compression.
        /// </summary>
        /// <param name="part">The configuration part.</param>
        /// <param name="settings">The settings to be used during serialization/deserialization.</param>
        /// <returns>The builder instance.</returns>
        public static ConfigurationBuilderCachePart WithNetJSONJsonSerializer(this ConfigurationBuilderCachePart part, NetJSONSettings settings)
        {
            NotNull(part, nameof(part));

            return(part.WithSerializer(typeof(GzNetJSONCacheSerializer), settings));
        }
Exemplo n.º 27
0
		internal static bool NeedQuotes(Type type, NetJSONSettings settings) {
			return NetJSON.NeedQuotes(type, settings);
		}