Esempio n. 1
0
        static MsgUtils()
        {
            // Initialize formatter to default for values of indeterminate type.
            DefaultValueFormatter = val => string.Format(Fmt_Default, val);

            AddFormatter(next => val => val is ValueType ? string.Format(Fmt_ValueType, val) : next(val));

            AddFormatter(next => val => val is DateTime ? FormatDateTime((DateTime)val) : next(val));

            AddFormatter(next => val => val is decimal ? FormatDecimal((decimal)val) : next(val));

            AddFormatter(next => val => val is float ? FormatFloat((float)val) : next(val));

            AddFormatter(next => val => val is double ? FormatDouble((double)val) : next(val));

            AddFormatter(next => val => val is char ? string.Format(Fmt_Char, val) : next(val));

            AddFormatter(next => val => val is IEnumerable ? FormatCollection((IEnumerable)val, 0, 10) : next(val));

            AddFormatter(next => val => val is string ? FormatString((string)val) : next(val));

            AddFormatter(next => val => val.GetType().IsArray ? FormatArray((Array)val) : next(val));

#if NETCF
            AddFormatter(next => val =>
            {
                var vi = val as System.Reflection.MethodInfo;
                return (vi != null && vi.IsGenericMethodDefinition)
                        ? string.Format(Fmt_Default, vi.Name + "<>") 
                        : next(val);
            });
#endif
        }
Esempio n. 2
0
        static MsgUtils()
        {
            // Initialize formatter to default for values of indeterminate type.
            DefaultValueFormatter = val => string.Format(Fmt_Default, val);

            AddFormatter(next => val => val is ValueType ? string.Format(Fmt_ValueType, val) : next(val));

            AddFormatter(next => val => val is DateTime ? FormatDateTime((DateTime)val) : next(val));

            AddFormatter(next => val => val is DateTimeOffset ? FormatDateTimeOffset ((DateTimeOffset)val) : next (val));

            AddFormatter(next => val => val is decimal ? FormatDecimal((decimal)val) : next(val));

            AddFormatter(next => val => val is float ? FormatFloat((float)val) : next(val));

            AddFormatter(next => val => val is double ? FormatDouble((double)val) : next(val));

            AddFormatter(next => val => val is char ? string.Format(Fmt_Char, val) : next(val));

            AddFormatter(next => val => val is IEnumerable ? FormatCollection((IEnumerable)val, 0, 10) : next(val));

            AddFormatter(next => val => val is string ? FormatString((string)val) : next(val));

            AddFormatter(next => val => val.GetType().IsArray ? FormatArray((Array)val) : next(val));            
        }
Esempio n. 3
0
		public TypeInfo(InfoBinderInterface binder, int namespaceIndex, string localName, int baseTypeIndex, int memberBegin,
					 int memberEnd, FacetInfo[] facets, WhitespaceType whitespace)
		{
			this.namespaceIndex = namespaceIndex;
			this.localName = localName;
			this.baseTypeIndex = baseTypeIndex;
			this.memberBegin = memberBegin;
			this.memberEnd = memberEnd;
			this.facets = facets;
			this.whitespace = whitespace;
			this.binder = binder;
			this.formatter = null;
		}
 protected internal virtual string ProcessResult(string result, IMapping mapping)
 {
     if (string.IsNullOrWhiteSpace(result))
     {
         return(string.Empty);
     }
     if (result.StartsWith("\"") && result.EndsWith("\"") && result.Length >= 2)
     {
         result = result.Substring(1, result.Length - 2);
     }
     if (result.StartsWith("#") && result.EndsWith("#") && result.Length >= 2)
     {
         result = result.Substring(1, result.Length - 2);
     }
     if (mapping is ISupportFormat && (mapping as ISupportFormat).HasFormat)
     {
         result = ValueFormatter.FormatValue(result, (mapping as ISupportFormat).Format);
     }
     result = this.ResizeResult(result, mapping);
     return(result);
 }
Esempio n. 5
0
        protected GuiSlider CreateSlider(ValueFormatter <double> valueFormatter, Func <AlexOptions, OptionsProperty <double> > optionsAccessor, double?minValue = null, double?maxValue = null, double?stepInterval = null)
        {
            var slider = CreateValuedControl <GuiSlider, double>(valueFormatter, optionsAccessor);

            if (minValue.HasValue)
            {
                slider.MinValue = minValue.Value;
            }

            if (maxValue.HasValue)
            {
                slider.MaxValue = maxValue.Value;
            }

            if (stepInterval.HasValue)
            {
                slider.StepInterval = stepInterval.Value;
            }

            return(slider);
        }
Esempio n. 6
0
 // Rates are in units of |value| per real-time second.
 public DifferentialSlider(string label,
                 string unit,
                 double log10_lower_rate,
                 double log10_upper_rate,
                 double min_value,
                 double max_value,
                 ValueFormatter formatter = null)
 {
     label_ = label;
     unit_ = unit;
     culture_= new CultureInfo("");
     culture_.NumberFormat.NumberGroupSeparator = "'";
     if (formatter == null) {
       format_ = v => v.ToString("#,0.000", culture_);
     } else {
       format_ = formatter;
     }
     log10_lower_rate_ = log10_lower_rate;
     log10_upper_rate_ = log10_upper_rate;
     min_value_ = min_value;
     max_value_ = max_value;
 }
Esempio n. 7
0
        bool AppendJsonProperty(string propertyName, object propertyValue, StringBuilder builder, string itemSeparator)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                return(false);
            }

            builder.Append(itemSeparator);

            if (!ValueFormatter.FormatValue(propertyName, null, MessageTemplates.CaptureType.Serialize, null, builder))
            {
                return(false);
            }

            builder.Append(": ");
            if (!ValueFormatter.FormatValue(propertyValue, null, MessageTemplates.CaptureType.Serialize, null, builder))
            {
                return(false);
            }

            return(true);
        }
Esempio n. 8
0
        private string FormatKeyValues(string tablePath, IList <object> keyValues)
        {
            var    valueFormatter = new ValueFormatter();
            string formattedKeyValues;

            if (keyValues.Count == 1)
            {
                formattedKeyValues = valueFormatter.Format(keyValues);
            }
            else
            {
                var tableName      = ExtractTableNames(tablePath).First();
                var keyNames       = _getKeyNames(tableName);
                var namedKeyValues = new Dictionary <string, object>();
                for (int index = 0; index < keyNames.Count(); index++)
                {
                    namedKeyValues.Add(keyNames[index], keyValues[index]);
                }
                formattedKeyValues = valueFormatter.Format(namedKeyValues);
            }
            return("(" + HttpUtility.UrlEncode(formattedKeyValues) + ")");
        }
        public void SetAndRestoreValueFormatter()
        {
            var context           = new TestExecutionContext(setupContext);
            var originalFormatter = context.CurrentValueFormatter;

            try
            {
                ValueFormatter f = val => "dummy";
                context.AddFormatter(next => f);
                Assert.That(context.CurrentValueFormatter, Is.EqualTo(f));

                context.EstablishExecutionEnvironment();
                Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("dummy"));
            }
            finally
            {
                setupContext.EstablishExecutionEnvironment();
            }

            Assert.That(TestExecutionContext.CurrentContext.CurrentValueFormatter, Is.EqualTo(originalFormatter));
            Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("123"));
        }
Esempio n. 10
0
        protected override void UpdateCanonicalData(CanonicalData canonicalData)
        {
            foreach (var canonicalDataCase in canonicalData.Cases)
            {
                canonicalDataCase.UseFullDescriptionPath = true;

                if (canonicalDataCase.Property == "new")
                {
                    continue;
                }

                canonicalDataCase.TestedMethodType = TestedMethodType.Instance;

                if (canonicalDataCase.Input.ContainsKey("key"))
                {
                    canonicalDataCase.SetConstructorInputParameters("key");
                }

                if (canonicalDataCase.Input.TryGetValue("ciphertext", out var cipherText))
                {
                    if (cipherText == "cipher.key")
                    {
                        canonicalDataCase.Input["ciphertext"] = new UnescapedValue("sut.Key.Substring(0, 10)");
                    }
                    else if (cipherText == "cipher.encode")
                    {
                        var plaintext = ValueFormatter.Format(canonicalDataCase.Input["plaintext"]);
                        canonicalDataCase.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})");
                        canonicalDataCase.SetInputParameters("ciphertext");
                    }
                }

                if (canonicalDataCase.Expected is string s && s == "cipher.key")
                {
                    canonicalDataCase.Expected = new UnescapedValue("sut.Key.Substring(0, 10)");
                }
            }
        }
Esempio n. 11
0
 // Rates are in units of |value| per real-time second.
 public DifferentialSlider(string label,
                           string unit,
                           double log10_lower_rate,
                           double log10_upper_rate,
                           double zero_value = 0,
                           double min_value = double.NegativeInfinity,
                           double max_value = double.PositiveInfinity,
                           ValueFormatter formatter = null,
                           ValueParser parser = null,
                           UnityEngine.Color? text_colour = null) {
   label_ = label;
   unit_ = unit;
   if (formatter == null) {
     formatter_ = v => v.ToString("#,0.000", Culture.culture);
   } else {
     formatter_ = formatter;
   }
   if (parser == null) {
     // As a special exemption we allow a comma as the decimal separator.
     parser_ = (string s, out double value) =>
                   Double.TryParse(s.Replace(',', '.'),
                                   NumberStyles.AllowDecimalPoint |
                                   NumberStyles.AllowLeadingSign |
                                   NumberStyles.AllowLeadingWhite |
                                   NumberStyles.AllowThousands |
                                   NumberStyles.AllowTrailingWhite,
                                   Culture.culture.NumberFormat,
                                   out value);
   } else {
     parser_ = parser;
   }
   log10_lower_rate_ = log10_lower_rate;
   log10_upper_rate_ = log10_upper_rate;
   zero_value_ = zero_value;
   min_value_ = min_value;
   max_value_ = max_value;
   text_colour_ = text_colour;
 }
Esempio n. 12
0
        private static UnescapedValue RenderTree(dynamic tree)
        {
            if (tree == null)
            {
                return(null);
            }

            var sb = new StringBuilder();

            var label = ValueFormatter.Format(tree["label"]);

            if (tree.ContainsKey("children"))
            {
                var children = string.Join(", ", ((object[])tree["children"]).Select(RenderTree));
                sb.Append($"new Tree({label}, {children})");
            }
            else
            {
                sb.Append($"new Tree({label})");
            }

            return(new UnescapedValue(sb.ToString()));
        }
Esempio n. 13
0
        static MsgUtils()
        {
            // Initialize formatter to default for values of indeterminate type.
            DefaultValueFormatter = val => string.Format(Fmt_Default, val);

            AddFormatter(next => val => val is ValueType ? string.Format(Fmt_ValueType, val) : next(val));

            AddFormatter(next => val => val is DateTime ? FormatDateTime((DateTime)val) : next(val));

#if !NETCF
            AddFormatter(next => val => val is DateTimeOffset ? FormatDateTimeOffset((DateTimeOffset)val) : next(val));
#endif

            AddFormatter(next => val => val is decimal ? FormatDecimal((decimal)val) : next(val));

            AddFormatter(next => val => val is float?FormatFloat((float)val) : next(val));

            AddFormatter(next => val => val is double?FormatDouble((double)val) : next(val));

            AddFormatter(next => val => val is char?string.Format(Fmt_Char, val) : next(val));

            AddFormatter(next => val => val is IEnumerable ? FormatCollection((IEnumerable)val, 0, 10) : next(val));

            AddFormatter(next => val => val is string?FormatString((string)val) : next(val));

            AddFormatter(next => val => val.GetType().IsArray ? FormatArray((Array)val) : next(val));

#if NETCF
            AddFormatter(next => val =>
            {
                var vi = val as System.Reflection.MethodInfo;
                return((vi != null && vi.IsGenericMethodDefinition)
                        ? string.Format(Fmt_Default, vi.Name + "<>")
                        : next(val));
            });
#endif
        }
 // Rates are in units of |value| per real-time second.
 public DifferentialSlider(string label,
           string unit,
           double log10_lower_rate,
           double log10_upper_rate,
           double min_value = double.NegativeInfinity,
           double max_value = double.PositiveInfinity,
           ValueFormatter formatter = null,
           UnityEngine.Color? text_colour = null)
 {
     label_ = label;
     unit_ = unit;
     culture_= new CultureInfo("");
     culture_.NumberFormat.NumberGroupSeparator = "'";
     if (formatter == null) {
       format_ = v => v.ToString("#,0.000", culture_);
     } else {
       format_ = formatter;
     }
     log10_lower_rate_ = log10_lower_rate;
     log10_upper_rate_ = log10_upper_rate;
     min_value_ = min_value;
     max_value_ = max_value;
     text_colour_ = text_colour;
 }
Esempio n. 15
0
 protected virtual void DrawEntryValue(CGContext context, IPointEntry pointEntry, CGPoint position, TextStyle textStyle)
 => DrawHelper.DrawText(context, ValueFormatter.Invoke(pointEntry), position, textStyle);
Esempio n. 16
0
 /// <summary>
 /// Add a formatter to the chain of responsibility.
 /// </summary>
 /// <param name="formatterFactory"></param>
 public static void AddFormatter(ValueFormatterFactory formatterFactory)
 {
     ValueFormatter = formatterFactory(ValueFormatter);
 }
Esempio n. 17
0
 /// <summary>
 /// This method provides a simplified way to add a ValueFormatter
 /// delegate to the chain of responsibility, creating the factory
 /// delegate internally. It is useful when the Type of the object
 /// is the only criterion for selection of the formatter, since
 /// it can be used without getting involved with a compound function.
 /// </summary>
 /// <typeparam name="TSUPPORTED">The type supported by this formatter</typeparam>
 /// <param name="formatter">The ValueFormatter delegate</param>
 public static void AddFormatter <TSUPPORTED>(ValueFormatter formatter)
 {
     AddFormatter(next => val => (val is TSUPPORTED) ? formatter(val) : next(val));
 }
 public static string ToODataString(this long number, ValueFormatter.FormattingStyle formattingStyle)
 {
     var value = number.ToString(CultureInfo.InvariantCulture);
     return string.Format(@"{0}L", value);
 }
 public static string ToODataString(this DateTimeOffset dateTimeOffset, ValueFormatter.FormattingStyle formattingStyle)
 {
     var value = dateTimeOffset.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ");
     return string.Format(@"datetimeoffset'{0}'", value);
 }
Esempio n. 20
0
 /// <summary>
 /// Adds a new ValueFormatterFactory to the chain of formatters
 /// </summary>
 /// <param name="formatterFactory">The new factory</param>
 public void AddFormatter(ValueFormatterFactory formatterFactory)
 {
     CurrentValueFormatter = formatterFactory(CurrentValueFormatter);
 }
Esempio n. 21
0
 /// <summary>
 /// Adds a new ValueFormatterFactory to the chain of formatters
 /// </summary>
 /// <param name="formatterFactory">The new factory</param>
 public void AddFormatter(ValueFormatterFactory formatterFactory)
 {
     CurrentValueFormatter = formatterFactory(CurrentValueFormatter);
 }
        protected virtual bool ProcessAsVirtualField(FieldNode fieldNode, ConstantNode valueNode, float boost, ComparisonType comparison, ElasticSearchQueryMapperState state, out BaseQuery query)
        {
            query = null;
            if (_fieldQueryTranslators == null)
            {
                return(false);
            }
            var translator = _fieldQueryTranslators.GetTranslator(fieldNode.FieldKey.ToLowerInvariant());

            if (translator == null)
            {
                return(false);
            }

            var formattedValue = ValueFormatter.FormatValueForIndexStorage(valueNode.Value);
            var fieldQuery     = translator.TranslateFieldQuery(fieldNode.FieldKey, formattedValue, comparison, FieldNameTranslator);         //TODO: does the fieldNode.FieldKey value need to be formatted here?

            if (fieldQuery == null)
            {
                return(false);
            }

            var queryList = new List <BaseQuery>();

            if (fieldQuery.FieldComparisons != null)
            {
                foreach (var tuple in fieldQuery.FieldComparisons)
                {
                    var indexFieldName = FieldNameTranslator.GetIndexFieldName(tuple.Item1);
                    switch (tuple.Item3)
                    {
                    case ComparisonType.Equal:
                        queryList.Add(HandleEqual(indexFieldName, tuple.Item2, boost));
                        break;

                    case ComparisonType.LessThan:
                        queryList.Add(HandleLessThan(indexFieldName, tuple.Item2, boost));
                        break;

                    case ComparisonType.LessThanOrEqual:
                        queryList.Add(HandleLessThanOrEqual(indexFieldName, tuple.Item2, boost));
                        break;

                    case ComparisonType.GreaterThan:
                        queryList.Add(HandleGreaterThan(indexFieldName, tuple.Item2, boost));
                        break;

                    case ComparisonType.GreaterThanOrEqual:
                        queryList.Add(HandleGreaterThanOrEqual(indexFieldName, tuple.Item2, boost));
                        break;

                    default:
                        throw new InvalidOperationException("Unknown comparison type: " + tuple.Item3);
                    }
                }
                foreach (var q in queryList)
                {
                    if (query == null)
                    {
                        query = q;
                    }
                    else
                    {
                        query &= q;
                    }
                }
            }

            if (fieldQuery.QueryMethods != null)
            {
                foreach (var method in fieldQuery.QueryMethods)
                {
                    state.AdditionalQueryMethods.Add(method);
                }
            }

            state.VirtualFieldProcessors.Add(translator);

            return(true);
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            FileInfo = new FileInformation();


            while (ValueFormatter.isEmpty(FileInfo.InputFileName))
            {
                Out.WriteLine("Please copy and paste file path in .csv or .tsv format");
                FileInfo.InputFileName = ReadLine();
            }

            FileInfo.ReadResults = GetFileName.ReadFileName(FileInfo.InputFileName);



            string numberOfFields = null;
            int    temp2;

            while (ValueFormatter.isEmpty(numberOfFields) || !int.TryParse(numberOfFields, out temp2))
            {
                WriteLine("Enter number of fields");
                numberOfFields = ReadLine();
            }

            int fieldsInRecords = 0;

            try
            {
                fieldsInRecords         = Convert.ToInt32(numberOfFields);
                FileInfo.NumberOfFields = fieldsInRecords;

                FileInfo.Results    = GetLines.ReturnDetailRecords(FileInfo.ReadResults);
                FileInfo.NewResults = FileInfo.Results.Skip(1).ToList();
                char delimiter = GetFileName.CheckFileName(FileInfo.InputFileName);
                //Once you run this, it'll write the files to your bin direcotry
                FileInfo.EnvironmentDirectory = WriteToFile.GetEnvironmentDirectory();

                foreach (var rec in FileInfo.NewResults)
                {
                    var returnedFields  = GetLines.ReturnFields(rec, delimiter);
                    var isRecordCorrect = GetLines.GetFieldCount(returnedFields, fieldsInRecords);
                    if (isRecordCorrect == false)
                    {
                        var pathCombined = Path.Combine(FileInfo.EnvironmentDirectory, "errorrecs.txt");
                        Out.WriteLine($"directory is {pathCombined}");
                        WriteToFile.WriteErrorsToFile(pathCombined, rec);
                    }
                    else
                    {
                        var pathCombined = Path.Combine(FileInfo.EnvironmentDirectory, "correct.txt");
                        Out.WriteLine($"directory is {pathCombined}");
                        WriteToFile.WriteErrorsToFile(pathCombined, rec);
                    }
                }

                Console.WriteLine($"the delimiter is {delimiter}");
                Console.WriteLine(FileInfo.NewResults.Count);
            }
            catch (System.FormatException fe)
            {
                Out.WriteLine($"No fields were read {fe}");
            }

            Console.Out.WriteLine("Bonsoir, Elliot");
            Console.ReadKey();
        }
Esempio n. 24
0
 /// <summary>
 /// Add a formatter to the chain of responsibility.
 /// </summary>
 /// <param name="formatterFactory"></param>
 public static void AddFormatter(ValueFormatterFactory formatterFactory)
 {
     DefaultValueFormatter = formatterFactory(DefaultValueFormatter);
 }
 public static string ToODataString(this TimeSpan timeSpan, ValueFormatter.FormattingStyle formattingStyle)
 {
     var value = timeSpan.ToString();
     return string.Format(@"time'{0}'", value);
 }
Esempio n. 26
0
 public static void AddFormatter <TSupported>(ValueFormatter formatter)
 {
     AddFormatter(next => val => (val is TSupported) ? formatter(val) : next(val));
 }
Esempio n. 27
0
 public TypeInfo(InfoBinderInterface binder, int namespaceIndex, string localName, int baseTypeIndex, int memberBegin,
                 int memberEnd, FacetInfo[] facets, WhitespaceType whitespace, ValueFormatter frmatter)
 {
     this.namespaceIndex = namespaceIndex;
     this.localName      = localName;
     this.baseTypeIndex  = baseTypeIndex;
     this.memberBegin    = memberBegin;
     this.memberEnd      = memberEnd;
     this.facets         = facets;
     this.whitespace     = whitespace;
     this.binder         = binder;
     this.formatter      = frmatter;
 }
 public static string ToODataString(this Guid guid, ValueFormatter.FormattingStyle formattingStyle)
 {
     var value = guid.ToString();
     return string.Format(@"guid'{0}'", value);
 }
Esempio n. 29
0
 /// <summary>
 /// Obtains settings from category and formatter.
 /// </summary>
 /// @param <T>  the type of the value </param>
 /// <param name="category">  the category of the type </param>
 /// <param name="formatter">  the formatter the use for the type </param>
 /// <returns> the format settings </returns>
 public static FormatSettings <T> of <T>(FormatCategory category, ValueFormatter <T> formatter)
 {
     return(new FormatSettings <T>(category, formatter));
 }
Esempio n. 30
0
        public void TestGivenValue()
        {
            var result = ValueFormatter.Format(7);

            Assert.AreEqual("The value is 7.", result);
        }
Esempio n. 31
0
        public void TestDefaultValue()
        {
            var result = ValueFormatter.Format(null);

            Assert.AreEqual("The value is 42.", result);
        }
Esempio n. 32
0
 /// <summary>
 /// Add a formatter to the chain of responsibility.
 /// </summary>
 /// <param name="formatterFactory"></param>
 public static void AddFormatter(ValueFormatterFactory formatterFactory)
 {
     DefaultValueFormatter = formatterFactory(DefaultValueFormatter);
 }
Esempio n. 33
0
        protected override string RenderTestMethodBodyArrange(TestMethodBody testMethodBody)
        {
            // The ValueFormatter doesn't handle Dictionary<int, IList<string>>. Need to format manually.
            Dictionary<int, string[]> inputDictionary = testMethodBody.CanonicalDataCase.Properties["input"];
            var newInput = FormatMultiLineEnumerable(
                inputDictionary.Keys.Select((key, i) => $"[{ValueFormatter.Format(key)}] = {ValueFormatter.Format(inputDictionary[key])}" + (i < inputDictionary.Keys.Count - 1 ? "," : "")), 
                "input", "new Dictionary<int, IList<string>>");
            newInput = AddTrailingSemicolon(newInput);

            var arrangeVariables = testMethodBody.Data.Variables.ToList();
            arrangeVariables.RemoveAt(0);
            arrangeVariables.InsertRange(0, newInput);
            testMethodBody.ArrangeTemplateParameters = new { Variables = arrangeVariables };

            return base.RenderTestMethodBodyArrange(testMethodBody);
        }
Esempio n. 34
0
        /// <summary>
        /// Serialize a unique EntityItem
        /// </summary>
        /// <param name="item">EntityItem to serialize</param>
        /// <returns>Entity item as string</returns>
        public override string SerializeItem(EntityItem <object> item)
        {
            string parts        = null;
            string strType      = null;
            string strContainer = null;
            string strValue     = null;
            Type   type         = null;

            var itemSerialize = ItemsSerialize
                                .Where(f => f.CanSerialize(this, item))
                                .LastOrDefault();

            if (itemSerialize != null)
            {
                var info = itemSerialize.GetSerializeInfo(this, item);
                type         = info.Type;
                strContainer = info.ContainerName;
            }

            if (type != null)
            {
                if (ShowType == ShowTypeOptions.TypeNameOnlyInRoot && item.GetType() == typeof(ComplexEntity))
                {
                    strType = type.Name;
                }
                else if (ShowType == ShowTypeOptions.TypeName)
                {
                    strType = type.Name;
                }
                else if (ShowType == ShowTypeOptions.FullTypeName)
                {
                    strType = type.FullName;
                }
            }

            if (!string.IsNullOrWhiteSpace(strType) && string.IsNullOrWhiteSpace(strContainer))
            {
                parts = $"{strType}";
            }
            else if (!string.IsNullOrWhiteSpace(strType) && !string.IsNullOrWhiteSpace(strContainer))
            {
                parts = $"{strType}{Constants.IDENTIFIER_SEPARATOR}{strContainer}";
            }
            else if (string.IsNullOrWhiteSpace(strType) && !string.IsNullOrWhiteSpace(strContainer))
            {
                parts = $"{strContainer}";
            }

            // Get value
            strValue = ValueFormatter.Format(type, item.Entity);

            // When is not primitive entity use hashcode
            var separatorValue = $"{Constants.KEY_VALUE_SEPARATOR} ";

            if (strValue == null && item.Entity != null)
            {
                // get entityId
                strValue       = GetEntityIdCallback?.Invoke(item).ToString() ?? item.Entity.GetHashCode().ToString();
                separatorValue = Constants.IDENTIFIER_SEPARATOR;
            }
            else if (strValue == null)
            {
                separatorValue = null;
            }

            if (string.IsNullOrWhiteSpace(parts))
            {
                separatorValue = null;
            }

            return($"{parts}{separatorValue}{strValue}");
        }
 public void SetValue(int value)
 {
     _label.text = ValueFormatter.FormatResourceValue(value);
 }
        public void ValueFormatter()
        {
            var formatter = new ValueFormatter <double>(dbl => ((int)dbl).ToString());

            formatter.Format(2.2).Should().Be("2");
        }
Esempio n. 37
0
        private static object ConvertToType(dynamic rawValue)
        {
            if (IsComplexNumber(rawValue))
            {
                return(new UnescapedValue($"new ComplexNumber({ValueFormatter.Format(ConvertMathDouble(rawValue[0]))}, {ValueFormatter.Format(ConvertMathDouble(rawValue[1]))})"));
            }

            return(rawValue);
        }
Esempio n. 38
0
        void PositionChanged(Geolocator sender, PositionChangedEventArgs e)
        {
            // try getting altitude 3 times before telling them 0:
            if (e.Position.Coordinate.Altitude == 0 && tryCount < 3)
            {
                tryCount += 1;
                return;
            }

            if (!App.RunningInBackground)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    // hide loading if needed:
                    if (pbLoading.Visibility == System.Windows.Visibility.Visible)
                    {
                        pbLoading.Visibility = System.Windows.Visibility.Collapsed;
                    }

                    GeoCoordinate location = new GeoCoordinate(e.Position.Coordinate.Latitude, e.Position.Coordinate.Longitude);
                    if (chkKeepCentered.IsChecked == true)
                    {
                        MainMap.Center = location;
                    }
                    MainMap.ZoomLevel = 15;

                    if (App.listChartData == null || App.listChartData.Count() == 0)
                    {
                        btnStartStop.Visibility    = System.Windows.Visibility.Visible;
                        chkKeepCentered.Visibility = System.Windows.Visibility.Visible;

                        totalDistanceInMeters = 0; // initialize
                        timer          = new DispatcherTimer();
                        timer.Interval = TimeSpan.FromSeconds(1);
                        timer.Tick    += timer_Tick;
                        totalTime      = new TimeSpan();
                        timer.Start();

                        // update status:
                        lblStatus.Text = AppResources.FoundPosition;

                        // center the map on our current location:



                        // add a pushpin with the current location:
                        AddPushpin(location);

                        // first time through:
                        App.listChartData = new List <ChartData>();
                        App.listChartData.Add(new ChartData(e.Position.Coordinate, 0, settings.Options.DistanceUnit));
                        App.LastCoordinate = e.Position.Coordinate;

                        return;
                    }
                    else
                    {
                        GeoCoordinate g1 = new GeoCoordinate(App.LastCoordinate.Latitude, App.LastCoordinate.Longitude);
                        GeoCoordinate g2 = new GeoCoordinate(e.Position.Coordinate.Latitude, e.Position.Coordinate.Longitude);

                        double distanceToNextCoordinate = (g1.GetDistanceTo(g2));

                        g1 = null;
                        g2 = null;

                        if (distanceToNextCoordinate > 1)
                        {
                            totalDistanceInMeters += distanceToNextCoordinate;
                            App.listChartData.Add(new ChartData(e.Position.Coordinate, totalDistanceInMeters, settings.Options.DistanceUnit));
                            DrawLine(e.Position.Coordinate);
                            App.LastCoordinate = e.Position.Coordinate;
                        }
                    }

                    // update status with current elevation:
                    lblStatus.Text = AppResources.CurrentElevationColon + ValueFormatter.GetElevationFormatted(e.Position.Coordinate.Altitude, settings.Options.ElevationUnit);
                });
            }
            else
            {
                Dispatcher.BeginInvoke(() =>
                {
                    // initialize temp data if we need to:
                    if (App.tempChartData == null)
                    {
                        App.tempChartData = new List <ChartData>();
                    }


                    // initialize timer if we need to:
                    if (timer == null)
                    {
                        timer          = new DispatcherTimer();
                        timer.Interval = TimeSpan.FromSeconds(1);
                        timer.Tick    += timer_Tick;
                        totalTime      = new TimeSpan();
                        timer.Start();
                    }

                    // if we don't have a previous coordinate, set it and continue:
                    if (App.LastCoordinate != null)
                    {
                        App.LastCoordinate = e.Position.Coordinate;
                        App.tempChartData.Add(new ChartData(e.Position.Coordinate, totalDistanceInMeters, settings.Options.DistanceUnit));
                    }
                    else
                    {
                        // if we have
                        GeoCoordinate g1 = new GeoCoordinate(App.LastCoordinate.Latitude, App.LastCoordinate.Longitude);
                        GeoCoordinate g2 = new GeoCoordinate(e.Position.Coordinate.Latitude, e.Position.Coordinate.Longitude);

                        double distanceToNextCoordinate = (g1.GetDistanceTo(g2));

                        g1 = null;
                        g2 = null;

                        if (distanceToNextCoordinate > 1)
                        {
                            totalDistanceInMeters += distanceToNextCoordinate;
                            App.tempChartData.Add(new ChartData(e.Position.Coordinate, totalDistanceInMeters, settings.Options.DistanceUnit));
                            App.LastCoordinate = e.Position.Coordinate;
                        }
                    }
                });
            }
        }
        public void Initialize()
        {
            XmlConfigurator.Configure();

            this.formatter = new ValueFormatter();
        }