Ejemplo n.º 1
0
        public override string ToString()
        {
            var buffer = new StringBuilder();

            foreach (DirectiveInput directive in Directives)
            {
                buffer.AppendIfNotEmpty(' ')
                .Append(directive);
            }

            if (!string.IsNullOrWhiteSpace(CommandName))
            {
                buffer.AppendIfNotEmpty(' ')
                .Append(CommandName);
            }

            foreach (CommandParameterInput parameter in Parameters)
            {
                buffer.AppendIfNotEmpty(' ')
                .Append(parameter);
            }

            foreach (CommandOptionInput option in Options)
            {
                buffer.AppendIfNotEmpty(' ')
                .Append(option);
            }

            return(buffer.ToString());
        }
Ejemplo n.º 2
0
        public override string ToString()
        {
            var buffer = new StringBuilder();

            foreach (var directive in Directives)
            {
                buffer.AppendIfNotEmpty(' ');
                buffer
                .Append('[')
                .Append(directive)
                .Append(']');
            }

            foreach (var argument in Arguments)
            {
                buffer.AppendIfNotEmpty(' ');
                buffer.Append(argument);
            }

            foreach (var option in Options)
            {
                buffer.AppendIfNotEmpty(' ');
                buffer.Append(option);
            }

            return(buffer.ToString());
        }
Ejemplo n.º 3
0
        public static String GetUserAgent(string applicationName, string system, string version, string projectUrl)
        {
            StringBuilder stringBuilder = new StringBuilder();

            if (!String.IsNullOrWhiteSpace(applicationName))
            {
                stringBuilder.Append(applicationName);
            }

            if (!String.IsNullOrWhiteSpace(system))
            {
                stringBuilder.AppendIfNotEmpty(" - ");
                stringBuilder.Append(system);
            }

            if (!String.IsNullOrWhiteSpace(version))
            {
                stringBuilder.AppendIfNotEmpty(" - ");
                stringBuilder.Append($"Version {version}");
            }

            if (!String.IsNullOrWhiteSpace(projectUrl))
            {
                stringBuilder.AppendIfNotEmpty(" - ");
                stringBuilder.Append(projectUrl);
            }

            return(stringBuilder.ToString());
        }
        // internal to allow unit testing
        internal StringBuilder CreateWhereClause(EntityParameterCollection parameters)
        {
            Debug.Assert(parameters != null, "parameters != null");

            var whereClause  = new StringBuilder();
            var parameterMap = new Dictionary <string, string>(StringComparer.Ordinal);

            foreach (var alias in _filterAliases)
            {
                var allows   = new StringBuilder();
                var excludes = new StringBuilder();
                foreach (var entry in _filters)
                {
                    if (entry.Effect == EntityStoreSchemaFilterEffect.Allow)
                    {
                        AppendFilterEntry(allows, alias, entry, parameterMap);
                    }
                    else
                    {
                        Debug.Assert(entry.Effect == EntityStoreSchemaFilterEffect.Exclude, "did you add new value?");
                        AppendFilterEntry(excludes, alias, entry, parameterMap);
                    }
                }

                if (allows.Length != 0)
                {
                    // AND appended if this is not the first condition
                    whereClause
                    .AppendIfNotEmpty(Environment.NewLine)
                    .AppendIfNotEmpty("AND")
                    .AppendIfNotEmpty(Environment.NewLine);

                    whereClause
                    .Append("(")
                    .Append(allows)
                    .Append(")");
                }

                if (excludes.Length != 0)
                {
                    // AND appended if this is not the first condition
                    whereClause
                    .AppendIfNotEmpty(Environment.NewLine)
                    .AppendIfNotEmpty("AND")
                    .AppendIfNotEmpty(Environment.NewLine);

                    whereClause
                    .Append("NOT (")
                    .Append(excludes)
                    .Append(")");
                }
            }

            foreach (var entry in parameterMap)
            {
                parameters.AddWithValue(entry.Value, entry.Key);
            }

            return(whereClause);
        }
Ejemplo n.º 5
0
        /// <inheritdoc />
        public override string ToString()
        {
            var buffer = new StringBuilder();

            buffer.Append(Alias.Length > 1 ? "--" : "-");
            buffer.Append(Alias);

            foreach (var value in Values)
            {
                buffer.AppendIfNotEmpty(' ');

                var isEscaped = value.Contains(" ");

                if (isEscaped)
                {
                    buffer.Append('"');
                }

                buffer.Append(value);

                if (isEscaped)
                {
                    buffer.Append('"');
                }
            }

            return(buffer.ToString());
        }
Ejemplo n.º 6
0
        public static string ToText(this MonsterAttackType attack, string delimiter)
        {
            var sb = new StringBuilder();
            if (attack.IsEmpty) {
                return String.Empty;
            }
            else if (attack.Damage.IsEmpty) {
                sb.Append(attack.Description);
            }
            else {
                sb.AppendIfNotEmpty(attack.ToString());
            }

            for (int i = 0; i < attack.FailedSavingThrows.Count; ++i) {
                var failed = attack.FailedSavingThrows[i];
                sb.AppendFormat("{0}    {1} Failed Saving Throw: {2}", delimiter, (i + 1).ToIteration(), failed); // failed.ToHtml(power));
            }
            foreach (var sustain in attack.Sustains) {
                sb.AppendFormat("{0}    Sustain", delimiter);
                sb.AppendFormatIfNotEmpty(" {0}", sustain.Action);
                sb.AppendFormat(": {0}", sustain.Description); //sustain.ToHtml(power));
            }

            foreach (var attackInner in attack.Attacks) {
                sb.AppendFormat("{0}    {1}: {2}", delimiter, attackInner.Name, attackInner.Effect);
            }

            if (!attack.Damage.IsEmpty) {
                foreach (var after in attack.AfterEffects) {
                    sb.AppendFormat("{0}    Aftereffect: {1}", delimiter, after); //after.ToHtml(power));
                }
            }

            return sb.ToString();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// For each entry makes sure the text on each line is not longer than specified.
        /// Any entry text that already contains a carriage return will not be altered.
        /// </summary>
        /// <param name="maxLineLength">Max line length in number of characters.</param>
        /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="maxLineLength" /> must be greater than zero.</exception>
        public void SetTextLineMaxLength(int maxLineLength)
        {
            if (maxLineLength < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(maxLineLength), "Max line length must be greater than zero.");
            }

            foreach (var entry in Entries)
            {
                if (entry.Text.Length <= maxLineLength)
                {
                    continue;
                }

                if (entry.Text.ContainsReturnChar())
                {
                    continue;
                }

                var endText = entry.Text.Right(maxLineLength);

                var sb = new StringBuilder();

                int start      = 0;
                int charsAdded = 0;

                while (charsAdded < entry.Text.Length)
                {
                    var line = entry.Text.SafeSubstring(start, maxLineLength);

                    if (line.Length == maxLineLength &&
                        line != endText &&
                        !line.EndsWithSentenceEndChar())
                    {
                        int i = line.Length - 1;

                        // Walk back to first space
                        while (line[i] != ' ')
                        {
                            line = entry.Text.SafeSubstring(start, i);
                            i--;
                        }

                        start = start + i + 1;
                    }
                    else
                    {
                        start += line.Length;
                    }

                    sb.AppendIfNotEmpty(NewLine);

                    charsAdded += line.Length;
                    sb.Append(line.TrimEnd());
                }

                entry.Text = sb.ToString();
            }
        }
Ejemplo n.º 8
0
            public void WhenValueIsNull_ThenDoNothing()
            {
                var sut = new StringBuilder("something");

                sut.AppendIfNotEmpty(null);

                Assert.That(sut.ToString(), Is.EqualTo("something"));
            }
Ejemplo n.º 9
0
            public void WhenEmpty_ThenDoNothing()
            {
                var sut = new StringBuilder();

                sut.AppendIfNotEmpty("value");

                Assert.That(sut.ToString(), Is.Empty);
            }
Ejemplo n.º 10
0
            public void WhenNotEmpty_ThenAppend()
            {
                var sut = new StringBuilder("something");

                sut.AppendIfNotEmpty("value");

                Assert.That(sut.ToString(), Is.EqualTo("somethingvalue"));
            }
Ejemplo n.º 11
0
        /// <summary>
        /// Delimits the specified collection.
        /// </summary>
        /// <param name="col">The collection.</param>
        /// <param name="delimiter">The delimiter.</param>
        /// <returns>A delimited string representation of the collection.</returns>
        public static string Delimit(this IEnumerable <string> col, string delimiter = ", ")
        {
            var builder = new StringBuilder();

            foreach (var item in col.ThrowIfNull(nameof(col)))
            {
                builder.AppendIfNotEmpty(delimiter);
                builder.Append(item);
            }

            return(builder.ToString());
        }
        /// <summary>
        /// Returns the serialized form of this object.
        /// </summary>
        /// <param name="includeClientArtifacts">If true, the client supplied artifacts of id, timestamp, and nonce are included.</param>
        /// <returns></returns>
        private string ToHeaderParameter(bool includeClientArtifacts)
        {
            char          trailer = ',';
            StringBuilder result  = new StringBuilder();

            if (includeClientArtifacts)
            {
                result
                .AppendIfNotEmpty(ID, this.Id, trailer)
                .AppendIfNotEmpty(TS, (this.Timestamp > 0 ? this.Timestamp.ToString() : String.Empty), trailer)
                .AppendIfNotEmpty(NONCE, this.Nonce, trailer);
            }

            result
            .AppendIfNotEmpty(EXT, this.ApplicationSpecificData, trailer)
            .AppendIfNotEmpty(MAC, this.Mac == null ? null : this.Mac.ToBase64String(), trailer)
            .AppendIfNotEmpty(HASH, this.PayloadHash == null ? null : this.PayloadHash.ToBase64String(), trailer);

            return(result.ToString()
                   .Trim().Trim(trailer)); // Remove the trailing trailer and space for the last pair
        }
Ejemplo n.º 13
0
        private async ValueTask WriteAttachmentsAsync(IReadOnlyList <Attachment> attachments)
        {
            var buffer = new StringBuilder();

            foreach (var attachment in attachments)
            {
                buffer
                .AppendIfNotEmpty(',')
                .Append(await Context.ResolveMediaUrlAsync(attachment.Url));
            }

            await _writer.WriteAsync(CsvEncode(buffer.ToString()));
        }
Ejemplo n.º 14
0
        public override string ToString()
        {
            var buffer = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(Name))
            {
                buffer.Append(Name);
            }

            foreach (var parameter in Parameters)
            {
                buffer.AppendIfNotEmpty(' ');
                buffer.Append(parameter);
            }

            foreach (var option in Options)
            {
                buffer.AppendIfNotEmpty(' ');
                buffer.Append(option);
            }

            return(buffer.ToString());
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Delimits the specified collection.
        /// </summary>
        /// <typeparam name="T">The type of the value item in the KeyValuePair</typeparam>
        /// <param name="col">The collection.</param>
        /// <param name="delimiter">The delimiter.</param>
        /// <param name="keyValueSeparator">The key value separator.</param>
        /// <returns>
        /// A delimited string representation of the collection.
        /// </returns>
        public static string Delimit <T>(this IEnumerable <KeyValuePair <string, T> > col, string delimiter = ", ", string keyValueSeparator = ": ")
        {
            var builder = new StringBuilder();

            foreach (var item in col.ThrowIfNull(nameof(col)))
            {
                builder.AppendIfNotEmpty(delimiter);
                builder.Append(item.Key);
                builder.Append(keyValueSeparator);
                builder.Append(item.Value);
            }

            return(builder.ToString());
        }
Ejemplo n.º 16
0
        /// <inheritdoc />
        public override string ToString()
        {
            var buffer = new StringBuilder();

            if (!CommandName.IsNullOrWhiteSpace())
            {
                buffer.Append(CommandName);
            }

            foreach (var directive in Directives)
            {
                buffer.AppendIfNotEmpty(' ');
                buffer.Append(directive);
            }

            foreach (var option in Options)
            {
                buffer.AppendIfNotEmpty(' ');
                buffer.Append(option);
            }

            return(buffer.ToString());
        }
        private static void AppendComparisonFragment(
            StringBuilder filterFragment, string alias, string propertyName, string parameterName)
        {
            Debug.Assert(filterFragment != null, "filterFragment != null");
            Debug.Assert(alias != null, "alias != null");
            Debug.Assert(propertyName != null, "propertyName != null");

            filterFragment
            .AppendIfNotEmpty(" AND ")
            .Append(alias)
            .Append(".")
            .Append(propertyName)
            .Append(" LIKE @")
            .Append(parameterName);
        }
        /// <summary>
        /// Returns the header parameter to be put into the HTTP WWW-Authenticate header. The field ts has the timestamp
        /// in UNIX time corresponding to the server clock and the field tsm is the MAC calculated for the normalized
        /// timestamp data using the shared symmetric key and the algorithm agreed upon.
        /// </summary>
        /// <returns></returns>
        internal string ToWwwAuthenticateHeaderParameter()
        {
            Hasher hasher = new Hasher(credential.Algorithm);

            byte[] data = this.ToString().ToBytesFromUtf8();

            string tsm = hasher.ComputeHmac(data, credential.Key).ToBase64String();

            char trailer = ',';

            StringBuilder result = new StringBuilder();
            result.AppendIfNotEmpty(TS, fresh.ToString(), trailer)
                .AppendIfNotEmpty(TSM, tsm, trailer);

            return result.ToString().Trim().Trim(trailer);
        }
        /// <summary>
        /// Returns the header parameter to be put into the HTTP WWW-Authenticate header. The field ts has the timestamp
        /// in UNIX time corresponding to the server clock and the field tsm is the MAC calculated for the normalized
        /// timestamp data using the shared symmetric key and the algorithm agreed upon.
        /// </summary>
        /// <returns></returns>
        internal string ToWwwAuthenticateHeaderParameter()
        {
            Hasher hasher = new Hasher(credential.Algorithm);

            byte[] data = this.ToString().ToBytesFromUtf8();

            string tsm = hasher.ComputeHmac(data, credential.Key).ToBase64String();

            char trailer = ',';

            StringBuilder result = new StringBuilder();
            result.AppendIfNotEmpty(TS, fresh.ToString(), trailer)
                .AppendIfNotEmpty(TSM, tsm, trailer);

            return result.ToString().Trim().Trim(trailer);
        }
Ejemplo n.º 20
0
        public static string ListToDelimitedString(List <string> fields, string delimiter)
        {
            StringBuilder csv = new StringBuilder();

            foreach (string field in fields)
            {
                string text = field;
                if (text != null)
                {
                    text = text.Replace("\"", "\"\"");
                }

                csv.AppendIfNotEmpty(delimiter).Append("\"").Append(text).Append("\"");
            }

            return(csv.ToString());
        }
Ejemplo n.º 21
0
    private async ValueTask WriteAttachmentsAsync(
        IReadOnlyList <Attachment> attachments,
        CancellationToken cancellationToken = default)
    {
        var buffer = new StringBuilder();

        foreach (var attachment in attachments)
        {
            cancellationToken.ThrowIfCancellationRequested();

            buffer
            .AppendIfNotEmpty(',')
            .Append(await Context.ResolveMediaUrlAsync(attachment.Url, cancellationToken));
        }

        await _writer.WriteAsync(CsvEncode(buffer.ToString()));
    }
Ejemplo n.º 22
0
        /// <summary>
        /// Converts a hashtable of strings to a delimited list.
        /// </summary>
        /// <param name="col">The strings to delimit.</param>
        /// <param name="delimiter">The delimiter to split the strings by.</param>
        /// <param name="excludeKeys">A flag to indicate if keys should be excluded.</param>
        /// <param name="keyValueSeparator">The key value separator.</param>
        /// <returns>
        /// The delimited string.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">The Hashtable passed in is null.</exception>
        public static string Delimit(this IDictionary col, string delimiter = ", ", bool excludeKeys = false, string keyValueSeparator = ": ")
        {
            var builder = new StringBuilder();

            foreach (DictionaryEntry item in col.ThrowIfNull(nameof(col)))
            {
                builder.AppendIfNotEmpty(delimiter);
                if (!excludeKeys)
                {
                    builder.Append(item.Key);
                    builder.Append(keyValueSeparator);
                }
                builder.Append(item.Value);
            }

            return(builder.ToString());
        }
Ejemplo n.º 23
0
        private async ValueTask WriteReactionsAsync(IReadOnlyList <Reaction> reactions)
        {
            var buffer = new StringBuilder();

            foreach (var reaction in reactions)
            {
                buffer
                .AppendIfNotEmpty(',')
                .Append(reaction.Emoji.Name)
                .Append(' ')
                .Append('(')
                .Append(reaction.Count)
                .Append(')');
            }

            await _writer.WriteAsync(CsvEncode(buffer.ToString()));
        }
Ejemplo n.º 24
0
    private async ValueTask WriteReactionsAsync(
        IReadOnlyList <Reaction> reactions,
        CancellationToken cancellationToken = default)
    {
        var buffer = new StringBuilder();

        foreach (var reaction in reactions)
        {
            cancellationToken.ThrowIfCancellationRequested();

            buffer
            .AppendIfNotEmpty(',')
            .Append(reaction.Emoji.Name)
            .Append(' ')
            .Append('(')
            .Append(reaction.Count)
            .Append(')');
        }

        await _writer.WriteAsync(CsvEncode(buffer.ToString()));
    }
Ejemplo n.º 25
0
        /// <summary>
        /// ######### ######### ########## ######## # ########.
        /// </summary>
        /// <param name="sysLicPackageGuid">############# ######## ##############.</param>
        /// <returns>######## ########, #### ########## ############ ########
        /// ######## ######### ######### ##########, ### ###### ######, # ######### ######.</returns>
        private string HasLicErrors(Guid sysLicPackageGuid)
        {
            var sb = new StringBuilder();

            foreach (Entity item in AvailablePackages)
            {
                Guid sysLicPackageId = item.GetTypedColumnValue <Guid>("SysLicPackageId");
                if (sysLicPackageId == sysLicPackageGuid)
                {
                    string     operations = item.GetTypedColumnValue <string>("Operations");
                    SysLicType licType    = item.GetTypedColumnValue <SysLicType>("LicType");
                    if (!operations.Contains("IsServerLicPackage") && licType == SysLicType.Personal &&
                        item.GetTypedColumnValue <int>("PersonalLicCount") >=
                        item.GetTypedColumnValue <int>("Count"))
                    {
                        sb.AppendIfNotEmpty(", ");
                        sb.Append(item.GetTypedColumnValue <string>("SysPackageName"));
                    }
                }
            }
            return(sb.ToString());
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Builds a string that contains a parsing error message.
        /// </summary>
        /// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
        /// <param name="formatError">The error formatting delegate.</param>
        /// <param name="formatMutuallyExclusiveSetErrors">The specialized <see cref="CommandLine.MutuallyExclusiveSetError"/> sequence formatting delegate.</param>
        /// <param name="indent">Number of spaces used to indent text.</param>
        /// <returns>The <see cref="System.String"/> that contains the parsing error message.</returns>
        public static string RenderParsingErrorsText <T>(
            ParserResult <T> parserResult,
            Func <Error, string> formatError,
            Func <IEnumerable <MutuallyExclusiveSetError>, string> formatMutuallyExclusiveSetErrors,
            int indent)
        {
            if (parserResult == null)
            {
                throw new ArgumentNullException("parserResult");
            }

            var meaningfulErrors =
                FilterMeaningfulErrors(((NotParsed <T>)parserResult).Errors);

            if (meaningfulErrors.Empty())
            {
                return(string.Empty);
            }

            var text = new StringBuilder();

            meaningfulErrors
            .Where(e => e.Tag != ErrorType.MutuallyExclusiveSetError)
            .ForEach(
                error =>
            {
                var line = new StringBuilder(indent.Spaces())
                           .Append(formatError(error));
                text.AppendLine(line.ToString());
            });

            return(text.AppendIfNotEmpty(
                       formatMutuallyExclusiveSetErrors(
                           meaningfulErrors.OfType <MutuallyExclusiveSetError>()))
                   .ToString());
        }
        // internal to allow unit testing
        internal static StringBuilder AppendFilterEntry(
            StringBuilder segment, string alias, EntityStoreSchemaFilterEntry entry, ParameterCollectionBuilder parameters)
        {
            Debug.Assert(segment != null, "segment != null");
            Debug.Assert(alias != null, "alias != null");
            Debug.Assert(entry != null, "entry != null");
            Debug.Assert(parameters != null, "parameters != null");

            var filterText = new StringBuilder();

            AppendComparison(filterText, alias, "CatalogName", entry.Catalog, parameters);
            AppendComparison(filterText, alias, "SchemaName", entry.Schema, parameters);
            AppendComparison(
                filterText, alias, "Name",
                entry.Catalog == null && entry.Schema == null && entry.Name == null ? "%" : entry.Name,
                parameters);
            segment
            .AppendIfNotEmpty(" OR ")
            .Append("(")
            .Append(filterText)
            .Append(")");

            return(segment);
        }
Ejemplo n.º 28
0
 private static void JoinCore(StringBuilder builder, IEnumerable<string> collection, string separator)
 {
     using (var enumerator = collection.GetEnumerator())
         if (enumerator.MoveNext())
         {
             builder.AppendIfNotEmpty(enumerator.Current);
             while (enumerator.MoveNext())
                 builder
                     .Append(separator)
                     .AppendIfNotEmpty(enumerator.Current);
         }
 }
        /// <summary>
        /// Returns the serialized form of this object.
        /// </summary>
        /// <param name="includeClientArtifacts">If true, the client supplied artifacts of id, timestamp, and nonce are included.</param>
        /// <returns></returns>
        private string ToHeaderParameter(bool includeClientArtifacts)
        {
            char trailer = ',';
            StringBuilder result = new StringBuilder();

            if (includeClientArtifacts)
            {
                result
                    .AppendIfNotEmpty(ID, this.Id, trailer)
                    .AppendIfNotEmpty(TS, (this.Timestamp > 0 ? this.Timestamp.ToString() : String.Empty), trailer)
                    .AppendIfNotEmpty(NONCE, this.Nonce, trailer);
            }

            result
                .AppendIfNotEmpty(EXT, this.ApplicationSpecificData, trailer)
                .AppendIfNotEmpty(MAC, this.Mac == null ? null : this.Mac.ToBase64String(), trailer)
                .AppendIfNotEmpty(HASH, this.PayloadHash == null ? null : this.PayloadHash.ToBase64String(), trailer);

            return result.ToString()
                .Trim().Trim(trailer); // Remove the trailing trailer and space for the last pair
        }
        // internal to allow unit testing
        internal static StringBuilder AppendFilterEntry(
            StringBuilder segment, string alias, EntityStoreSchemaFilterEntry entry, EntityParameterCollection parameters)
        {
            Debug.Assert(segment != null, "segment != null");
            Debug.Assert(alias != null, "alias != null");
            Debug.Assert(entry != null, "entry != null");
            Debug.Assert(parameters != null, "parameters != null");

            var filterText = new StringBuilder();
            AppendComparison(filterText, alias, "CatalogName", entry.Catalog, parameters);
            AppendComparison(filterText, alias, "SchemaName", entry.Schema, parameters);
            AppendComparison(
                filterText, alias, "Name",
                entry.Catalog == null && entry.Schema == null && entry.Name == null ? "%" : entry.Name,
                parameters);
            segment
                .AppendIfNotEmpty(" OR ")
                .Append("(")
                .Append(filterText)
                .Append(")");

            return segment;
        }
 /// <summary>
 /// Ajoute un espace au <paramref name="stringBuilder"/> si <paramref name="stringBuilder"/> non vide
 /// </summary>
 /// <param name="stringBuilder">StringBuilder</param>
 /// <returns>StringBuilder</returns>
 public static StringBuilder AppendSpaceIfNotEmpty(this StringBuilder stringBuilder)
 {
     stringBuilder.AppendIfNotEmpty(" ");
     return(stringBuilder);
 }
Ejemplo n.º 32
0
 private static void JoinCore(StringBuilder builder, IEnumerable<string> collection)
 {
     foreach (string item in collection)
         builder.AppendIfNotEmpty(item);
 }
        private static void AppendComparisonFragment(
            StringBuilder filterFragment, string alias, string propertyName, string parameterName)
        {
            Debug.Assert(filterFragment != null, "filterFragment != null");
            Debug.Assert(alias != null, "alias != null");
            Debug.Assert(propertyName != null, "propertyName != null");

            filterFragment
                .AppendIfNotEmpty(" AND ")
                .Append(alias)
                .Append(".")
                .Append(propertyName)
                .Append(" LIKE @")
                .Append(parameterName);
        }
Ejemplo n.º 34
0
 public static void AppendTagStart(this StringBuilder sb, string tag)
 {
     sb.AppendIfNotEmpty(tag, " <{0}");
 }
Ejemplo n.º 35
0
        /// <summary>Concatenates the specified separator between each element of the specified collection of strings,
        /// with an optional prefix and suffix, yielding a single concatenated string.</summary>
        /// <param name="collection">The collection of elements to join.</param>
        /// <param name="prefix">The optional prefix to concatenate before the first element.</param>
        /// <param name="separator">The separator to concatenate between each element.</param>
        /// <param name="suffix">The optional suffix to concatenate after the last element.</param>
        /// <returns>The single concatenated string.</returns>
        public static string Join(
            this IEnumerable<string> collection,
            string prefix,
            string separator,
            string suffix)
        {
            if (collection == null) throw new ArgumentNullException("collection");

            StringBuilder builder = new StringBuilder();

            builder.AppendIfNotEmpty(prefix);

            if (separator.IsNullOrEmpty())
                JoinCore(builder, collection);
            else JoinCore(builder, collection, separator);

            return builder.AppendIfNotEmpty(suffix).ToString();
        }
Ejemplo n.º 36
0
 public static void AppendTagEnd(this StringBuilder sb, string tag)
 {
     sb.AppendIfNotEmpty(tag, " </{0}>");
 }
        // internal to allow unit testing
        internal StringBuilder CreateWhereClause(EntityParameterCollection parameters)
        {
            Debug.Assert(parameters != null, "parameters != null");

            var whereClause = new StringBuilder();
            foreach (var alias in _filterAliases)
            {
                var allows = new StringBuilder();
                var excludes = new StringBuilder();
                foreach (var entry in _filters)
                {
                    if (entry.Effect == EntityStoreSchemaFilterEffect.Allow)
                    {
                        AppendFilterEntry(allows, alias, entry, parameters);
                    }
                    else
                    {
                        Debug.Assert(entry.Effect == EntityStoreSchemaFilterEffect.Exclude, "did you add new value?");
                        AppendFilterEntry(excludes, alias, entry, parameters);
                    }
                }

                if (allows.Length != 0)
                {
                    // AND appended if this is not the first condition
                    whereClause
                        .AppendIfNotEmpty(Environment.NewLine)
                        .AppendIfNotEmpty("AND")
                        .AppendIfNotEmpty(Environment.NewLine);

                    whereClause
                        .Append("(")
                        .Append(allows)
                        .Append(")");
                }

                if (excludes.Length != 0)
                {
                    // AND appended if this is not the first condition
                    whereClause
                        .AppendIfNotEmpty(Environment.NewLine)
                        .AppendIfNotEmpty("AND")
                        .AppendIfNotEmpty(Environment.NewLine);

                    whereClause
                        .Append("NOT (")
                        .Append(excludes)
                        .Append(")");
                }
            }
            return whereClause;
        }
Ejemplo n.º 38
0
        /// <inheritdoc />
        public CommandInput ParseCommandInput(IReadOnlyList <string> commandLineArguments)
        {
            commandLineArguments.GuardNotNull(nameof(commandLineArguments));

            var commandNameBuilder = new StringBuilder();
            var directives         = new List <string>();
            var optionsDic         = new Dictionary <string, List <string> >();

            // Option aliases and values are parsed in pairs so we need to keep track of last alias
            var lastOptionAlias = "";

            foreach (var commandLineArgument in commandLineArguments)
            {
                // Encountered option name
                if (commandLineArgument.StartsWith("--", StringComparison.OrdinalIgnoreCase))
                {
                    // Extract option alias
                    lastOptionAlias = commandLineArgument.Substring(2);

                    if (!optionsDic.ContainsKey(lastOptionAlias))
                    {
                        optionsDic[lastOptionAlias] = new List <string>();
                    }
                }

                // Encountered short option name or multiple short option names
                else if (commandLineArgument.StartsWith("-", StringComparison.OrdinalIgnoreCase))
                {
                    // Handle stacked options
                    foreach (var c in commandLineArgument.Substring(1))
                    {
                        // Extract option alias
                        lastOptionAlias = c.AsString();

                        if (!optionsDic.ContainsKey(lastOptionAlias))
                        {
                            optionsDic[lastOptionAlias] = new List <string>();
                        }
                    }
                }

                // Encountered directive or (part of) command name
                else if (lastOptionAlias.IsNullOrWhiteSpace())
                {
                    if (commandLineArgument.StartsWith("[", StringComparison.OrdinalIgnoreCase) &&
                        commandLineArgument.EndsWith("]", StringComparison.OrdinalIgnoreCase))
                    {
                        // Extract directive
                        var directive = commandLineArgument.Substring(1, commandLineArgument.Length - 2);

                        directives.Add(directive);
                    }
                    else
                    {
                        commandNameBuilder.AppendIfNotEmpty(' ');
                        commandNameBuilder.Append(commandLineArgument);
                    }
                }

                // Encountered option value
                else if (!lastOptionAlias.IsNullOrWhiteSpace())
                {
                    optionsDic[lastOptionAlias].Add(commandLineArgument);
                }
            }

            var commandName = commandNameBuilder.Length > 0 ? commandNameBuilder.ToString() : null;
            var options     = optionsDic.Select(p => new CommandOptionInput(p.Key, p.Value)).ToArray();

            return(new CommandInput(commandName, directives, options));
        }
Ejemplo n.º 39
0
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.AppendLine( "     Type: " + Type );
            sb.AppendLine( "SaveIndex: " + SaveIndex );
            sb.AppendLine( "     Name: " + Name );
            sb.AppendLine( "   Gender: " + Gender );
            sb.AppendLine( "Public ID: " + PublicId );
            sb.AppendLine( "Secret ID: " + SecretId );
            sb.AppendLine( "      Key: " + SecurityKey );
            sb.AppendLine( "     Time: " + TimePlayed );
            sb.AppendLine( " Gamecode: " + GameCode );
            sb.AppendLine( "    Money: " + Money );
            sb.AppendLine( "    Rival: " + Rival );

            sb.AppendLine( "Teamsize:\t" + TeamSize );
            for( int i = 0; i < Team.Count; i++ )
                sb.AppendIfNotEmpty( Team[i].Brief(), i );

            sb.AppendLine( "PC Items:" );
            for( int i = 0; i < PCItems.Count; i++ )
                sb.AppendIfNotEmpty( PCItems[i].ToString(), i );

            sb.AppendLine( "Bag Items:" );
            for( int i = 0; i < Items.Count; i++ )
                sb.AppendIfNotEmpty( Items[i].ToString(), i );

            sb.AppendLine( "Key Items:" );
            for( int i = 0; i < KeyItems.Count; i++ )
                sb.AppendIfNotEmpty( KeyItems[i].ToString(), i );

            sb.AppendLine( "Ball pocket:" );
            for( int i = 0; i < BallPocket.Count; i++ )
                sb.AppendIfNotEmpty( BallPocket[i].ToString(), i );

            sb.AppendLine( "TM case:" );
            for( int i = 0; i < TMCase.Count; i++ )
                sb.AppendIfNotEmpty( TMCase[i].ToString(), i );

            sb.AppendLine( "Berries:" );
            for( int i = 0; i < Berries.Count; i++ )
                sb.AppendIfNotEmpty( Berries[i].ToString(), i );

            sb.AppendLine( "PC buffer:" );
            string pre = string.Empty;
            for( int i = 0; i < PcBuffer.Count; i++ )
            {
                if( i % 30 == 0 )
                    pre = "PC Box #" + Math.Floor( i / 30.0 );
                if( sb.AppendIfNotEmpty( PcBuffer[i].Brief(), i, pre ) )
                    pre = string.Empty;
            }
            return sb.ToString();
        }