/// <summary>
        /// Add conjunctions, such as commas "," and "ands" to 
        /// concatenate the given phrases into a sentence.
        /// </summary>
        /// <param name="effectSpans">
        /// The lists of lists of <see cref="EffectSpan"/> to
        /// add conjunctions to. This cannot be null and no element
        /// within hte list can be null.
        /// </param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="effectSpans"/> cannot be null and no 
        /// element within it can be null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="effectSpans"/> cannot be empty.
        /// </exception>
        public static IEnumerable<EffectSpan> AddConjunctions(this IList<List<EffectSpan>> effectSpans)
        {
            if (effectSpans == null)
            {
                throw new ArgumentNullException("effectSpans");
            }
            if (!effectSpans.Any())
            {
                throw new ArgumentException("Cannot be empty", "effectSpans");
            }
            if (effectSpans.Any(x => x == null))
            {
                throw new ArgumentNullException("effectSpans");
            }

            List<EffectSpan> result;

            result = new List<EffectSpan>();
            for (int i = 0; i < effectSpans.Count(); i++)
            {
                result.AddRange(effectSpans[i]);

                if (i < effectSpans.Count() - 2)
                {
                    result.Add(new EffectSpan(", "));
                }
                else if (i == effectSpans.Count() - 2)
                {
                    result.Add(new EffectSpan(" and "));
                }
            }

            return result;
        }
		public static Visibility GetVisibility(this SyntaxTokenList tokenList, Visibility defaultVisibility = Visibility.Private)
		{
			Requires.InRange(defaultVisibility, () => defaultVisibility);

			var isPrivate = tokenList.Any(SyntaxKind.PrivateKeyword);
			var isProtected = tokenList.Any(SyntaxKind.ProtectedKeyword);
			var isInternal = tokenList.Any(SyntaxKind.InternalKeyword);
			var isPublic = tokenList.Any(SyntaxKind.PublicKeyword);

			if (isPrivate && !isProtected && !isInternal && !isPublic)
				return Visibility.Private;

			if (isProtected && !isPrivate && !isInternal && !isPublic)
				return Visibility.Protected;

			if (isInternal && !isPrivate && !isProtected && !isPublic)
				return Visibility.Internal;

			if (isProtected && isInternal && !isPrivate && !isPublic)
				return Visibility.ProtectedInternal;

			if (isPublic && !isPrivate && !isProtected && !isInternal)
				return Visibility.Public;

			return defaultVisibility;
		}
 /// <summary>Propagates any exceptions that occurred on the specified tasks.</summary>
 /// <param name="tasks">The Task instances whose exceptions are to be propagated.</param>
 public static void PropagateExceptions(this Task [] tasks)
 {
     if (tasks == null) throw new ArgumentNullException("tasks");
     if (tasks.Any(t => t == null)) throw new ArgumentException("tasks");
     if (tasks.Any(t => !t.IsCompleted)) throw new InvalidOperationException("A task has not completed.");
     Task.WaitAll(tasks);
 }
        public static bool IsShowAllText(this IEnumerable<FilterCriteria> criteriaGroup)
        {
            if (criteriaGroup.Any(c => c.Entity == FilterService.ShortcutPrice))
                return false;

            return (criteriaGroup.Count() >= FilterService.MaxDisplayCriteria || criteriaGroup.Any(c => !c.IsInactive));
        }
        public static EtagMatch EtagMatches(this IEnumerable<string> values, string etag)
        {
            if (values == null || !values.Any()) return EtagMatch.None;

            return values.Any(x => x.Equals(etag, StringComparison.Ordinal) || x == "*")
                ? EtagMatch.Yes
                : EtagMatch.No;
        }
Exemplo n.º 6
0
 public static bool Duplicates(this IQueryable<User> query, Guid? oldUserId, string username)
 {
     if (oldUserId == null)
     {
         return query.Any(x => x.Username == username);
     }
     return query.Any(x => x.Id != oldUserId && x.Username == username);
 }
Exemplo n.º 7
0
        public static string Humanize(this string input)
        {
            // if input is all capitals (e.g. an acronym) then return it without change
            if (!input.Any(Char.IsLower) && !input.Any(Char.IsDigit))
                return input;

            if (input.Contains("_"))
                return FromUnderscoreSeparatedWords(input);

            return FromPascalCase(input);
        }
Exemplo n.º 8
0
        public static OrderStateBase OrderStatus(this IEnumerable<IOrderStatusIDContainer> items)
        {
            if (!items.Any()) return null;

            if (items.Any(i => i.OrderStatus() is BackorderedState))
                return (items.First(i => i.OrderStatus() is BackorderedState)).OrderStatus();

            var relevantItems = items.Where(i => i.OrderStatus() is NoneState == false);
            if (relevantItems.Any())
                return relevantItems.First(i => i.OrderStatusID == relevantItems.Min(o => o.OrderStatusID)).OrderStatus();

            return items.First().OrderStatus();
        }
        /// <summary>
        ///     Get correct seo keyword by language from list of given keywords
        /// </summary>
        /// <param name="keywords">The keywords.</param>
        /// <param name="language">The language.</param>
        /// <returns></returns>
        public static SeoKeyword SeoKeyword(this IEnumerable<SeoKeyword> keywords, string language = null)
        {
            if (keywords == null || !keywords.Any())
            {
                return null;
            }

            var langInfo = language != null ? language.TryGetCultureInfo() : Thread.CurrentThread.CurrentUICulture;
            language = langInfo != null ? langInfo.Name : language;

            //Filter keywords with valid language
            keywords = keywords.Where(x => x.Language.TryGetCultureInfo() != null);

            if (keywords.Any())
            {
                var seoKeyword =
                    keywords.FirstOrDefault(
                        x => x.Language.Equals(language, StringComparison.InvariantCultureIgnoreCase));

                if (seoKeyword != null)
                {
                    return seoKeyword;
                }

                //Default language failover scenario
                Shop store = null;

                //if (store == null) throw new NullReferenceException("store is not initialized");
                //Current store can be null when called from StoreHttpModule and store is not yet initialzed
                if (store == null /*&& keywords.ElementAt(0).KeywordType == SeoUrlKeywordTypes.Store*/)
                {
                    var allShops = SiteContext.Current.Shops;

                    if (!allShops.Any())
                    {
                        return null;
                    }

                    store = allShops.FirstOrDefault(x => x.StoreId.Equals(keywords.ElementAt(0).Keyword, StringComparison.InvariantCultureIgnoreCase));
                }

                if (store != null && !store.DefaultLanguage.Equals(language, StringComparison.OrdinalIgnoreCase))
                {
                    return
                        keywords.FirstOrDefault(
                            x => x.Language.Equals(store.DefaultLanguage, StringComparison.InvariantCultureIgnoreCase));
                }
            }

            return null;
        }
Exemplo n.º 10
0
 public static string UpperFirst(this string input)
 {
     if (!input.Any()) return input;
     var result = input.Substring(0, 1).ToUpper();
     if (input.Length > 1) result += input.Substring(1, input.Length - 1);
     return result;
 }
        public static bool HasClaim(this IEnumerable<Claim> claims, string type)
        {
            if (claims == null) throw new ArgumentNullException("type");
            if (String.IsNullOrWhiteSpace(type)) throw new ArgumentNullException("type");

            return claims.Any(x => x.Type == type);
        }
Exemplo n.º 12
0
        public static string ToText(this DumpLevel dumpLevel, string nullRepresentation = "<null>", string indentString = "\t")
        {
            var dumpText = string.Empty;

            string indent = string.Empty;
            for (var i = 0; i < dumpLevel.Level + 1; i++)
                indent += indentString;

            if (dumpLevel is StopDumpLevel)
            {
                dumpText += "...";
            }
            else if (dumpLevel.Any())
            {
                dumpText += dumpLevel.Type.ToString();
                foreach (var child in dumpLevel)
                {
                    dumpText += Environment.NewLine + indent + " - " + child.Header + " : ";
                    dumpText += child.ToText(nullRepresentation, indentString);
                }
            }
            else
            {
                if (dumpLevel.Value == null)
                    dumpText += nullRepresentation;
                else
                    dumpText += dumpLevel.Value.ToString();
            }

            return dumpText;
        }
 public static void ShouldMatch(this IEnumerable<DownloadedImageDTO> expected, IEnumerable<DownloadedImageDTO> actual)
 {
     foreach (var dto in actual)
     {
         Assert.That(expected.Any(d => IsMatch(d, dto)), "No match for: " + dto.URL);
     }
 }
Exemplo n.º 14
0
        public static string TryGetValue(this TableRow row, string header)
        {
            if (row.Any(f => f.Key == header))
                return row[header];

            return null;
        }
Exemplo n.º 15
0
 public static void CheckIfThereAreAnyFor(this IEnumerable<object> handlers, Type messageType)
 {
     if (!handlers.Any())
     {
         throw new NotSupportedException(string.Format("There is no handler registered for the {0}.", messageType.FullName));
     }
 }
 public static void AddIfMissing(this PresentationFrameworkCollection<ResourceDictionary> collection, ResourceDictionary resourceDictionary)
 {
     if (!collection.Any(rd => rd.Source.OriginalString.Equals(resourceDictionary.Source.OriginalString)))
     {
         collection.Add(resourceDictionary);
     }
 }
Exemplo n.º 17
0
 public static Employee AddEmployee(this EmployeeData employeeData, string firstName, string lastName,bool isenabled)
 {
     int customerNumber = employeeData.Any() ? employeeData.Max(m => m.EmployeeNumber) + 1 : EmployeeData.EmployeeNumberSeed;
     Employee employee = new Employee() { EmployeeNumber = customerNumber, FirstName = firstName, LastName = lastName, IsEnabled=isenabled};
     employeeData.Add(employee);
     return employee;
 }
Exemplo n.º 18
0
 public static void VerifyQuery(this IEnumerable<KeyValuePair<string, string>> queryParams,
     IEnumerable<string> odataOptionsExceptions)
 {
     var exceptionParam = odataOptionsExceptions.Where(x => queryParams.Any(y => y.Key == x)).FirstOrDefault();
     if(exceptionParam != null)
         throw new NotSupportedException(String.Format("{0} is not supported in this endpoint", exceptionParam));
 }
        // This mirrors BinaryReader.ReadString2 and BitReader.ReadString
        public static IEnumerable<byte> Serialize(this string s)
        {
            var result = new List<byte>();

            int length = s.Length + 1; // +1 for trailing 0
            bool isUnicode = s.Any(c => c > 255);
            if (isUnicode)
            {
                length *= -1;
            }

            result.AddRange(BitConverter.GetBytes(length));

            if ( s.Length > 0 )
            {

                if (isUnicode)
                {
                    result.AddRange(Encoding.Unicode.GetBytes(s));

                    result.Add(0);// Trailing 0 (16 bits for unicode)
                    result.Add(0);
                }
                else
                {
                    result.AddRange(Encoding.GetEncoding(1252).GetBytes(s));
                    result.Add(0); // Trailing 0
                }
            }

            return result;
        }
Exemplo n.º 20
0
 internal static RoleGrant ByUser(this ICollection<RoleGrant> enumerable, Guid userEntityId)
 {
     if (enumerable == null || !enumerable.Any()) return null;
     if (userEntityId == Guid.Empty)
         throw new InvalidOperationException(string.Format("EntityId Guid is empty ({0}).", Guid.Empty));
     return enumerable.SingleOrDefault(g => g.User.EntityId == userEntityId);
 }
Exemplo n.º 21
0
 internal static RoleGrant ByRole(this ICollection<RoleGrant> enumerable, string roleName)
 {
     if (enumerable == null || !enumerable.Any()) return null;
     if (string.IsNullOrWhiteSpace(roleName))
         throw new ArgumentException("Cannot be null or whitespace.", "roleName");
     return enumerable.SingleOrDefault(g => g.Role.Name == roleName);
 }
Exemplo n.º 22
0
        public static string ToString(this IEnumerable<int> value)
        {
            if (value == null || !value.Any())
                return string.Empty;

            return string.Join(",", value);
        }
        public static bool ContainsSame(this IEnumerable<PropertyInfo> enumerable, PropertyInfo propertyInfo)
        {
            DebugCheck.NotNull(enumerable);
            DebugCheck.NotNull(propertyInfo);

            return enumerable.Any(propertyInfo.IsSameAs);
        }
 private static bool HasAllRecords(this List<IDataProvider> response)
 {
     if (response == null || !response.Any()) return false;
     return response.FirstOrDefault(
                    s => (s.ResponseState == DataProviderResponseState.NoRecords ||
                        s.ResponseState == DataProviderResponseState.TechnicalError || s.ResponseState == DataProviderResponseState.VinShort)) == null;
 }
Exemplo n.º 25
0
 public static void should_not_contain(this IEnumerable<dynamic> squares, int x, int y)
 {
     if (squares.Any(s => s.X == x && s.Y == y))
     {
         throw new InvalidOperationException(string.Format("squares contains: {0}, {1}", x, y));
     }
 }
Exemplo n.º 26
0
        public static DateTime MaxDate(this IEnumerable<DateTime> left, IEnumerable<DateTime> right)
        {
            var maxLeft = left.Any() ? left.Max() : DateTime.MinValue;
            var maxRight = right.Any() ? right.Max() : DateTime.MinValue;

            return maxLeft.Ticks > maxRight.Ticks ? maxLeft : maxRight;
        }
        /// <summary>
        /// Validates the chromosomes.
        /// </summary>
        /// <param name="chromosomes">The chromosomes.</param>
        public static void ValidateGenes(this IList<IChromosome> chromosomes)
        {
            if (chromosomes.Any(c => c.GetGenes().Any(g => g.Value == null)))
            {
				throw new InvalidOperationException("The chromosome '{0}' is generating genes with null value.".With(chromosomes.First().GetType().Name));
            }
        }
Exemplo n.º 28
0
        public static DateTime MinDate(this IEnumerable<DateTime> left, IEnumerable<DateTime> right)
        {
            var minLeft = left.Any() ? left.Min() : DateTime.MaxValue;
            var minRight = right.Any() ? right.Min() : DateTime.MaxValue;

            return minLeft.Ticks < minRight.Ticks ? minLeft : minRight;
        }
        internal static IEnumerable<LoginPageLink> Render(this IEnumerable<LoginPageLink> links, string baseUrl, string signinId)
        {
            if (links == null || !links.Any()) return null;

            var result = new List<LoginPageLink>();
            foreach (var link in links)
            {
                var url = link.Href;
                if (url.StartsWith("~/"))
                {
                    url = url.Substring(2);
                    url = baseUrl + url;
                }

                url = url.AddQueryString("signin=" + signinId);

                result.Add(new LoginPageLink
                {
                    Type = link.Type,
                    Text = link.Text,
                    Href = url
                });
            }
            return result;
        }
Exemplo n.º 30
0
        public static byte[] ToBytes(this string text)
        {
            if (text.Any(x => x > (char)127))
                throw new ArgumentOutOfRangeException(text, "only ASCII values are allowed");

            return System.Text.Encoding.Default.GetBytes(text);
        }