/// <summary>
 /// Get the <see cref="IString"/> of a <see cref="ILineString"/>.
 ///
 /// If parameter "String" exists and <paramref name="resolver"/> is provided then value is resolved using
 /// the default string format or the format that can be found.
 /// </summary>
 /// <param name="line"></param>
 /// <param name="resolver">(optional) type resolver that resolves "IStringFormat" parameter into type. Returns null, if could not resolve, exception if resolve fails</param>
 /// <param name="fallbackStringFormat">(optional) fallback string format to use in case line didnt have one</param>
 /// <returns>value</returns>
 /// <exception cref="LineException">error parsing</exception>
 public static IString GetString(this ILine line, IResolver resolver = null, IStringFormat fallbackStringFormat = null)
 {
     for (ILine part = line; part != null; part = part.GetPreviousPart())
     {
         if (part is ILineString valuePart && valuePart.String != null)
         {
             return(valuePart.String);
         }
         if (resolver != null && part is ILineParameterEnumerable lineParameters)
         {
             foreach (ILineParameter parameter in lineParameters)
             {
                 if (parameter.ParameterName == "String" && parameter.ParameterValue != null)
                 {
                     IStringFormat stringFormat = line.FindStringFormat(resolver) ?? fallbackStringFormat;
                     return(stringFormat.Parse(parameter.ParameterValue));
                 }
             }
         }
         if (part is ILineParameter lineParameter && lineParameter.ParameterName == "String" && lineParameter.ParameterValue != null)
         {
             IStringFormat stringFormat = line.FindStringFormat(resolver) ?? fallbackStringFormat;
             return(stringFormat.Parse(lineParameter.ParameterValue));
         }
     }
     return(StatusString.Null);
 }
Exemple #2
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        public PlotSurface2D()
        {
            // only create this once.
            titleDrawFormat_           = Factory.Instance.CreateStringFormat();
            titleDrawFormat_.Alignment = StringAlignment.Center;

            Init();
        }
Exemple #3
0
 /// <summary>
 /// Print <paramref name="str"/> into string that represents the notation of this <see cref="IStringFormat"/>.
 ///
 /// If print fails, then states is set:
 /// <list type="bullet">
 ///     <item><see cref="LineStatus.StringFormatErrorPrintNoCapabilityPluralCategory"/></item>
 ///     <item><see cref="LineStatus.StringFormatErrorPrintNoCapabilityPlaceholder"/></item>
 ///     <item><see cref="LineStatus.StringFormatErrorPrintUnsupportedExpression"/></item>
 ///     <item><see cref="LineStatus.StringFormatFailedNoPrinter"/></item>
 /// </list>
 /// </summary>
 /// <param name="stringFormat"></param>
 /// <param name="str"></param>
 /// <returns>format string</returns>
 public static LineString Print(this IStringFormat stringFormat, IString str)
 {
     if (stringFormat is IStringFormatPrinter printer)
     {
         return(printer.Print(str));
     }
     return(new LineString(null, (Exception)null, LineStatus.StringFormatFailedNoPrinter));
 }
Exemple #4
0
        /// <summary>
        /// Sets <see cref="IStringFormat"/> metadata to schema.
        /// </summary>
        /// <typeparam name="TSchema">Schema type.</typeparam>
        /// <param name="schema">Source schema.</param>
        /// <param name="format">Format metadata.</param>
        /// <returns>The same schema.</returns>
        public static TSchema SetStringFormat <TSchema>(this TSchema schema, IStringFormat format)
            where TSchema : ISchema
        {
            schema.AssertArgumentNotNull(nameof(schema));
            format.AssertArgumentNotNull(nameof(format));

            return(schema.SetMetadata(format));
        }
Exemple #5
0
 /// <summary>
 /// Parse format string into an <see cref="IString"/>.
 ///
 /// If parse fails this method should return an instance where state is <see cref="LineStatus.StringFormatErrorMalformed"/>.
 /// If parse succeeds, the returned instance should have state <see cref="LineStatus.StringFormatOk"/> or some other format state.
 /// If <paramref name="str"/> is null then stat is <see cref="LineStatus.StringFormatFailedNull"/>.
 /// If <paramref name="stringFormat"/> is not <see cref="IStringFormatParser"/>, then stat is <see cref="LineStatus.StringFormatFailedNoParser"/>.
 /// </summary>
 /// <param name="stringFormat"></param>
 /// <param name="str"></param>
 /// <returns>format string</returns>
 /// <exception cref="ArgumentException">If <paramref name="stringFormat"/> doesn't implement <see cref="IStringFormatParser"/></exception>
 public static IString Parse(this IStringFormat stringFormat, string str)
 {
     if (str == null)
     {
         return(new StatusString(str, LineStatus.StringFormatFailedNull));
     }
     if (stringFormat is IStringFormatParser parser)
     {
         return(parser.Parse(str));
     }
     return(new StatusString(str, LineStatus.StringFormatFailedNoParser));
 }
Exemple #6
0
        private void factoryMethodPatternBtn_Click(object sender, RoutedEventArgs e)
        {
            FormatFactory ff = new FormatFactory();

            IStringFormat hash         = ff.GetFormat(FormatsType.FormatHash);
            IStringFormat forwardSlash = ff.GetFormat(FormatsType.FormatForwardSlash);
            IStringFormat dots         = ff.GetFormat(FormatsType.FormatDots);

            statusBarTB.Text =
                "Hash: " + hash.getFormat("Hello World") + ", " +
                "forward slash: " + forwardSlash.getFormat("New world of Programming Awaits You") + ", " +
                "dots: " + dots.getFormat("GoF Patterns in C#");
        }
Exemple #7
0
        /// <summary>
        /// link: https://en.wikipedia.org/wiki/Adapter_pattern
        /// TODO Add Adapter factory with formats.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void adapterTrial3PatternBtn_Click(object sender, RoutedEventArgs e)
        {
            string data = "";
            ClassA a    = new ClassA();
            ClassB b    = new ClassB();

            AdapterFormatsFactory aff = new AdapterFormatsFactory();

            IStringFormat hashFormat         = aff.GetFormat(AdapterFormatsType.ClassFormatHash, a);
            IStringFormat forwardSlashFormat = aff.GetFormat(AdapterFormatsType.ClassFormatForwardSlash, a);
            IStringFormat dotsFormat         = aff.GetFormat(AdapterFormatsType.ClassFormatDots, a);

            FormatHashAdapter hashAdapter  = new FormatHashAdapter();
            IStringProvider   hashProvider = (IStringProvider)(hashAdapter.adapt(a));

            data              = hashProvider.getStringData();
            statusBarTB.Text += "hashAdapter: " + data + ", ";

            FormatForwardSlashAdapter forwardSlashAdapter  = new FormatForwardSlashAdapter();
            IStringProvider           forwardSlashProvider = (IStringProvider)(forwardSlashAdapter.adapt(a));

            data              = forwardSlashProvider.getStringData();
            statusBarTB.Text += "forwardSlashProvider: " + data + ", ";

            FormatDotsAdapter forwardDotsAdapter = new FormatDotsAdapter();
            IStringProvider   dotsProvider       = (IStringProvider)(forwardDotsAdapter.adapt(a));

            data              = dotsProvider.getStringData();
            statusBarTB.Text += "dotsProvider: " + data + ", ";

            b.setStringData(data);

            statusBarTB.Text += "\n Class B: " + b.getStringData();

            // TODO Code with old classes but works
            //a = new ClassA();
            //b = new ClassB();

            //ClassAFormat1Adapter adapter = new ClassAFormat1Adapter();

            //IStringProvider strProvider = (IStringProvider)(adapter.adapt(a));
            //string field = strProvider.getStringData();
            //b.setStringData(field);

            //statusBarTB.Text = b.getStringData();
        }
Exemple #8
0
        /// <summary>
        /// Search linked list and finds the effective (left-most) <see cref="ILineStringFormat"/> key.
        ///
        /// Returns parameter "StringFormat" value as <see cref="IStringFormat"/>, if <paramref name="resolver"/> is provided.
        ///
        /// If implements <see cref="ILineStringFormat"/> returns the type.
        /// </summary>
        /// <param name="line"></param>
        /// <param name="resolver">(optional) type resolver that resolves "IStringFormat" parameter into type. Returns null, if could not resolve, exception if resolve fails</param>
        /// <returns>type info or null</returns>
        /// <exception cref="Exception">from <paramref name="resolver"/></exception>
        public static IStringFormat FindStringFormat(this ILine line, IResolver resolver = null)
        {
            IStringFormat type = null;

            for (ILine l = line; l != null; l = l.GetPreviousPart())
            {
                if (l is ILineStringFormat part && part.StringFormat != null)
                {
                    type = part.StringFormat; continue;
                }
                if (resolver != null && l is ILineParameterEnumerable lineParameters)
                {
                    IStringFormat tt = null;
                    foreach (ILineParameter parameter in lineParameters)
                    {
                        if (parameter.ParameterName == "StringFormat" && parameter.ParameterValue != null)
                        {
                            tt = resolver.Resolve <IStringFormat>(parameter.ParameterValue);
                            if (tt != null)
                            {
                                break;
                            }
                        }
                    }
                    if (tt != null)
                    {
                        type = tt; continue;
                    }
                }
                if (resolver != null && l is ILineParameter lineParameter && lineParameter.ParameterName == "StringFormat" && lineParameter.ParameterValue != null)
                {
                    IStringFormat t = resolver.Resolve <IStringFormat>(lineParameter.ParameterValue);
                    if (t != null)
                    {
                        type = t;
                    }
                }
            }
            return(type);
        }
 /// <summary>
 /// Try get string that implements <see cref="IString"/>.
 /// </summary>
 /// <param name="line"></param>
 /// <param name="result"></param>
 /// <param name="resolver">(optional) type resolver that resolves "StringFormat" parameter into type. Returns null, if could not resolve, exception if resolve fails</param>
 /// <returns>true if part was found</returns>
 public static bool TryGetString(this ILine line, out IString result, IResolver resolver = null)
 {
     try
     {
         for (ILine part = line; part != null; part = part.GetPreviousPart())
         {
             if (part is ILineString valuePart && valuePart.String != null)
             {
                 result = valuePart.String; return(true);
             }
             if (resolver != null && part is ILineParameterEnumerable lineParameters)
             {
                 foreach (ILineParameter parameter in lineParameters)
                 {
                     if (parameter.ParameterName == "String" && parameter.ParameterValue != null)
                     {
                         IStringFormat stringFormat = line.FindStringFormat(resolver);
                         result = stringFormat.Parse(parameter.ParameterValue);
                         return(true);
                     }
                 }
             }
             if (resolver != null && part is ILineParameter lineParameter && lineParameter.ParameterName == "String" && lineParameter.ParameterValue != null)
             {
                 IStringFormat stringFormat = line.FindStringFormat(resolver);
                 result = stringFormat.Parse(lineParameter.ParameterValue);
                 return(true);
             }
         }
         result = new StatusString(null, LineStatus.StringFormatFailedNull);
         return(false);
     } catch (Exception)
     {
         result = new StatusString(null, LineStatus.FailedUnknownReason);
         return(false);
     }
 }
        /// <summary>
        /// Scan features from a line
        /// </summary>
        /// <param name="line"></param>
        /// <exception cref="LineException">If resolve fails.</exception>
        public void ScanFeatures(ILine line)
        {
            bool valueSet = false;

            for (ILine l = line; l != null; l = l.GetPreviousPart())
            {
                if (l is ILineValue fa && fa != null)
                {
                    ValueArgs = fa.Value;
                }
                if (l is ILineCulturePolicy cp && cp != null)
                {
                    CulturePolicy = cp.CulturePolicy;
                }
                if (l is ILineCulture c && c.Culture != null)
                {
                    Culture = c.Culture;
                }
                if (l is ILineFormatProvider fp && fp.FormatProvider != null)
                {
                    FormatProviders.AddIfNew(fp.FormatProvider);
                }
                if (l is ILineFunctions funcs && funcs.Functions != null)
                {
                    Functions.AddIfNew(funcs.Functions);
                }
                if (l is ILineInlines inlines)
                {
                    Inlines.AddIfNew(inlines);
                }
                if (l is ILineLogger ll && ll.Logger is IStringResolverLogger logger)
                {
                    Loggers.AddIfNew(logger);
                }
                if (l is ILinePluralRules pl && pl.PluralRules != null)
                {
                    PluralRules = pl.PluralRules;
                }
                if (l is ILineStringFormat sf && sf.StringFormat != null)
                {
                    StringFormat = sf.StringFormat;
                }
                if (!valueSet && l is ILineString lv && lv.String != null)
                {
                    String = lv.String; StringText = null; valueSet = true;
                }
                if (l is ILineAsset la && la.Asset != null)
                {
                    Assets.AddIfNew(la.Asset);
                }

                if (l is ILineParameterEnumerable lineParameters)
                {
                    foreach (ILineParameter lineParameter in lineParameters)
                    {
                        string name = lineParameter.ParameterName, value = lineParameter.ParameterValue;

                        if (name == "Culture")
                        {
                            try { Culture = CultureInfo.GetCultureInfo(value); } catch (Exception) { }
                        }

                        else if (name == "FormatProvider" && !(l is ILineFormatProvider fp_ && fp_.FormatProvider != null /*to not add second time*/))
                        {
                            IFormatProvider _fp;
                            if (Resolvers.TryResolve <IFormatProvider>(value, out _fp))
                            {
                                FormatProviders.AddIfNew(_fp);
                            }
                            else
                            {
                                Status.UpStringFormat(LineStatus.ResolveErrorFormatProviderResolveFailed);
                            }
                        }

                        else if (name == "Functions" && !(l is ILineFunctions funcs_ && funcs_.Functions != null /*to not add second time*/))
                        {
                            IFunctions _funcs;
                            if (Resolvers.TryResolve <IFunctions>(value, out _funcs))
                            {
                                Functions.AddIfNew(_funcs);
                            }
                            else
                            {
                                Status.UpStringFormat(LineStatus.ResolveErrorFunctionsResolveFailed);
                            }
                        }
Exemple #11
0
 /// <summary>
 /// Append string format.
 /// </summary>
 /// <param name="lineFactory"></param>
 /// <param name="stringFormat"></param>
 /// <returns>new key</returns>
 /// <exception cref="LineException">If could not be appended</exception>
 public static ILineStringFormat StringFormat(this ILineFactory lineFactory, IStringFormat stringFormat)
 => lineFactory.Create <ILineStringFormat, IStringFormat>(null, stringFormat);
Exemple #12
0
 /// <summary>
 /// Append string format.
 /// </summary>
 /// <param name="line"></param>
 /// <param name="stringFormat"></param>
 /// <returns>new key</returns>
 /// <exception cref="LineException">If could not be appended</exception>
 public static ILineStringFormat StringFormat(this ILine line, IStringFormat stringFormat)
 => line.Append <ILineStringFormat, IStringFormat>(stringFormat);
 /// <summary>
 /// Create format string that parses formulation <paramref name="text"/> lazily.
 /// </summary>
 /// <param name="text"></param>
 /// <param name="stringFormat"></param>
 public TextString(string text, IStringFormat stringFormat = default)
 {
     Text = text ?? throw new ArgumentNullException(nameof(text));
     this.StringFormat = stringFormat ?? TextFormat.Default;
 }
        public static void Main(string[] args)
        {
            {
                #region Snippet_0a
                IStringFormat stringFormat = CSharpFormat.Default;
                IString       str          = stringFormat.Parse("Hello, {0}.");
                #endregion Snippet_0a
            }
            {
                #region Snippet_0b
                ILine line = LineRoot.Global.Key("").Format("Hello, {0}.");
                #endregion Snippet_0b
            }
            {
                #region Snippet_1a
                IStringFormat stringFormat = TextFormat.Default;
                IString       str          = stringFormat.Parse("{in braces}");
                #endregion Snippet_1a
            }
            {
                #region Snippet_1b
                ILine line = LineRoot.Global.Key("").Text("{in braces}");
                #endregion Snippet_1b
            }

            {
                #region Snippet_2a
                IStringFormat stringFormat = CSharpFormat.Default;
                IString       str          = stringFormat.Parse("Hello, {0}.");
                #endregion Snippet_2a
                #region Snippet_2b
                ILine line = LineRoot.Global.Key("Hello").String(str);
                #endregion Snippet_2b
                #region Snippet_2c
                LineString lineString = line.Value("Corellia Melody").ResolveString();
                #endregion Snippet_2c
                #region Snippet_2d
                if (!lineString.Failed)
                {
                    Console.WriteLine(lineString.Value);
                }
                #endregion Snippet_2d
            }
            {
                #region Snippet_3
                // Convert unescaped string "{not placeholder}" to IString
                IString ss = TextFormat.Default.Parse("{not placeholder}");
                // Escape with CSharpFormat to "\{not placeholder\}"
                string str = CSharpFormat.Default.Print(ss);
                // Convert escaped string back to IString
                IString cs = CSharpFormat.Default.Parse(str);
                // Unescape IString back to "{not placeholder}"
                string tt = TextFormat.Default.Print(cs);
                #endregion Snippet_3
                Console.WriteLine(tt);
            }
            {
                #region Snippet_4
                #endregion Snippet_4
            }
            {
                #region Snippet_5
                #endregion Snippet_5
            }
            {
                #region Snippet_6
                #endregion Snippet_6
            }
            {
                #region Snippet_7
                #endregion Snippet_7
            }
            {
                #region Snippet_8
                #endregion Snippet_8
            }
        }
Exemple #15
0
 /// <summary>
 /// Add format to map.
 /// </summary>
 /// <param name="formats"></param>
 /// <param name="format"></param>
 /// <returns><paramref name="formats"/></returns>
 public static IDictionary <string, IStringFormat> Add(this IDictionary <string, IStringFormat> formats, IStringFormat format)
 {
     formats[format.Name] = format;
     return(formats);
 }
Exemple #16
0
 /// <summary>
 /// Create reader
 /// </summary>
 /// <param name="ext"></param>
 /// <param name="valueParser"></param>
 public ResourcesLineReader(string ext, IStringFormat valueParser)
 {
     this.Extension   = ext;
     this.ValueParser = valueParser as IStringFormatParser ?? throw new ArgumentNullException(nameof(valueParser));
 }
 /// <summary>
 /// Create format string that parses formulation <paramref name="text"/> lazily.
 /// </summary>
 /// <param name="text"></param>
 /// <param name="stringFormat"></param>
 public CSharpString(string text, IStringFormat stringFormat)
 {
     Text              = text;
     status            = text == null ? LineStatus.StringFormatFailedNull : LineStatus.StringFormatFailedNoResult;
     this.StringFormat = stringFormat;
 }
Exemple #18
0
 public static SD.StringFormat Unwrap(this IStringFormat obj) => ((StringFormat)obj)?.Inner;
 /// <summary>
 /// Initializes a new instance of <see cref="NullApplicationStructure"/>
 /// </summary>
 public NullApplicationStructure()
 {
     AllStructureFormats = new IStringFormat[0];
 }
Exemple #20
0
 /// <summary>
 /// Construct root, for subclasses.
 /// </summary>
 /// <param name="appender"></param>
 /// <param name="prevKey"></param>
 /// <param name="asset"></param>
 /// <param name="culturePolicy"></param>
 /// <param name="stringResolver"></param>
 /// <param name="resourceResolver"></param>
 /// <param name="stringFormat"></param>
 /// <param name="formatProvider"></param>
 /// <param name="logger"></param>
 /// <param name="functions"></param>
 public LinkedTo(ILineFactory appender, ILine prevKey, IAsset asset = null, ICulturePolicy culturePolicy = null, IStringResolver stringResolver = null, IResourceResolver resourceResolver = null, IStringFormat stringFormat = null, IFormatProvider formatProvider = null, ILogger logger = null, IFunctions functions = null) :
     base(appender, prevKey, asset, culturePolicy, stringResolver, resourceResolver, stringFormat, formatProvider, logger, functions)
 {
 }