Esempio n. 1
0
 public ClientNodeConfiguration()
 {
     MaxConnections = 50;
     MinConnections = 5;
     MaxIdleTime = TimeSpan.FromMinutes(1);
     MaxBusyTime = TimeSpan.FromMinutes(1);
     SendTimeout = TimeSpan.FromSeconds(5);
     ReceiveTimeout = TimeSpan.FromSeconds(5);
     ConnectTimeout = TimeSpan.FromSeconds(5);
     MaintenanceInterval = TimeSpan.FromSeconds(300);
     Weight = ClientNodeWeight.Medium;
 }
Esempio n. 2
0
        /// <summary>
        /// Returns default Timespan value if not a valid Timespan.
        /// </summary>
        public static TimeSpan ValidateDuration(string value)
        {
            TimeSpan interval;

#if NET45 || NET46
            if (!TimeSpan.TryParse(value, CultureInfo.InvariantCulture, out interval))
#else
            if (!TimeSpanEx.TryParse(value, CultureInfo.InvariantCulture, out interval))
#endif
            {
                CoreEventSource.Log.TelemetryIncorrectDuration();
                return(TimeSpan.Zero);
            }

            return(interval);
        }
Esempio n. 3
0
        public static void Write(byte value, out bool dout)
        {
            const byte maxValue = 180;
            byte       current  = value < maxValue ? (byte)value : maxValue;

            dout = true;
            FPGA.Runtime.Delay(TimeSpanEx.FromMicroseconds(544));
            for (ushort i = 0; i < 1945; i++)
            {
                // wait for 10 microseconds for each degree
                FPGA.Runtime.Delay(TimeSpanEx.FromMicroseconds(10));
                if (i == current)
                {
                    dout = false;
                }
            }
        }
Esempio n. 4
0
        public static void SyncWrite(
            uint[] rgb,
            uint offset,
            int length,
            out bool DOUT)
        {
            FPGA.Config.Default(out DOUT, false);
            uint pixel = 0;

            for (uint addr = 0; addr < length; addr++)
            {
                Func <uint> actualAddr = () => addr + offset;
                pixel = rgb[actualAddr()];

                uint ordered = (uint)(
                    ((byte)(pixel >> 8) << 16) | // green
                    ((byte)(pixel >> 16) << 8) | // red
                    (byte)(pixel)
                    );

                Func <bool> bitValue = () => FPGA.Config.Bit(ordered, 23);

                for (byte bit = 0; bit < 24; bit++)
                {
                    if (bitValue())
                    {
                        DOUT = true;
                        FPGA.Runtime.Delay(TimeSpanEx.FromNanoseconds(700));
                        DOUT = false;
                        FPGA.Runtime.Delay(TimeSpanEx.FromNanoseconds(600));
                    }
                    else
                    {
                        DOUT = true;
                        FPGA.Runtime.Delay(TimeSpanEx.FromNanoseconds(350));
                        DOUT = false;
                        FPGA.Runtime.Delay(TimeSpanEx.FromNanoseconds(800));
                    }

                    ordered = ordered << 1;
                }
            }

            FPGA.Runtime.Delay(TimeSpan.FromMilliseconds(10));
        }
Esempio n. 5
0
        /// <summary>
        /// Set the Range Filter for the currently selected stock
        /// </summary>
        /// <param name="numberOfMonths"></param>
        public void SetStockDisplayRange(double numberOfMonths)
        {
            if (_stocks.Count == 0)
            {
                return;
            }

            DebugManager.Time("StockViewModel.StockDisplayRangeChanged");
            //var numberOfDays = DateTime.Now.Subtract(startDate).TotalDays;
            var numberOfDays = TimeSpanEx.FromMonths(numberOfMonths).TotalDays;

            _stockDisplayRange = numberOfMonths;
            _stocks.Each(x => x.RangeFilter = numberOfMonths);
            var minimumValue = DateTime.Now;

            if (numberOfDays == 0)
            {
                foreach (StockInfoViewModel stock in _stocks)
                {
                    if (stock.Data != null)
                    {
                        if (stock.Data.Count() > 0)
                        {
                            DateTime date = stock.Data.First().Date;
                            if (date < minimumValue)
                            {
                                minimumValue = date;
                            }
                        }
                    }
                }
            }
            else
            {
                //minimumValue = DateTime.Now.AddMonths(-1 * numberOfMonths);
                minimumValue = DateTime.Now.AddDays(-1 * numberOfDays);
            }

            DebugManager.Log("StockViewModel.StockDisplayRangeChanged to " + numberOfMonths + " months");
            DebugManager.Time("StockViewModel.StockDisplayRangeChanged");
            this.MinimumValue = minimumValue;

            OnPropertyChanged("MinimumValue");
        }
Esempio n. 6
0
        private void InternalCalculateMinorTicks(DateTime org, DateTime end, TimeSpanEx majorSpan, TimeSpanEx minorSpan)
        {
            _minorTicks.Clear();

            if (majorSpan._span.Ticks <= 0)
            {
                return;
            }

            DateTime currentMajor = majorSpan.RoundDown(org);
            DateTime nextMajor    = TimeSpanEx.Add(currentMajor, majorSpan);
            DateTime x            = TimeSpanEx.Add(currentMajor, minorSpan);

            while (x <= end)
            {
                while (nextMajor <= x)
                {
                    nextMajor = TimeSpanEx.Add(nextMajor, majorSpan);
                }

                if (x >= org && x != nextMajor)
                {
                    _minorTicks.Add(x);
                }

                x = TimeSpanEx.Add(x, majorSpan);
            }

            // Remove suppressed ticks
            _suppressedMinorTicks.RemoveSuppressedTicks(_minorTicks);

            if (!_additionalMinorTicks.IsEmpty)
            {
                foreach (AltaxoVariant v in _additionalMinorTicks.Values)
                {
                    _minorTicks.Add(v);
                }
            }
        }
        [TestCase(5, 3, 10, /*inflow:*/ 0, 0, 0, 0, 0, 0, 51, 0, 0, 0)] // alert delayed: 0, 0, [0, 0, 0, 0, 51], 0, 0, 0
        public void RaiseAlertWhithDelay(int monitoredPeriodSeconds, int delaySeconds, int hitsPerSecondsThreshold, params int[] inflow)
        {
            DateTime?alertRepotTime = null;

            var alertHandler = new Mock <IAlertHandler>();

            alertHandler
            .Setup(x => x.RaiseAlert(It.IsAny <DateTime>(), It.IsAny <int>()))
            .Callback((DateTime timeStamp, int hitCount) => alertRepotTime = timeStamp);

            var options = this.CreateOptions(monitoredPeriodSeconds, delaySeconds, hitsPerSecondsThreshold);
            var utcNow  = this.StartUtc;

            var alertManager = new AlertManager(options, alertHandler.Object);

            // [0, 0, 0, 0, 0], 0
            alertManager.Initialize(utcNow);

            foreach (var requestsCount in inflow)
            {
                alertHandler.Verify(x => x.RaiseAlert(It.IsAny <DateTime>(), It.IsAny <int>()), Times.Never());

                // -> [n, n, n, n, n], requestsCount
                alertManager.Process(this.CreateLogs(requestsCount, utcNow));

                utcNow.IncreaseBySeconds(1);

                // -> [n, n, n, n, requestsCount], 0
                alertManager.MoveMonitoredPeriod(utcNow);
            }

            var expectedAlertReportTime = utcNow.FloorSeconds(1) - TimeSpanEx.FromSecondsInt(delaySeconds);

            alertHandler.Verify(x => x.RaiseAlert(It.IsAny <DateTime>(), It.IsAny <int>()), Times.Once());

            Assert.AreEqual(expectedAlertReportTime, alertRepotTime.Value);
        }
Esempio n. 8
0
        public static void SingleMotorDriver(
            sbyte value,
            FPGA.OutputSignal <bool> pin1,
            FPGA.OutputSignal <bool> pin2,
            FPGA.OutputSignal <bool> enabled)
        {
            bool internalPin1 = false, internalPin2 = false, internalEnabled = false;

            FPGA.Config.Link(internalPin1, out pin1);
            FPGA.Config.Link(internalPin2, out pin2);
            FPGA.Config.Link(internalEnabled, out enabled);

            Action pwm = () =>
            {
                while (true)
                {
                    if (value == 0)
                    {
                        internalEnabled = false;
                        internalPin1    = false;
                        internalPin2    = false;
                    }
                    else
                    {
                        byte steps = 0;
                        if (value > 0)
                        {
                            internalPin1 = false;
                            internalPin2 = true;
                            steps        = (byte)value;
                        }
                        else
                        {
                            steps        = (byte)(0 - value);
                            internalPin2 = false;
                            internalPin1 = true;
                        }

                        byte counter = 0;
                        while (counter < 128)
                        {
                            if (counter <= steps)
                            {
                                internalEnabled = true;
                            }
                            else
                            {
                                internalEnabled = false;
                            }

                            FPGA.Runtime.Delay(TimeSpanEx.FromMicroseconds(100));
                            counter++;
                        }
                    }
                }
            };

            bool trigger = true;

            FPGA.Config.OnSignal(trigger, pwm);
        }
Esempio n. 9
0
 private TimeSpan TrimInvalidationDelay(TimeSpan delay)
 => TimeSpanEx.Min(delay, MaxInvalidationDelay);
Esempio n. 10
0
        /// <summary>
        /// Calculates the number of minor ticks from the major span value and the target number of minor ticks.
        /// </summary>
        /// <param name="majorSpan">Major span value.</param>
        /// <param name="targetNumberOfMinorTicks">Target number of minor ticks.</param>
        /// <returns></returns>
        private static TimeSpanEx CalculateNumberOfMinorTicks(TimeSpanEx majorSpan, int targetNumberOfMinorTicks)
        {
            if (targetNumberOfMinorTicks <= 0)
            {
                return(majorSpan);
            }

            switch (majorSpan._unit)
            {
            case TimeSpanExUnit.Years:
            {
                long years = majorSpan._span.Ticks;
                int  ticks = LinearTickSpacing.CalculateNumberOfMinorTicks(years, targetNumberOfMinorTicks);
                if (ticks < years && ticks > 0 && 0 == years % ticks)
                {
                    return(TimeSpanEx.FromYears(years / ticks));
                }
                double minDiff  = double.MaxValue;
                var    result   = TimeSpanEx.FromYears(1);
                var    divisors = Calc.PrimeNumberMath.GetNeighbouringDivisors(years, targetNumberOfMinorTicks, years);
                foreach (var c in divisors)
                {
                    double dticks = years / c;
                    var    diff   = GetMinorTickDifferencePenalty(dticks, targetNumberOfMinorTicks);
                    if (diff < minDiff)
                    {
                        minDiff = diff;
                        result  = TimeSpanEx.FromYears(years / c);
                    }
                }
                divisors = Calc.PrimeNumberMath.GetNeighbouringDivisors(years * 12, targetNumberOfMinorTicks, years * 12);
                foreach (var c in divisors)
                {
                    double dticks = (years * 12) / c;
                    var    diff   = GetMinorTickDifferencePenalty(dticks, targetNumberOfMinorTicks);
                    if (diff < minDiff)
                    {
                        minDiff = diff;
                        result  = TimeSpanEx.FromMonths((years * 12) / c);
                    }
                }
                return(result);
            }

            case TimeSpanExUnit.Month:
            {
                long months = majorSpan._span.Ticks;
                int  ticks  = LinearTickSpacing.CalculateNumberOfMinorTicks(months, targetNumberOfMinorTicks);
                if (ticks < months && ticks > 0 && 0 == months % ticks)
                {
                    return(TimeSpanEx.FromMonths(months / ticks));
                }

                double minDiff  = double.MaxValue;
                var    result   = TimeSpanEx.FromMonths(1);
                var    divisors = Calc.PrimeNumberMath.GetNeighbouringDivisors(months, targetNumberOfMinorTicks, months);
                foreach (var c in divisors)
                {
                    double dticks = months / c;
                    var    diff   = GetMinorTickDifferencePenalty(dticks, targetNumberOfMinorTicks);
                    if (diff < minDiff)
                    {
                        minDiff = diff;
                        result  = TimeSpanEx.FromMonths(months / c);
                    }
                }
                return(result);
            }

            case TimeSpanExUnit.Span:
            {
                double days = TimeSpanEx.Divide(majorSpan, TimeSpanEx.FromDays(1));
                if (days > 1)
                {
                    int ticks = LinearTickSpacing.CalculateNumberOfMinorTicks(days, targetNumberOfMinorTicks);
                    if (ticks < days)
                    {
                        return(TimeSpanEx.FromTicks(majorSpan._span.Ticks / ticks));
                    }
                }

                var    result  = TimeSpanEx.FromDays(1);
                double minDiff = double.MaxValue;
                foreach (var c in _possibleMinorTicksForDays)
                {
                    double dticks = TimeSpanEx.Divide(majorSpan, c);
                    var    diff   = Math.Abs(dticks - targetNumberOfMinorTicks);
                    if (diff < minDiff)
                    {
                        minDiff = diff;
                        result  = c;
                    }
                }
                return(result);
            }

            default:
                throw new NotImplementedException(string.Format("Unit {0} is unknown here", majorSpan._unit));
            }
        }
Esempio n. 11
0
        /// <summary>Applies the tick snapping settings to the scale origin and scale end. This is done by a determination of the number of decades per major tick and the minor ticks per major tick interval.
        /// Then, the snapping values are applied, and the org and end values of the scale are adjusted (if allowed so).</summary>
        /// <param name="overriddenScaleSpan">The overriden scale span.</param>
        /// <param name="scaleOrg">The scale origin.</param>
        /// <param name="scaleEnd">The scale end.</param>
        /// <param name="isOrgExtendable">If set to <c>true</c>, it is allowed to adjust the scale org value.</param>
        /// <param name="isEndExtendable">if set to <c>true</c>, it is allowed to adjust the scale end value.</param>
        /// <param name="propOrg">The adjusted scale orgin.</param>
        /// <param name="propEnd">The adjusted scale end.</param>
        /// <param name="majorSpan">The physical value that corresponds to one major tick interval.</param>
        /// <param name="minorTicks">Number of minor ticks per major tick interval. This variable has some special values (see <see cref="MinorTicks"/>).</param>
        /// <returns>True if at least either org or end were adjusted to a new value.</returns>
        private bool GetOrgEndWithTickSnappingOnly(TimeSpan overriddenScaleSpan, DateTime scaleOrg, DateTime scaleEnd, bool isOrgExtendable, bool isEndExtendable, out DateTime propOrg, out DateTime propEnd, out TimeSpanEx majorSpan, out TimeSpanEx minorTicks)
        {
            bool modified = false;

            propOrg = scaleOrg;
            propEnd = scaleEnd;

            if (null != _userDefinedMajorSpan)
            {
                majorSpan = _userDefinedMajorSpan.Value;
            }
            else
            {
                majorSpan = CalculateMajorSpan(overriddenScaleSpan, _targetNumberOfMajorTicks);
            }

            minorTicks = majorSpan;
            if (null != _userDefinedMinorTicks)
            {
                var mticks = Math.Abs(_userDefinedMinorTicks.Value);
                if (mticks > 0)
                {
                    switch (majorSpan._unit)
                    {
                    case TimeSpanExUnit.Years:
                    {
                        long years = majorSpan._span.Ticks;
                        if (years >= mticks)
                        {
                            minorTicks = TimeSpanEx.FromYears(years / mticks);
                        }
                        else if (years * 12 >= mticks)
                        {
                            minorTicks = TimeSpanEx.FromMonths(years * 12 / mticks);
                        }
                    }
                    break;

                    case TimeSpanExUnit.Month:
                    {
                        long months = majorSpan._span.Ticks;
                        if (months >= mticks)
                        {
                            minorTicks = TimeSpanEx.FromMonths(months / mticks);
                        }
                    }
                    break;

                    case TimeSpanExUnit.Span:
                    {
                        minorTicks = TimeSpanEx.FromTicks(majorSpan._span.Ticks / mticks);
                    }
                    break;

                    default:
                        throw new NotImplementedException();
                    }
                }
            }
            else
            {
                minorTicks = CalculateNumberOfMinorTicks(majorSpan, _targetNumberOfMinorTicks);
            }

            if (isOrgExtendable)
            {
                propOrg   = GetOrgOrEndSnappedToTick(scaleOrg, majorSpan, minorTicks, _snapOrgToTick, false);
                modified |= BoundaryTickSnapping.SnapToNothing != _snapOrgToTick;
            }

            if (isEndExtendable)
            {
                propEnd   = GetOrgOrEndSnappedToTick(scaleEnd, majorSpan, minorTicks, _snapEndToTick, true);
                modified |= BoundaryTickSnapping.SnapToNothing != _snapEndToTick;
            }

            return(modified);
        }
        public static Configuration Read(string filePath)
        {
            XmlReaderSettings configReaderSettings = new XmlReaderSettings {
                ValidationType  = ValidationType.Schema,
                ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ReportValidationWarnings
            };

            string configSchemaPath = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath) + ".xsd");

            configReaderSettings.Schemas.Add(null, configSchemaPath);

            XmlDocument document = new XmlDocument();

            using (XmlReader configReader = XmlReader.Create(filePath, configReaderSettings))
                document.Load(configReader);

            // Before validating using the schema, first check if the configuration file's version matches with the supported version.
            XmlElement rootElement = document.DocumentElement;
            string     fileVersionRaw;

            if (rootElement.HasAttribute("Version"))
            {
                fileVersionRaw = rootElement.GetAttribute("Version");
            }
            else
            {
                fileVersionRaw = "1.0";
            }

            if (fileVersionRaw != Configuration.CurrentVersion)
            {
                throw new FormatException(string.Format(
                                              "The configuration file is either outdated or too new. Expected version was: {0}. File version is: {1}",
                                              Configuration.CurrentVersion, fileVersionRaw
                                              ));
            }

            Configuration resultingConfig = new Configuration(false);

            resultingConfig.OverrideVanillaCircuits = BoolEx.ParseEx(rootElement["OverrideVanillaCircuits"].InnerXml);
            resultingConfig.AdvancedCircuitsEnabled = BoolEx.ParseEx(rootElement["AdvancedCircuitsEnabled"].InnerText);
            resultingConfig.MaxTrapsPerCircuit      = int.Parse(rootElement["MaxTrapsPerCircuit"].InnerText);
            resultingConfig.MaxStatuesPerCircuit    = int.Parse(rootElement["MaxStatuesPerCircuit"].InnerText);
            resultingConfig.MaxPumpsPerCircuit      = int.Parse(rootElement["MaxPumpsPerCircuit"].InnerText);
            resultingConfig.MaxCircuitLength        = int.Parse(rootElement["MaxCircuitLength"].InnerText);
            if (string.IsNullOrWhiteSpace(rootElement["MaxTimerActivityTime"].InnerText))
            {
                resultingConfig.MaxTimerActivityTime = TimeSpan.Zero;
            }
            else
            {
                TimeSpan maxTimerActivityTime;
                if (TimeSpanEx.TryParseShort(rootElement["MaxTimerActivityTime"].InnerText, out maxTimerActivityTime))
                {
                    resultingConfig.MaxTimerActivityTime = maxTimerActivityTime;
                }
            }
            resultingConfig.SignConfig           = SignConfig.FromXmlElement(rootElement["SignConfig"]);
            resultingConfig.BlockActivatorConfig = BlockActivatorConfig.FromXmlElement(rootElement["BlockActivatorConfig"]);

            XmlElement pumpConfigsNode = rootElement["PumpConfigs"];

            foreach (XmlNode pumpConfigNode in pumpConfigsNode.ChildNodes)
            {
                XmlElement pumpConfigElement = (pumpConfigNode as XmlElement);
                if (pumpConfigElement == null)
                {
                    continue;
                }

                PaintColor paintColor = (PaintColor)Enum.Parse(typeof(PaintColor), pumpConfigElement.Attributes["Paint"].Value);
                resultingConfig.PumpConfigs.Add(paintColor, PumpConfig.FromXmlElement(pumpConfigElement));
            }

            XmlElement trapConfigsNode = rootElement["TrapConfigs"];

            foreach (XmlNode trapConfigNode in trapConfigsNode.ChildNodes)
            {
                XmlElement trapConfigElement = (trapConfigNode as XmlElement);
                if (trapConfigElement == null)
                {
                    continue;
                }

                TrapStyle  trapStyle  = (TrapStyle)Enum.Parse(typeof(TrapStyle), trapConfigElement.Attributes["TrapType"].Value);
                PaintColor paintColor = (PaintColor)Enum.Parse(typeof(PaintColor), trapConfigElement.Attributes["Paint"].Value);
                resultingConfig.TrapConfigs.Add(new TrapConfigKey(trapStyle, paintColor), TrapConfig.FromXmlElement(trapConfigElement));
            }

            /*XmlElement explosivesConfigsNode = rootElement["ExplosivesConfigs"];
             * foreach (XmlNode explosivesConfigNode in explosivesConfigsNode.ChildNodes) {
             * XmlElement explosivesConfigElement = (explosivesConfigNode as XmlElement);
             * if (explosivesConfigElement == null)
             *  continue;
             *
             * ComponentConfigProfile componentConfigProfile = (ComponentConfigProfile)Enum.Parse(typeof(ComponentConfigProfile), explosivesConfigElement.Attributes["Profile"].Value);
             * resultingConfig.explosivesConfigs.Add(componentConfigProfile, ExplosivesConfig.FromXmlElement(explosivesConfigElement));
             * }*/

            XmlElement wirelessTransmitterConfigsNode = rootElement["WirelessTransmitterConfigs"];

            foreach (XmlNode wirelessTransmitterConfigNode in wirelessTransmitterConfigsNode.ChildNodes)
            {
                XmlElement wirelessTransmitterConfigElement = (wirelessTransmitterConfigNode as XmlElement);
                if (wirelessTransmitterConfigElement == null)
                {
                    continue;
                }

                PaintColor paintColor = (PaintColor)Enum.Parse(typeof(PaintColor), wirelessTransmitterConfigElement.Attributes["Paint"].Value);
                resultingConfig.WirelessTransmitterConfigs.Add(paintColor, WirelessTransmitterConfig.FromXmlElement(wirelessTransmitterConfigElement));
            }

            XmlElement statueConfigsNode = rootElement["StatueConfigs"];

            foreach (XmlNode statueConfigNode in statueConfigsNode.ChildNodes)
            {
                XmlElement statueConfigElement = (statueConfigNode as XmlElement);
                if (statueConfigElement == null)
                {
                    continue;
                }

                StatueStyle statueStyle = (StatueStyle)Enum.Parse(typeof(StatueStyle), statueConfigElement.Attributes["StatueType"].Value);
                resultingConfig.StatueConfigs.Add(statueStyle, StatueConfig.FromXmlElement(statueConfigElement));
            }

            return(resultingConfig);
        }
Esempio n. 13
0
        private object ConvertValue(TypeInfo typeInfo, object value)
        {
            var stringValue = Convert.ToString(value, Culture);

            // check for nullable and extract underlying type
            if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                // Since the type is nullable and no value is provided return null
                if (stringValue.IsEmpty())
                {
                    return(null);
                }

                typeInfo = typeInfo.GetGenericArguments()[0].GetTypeInfo();
            }

            if (typeInfo.AsType() == typeof(object))
            {
                if (value == null)
                {
                    return(null);
                }

                typeInfo = value.GetType().GetTypeInfo();
            }

            var type = typeInfo.AsType();

            if (typeInfo.IsPrimitive)
            {
                return(value.ChangeType(type, Culture));
            }

            if (typeInfo.IsEnum)
            {
                return(((Type)type).FindEnumValue(stringValue, Culture));
            }

            if (type == typeof(Uri))
            {
                return(new Uri(stringValue, UriKind.RelativeOrAbsolute));
            }

            if (type == typeof(string))
            {
                return(stringValue);
            }

            if (type == typeof(DateTime) || type == typeof(DateTimeOffset))
            {
                DateTime dt;

                if (DateFormat.HasValue())
                {
                    dt = DateTime.ParseExact(stringValue, DateFormat, Culture,
                                             DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
                }
                else
                {
                    // try parsing instead
                    dt = stringValue.ParseJsonDate(Culture);
                }

                if (type == typeof(DateTime))
                {
                    return(dt);
                }

                if (type == typeof(DateTimeOffset))
                {
                    return((DateTimeOffset)dt);
                }
            }
            else if (type == typeof(decimal))
            {
                if (value is double)
                {
                    return((decimal)(double)value);
                }

                return(stringValue.Contains("e")
                                        ? decimal.Parse(stringValue, NumberStyles.Float, Culture)
                                        : decimal.Parse(stringValue, Culture));
            }
            else if (type == typeof(Guid))
            {
                return(string.IsNullOrEmpty(stringValue)
                                        ? Guid.Empty
                                        : new Guid(stringValue));
            }
            else if (type == typeof(TimeSpan))
            {
                // This should handle ISO 8601 durations
                TimeSpan timeSpan;
                return(TimeSpanEx.TryParse(stringValue, out timeSpan) ? timeSpan : XmlConvert.ToTimeSpan(stringValue));
            }
            else if (type.GetTypeInfo().IsGenericType)
            {
                var genericTypeDef = type.GetGenericTypeDefinition();

                if (genericTypeDef == typeof(IEnumerable <>) || genericTypeDef == typeof(IList <>))
                {
                    var itemType = typeInfo.GetGenericArguments()[0];
                    var listType = typeof(List <>).MakeGenericType(itemType);
                    return(BuildList(listType, value));
                }

                if (genericTypeDef == typeof(List <>))
                {
                    return(BuildList(type, value));
                }

                if (genericTypeDef == typeof(Dictionary <,>))
                {
                    return(BuildDictionary(type, value));
                }

                // nested property classes
                return(CreateAndMap(type, value));
            }
            else if (((Type)type).IsSubclassOfRawGeneric(typeof(List <>)))
            {
                // handles classes that derive from List<T>
                return(BuildList(type, value));
            }
            else if (type == typeof(JsonObject))
            {
                // simplify JsonObject into a Dictionary<string, object>
                return(BuildDictionary(typeof(Dictionary <string, object>), value));
            }
            else
            {
                // nested property classes
                return(CreateAndMap(type, value));
            }

            return(null);
        }
Esempio n. 14
0
 protected virtual TimeSpan TrimInvalidationDelay(TimeSpan delay)
 => TimeSpanEx.Min(delay, MaxInvalidationDelay);
Esempio n. 15
0
        public static void stats(Arg arg)
        {
            TextTable table = new TextTable();

            table.AddColumn("id");
            table.AddColumn("name");
            table.AddColumn("time");
            table.AddColumn("kills");
            table.AddColumn("deaths");
            table.AddColumn("suicides");
            table.AddColumn("player");
            table.AddColumn("building");
            table.AddColumn("entity");
            Action <ulong, string> action = delegate(ulong id, string name)
            {
                ServerStatistics.Storage storage = ServerStatistics.Get(id);
                string text2  = TimeSpanEx.ToShortString(TimeSpan.FromSeconds(storage.Get("time")));
                string text3  = storage.Get("kill_player").ToString();
                string text4  = (storage.Get("deaths") - storage.Get("death_suicide")).ToString();
                string text5  = storage.Get("death_suicide").ToString();
                string text6  = storage.Get("hit_player_direct_los").ToString();
                string text7  = storage.Get("hit_player_indirect_los").ToString();
                string text8  = storage.Get("hit_building_direct_los").ToString();
                string text9  = storage.Get("hit_building_indirect_los").ToString();
                string text10 = storage.Get("hit_entity_direct_los").ToString();
                string text11 = storage.Get("hit_entity_indirect_los").ToString();
                table.AddRow(id.ToString(), name, text2, text3, text4, text5, text6 + " / " + text7, text8 + " / " + text9, text10 + " / " + text11);
            };
            ulong uInt = arg.GetUInt64(0, 0uL);

            if (uInt == 0L)
            {
                string @string = arg.GetString(0);
                foreach (BasePlayer activePlayer in BasePlayer.activePlayerList)
                {
                    try
                    {
                        if (BaseEntityEx.IsValid(activePlayer))
                        {
                            string text = activePlayer.displayName.QuoteSafe();
                            if (@string.Length <= 0 || text.Contains(@string, CompareOptions.IgnoreCase))
                            {
                                action(activePlayer.userID, text);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        table.AddRow(activePlayer.UserIDString, ex.Message.QuoteSafe());
                    }
                }
            }
            else
            {
                string     arg2       = "N/A";
                BasePlayer basePlayer = BasePlayer.FindByID(uInt);
                if ((bool)basePlayer)
                {
                    arg2 = basePlayer.displayName.QuoteSafe();
                }
                action(uInt, arg2);
            }
            arg.ReplyWith(table.ToString());
        }