private static string RunChain(
            X509Chain chain,
            X509Certificate2 cert,
            string msg)
        {
            bool success = chain.Build(cert);

            FormattableString errMsg = null;

            if (!success)
            {
                for (int i = 0; i < chain.ChainElements.Count; i++)
                {
                    X509ChainElement element = chain.ChainElements[i];

                    if (element.ChainElementStatus.Length != 0)
                    {
                        X509ChainStatusFlags flags =
                            element.ChainElementStatus.Select(ces => ces.Status).Aggregate((a, b) => a | b);

                        errMsg = $"{msg}: chain error at depth {i}: {flags}";
                        break;
                    }
                }
            }

            return(errMsg?.ToString(formatProvider: CultureInfo.CurrentCulture));
        }
Ejemplo n.º 2
0
 private static void InterpolatedStringsWithCulture()
 {
     var culture = CultureInfo.GetCultureInfo("sl-SI");
     var a       = 3.5;
     var b       = 12.25;
     FormattableString formattableString = $"  {a,5:0.00}\n+ {b,5:0.00}\n= {a + b,5:0.00}";
     var formatted = formattableString.ToString(culture); // = "   3,50\n+ 12,25\n= 15,75"
 }
        public static String GetPwshEnvString(this FormattableString str, out IEnumerable <KeyValuePair <String, Object?> > args, string prefix = "")
        {
            var formatter = new EnvArgFormatter(prefix);
            var result    = str.ToString(new EnvArgFormatProvider(formatter));

            args = formatter.GetEnvArgs();
            return(result);
        }
        public void Format_WithNullArg_ReturnsEmptyString()
        {
            FormattableString formattableString = $"{null}";

            var actual = formattableString.ToString(new UriFormatProvider());

            Assert.AreEqual(string.Empty, actual);
        }
Ejemplo n.º 5
0
 public void Log(LogSeverity severity, string source, FormattableString message, Exception exception = null)
 {
     if (severity <= Level)
     {
         try { Message(this, new LogMessageEventArgs(severity, source, message.ToString(), exception)); }
         catch { } //We dont want to log on log errors
     }
 }
Ejemplo n.º 6
0
        public void TestNoParams()
        {
            FormattableString formattableString = TestFormatNoParams.FormattableWith(new { Replacement1 = Replacement1, Replacement2 = Replacement2 });

            Assert.Equal(TestFormatNoParams, formattableString.Format);
            Assert.Equal(0, formattableString.ArgumentCount);
            Assert.Equal(TestFormatNoParams, formattableString.ToString());
        }
Ejemplo n.º 7
0
    public static string DisplayGermanExchangeStudents(string studentA
                                                       , string studentB, DateTime start, float hours)
    {
        FormattableString text = $"{studentA} and {studentB} have been dating since {start:d} - that's {hours:n2} hours";
        var germanCultureInfo  = CultureInfo.GetCultureInfo("de-DE");

        return(text.ToString(germanCultureInfo));
    }
        private static void RunChain(
            X509Chain chain,
            X509Certificate2 cert,
            bool expectSuccess,
            string msg)
        {
            bool success = chain.Build(cert);

            FormattableString errMsg = null;

            if (expectSuccess && !success)
            {
                for (int i = 0; i < chain.ChainElements.Count; i++)
                {
                    X509ChainElement element = chain.ChainElements[i];

                    if (element.ChainElementStatus.Length != 0)
                    {
                        X509ChainStatusFlags flags =
                            element.ChainElementStatus.Select(ces => ces.Status).Aggregate((a, b) => a | b);

                        errMsg = $"{msg}: Initial chain error at depth {i}: {flags}";
                        break;
                    }
                }
            }
            else if (!expectSuccess && success)
            {
                errMsg = $"{msg}: Chain fails when expected";
            }

            if (errMsg != null)
            {
                DisposeChainCerts(chain);
            }

            if (expectSuccess)
            {
                Assert.True(success, errMsg?.ToString());
            }
            else
            {
                Assert.False(success, errMsg?.ToString());
            }
        }
Ejemplo n.º 9
0
        public static void DisplayString(this FormattableString s)
        {
            WriteLine("display string");
            WriteLine($"Format: {s.Format}");
            WriteLine($"Argument count: {s.ArgumentCount}");

            WriteLine(s.ToString());
            WriteLine();
        }
        public void Format_WithFormattable_UsesSpecifiedFormat()
        {
            var value = Math.PI;
            FormattableString formattableString = $"{value:0.##}";

            var actual = formattableString.ToString(new UriFormatProvider());

            Assert.AreEqual("3.14", actual);
        }
        public void Format_WithTimeSpan_UsesLittleCFormat()
        {
            var value = new TimeSpan(15, 30, 0);
            FormattableString formattableString = $"{value}";

            var actual = formattableString.ToString(new UriFormatProvider());

            Assert.AreEqual("15%3a30%3a00", actual);
        }
        public void Format_WithDateTime_UsesLittleSFormat()
        {
            var value = new DateTime(2018, 4, 16, 15, 30, 0);
            FormattableString formattableString = $"{value}";

            var actual = formattableString.ToString(new UriFormatProvider());

            Assert.AreEqual("2018-04-16T15%3a30%3a00", actual);
        }
        public void Format_WithDateTimeOffset_UsesBigOFormat()
        {
            var value = new DateTimeOffset(2018, 4, 16, 15, 30, 0, TimeSpan.FromHours(3));
            FormattableString formattableString = $"{value}";

            var actual = formattableString.ToString(new UriFormatProvider());

            Assert.AreEqual("2018-04-16T15%3a30%3a00.0000000%2b03%3a00", actual);
        }
        public void Format_WithRawUnsafeArg_ReturnsSameArg()
        {
            var value = "URI unsafe string";
            FormattableString formattableString = $"{value:raw}";

            var actual = formattableString.ToString(new UriFormatProvider());

            Assert.AreEqual("URI unsafe string", actual);
        }
        public void Format_WithUriUnsafeArg_ReturnsUriEncodedArg()
        {
            var value = "URI unsafe string";
            FormattableString formattableString = $"{value}";

            var actual = formattableString.ToString(new UriFormatProvider());

            Assert.AreEqual("URI+unsafe+string", actual);
        }
Ejemplo n.º 16
0
        public void TestReplacement3()
        {
            FormattableString formattableString = TestFormat3.FormattableWith(new { Replacement1 = Replacement1 });

            Assert.Equal(TestFormat3Composite, formattableString.Format);
            Assert.Equal(1, formattableString.ArgumentCount);
            Assert.Equal(Replacement1, formattableString.GetArgument(0));
            Assert.Equal(TestFormat3Solution, formattableString.ToString());
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Format the given object in the invariant culture. This static method may be
        /// imported in C# by
        /// <code>
        /// using static System.FormattableString;
        /// </code>.
        /// Within the scope
        /// of that import directive an interpolated string may be formatted in the
        /// invariant culture by writing, for example,
        /// <code>
        /// Invariant($"{{ lat = {latitude}; lon = {longitude} }}")
        /// </code>
        /// </summary>
        public static string Invariant(FormattableString formattable)
        {
            if (formattable == null)
            {
                throw new ArgumentNullException("formattable");
            }

            return(formattable.ToString(Globalization.CultureInfo.InvariantCulture));
        }
Ejemplo n.º 18
0
        public void WriteLine(FormattableString str)
        {
            if (str == null)
            {
                throw new ArgumentNullException(nameof(str));
            }

            _writer.WriteLine(str.ToString());
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Format the given object in the invariant culture. This static method may be
        /// imported in C# by
        /// <code>
        /// using static System.FormattableString;
        /// </code>.
        /// Within the scope
        /// of that import directive an interpolated string may be formatted in the
        /// invariant culture by writing, for example,
        /// <code>
        /// Invariant($"{{ lat = {latitude}; lon = {longitude} }}")
        /// </code>
        /// </summary>
        public static string Invariant(FormattableString formattable)
        {
            if (formattable == null)
            {
                throw new ArgumentNullException("formattable");
            }

            return formattable.ToString(Globalization.CultureInfo.InvariantCulture);
        }
Ejemplo n.º 20
0
        public static string CurrentCulture(FormattableString formattable)
        {
            if (formattable == null)
            {
                throw new ArgumentNullException(nameof(formattable));
            }

            return(formattable.ToString(Globalization.CultureInfo.CurrentCulture));
        }
Ejemplo n.º 21
0
        public string Parameterize(FormattableString query, out IDictionary <string, object> parameter)
        {
            var formatter = new AqlQueryFormatter();
            var queryExp  = query.ToString(formatter);

            parameter = formatter.Context.Parameters;

            return(queryExp);
        }
Ejemplo n.º 22
0
 public static Generator <String> Template(FormattableString formattable)
 {
     return(Wrap(delegate(Context ctx)
     {
         var provider = new GFormatProvider(ctx);
         var res = formattable.ToString(provider);
         return CovariantTuple <String, Context> .Create(res, ctx);
     }));
 }
Ejemplo n.º 23
0
        public void TestNestedProperties()
        {
            FormattableString formattableString = TestFormat5.FormattableWith(new { Foo = new { Replacement1 = Replacement1 } });

            Assert.Equal(TestFormat5Composite, formattableString.Format);
            Assert.Equal(1, formattableString.ArgumentCount);
            Assert.Equal(Replacement1, formattableString.GetArgument(0));
            Assert.Equal(TestFormat5Solution, formattableString.ToString());
        }
Ejemplo n.º 24
0
        public async Task <DataSet> QueryAsync(FormattableString formattableQuery)
        {
            logger.LogInformation(formattableQuery.Format, formattableQuery.GetArguments());

            //Creiamo dei SqliteParameter a partire dalla FormattableString
            var queryArguments   = formattableQuery.GetArguments();
            var sqliteParameters = new List <SqliteParameter>();

            for (var i = 0; i < queryArguments.Length; i++)
            {
                if (queryArguments[i] is Sql)
                {
                    continue;
                }
                var parameter = new SqliteParameter(i.ToString(), queryArguments[i]);
                sqliteParameters.Add(parameter);
                queryArguments[i] = "@" + i;
            }
            string query = formattableQuery.ToString();

            //Colleghiamoci al database Sqlite, inviamo la query e leggiamo i risultati
            string connectionString = connectionStringOptions.CurrentValue.Default;

            using (var conn = new SqliteConnection(connectionString))
            {
                await conn.OpenAsync();

                using (var cmd = new SqliteCommand(query, conn))
                {
                    //Aggiungiamo i SqliteParameters al SqliteCommand
                    cmd.Parameters.AddRange(sqliteParameters);

                    //Inviamo la query al database e otteniamo un SqliteDataReader
                    //per leggere i risultati
                    using (var reader = await cmd.ExecuteReaderAsync())
                    {
                        var dataSet = new DataSet();

                        //TODO: La riga qui sotto va rimossa quando la issue sarà risolta
                        //https://github.com/aspnet/EntityFrameworkCore/issues/14963
                        dataSet.EnforceConstraints = false;

                        //Creiamo tanti DataTable per quante sono le tabelle
                        //di risultati trovate dal SqliteDataReader
                        do
                        {
                            var dataTable = new DataTable();
                            dataSet.Tables.Add(dataTable);
                            dataTable.Load(reader);
                        } while (!reader.IsClosed);

                        return(dataSet);
                    }
                }
            }
        }
        public static string Hummanize(this HealthCheck.Result healthCheckResult)
        {
#if NET452
            var formatProvider = new HumanizeHealthCheckResultFormatter();
            return(formatProvider.Format(string.Empty, healthCheckResult, null));
#else
            FormattableString healthCheckResultString = $"{healthCheckResult}";
            return(healthCheckResultString.ToString(new HumanizeMetricValueFormatProvider <HealthCheck.Result>()));
#endif
        }
        public static string Hummanize(this EnvironmentInfo environmentInfo)
        {
#if NET452
            var formatProvider = new HumanizeEnvironmentInfoFormatter();
            return(formatProvider.Format(string.Empty, environmentInfo, null));
#else
            FormattableString environmentInfoString = $"{environmentInfo}";
            return(environmentInfoString.ToString(new HumanizeMetricValueFormatProvider <EnvironmentInfo>()));
#endif
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Test FormattableString
        /// </summary>
        public void FormattableString()
        {
            Console.WriteLine("\n***FORMATTABLESTRING***");

            var dateOfBirth           = new DateTime(1675, 10, 25);
            FormattableString fString = $"You were born on {dateOfBirth:d}";
            var culture = CultureInfo.GetCultureInfo("en-GB");

            Console.WriteLine(fString.ToString(culture));
        }
Ejemplo n.º 28
0
        static string TestResource(FormattableString fileName)
        {
            string path = Path.Combine(Environment.CurrentDirectory, "Resources", fileName.ToString(CultureInfo.InvariantCulture));

            if (File.Exists(path))
            {
                return(path);
            }
            throw new IOException($"Cannot not find test resource: {Path.GetFullPath(path)}");
        }
Ejemplo n.º 29
0
        // TODO Add User and Threads "interfaces"

        public void SetMessage(FormattableString message)
        {
            if (Level == null)
            {
                Level = SeverityLevel.Info;
            }

            Message     = message.ToString();
            Fingerprint = new [] { message.Format, Level.ToString() };
        }
Ejemplo n.º 30
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string) && value is Vector4 vector)
            {
                FormattableString formattableString = $"{vector.X},{vector.Y},{vector.Z},{vector.W}";
                return(formattableString.ToString(culture));
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
Ejemplo n.º 31
0
        public void TestReplacement4()
        {
            FormattableString formattableString = TestFormat4.FormattableWith(new { Replacement1 = Replacement1, Replacement2 = Replacement2 });

            Assert.Equal(TestFormat4Composite, formattableString.Format);
            Assert.Equal(2, formattableString.ArgumentCount);
            Assert.Equal(Replacement1, formattableString.GetArgument(0));
            Assert.Equal(Replacement2, formattableString.GetArgument(1));
            Assert.Equal(TestFormat4Solution, formattableString.ToString());
        }