public async Task<SecretValidationResult> ValidateAsync(ParsedSecret parsedSecret, IEnumerable<Secret> secrets)
        {
            var expiredSecrets = secrets.Where(s => s.Expiration.HasExpired());
            if (expiredSecrets.Any())
            {
                expiredSecrets.ToList().ForEach(
                    ex => Logger.InfoFormat("Secret [{0}] is expired", ex.Description ?? "no description"));
            }

            var currentSecrets = secrets.Where(s => !s.Expiration.HasExpired());

            // see if a registered validator can validate the secret
            foreach (var validator in _validators)
            {
                var secretValidationResult = await validator.ValidateAsync(currentSecrets, parsedSecret);

                if (secretValidationResult.Success)
                {
                    Logger.DebugFormat("Secret validator success: {0}", validator.GetType().Name);
                    return secretValidationResult;
                }
            }

            Logger.Info("Secret validators could not validate secret");
            return new SecretValidationResult { Success = false };
        }
Example #2
0
        public static List<CategoryEntry> BuildCategoryTree(int? parentId, IEnumerable<CategoryEntry> all)
        {
            IEnumerable<CategoryEntry> categories = null;

            if (parentId == null)
            {
                categories = all.Where(c => c.ParentId == null);
            }
            else
            {
                categories = all.Where(c => c.ParentId == parentId);
            }

            var entries = new List<CategoryEntry>();
            foreach (var root in categories)
            {
                var entry = new CategoryEntry
                {
                    Id = root.Id,
                    Name = root.Name,
                    ParentId = parentId
                };

                entry.Children = BuildCategoryTree(entry.Id, all);

                entries.Add(entry);
            }

            return entries;
        }
        public IEnumerable<IOperation> Process(IEnumerable<IOperation> operations)
        {
            var operation = operations.Where(x => x.GetRequestCodec() != null)
                                .OrderByDescending(x => x.GetRequestCodec()).FirstOrDefault()
                            ?? operations.Where(x => x.Inputs.AllReady())
                                   .OrderByDescending(x => x.Inputs.CountReady()).FirstOrDefault();
            if (operation == null)
            {
                Log.OperationNotFound();
                yield break;
            }

            Log.OperationFound(operation);

            if (operation.GetRequestCodec() != null)
            {
                var codecInstance = CreateMediaTypeReader(operation);

                var codecType = codecInstance.GetType();
                Log.CodecLoaded(codecType);

                if (codecType.Implements(typeof(IKeyedValuesMediaTypeReader<>)))
                    if (TryAssignKeyedValues(_request.Entity, codecInstance, codecType, operation))
                    {
                        yield return operation;
                        yield break;
                    }

                if (codecType.Implements<IMediaTypeReader>())
                    if (!TryReadPayloadAsObject(_request.Entity, (IMediaTypeReader)codecInstance, operation))
                        yield break;
            }
            yield return operation;
        }
Example #4
0
        public void PlaySounds(IEnumerable<ProjectStatus> currentBuildData)
        {
            var newlyBrokenBuilds =
                currentBuildData.Where(proj => proj.IsBroken)
                                .Intersect(_previousBuildData.Where(proj => !proj.IsBroken));

            if (newlyBrokenBuilds.Any())
            {
                _audioPlayer.Play(_brokenBuildSound);
                _audioPlayer.Say(_speechMaker.BuildIsBroken(newlyBrokenBuilds));
            }
            else
            {
                var newlyFixedBuilds =
                    currentBuildData.Where(proj => proj.IsSuccessful)
                                    .Intersect(_previousBuildData.Where(proj => !proj.IsSuccessful));

                if (newlyFixedBuilds.Any())
                {
                    _audioPlayer.Play(_fixedBuildSound);
                    _audioPlayer.Say(_speechMaker.BuildIsFixed(newlyFixedBuilds));
                }
            }

            _previousBuildData = currentBuildData;
        }
Example #5
0
 /// <summary>
 /// Permet de filtrer sur les parametres d'une fonction pour les fonctions surchargées
 /// </summary>
 /// <param name="methods"></param>
 /// <param name="parameters"></param>
 /// <returns></returns>
 private static MethodInfo FilterMethodByParams(IEnumerable<MethodInfo> methods, IEnumerable<object> parameters)
 {
     if (parameters != null)
     {
         var paramsNull = parameters.Where(p => p.Equals(null));
         if (!paramsNull.Any())
         {
             IEnumerable<Type> types = parameters.Select(param => param.GetType());
             var methodsFiltered = methods.Where(m => m.GetParameters().Count() == parameters.Count());
             if (methodsFiltered.Any())
             {
                 foreach (var methodInfo in methodsFiltered)
                 {
                     if (types.SequenceEqual(methodInfo.GetParameters().Select(p => p.ParameterType).ToList()))
                     {
                         return methodInfo;
                     }
                 }
             }
         }
         else
         {
             var methodsFiltered = methods.Where(m => m.GetParameters().Count() == parameters.Count());
             if (methodsFiltered.Any())
             {
                 return methodsFiltered.First();
             }
         }
     }
     return null;
 }
        public PlayerDashBoardViewModel(IEnumerable<League> leagues, Season currentSeason, IEnumerable<PlayerPredictionSummary> predictions, IEnumerable<PlayerPredictionSummary> LastWeekPredictions, Player playerProfile, Week LastWeek, Boolean IsViewingMyOwnPage, IQueryable<Notification> repnotifications)
        {
            LeagueSelections = leagues.ToDictionary((x => x.Name), x => x.Id.ToString());
            CurrentSeasonText = string.Format("{0} - {1} to {2}", currentSeason.League.Name, currentSeason.SeasonStarts.ToLongDateString(), currentSeason.SeasonEnd.ToLongDateString());

            ThisWeek = currentSeason.GetCurrentWeekSeason();
            IsMyPage = IsViewingMyOwnPage;

            if (predictions != null)
            {
                PredictionsWithOutComes = predictions.Where(x => x.HasOutcome).OrderBy(y=>y.MatchDate);
                PredictionUpComingMatches = predictions.Where(x => !x.HasOutcome).OrderBy(y => y.MatchDate);
                ThisWeeksMotWId = ThisWeek != null && ThisWeek.MatchOfTheWeek != null ? ThisWeek.MatchOfTheWeek.Id : 0;
            }
            if (LastWeekPredictions != null)
            {
                PredictionsOfPreviousWeek = LastWeekPredictions.OrderBy(y => y.MatchDate);

                LastWeeksMotWId = LastWeek != null && LastWeek.MatchOfTheWeek != null ? LastWeek.MatchOfTheWeek.Id : 0;
            }

            //Build Players Table
            Points = currentSeason.Weeks.WeeksSoFar().Select(w => currentSeason.GetTotalPointsForAPlayersWeek(playerProfile, w)).ToList();
            WeekNames = currentSeason.Weeks.WeeksSoFar().Select(x => x.WeekStarts.Day.ordinalNum() + " " + x.WeekStarts.ToString("MMM")).ToArray();

            //set up notifications
            notifications = repnotifications.Take(3);

            AllPredictionsConfirmed = ThisWeek != null ? playerProfile.HasCompletedPredictions(ThisWeek) : true;
        }
Example #7
0
        public BPLPlayerViewModel(IEnumerable<League> leagues, Season currentSeason, IEnumerable<PlayerPredictionSummary> predictions, IEnumerable<PlayerPredictionSummary> LastWeekPredictions, Player LoggedInPlayer, Week LastWeek)
        {
            LeagueSelections = leagues.ToDictionary((x => x.Name), x => x.Id.ToString());
            CurrentSeasonText = string.Format("{0} - {1} to {2}", currentSeason.League.Name, currentSeason.SeasonStarts.ToLongDateString(), currentSeason.SeasonEnd.ToLongDateString());

            ThisWeek = currentSeason.GetCurrentWeekSeason();

            if (predictions != null)
            {
                PredictionsWithOutComes = predictions.Where(x => x.HasOutcome).OrderBy(y=>y.MatchDate);
                PredictionUpComingMatches = predictions.Where(x => !x.HasOutcome).OrderBy(y => y.MatchDate);
                ThisWeeksMotWId = ThisWeek != null && ThisWeek.MatchOfTheWeek != null ? ThisWeek.MatchOfTheWeek.Id : 0;
            }
            if (LastWeekPredictions != null)
            {
                PredictionsOfPreviousWeek = LastWeekPredictions.OrderBy(y => y.MatchDate);

                LastWeeksMotWId = LastWeek != null && LastWeek.MatchOfTheWeek != null ? LastWeek.MatchOfTheWeek.Id : 0;
            }

            //Build Players Table
            Points = currentSeason.Weeks.WeeksSoFar().Select(w => currentSeason.GetTotalPointsForAPlayersWeek(LoggedInPlayer, w)).ToList();
            WeekNames = currentSeason.Weeks.WeeksSoFar().Select(x => x.WeekStarts.Day.ordinalNum() + " " + x.WeekStarts.ToString("MMM")).ToArray();

            AllPredictionsConfirmed = ThisWeek != null ? LoggedInPlayer.HasCompletedPredictions(ThisWeek) : true;
        }
        public IEnumerable<IAsset> Process(IEnumerable<IAsset> assets)
        {
            var results = assets.Where(a => !a.IsProcessable).ToList();

            IEnumerable<IGrouping<IAssetKey, IAsset>> assetGroups = assets.Where(a => a.IsProcessable).GroupBy(asset => asset.Key);

            foreach (IGrouping<IAssetKey, IAsset> assetGroup in assetGroups) {
                if (assetGroup.Count() == 1) {
                    results.Add(assetGroup.Single());
                } else {

                    var combinedTextBuilder = new StringBuilder();
                    var associatedFilePaths = new List<string>();
                    foreach (IAsset asset in assetGroup.OrderByDescending(a => a.OnLayoutPage)) {
                        associatedFilePaths.AddRange(asset.Reader.AssociatedFilePaths);
                        combinedTextBuilder.AppendLine(asset.Reader.Content);
                    }

                    var newContent = combinedTextBuilder.ToString();

                    var newAsset = assetGroup.First();
                    newAsset.Reader = new MemoryAssetReader(associatedFilePaths, newContent);
                    results.Add(newAsset);
                }
            }

            return results;
        }
        internal static EntityStoreSchemaFilterEffect GetEffectViaFilter(
            this EntityStoreSchemaFilterEntry entryToTest, IEnumerable<EntityStoreSchemaFilterEntry> filterEntries)
        {
            var effect = EntityStoreSchemaFilterEffect.Exclude;

            // Look for the all filter for specific type of object; this includes the 'All' types filter
            foreach (var entry in filterEntries.Where(e => e.Name == "%" && (e.Types & entryToTest.Types) == entryToTest.Types))
            {
                effect = entry.Effect;
                break;
            }

            // Look for the specific type of object
            foreach (var entry in filterEntries.Where(
                e =>
                e.Catalog.Equals(entryToTest.Catalog ?? String.Empty, StringComparison.CurrentCulture) &&
                e.Schema.Equals(entryToTest.Schema ?? String.Empty, StringComparison.CurrentCulture) &&
                e.Name.Equals(entryToTest.Name ?? String.Empty, StringComparison.CurrentCulture)))
            {
                effect = entry.Effect;
                break;
            }

            return effect;
        }
 public void List(IEnumerable<SandRibbonObjects.ConversationDetails> conversations)
 {
     Dispatcher.Invoke((Action)delegate
     {
         rawConversationList = conversations.ToList();
         var list = new List<ConversationDetails>();
         var myConversations = conversations.Where(c => c.Author == me).OrderBy(c=>c.LastAccessed.Date).Take(2).ToList();
         if (myConversations.Count() > 0)
         {
             list.Add(new SeparatorConversation("My Conversations"));
             list.AddRange(myConversations);
         }
         list.Add(new SeparatorConversation("Conversations I've worked in"));
         var recentConversations = RecentConversationProvider.loadRecentConversations().Where(c => c.IsValid && conversations.Contains(c)).Take(2);
         list.AddRange(recentConversations);
         var recentAuthors = list.Select(c => c.Author).Where(c => c != me).Distinct().ToList();
         foreach (var author in recentAuthors)
         {
             var otherConversationsByThisAuthor = conversations.Where(c => c.IsValid && !list.Contains(c) && c.Author == author);
             if (otherConversationsByThisAuthor.Count() > 0)
             {
                 list.Add(new SeparatorConversation(string.Format("{0}'s other conversations:", author)));
                 list.AddRange(otherConversationsByThisAuthor.Take(2));
             }
         }
         this.conversations.ItemsSource = list;
     });
 }
        public static CurricularUnitForm Process(IEnumerable<KeyValuePair<string, string>> content)
        {
            if (content == null) return null;

            CurricularUnitForm cuf = new CurricularUnitForm();

            cuf.CUnit.Acronym = content.Where(p => p.Key == "acronym").FirstOrDefault().Value;
            cuf.CUnit.Name = content.Where(p => p.Key == "name").FirstOrDefault().Value;
            cuf.CUnit.ECTS = Double.Parse(content.Where(p => p.Key == "credits").FirstOrDefault().Value);

            cuf.Type.CourseType = (CourseType)Enum.Parse(typeof(CourseType), content.Where(p => p.Key == "coursetype").FirstOrDefault().Value);
            cuf.Type.Degree = (Degree)Enum.Parse(typeof(Degree), content.Where(p => p.Key == "degree").FirstOrDefault().Value);
            cuf.Type.Semester = (Semester)Enum.Parse(typeof(Semester), content.Where(p => p.Key == "semester").FirstOrDefault().Value);

            cuf.Description.CourseProgram = content.Where(p => p.Key == "courseprogram").FirstOrDefault().Value;
            cuf.Description.Language = "PT";
            cuf.Description.LearningResults = content.Where(p => p.Key == "learningresults").FirstOrDefault().Value;
            cuf.Description.Objectives = content.Where(p => p.Key == "objectives").FirstOrDefault().Value;
            cuf.Description.ResultEvaluation = content.Where(p => p.Key == "resultevaluation").FirstOrDefault().Value;

            //TODO Required Courses
            //TODO Verify Contents

            return cuf;
        }
Example #12
0
        /// <summary>
        /// Compares the current data from server to the cache
        /// </summary>
        /// <param name="contentModels"></param>
        /// <param name="update"></param>
        /// <param name="delete"></param>
        public void Compare(IEnumerable<ContentModel> contentModels, List<ContentModel> update, List<int> delete)
        {
            var cache = LoadCacheToMemory();

            // cache file doesn't exist, just push it all up
            if (cache == null)
            {
                update = contentModels.ToList();
                return;
            }

            foreach (var cm in contentModels)
            {
                var mids = cm.MediaModels.Select(a => a.MediaId);

                if (cache.Any(a => mids.Contains(a.MediaId) && a.Hash != cm.ModelHash && a.VideoType == cm.VideoType) ||
                    !cache.Any(a => mids.Contains(a.MediaId) && a.VideoType == cm.VideoType))
                {
                    update.Add(cm);
                }
            }

            // check for deletions
            var movieRemovals = cache.Where(a => a.VideoType == VideoType.Movie).Select(a => a.MediaId)
                                     .Except(contentModels.Where(a => a.VideoType == VideoType.Movie)
                                     .SelectMany(a => a.MediaModels.Select(b => b.MediaId)));

            delete.AddRange(cache.Where(a => movieRemovals.Contains(a.MediaId)).Select(a => a.ServerMediaId).ToList());

            var episodeRemovals = cache.Where(a => a.VideoType == VideoType.TvShowEpisode).Select(a => a.MediaId)
                                     .Except(contentModels.Where(a => a.VideoType == VideoType.TvShowEpisode)
                                     .SelectMany(a => a.MediaModels.Select(b => b.MediaId)));

            delete.AddRange(cache.Where(a => episodeRemovals.Contains(a.MediaId)).Select(a => a.ServerMediaId).ToList());
        }
Example #13
0
        public static IEnumerable<Order> OldMerge(IEnumerable<Order> orders)
        {
            var mergedOrders = orders.Where(x => x.Quantity != 1).ToList();
            var ids = mergedOrders.Select(x => x.MenuItemId).Distinct().ToArray();
            mergedOrders.AddRange(orders.Where(x => ids.Contains(x.MenuItemId) && x.Quantity == 1));
            foreach (var order in orders.Where(x => x.Quantity == 1 && !ids.Contains(x.MenuItemId)))
            {
                var ti = order;
                if (order.OrderTagValues.Count > 0)
                {
                    mergedOrders.Add(order);
                    continue;
                }

                var item =
                    mergedOrders.SingleOrDefault(
                        x =>
                        x.OrderTagValues.Count == 0 && x.MenuItemId == ti.MenuItemId &&
                        x.PortionName == ti.PortionName && x.CalculatePrice == ti.CalculatePrice && x.Price == ti.Price);
                if (item == null) mergedOrders.Add(order);
                else
                {
                    item.Quantity += order.Quantity;
                    item.ResetSelectedQuantity();
                }
            }

            return mergedOrders;
        }
        void Init(string subject, string name,
            IEnumerable<Claim> claims = null,
            string identityProvider = Constants.BuiltInIdentityProvider,
            string authenticationMethod = null,
            string authenticationType = Constants.PrimaryAuthenticationType
        )
        {
            if (String.IsNullOrWhiteSpace(subject)) throw new ArgumentNullException("subject");
            if (String.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name");
            if (String.IsNullOrWhiteSpace(identityProvider)) throw new ArgumentNullException("identityProvider");

            if (String.IsNullOrWhiteSpace(authenticationMethod))
            {
                if (identityProvider == Constants.BuiltInIdentityProvider)
                {
                    authenticationMethod = Constants.AuthenticationMethods.Password;
                }
                else
                {
                    authenticationMethod = Constants.AuthenticationMethods.External;
                }
            }

            var user = IdentityServerPrincipal.Create(subject, name, authenticationMethod, identityProvider, authenticationType);
            if (claims != null && claims.Any())
            {
                claims = claims.Where(x => !Constants.OidcProtocolClaimTypes.Contains(x.Type));
                claims = claims.Where(x => x.Type != Constants.ClaimTypes.Name);
                user.Identities.First().AddClaims(claims);
            }

            this.User = user;
        }
Example #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClassTypeTree"/> class.
        /// </summary>
        /// <param name="types">The types to build the tree out of.</param>
        public ClassTypeTree(IEnumerable<Type> types)
        {
            // ReSharper disable DoNotCallOverridableMethodsInConstructor

            var childList = new List<ClassTypeTree>();

            // Remove duplicates
            types = types.Where(x => x.IsClass).Distinct();

            // Grab the lowest-level types
            var baseTypes = types.Where(x => !types.Any(y => x != y && y.IsAssignableFrom(x)));

            // Grab the possible child types
            var remainingTypes = types.Except(baseTypes);
            foreach (var bt in baseTypes)
            {
                // Recursively build the tree
                childList.Add(CreateNode(this, bt, remainingTypes));
            }

            // Add the wildcard for the base level
            childList.Add(CreateNode(this, null, null));

            // Store the children
            _children = FinalizeChildren(childList);

            // ReSharper restore DoNotCallOverridableMethodsInConstructor
        }
        public static void Adjust(IEnumerable<ICrew> crews, IEnumerable<IAdjustment> adjustments)
        {
            IDictionary<Gender, IDictionary<string, TimeSpan>> offsets = new Dictionary<Gender, IDictionary<string, TimeSpan>> ();
            foreach (Gender gender in (Gender[]) Enum.GetValues(typeof(Gender))) {

                var fastest = crews.Where (cr => cr.FinishType == FinishType.Finished && cr.Gender == gender).Min (cr => cr.Elapsed);
                var floor = adjustments.Where(a => a.Minutes == fastest.Minutes).First();
                var ceiling = adjustments.Where(a => a.Minutes == fastest.Minutes+1).First();
                var offset = (fastest - new TimeSpan (0, fastest.Minutes, 0)).TotalSeconds;
                Logger.InfoFormat ("{0} adjustments based on time of {1}", gender, fastest);
                IDictionary<string, TimeSpan> local = new Dictionary<string, TimeSpan>();
                foreach(var kvp in floor.Adjustments)
                {
                    var adjustment = (int)Math.Round(kvp.Value + ((ceiling.Adjustments[kvp.Key]-kvp.Value)*(offset/60.0d)),0);
                    local.Add(kvp.Key, TimeSpan.FromSeconds(adjustment));
                    Logger.InfoFormat("{0}: {1}", kvp.Key, adjustment);
                }
                offsets.Add (gender, local);
            }

            // return; // urgent - validate
            foreach (var crew in crews) {
                if (!crew.IsMasters)
                    continue;
                crew.SetAdjusted (offsets [crew.Gender] [crew.EventCategory.MastersCategory]);
            }
        }
Example #17
0
        private static void AbilityAnalyzer(ILogMetrics data, IEnumerable<LogEntry> log)
        {
            var abilityNames = log.Where(m => m.ability.name != "").Select(m => m.ability.name).Distinct();
            foreach (var name in abilityNames)
            {
                var metrics = new AbilityMetrics();
                var abilityLog = log.Where(m => m.ability.name == name);

                var damageLog = abilityLog.DamageEffects();
                var healingLog = abilityLog.HealingEffects();
                var threatLog = abilityLog.ThreatEffects();

                data.AbilityMetrics.Add(metrics);

                metrics.Name = name;
                metrics.Number = abilityLog.First().ability.number;
                metrics.Count = abilityLog.Count();
                
                metrics.MaximumDamage = damageLog.IfEmpty(0, l => l.Max(m => m.result.amount));
                metrics.MinimumDamage = damageLog.IfEmpty(0, l => l.Min(m => m.result.amount));
                metrics.AverageDamage = damageLog.IfEmpty(0, l => l.Average(m => m.result.amount));

                metrics.MaximumHealing = healingLog.IfEmpty(0, l => l.Max(m => m.result.amount));
                metrics.MinimumHealing = healingLog.IfEmpty(0, l => l.Min(m => m.result.amount));
                metrics.AverageHealing = healingLog.IfEmpty(0, l => l.Average(m => m.result.amount));

                metrics.MaximumThreat = threatLog.IfEmpty(0, l => l.Max(m => m.result.amount));
                metrics.MinimumThreat = threatLog.IfEmpty(0, l => l.Min(m => m.result.amount));
                metrics.AverageThreat = threatLog.IfEmpty(0, l => l.Average(m => m.result.amount));

                metrics.CountOfCriticals = abilityLog.Where(m => m.result.isCritical).Count();
            }
            data.AbilityMetrics = data.AbilityMetrics.OrderByDescending(m => m.Count).ThenBy(m => m.Name).ToList();
        }
Example #18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["download"] != null)
                DownloadLogFile();

            try
            {
                _results = GetResults().Reverse();
            }
            catch
            {
                // File is locked because it's being written to. Ignore this and use the _results from last load (it's static).
            }

            if (_results != null)
            {
                filesProcessed.Text = _results.Count(r => r != null).ToString("#,#0");
                filesOptmized.Text = _results.Where(r => r != null && r.Saving > 0).Count().ToString("#,#0");
                totalSavings.Text = _results.Where(r => r != null).Sum(r => r.Saving).ToString("#,#0");

                double percent = double.Parse(totalSavings.Text) / (double)_results.Where(r => r != null).Sum(r => r.Original) * 100;
                totalPercent.Text = percent.ToString("#0.0");

                name.Text = _name;
                error.Visible = !File.Exists(_file);
                success.Visible = !error.Visible;
            }
        }
        //public void CallInitMethods(IEnumerable<string> initMethodNames, IEnumerable<string> endMethodNames, Func<string, MethodInfo> getMethod)
        //{
        //    Dictionary<string, MethodInfo> initMethods = CreateDictionary(initMethodNames);
        //    Dictionary<string, MethodInfo> endMethods = CreateDictionary(endMethodNames);

        //    bool callInit = _callInit;

        //    //if (forceCallInit)
        //    //    callInit = true;

        //    // check if init methods or end methods change
        //    if (!callInit && (!MethodsEquals(_initMethods, initMethods) || !MethodsEquals(_endMethods, endMethods)))
        //        callInit = true;


        //    if (callInit)
        //    {
        //        CallEndMethods();

        //        GetMethods(initMethods, getMethod);
        //        GetMethods(endMethods, getMethod);
        //        _initMethods = initMethods;
        //        _endMethods = endMethods;
        //        CallMethods(_initMethods, init: true);
        //        _callInit = false;
        //    }
        //}

        // callInit
        public void CallInitMethods(IEnumerable<InitEndMethod> initMethods, IEnumerable<InitEndMethod> endMethods, bool callInitRunOnce, Func<string, MethodInfo> getMethod)
        {
            Dictionary<string, MethodInfo> initMethodsRunAlways = CreateDictionary(initMethods.Where(method => method.RunType == RunType.Always).Select(method => method.Name));
            Dictionary<string, MethodInfo> endMethodsRunAlways = CreateDictionary(endMethods.Where(method => method.RunType == RunType.Always).Select(method => method.Name));
            Dictionary<string, MethodInfo> initMethodsRunOnce = CreateDictionary(initMethods.Where(method => method.RunType == RunType.Once).Select(method => method.Name));
            Dictionary<string, MethodInfo> endMethodsRunOnce = CreateDictionary(endMethods.Where(method => method.RunType == RunType.Once).Select(method => method.Name));

            //bool callInit = _callInit;

            // check if init methods or end methods change
            if (!callInitRunOnce && (!MethodsEquals(_initMethodsRunOnce, initMethodsRunOnce) || !MethodsEquals(_endMethodsRunOnce, endMethodsRunOnce)))
                callInitRunOnce = true;

            if (callInitRunOnce)
                CallEndMethodsRunOnce();

            CallEndMethodsRunAlways();

            if (callInitRunOnce)
            {
                GetMethods(initMethodsRunOnce, getMethod);
                GetMethods(endMethodsRunOnce, getMethod);
                _initMethodsRunOnce = initMethodsRunOnce;
                _endMethodsRunOnce = endMethodsRunOnce;
                CallMethods(_initMethodsRunOnce, always: false, init: true);
                _callInitRunOnce = false;
            }

            GetMethods(initMethodsRunAlways, getMethod);
            GetMethods(endMethodsRunAlways, getMethod);
            _endMethodsRunAlways = endMethodsRunAlways;
            CallMethods(initMethodsRunAlways, always: true, init: true);
        }
Example #20
0
        public static void ProcessCompilerResults(IEnumerable<CompilerResult> results)
        {
            var errors = results.Where(r => r.HasErrors).SelectMany(r => r.Errors);
            var clean = results.Where(r => !r.HasErrors).Select(r => r.FileName);

            if (errors.Any())
            {
                TableDataSource.Instance.AddErrors(errors);
            }

            if (results.Any(r => r.HasErrors))
            {
                if (results.Any(r => r.Errors.Any(e => !e.IsWarning)))
                {
                    WebCompilerPackage._dte.StatusBar.Text = "Error compiling. See Error List for details";
                    TableDataSource.Instance.BringToFront();
                }
                else
                {
                    WebCompilerInitPackage.StatusText($"Compiled with warnings");
                }
            }
            else
            {
                WebCompilerInitPackage.StatusText($"Compiled successfully");
            }

            TableDataSource.Instance.CleanErrors(clean);
        }
 protected SpecificationContainer(IEnumerable<Specification> specifications)
 {
   _totalSpecifications = specifications.Count();
   _passingSpecifications = specifications.Where(x => x.Status == Status.Passing).Count();
   _failingSpecifications = specifications.Where(x => x.Status == Status.Failing).Count();
   _notImplementedSpecifications = specifications.Where(x => x.Status == Status.NotImplemented).Count();
 }
 private IEnumerable<ResponseSet> FilterResponseSet(FilterParameters parameters, IEnumerable<ResponseSet> responseSets, Func<ResponseSet, DateTime> criteriaDate)
 {
     var resultCollection = new List<ResponseSet>();
     switch (parameters.Type)
     {
         case FilterType.ByDate:
             {
                 switch (parameters.Date.SelectedPeriod.Key)
                 {
                     case TimePeriods.After:
                         resultCollection = responseSets.Where(r => criteriaDate(r).Date > parameters.Date.SelectedDate.Date).ToList();
                         break;
                     case TimePeriods.At:
                         resultCollection = responseSets.Where(r => criteriaDate(r).Date == parameters.Date.SelectedDate.Date).ToList();
                         break;
                     case TimePeriods.Before:
                         resultCollection = responseSets.Where(r => criteriaDate(r).Date < parameters.Date.SelectedDate.Date).ToList();
                         break; 
                     case TimePeriods.Between:
                         resultCollection = responseSets.Where(r => criteriaDate(r).Date <= parameters.Date.SelectedEndDate.Date && criteriaDate(r).Date >= parameters.Date.SelectedStartDate.Date).ToList();
                         break;
                 };
             }
             break;
     }
     return resultCollection;
 }
        private static IEnumerable<LaneModel> GetOrderedLanes(IEnumerable<LaneModel> laneStats)
        {
            var orderedLaneStats = new List<LaneModel>();

            Func<LaneModel, bool> backLogPred = x => x.ClassType == LaneClassType.Backlog && x.Relation != "child";
            Func<LaneModel, bool> activePred = x => x.ClassType == LaneClassType.Active;
            Func<LaneModel, bool> archivePred = x => x.ClassType == LaneClassType.Archive && x.Relation != "child";

            if (laneStats.Any(backLogPred))
            {
                orderedLaneStats.AddRange(laneStats.Where(backLogPred).OrderBy(x => x.Index));
            }

            if (laneStats.Any(activePred))
            {
                orderedLaneStats.AddRange(laneStats.Where(activePred).OrderBy(x => x.Index));
            }

            if (laneStats.Any(archivePred))
            {
                orderedLaneStats.AddRange(laneStats.Where(archivePred).OrderBy(x => x.Index));
            }

            return orderedLaneStats;
        }
        static List<MenuViewModel> GenerateMenu(IEnumerable<MenuItem> menuItems, int parentId)
        {
            var menuTree = new List<MenuViewModel>();
            IEnumerable<MenuItem> upperLevelMenus;
            if (parentId == 0)
            {
                upperLevelMenus = menuItems.Where(m => m.ParentID == null).OrderBy(o=>o.Order).ThenBy(o=>o.Text);
            }
            else
            {
                upperLevelMenus = menuItems.Where(m => m.ParentID == parentId).OrderBy(o => o.Order).ThenBy(o => o.Text);
            }

            foreach (var menuItem in upperLevelMenus)
            {
                menuTree.Add(new MenuViewModel(menuItem));
            }

            foreach (var menu in menuTree)
            {
                var children = menuItems.Select(m => m.ParentID == menu.MenuItemID);
                if (menuItems.Select(m => m.ParentID == menu.MenuItemID).Any())
                    menu.SubMenus = GenerateMenu(menuItems, menu.MenuItemID);
            }
            return menuTree;
        }
        public StringBuilder GenerateContent(string requestPath, IEnumerable<IFileInfo> contents)
        {
            if (contents == null)
            {
                throw new ArgumentNullException("contents");
            }

            var builder = new StringBuilder();
            builder.AppendFormat("{0}\r\n", requestPath);
            builder.Append("\r\n");

            foreach (var subdir in contents.Where(info => info.IsDirectory))
            {
                builder.AppendFormat("{0}/\r\n", subdir.Name);
            }
            builder.Append("\r\n");

            foreach (var file in contents.Where(info => !info.IsDirectory))
            {
                builder.AppendFormat("{0}, {1}, {2}\r\n", file.Name, file.Length, file.LastModified);
            }
            builder.Append("\r\n");

            return builder;
        }
        /// <inheritdoc/>
        protected override IEnumerable<EdmProperty> MatchKeyProperty(
            EntityType entityType, IEnumerable<EdmProperty> primitiveProperties)
        {
            Check.NotNull(entityType, "entityType");
            Check.NotNull(primitiveProperties, "primitiveProperties");

            var matches = primitiveProperties
                .Where(p => Id.Equals(p.Name, StringComparison.OrdinalIgnoreCase));

            if (!matches.Any())
            {
                matches = primitiveProperties
                    .Where(p => (entityType.Name + Id).Equals(p.Name, StringComparison.OrdinalIgnoreCase));
            }

            // If the number of matches is more than one, then multiple properties matched differing only by
            // case--for example, "Id" and "ID". In such as case we throw and point the developer to using
            // data annotations or the fluent API to disambiguate.
            if (matches.Count() > 1)
            {
                throw Error.MultiplePropertiesMatchedAsKeys(matches.First().Name, entityType.Name);
            }

            return matches;
        }
        protected virtual IEnumerable<ChapterLink> CollectChapterLinks(string baseUrl, IEnumerable<IElement> linkElements,
            Func<IElement, bool> linkFilter = null)
        {
            if (linkFilter != null)
                linkElements = linkElements.Where(linkFilter);

            linkElements = linkElements.Where(p => p.LocalName == "a");

            foreach (IElement e in linkElements)
            {
                if (string.IsNullOrWhiteSpace(e.TextContent) || !e.HasAttribute("href"))
                    continue;

                string url = UrlHelper.ToAbsoluteUrl(baseUrl, e.GetAttribute("href"));

                if (string.IsNullOrEmpty(url))
                    continue;

                ChapterLink link = new ChapterLink
                {
                    Name = WebUtility.HtmlDecode(e.TextContent),
                    Url = url
                };

                yield return link;
            }
        }
Example #28
0
        public void Set(CircleController controller, IEnumerable<VotingDescriptor2> votings)
        {
            this.currentVotingListControl.Height = this.currentTabPage.ClientRectangle.Height - this.currentVotingListControl.Top;
              this.pastVotingListControl.Height = this.pastTabPage.ClientRectangle.Height - this.pastVotingListControl.Top;

              this.currentVotingListControl.Set(controller,
            votings.Where(voting =>
              voting.Status == VotingStatus.New ||
              voting.Status == VotingStatus.Sharing ||
              voting.Status == VotingStatus.Ready ||
              voting.Status == VotingStatus.Voting ||
              voting.Status == VotingStatus.Deciphering ||
              (voting.Status == VotingStatus.Finished &&
              DateTime.Now.Subtract(voting.VoteUntil).Days <= 14d))
              .OrderByDescending(voting => voting.VoteFrom));

              this.pastVotingListControl.Set(controller,
            votings.Where(voting =>
              voting.Status == VotingStatus.Aborted ||
              voting.Status == VotingStatus.Offline ||
              (voting.Status == VotingStatus.Finished &&
              DateTime.Now.Subtract(voting.VoteUntil).Days > 14d))
              .OrderByDescending(voting => voting.VoteFrom));

              this.certificateStatus.Controller = controller;
              this.certificateStatus.UpdateDisplay();
        }
        private  XElement ASIC(IEnumerable<XElement> rows) {
            bool hasASIC = rows.Where(x => x.Element("COMMODITYCLASS").Value == "ASIC").Any();
               if (hasASIC)
               {
                   XElement asic = new XElement("ASIC");
                   IEnumerable<string> orderkeys = rows.Where(x => x.Element("COMMODITYCLASS").Value == "ASIC").Select(x => x.Element("ORDERKEY").Value).Distinct();
                   foreach (string orderkey in orderkeys)
                   {
                       //表头/表体分组
                       XElement orderel = new XElement("ORDER");
                       orderel.Add(new XElement("ORDERKEY", orderkey));
                       string externorderkey = rows.Where(x =>
                           x.Element("ORDERKEY").Value == orderkey &&
                           x.Element("COMMODITYCLASS").Value == "ASIC").Select(x => x.Element("EXTERNORDERKEY").Value).First();
                       orderel.Add(new XElement("EXTERNORDERKEY", externorderkey));
                       string comcode = rows.Where(x =>
                           x.Element("ORDERKEY").Value == orderkey &&
                           x.Element("COMMODITYCLASS").Value == "ASIC").Select(x => x.Element("COMCODE").Value).First();
                       orderel.Add(new XElement("COMCODE", comcode));
                       XElement orderdetail = new XElement("ORDERDETAIL");
                       IEnumerable<XElement> detail = rows.Where(x =>
                           x.Element("ORDERKEY").Value == orderkey &&
                           x.Element("COMMODITYCLASS").Value == "ASIC").ToArray();
                       //orderdetail.Add(detail);
                       orderel.Add(detail);
                       asic.Add(orderel);

                   }
                   return asic;

               }
               else {
                   return null;
               }
        }
        private IEnumerable<CommandButtonViewModel<PaymentType>> CreatePaymentButtons(IEnumerable<PaymentType> paymentTypes, ForeignCurrency foreignCurrency)
        {
            var result = new List<CommandButtonViewModel<PaymentType>>();
            if (_settleCommand != null)
            {
                result.Add(new CommandButtonViewModel<PaymentType>
                {
                    Caption = Resources.Settle,
                    Command = _settleCommand,
                });
            }

            var pts = foreignCurrency == null ? paymentTypes.Where(x => x.Account == null || x.Account.ForeignCurrencyId == 0) : paymentTypes.Where(x => x.Account != null && x.Account.ForeignCurrencyId == foreignCurrency.Id);
            result.AddRange(pts
                .OrderBy(x => x.SortOrder)
                .Select(x => new CommandButtonViewModel<PaymentType>
                {
                    Caption = x.Name.Replace(" ", "\r"),
                    Command = _makePaymentCommand,
                    Color = x.ButtonColor,
                    Parameter = x
                }));

            if (_closeCommand != null)
            {
                result.Add(new CommandButtonViewModel<PaymentType>
                {
                    Caption = Resources.Close,
                    Command = _closeCommand,
                    Color = "Red"
                });
            }
            return result;
        }
 public static IEnumerable <T> Sample <T>(this IEnumerable <T> source, int interval)
 {
     return(source?.Where((value, index) => (index + 1) % interval == 0));
 }
Example #32
0
 public static IDictionary ToDictionary(this IEnumerable <PropertyInfo> properties)
 {
     return(properties?
            .Where(property => !string.IsNullOrWhiteSpace(property.GetValue(null) as string))
            .ToDictionary(property => property.Name.CamelCase(), property => (property.GetValue(null) as string)));
 }
Example #33
0
 public Paragraph(ParagraphType type, IEnumerable <XmlDocNode> content)
 {
     Type    = type;
     Content = new ReadOnlyCollection <XmlDocNode>(content?.Where(n => n != null).ToList() ?? new List <XmlDocNode>());
 }
Example #34
0
 public MarketPrices(IEnumerable <MarketPrices> prices) : this(prices?.Where(x => x != null).SelectMany(x => x.PricesList))
 {
 }
 private IEnumerable <SelectOption> GetOptions(string propertyName)
 => _options?.Where(opt => opt.PropertyName == propertyName).FirstOrDefault()?.Items;
Example #36
0
 /// <summary>
 /// Найти подписи по идентификаторам
 /// </summary>
 public IEnumerable <ISignatureLibraryApp> FindByIds(IEnumerable <string> ids) =>
 ids?.Where(id => _signaturesLibrary.ContainsKey(id)).
 Select(id => _signaturesLibrary[id]);
Example #37
0
 public IEnumerable <Product> Filter(IEnumerable <Product> items)
 {
     return(items?.Where(product => product.Size == _size));
 }
Example #38
0
 public IEnumerable <Product> Filter(IEnumerable <Product> items)
 {
     return(items?.Where(product => product.Color == _color));
 }
Example #39
0
 // breaks Open close principle. (every time when you add new filter)
 public IEnumerable <Product> BySize(IEnumerable <Product> products, Size size)
 {
     return(products?.Where(product => product.Size == size));
 }
Example #40
0
 private static IEnumerable <string> CustomProgramPaths(IEnumerable <ProgramSource> sources, IList <string> suffixes)
 => sources?.Where(programSource => Directory.Exists(programSource.Location) && programSource.Enabled)
 .SelectMany(programSource => ProgramPaths(programSource.Location, suffixes))
 .ToList() ?? Enumerable.Empty <string>();
 internal static DetectedFace FindFaceClosestToRegion(IEnumerable <DetectedFace> faces, BitmapBounds region)
 {
     return(faces?.Where(f => Util.AreFacesPotentiallyTheSame(region, f.FaceRectangle))
            .OrderBy(f => Math.Abs(region.X - f.FaceRectangle.Left) + Math.Abs(region.Y - f.FaceRectangle.Top)).FirstOrDefault());
 }
Example #42
0
 public void SetInputs(IEnumerable <IDocument> inputs) =>
 Inputs = inputs?.Where(x => x != null).ToImmutableArray() ?? ImmutableArray <IDocument> .Empty;
 public static string JoinIgnoreEmpty(this IEnumerable <string> values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v)));
Example #44
0
 public static IEnumerable <T> WithoutChangeAction <T>(this IEnumerable <T> rows, params ChangeAction?[] changeActions)
     where T : IMergeableRow
 => rows?.Where(i => !changeActions.Contains(i.ChangeAction));
Example #45
0
        /// <summary>
        /// Creates a SQL Statement for update-all operation.
        /// </summary>
        /// <param name="queryBuilder">The query builder to be used.</param>
        /// <param name="tableName">The name of the target table.</param>
        /// <param name="fields">The list of fields to be updated.</param>
        /// <param name="qualifiers">The list of the qualifier <see cref="Field"/> objects.</param>
        /// <param name="batchSize">The batch size of the operation.</param>
        /// <param name="primaryField">The primary field from the database.</param>
        /// <param name="identityField">The identity field from the database.</param>
        /// <returns>A sql statement for update-all operation.</returns>
        public virtual string CreateUpdateAll(QueryBuilder queryBuilder,
                                              string tableName,
                                              IEnumerable <Field> fields,
                                              IEnumerable <Field> qualifiers,
                                              int batchSize         = Constant.DefaultBatchOperationSize,
                                              DbField primaryField  = null,
                                              DbField identityField = null)
        {
            // Ensure with guards
            GuardTableName(tableName);
            GuardPrimary(primaryField);
            GuardIdentity(identityField);

            // Validate the multiple statement execution
            ValidateMultipleStatementExecution(batchSize);

            // Ensure the fields
            if (fields?.Any() != true)
            {
                throw new EmptyException($"The list of fields cannot be null or empty.");
            }

            // Check the qualifiers
            if (qualifiers?.Any() == true)
            {
                // Check if the qualifiers are present in the given fields
                var unmatchesQualifiers = qualifiers?.Where(field =>
                                                            fields?.FirstOrDefault(f =>
                                                                                   string.Equals(field.Name, f.Name, StringComparison.OrdinalIgnoreCase)) == null);

                // Throw an error we found any unmatches
                if (unmatchesQualifiers?.Any() == true)
                {
                    throw new InvalidQualifiersException($"The qualifiers '{unmatchesQualifiers.Select(field => field.Name).Join(", ")}' are not " +
                                                         $"present at the given fields '{fields.Select(field => field.Name).Join(", ")}'.");
                }
            }
            else
            {
                if (primaryField != null)
                {
                    // Make sure that primary is present in the list of fields before qualifying to become a qualifier
                    var isPresent = fields?.FirstOrDefault(f =>
                                                           string.Equals(f.Name, primaryField.Name, StringComparison.OrdinalIgnoreCase)) != null;

                    // Throw if not present
                    if (isPresent == false)
                    {
                        throw new InvalidQualifiersException($"There are no qualifier field objects found for '{tableName}'. Ensure that the " +
                                                             $"primary field is present at the given fields '{fields.Select(field => field.Name).Join(", ")}'.");
                    }

                    // The primary is present, use it as a default if there are no qualifiers given
                    qualifiers = primaryField.AsField().AsEnumerable();
                }
                else
                {
                    // Throw exception, qualifiers are not defined
                    throw new NullReferenceException($"There are no qualifier field objects found for '{tableName}'.");
                }
            }

            // Gets the updatable fields
            fields = fields
                     .Where(f => !string.Equals(f.Name, primaryField?.Name, StringComparison.OrdinalIgnoreCase) &&
                            !string.Equals(f.Name, identityField?.Name, StringComparison.OrdinalIgnoreCase) &&
                            qualifiers.FirstOrDefault(q => string.Equals(q.Name, f.Name, StringComparison.OrdinalIgnoreCase)) == null);

            // Check if there are updatable fields
            if (fields?.Any() != true)
            {
                throw new EmptyException("The list of updatable fields cannot be null or empty.");
            }

            // Initialize the builder
            var builder = queryBuilder ?? new QueryBuilder();

            // Build the query
            builder.Clear();

            // Iterate the indexes
            for (var index = 0; index < batchSize; index++)
            {
                queryBuilder
                .Update()
                .TableNameFrom(tableName, DbSetting)
                .Set()
                .FieldsAndParametersFrom(fields, index, DbSetting)
                .WhereFrom(qualifiers, index, DbSetting)
                .End();
            }

            // Return the query
            return(builder.GetString());
        }
 public ValidationError(IEnumerable <string> fields, string error)
 {
     this.fields = fields?.Where(x => !string.IsNullOrWhiteSpace(x))?.Select(x => x.Trim())?.ToArray() ?? new string[0];
     this.error  = error ?? string.Empty;
 }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="connection"></param>
        /// <param name="tableName"></param>
        /// <param name="dbFields"></param>
        /// <param name="batchSize"></param>
        /// <param name="fields"></param>
        /// <param name="commandText"></param>
        /// <returns></returns>
        private static InsertAllExecutionContext <TEntity> CreateInternal <TEntity>(IDbConnection connection,
                                                                                    string tableName,
                                                                                    IEnumerable <DbField> dbFields,
                                                                                    int batchSize,
                                                                                    IEnumerable <Field> fields,
                                                                                    string commandText)
            where TEntity : class
        {
            var dbSetting       = connection.GetDbSetting();
            var identity        = (Field)null;
            var inputFields     = (IEnumerable <DbField>)null;
            var identityDbField = dbFields?.FirstOrDefault(f => f.IsIdentity);

            // Set the identity field
            identity = IdentityCache.Get <TEntity>()?.AsField() ??
                       FieldCache
                       .Get <TEntity>()?
                       .FirstOrDefault(field =>
                                       string.Equals(field.Name.AsUnquoted(true, dbSetting), identityDbField?.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) ??
                       identityDbField?.AsField();

            // Filter the actual properties for input fields
            inputFields = dbFields?
                          .Where(dbField => dbField.IsIdentity == false)
                          .Where(dbField =>
                                 fields.FirstOrDefault(field => string.Equals(field.Name.AsUnquoted(true, dbSetting), dbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) != null)
                          .AsList();

            // Variables for the context
            var multipleEntitiesFunc = (Action <DbCommand, IList <TEntity> >)null;
            var identitySettersFunc  = (List <Action <TEntity, DbCommand> >)null;
            var singleEntityFunc     = (Action <DbCommand, TEntity>)null;
            var identitySetterFunc   = (Action <TEntity, object>)null;

            // Get if we have not skipped it
            if (identity != null)
            {
                identitySetterFunc = FunctionCache.GetDataEntityPropertySetterCompiledFunction <TEntity>(identity);
            }

            // Identity which objects to set
            if (batchSize <= 1)
            {
                singleEntityFunc = FunctionCache.GetDataEntityDbParameterSetterCompiledFunction <TEntity>(
                    string.Concat(typeof(TEntity).FullName, StringConstant.Period, tableName, ".InsertAll"),
                    inputFields?.AsList(),
                    null,
                    dbSetting);
            }
            else
            {
                multipleEntitiesFunc = FunctionCache.GetDataEntityListDbParameterSetterCompiledFunction <TEntity>(
                    string.Concat(typeof(TEntity).FullName, StringConstant.Period, tableName, ".InsertAll"),
                    inputFields?.AsList(),
                    null,
                    batchSize,
                    dbSetting);
            }

            // Return the value
            return(new InsertAllExecutionContext <TEntity>
            {
                CommandText = commandText,
                InputFields = inputFields,
                BatchSize = batchSize,
                SingleDataEntityParametersSetterFunc = singleEntityFunc,
                MultipleDataEntitiesParametersSetterFunc = multipleEntitiesFunc,
                IdentityPropertySetterFunc = identitySetterFunc,
                IdentityPropertySettersFunc = identitySettersFunc
            });
        }
Example #48
0
 public static IEnumerable <T> NotNull <T>(this IEnumerable <T> items)
 => items?.Where(i => i != null) ?? Array.Empty <T>();
Example #49
0
 static public ShipCargoSpaceTypeEnum?FromIventoryLabelParseShipCargoSpaceType(
     this string ShipCargoSpaceTypeLabel) =>
 InventoryCargoTypeAndSetLabel?.Where(CargoSpaceTypeAndSetLabel =>
                                      CargoSpaceTypeAndSetLabel.Value?.Any(Label => Label.EqualsIgnoreCase(ShipCargoSpaceTypeLabel)) ?? false)
 ?.CastToNullable()?.FirstOrDefault()?.Key;
Example #50
0
        /// <summary>
        /// 同步产品库
        /// </summary>
        private Dictionary <string, string> SyncProdcutLibrary(SE_MDBeautyCategoryProductConfigModel model, string userName)
        {
            lock (SyncLock_Save)
            {
                CachingLogsHelp.CacheItemRemove();

                List <string> SyncProdcutLibraryLog       = new List <string>();
                Dictionary <string, string> dicSQL        = new Dictionary <string, string>();
                List <BatchTreeModel>       dataTreeItems = JsonConvert.DeserializeObject <List <BatchTreeModel> >(model?.Brands);

                if (dataTreeItems != null && dataTreeItems.Any())
                {
                    #region 检测产品
                    var           _AdaptiveCarCheckBox = model.AdaptiveCarCheckBox?.Split(',');
                    List <string> sqlWhere             = new List <string>();
                    if (_AdaptiveCarCheckBox != null && _AdaptiveCarCheckBox.Any())
                    {
                        if (dataTreeItems != null && dataTreeItems.Any())
                        {
                            foreach (var a in dataTreeItems)
                            {
                                if (!string.IsNullOrWhiteSpace(a.CategorysName))
                                {
                                    if (a.Childs != null && a.Childs.Any())
                                    {
                                        foreach (var b in a.Childs)
                                        {
                                            foreach (var c in _AdaptiveCarCheckBox?.ToList())
                                            {
                                                sqlWhere.Add(string.Format("{0}|{1}|{2}", model.CategoryIds, a.ParentId + "," + b.Id, c));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        foreach (var c in _AdaptiveCarCheckBox?.ToList())
                                        {
                                            sqlWhere.Add(string.Format("{0}|{1}|{2}", model.CategoryIds, a.ParentId, c));
                                        }
                                    }
                                }
                                else
                                {
                                    SyncProdcutLibraryLog.Add($"检测产品: {model.Brands} 数据异常,请打开重试!,操作时间:{DateTime.Now.ToString()}");
                                }
                            }
                        }
                    }
                    string checkSQL = @"SELECT * FROM 
                               (
	                                SELECT ISNULL(CategoryIds,'') + '|' + ISNULL(Brands,'') + '|'+ ISNULL(CONVERT(nvarchar,AdaptiveCar),'') as 'TreeItems',* FROM SE_MDBeautyCategoryProductConfig WITH(NOLOCK)
                               ) AS tab1
                               WHERE tab1.TreeItems IN(" + "'" + string.Join("','", sqlWhere) + "'" + ")";

                    IEnumerable <SE_MDBeautyCategoryProductConfigModel> dataList = SE_MDBeautyCategoryProductConfigBLL.CustomQuery <SE_MDBeautyCategoryProductConfigModel>(checkSQL);
                    #endregion

                    #region 公共变量
                    string sqlInsert = @" INSERT [SE_MDBeautyCategoryProductConfig] (
                                             [ProdcutId],
                                             [ProdcutName],
                                             [CategoryIds],
                                             [Describe],
                                             [Commission],
                                             [BeginPrice],
                                             [EndPrice],
                                             [BeginPromotionPrice],
                                             [EndPromotionPrice],
                                             [EveryDayNum],
                                             [Brands],
                                             [RecommendCar],
                                             [AdaptiveCar],
                                             [IsDisable],
                                             [CreateTime],
                                             [IsNotShow]) VALUES ";

                    string sqlUpdate = @" UPDATE [SE_MDBeautyCategoryProductConfig]
                                           SET [ProdcutName] = {1}
                                              ,[Describe] = {2}
                                              ,[Commission] = @Commission
                                              ,[BeginPrice] = @BeginPrice
                                              ,[EndPrice] = @EndPrice
                                              ,[BeginPromotionPrice] = @BeginPromotionPrice
                                              ,[EndPromotionPrice] = @EndPromotionPrice
                                              ,[EveryDayNum] = @EveryDayNum
                                              ,[IsDisable] = @IsDisable
                                              ,[CreateTime] = GETDATE()
                                              ,[IsNotShow]=@IsNotShow 
                                          WHERE PId IN({0}) ";

                    List <string> sqlInsertWhere = new List <string>();
                    List <SE_MDBeautyCategoryProductConfigModel> sqlUpdateWhere = new List <SE_MDBeautyCategoryProductConfigModel>();
                    #endregion

                    #region 遍历品牌
                    foreach (var item in dataTreeItems)
                    {
                        if (!string.IsNullOrWhiteSpace(item.CategorysName))
                        {
                            if (item.Childs != null && item.Childs.Any()) //判断是否遍历子系列
                            {
                                #region 遍历系列
                                foreach (var itemChilds in item.Childs)
                                {
                                    #region 遍历车型
                                    using (IProductClient client = new ProductClient())
                                    {
                                        foreach (var itemCar in _AdaptiveCarCheckBox?.ToList())
                                        {
                                            Thread.Sleep(2000); //延时操作

                                            string itemCarName = (itemCar == "1" ? "五座轿车"
                                                                : itemCar == "2" ? "SUV/MPV"
                                                                : itemCar == "3" ? "SUV"
                                                                : itemCar == "4" ? "MPV"
                                                                : "");

                                            string _TreeItems   = string.Format("{0}|{1}|{2}", model.CategoryIds, item.ParentId + "," + itemChilds.Id, itemCar);
                                            var    _compareData = dataList?.Where(_ => _.TreeItems == _TreeItems)?.FirstOrDefault();
                                            if (_compareData == null)
                                            {
                                                #region  步添加到产品库
                                                Service.OperationResult <string> createResult = client.CreateProductV2(
                                                    new WholeProductInfo
                                                {
                                                    Name                  = item.Name + itemChilds.Name + itemCarName + item.CategorysName,
                                                    DisplayName           = item.Name + itemChilds.Name + itemCarName + item.CategorysName,
                                                    Description           = model.Describe?.Replace("$1", item.CategorysName)?.Replace("$2", itemChilds.Name),
                                                    PrimaryParentCategory = model.PrimaryParentCategory,
                                                    ProductID             = model.ProdcutId, //Common.PinYinConverter.ConvertToFirstSpell(item.Name + itemChilds.Name + itemCarName + item.CategorysName),
                                                    VariantID             = null,
                                                    Image_filename        = model.Image_filename,
                                                    CatalogName           = "CarPAR",
                                                    DefinitionName        = model.DefinitionName,
                                                    CreateDatetime        = DateTime.Now
                                                },
                                                    userName,
                                                    ChannelType.MenDian);

                                                if (createResult.Success && !string.IsNullOrWhiteSpace(createResult?.Result))
                                                {
                                                    sqlInsertWhere.Add(string.Format(" ( N'{14}',N'{0}',N'{1}',N'{2}',{3},{4},{5},{6},{7},{8},N'{9}',{10},{11},{12},N'{13}',{15}) \r\n",
                                                                                     item.Name + itemChilds.Name + itemCarName + item.CategorysName,
                                                                                     model.CategoryIds,
                                                                                     model.Describe?.Replace("$1", item.CategorysName)?.Replace("$2", itemChilds.Name),
                                                                                     model.Commission,
                                                                                     model.BeginPrice,
                                                                                     model.EndPrice,
                                                                                     model.BeginPromotionPrice,
                                                                                     model.EndPromotionPrice,
                                                                                     model.EveryDayNum,
                                                                                     item.ParentId + "," + itemChilds.Id,
                                                                                     model.RecommendCar,
                                                                                     itemCar,
                                                                                     model.IsDisable.GetHashCode(),
                                                                                     model.CreateTime,
                                                                                     createResult.Result, //产品ID
                                                                                     model.IsNotShow.GetHashCode()
                                                                                     ));
                                                }
                                                SyncProdcutLibraryLog.Add($"子集:添加,操作人:{userName},ErrorMessage:{createResult.ErrorMessage},Exception:{createResult.Exception},ErrorCode:{createResult.ErrorCode},Result:{createResult.Result},Success:{createResult.Success},操作时间:{DateTime.Now.ToString()}");
                                                #endregion
                                            }
                                            else
                                            {
                                                #region  步修改产品库
                                                Service.OperationResult <bool> updateResult = client.UpdateProduct(
                                                    new WholeProductInfo
                                                {
                                                    Name                  = item.Name + itemChilds.Name + itemCarName + item.CategorysName,
                                                    DisplayName           = item.Name + itemChilds.Name + itemCarName + item.CategorysName,
                                                    Description           = model.Describe?.Replace("$1", item.CategorysName)?.Replace("$2", ""),
                                                    PrimaryParentCategory = model.PrimaryParentCategory,
                                                    ProductID             = _compareData.ProdcutId.Split('|')[0],
                                                    VariantID             = _compareData.ProdcutId.Split('|')[1],
                                                    Image_filename        = model.Image_filename,
                                                    CatalogName           = "CarPAR",
                                                    DefinitionName        = model.DefinitionName
                                                },
                                                    userName,
                                                    ChannelType.MenDian);

                                                if (updateResult.Success && updateResult.Result)
                                                {
                                                    sqlUpdateWhere.Add(new SE_MDBeautyCategoryProductConfigModel()
                                                    {
                                                        ProdcutId   = _compareData.ProdcutId,
                                                        PId         = _compareData.PId,
                                                        ProdcutName = item.Name + itemChilds.Name + itemCarName + item.CategorysName,
                                                        Describe    = model.Describe?.Replace("$1", item.CategorysName)?.Replace("$2", itemChilds.Name),
                                                    });
                                                }
                                                SyncProdcutLibraryLog.Add($"子集:修改,操作人:{userName},ErrorMessage:{updateResult.ErrorMessage},Exception:{updateResult.Exception},ErrorCode:{updateResult.ErrorCode},ProdcutId:{_compareData.ProdcutId},Result:{updateResult.Result},Success:{updateResult.Success},操作时间:{DateTime.Now.ToString()}");
                                                #endregion
                                            }
                                        }
                                    }
                                    #endregion
                                }
                                #endregion
                            }
                            else
                            {
                                #region 遍历车型
                                using (IProductClient client = new ProductClient())
                                {
                                    foreach (var itemCar in _AdaptiveCarCheckBox?.ToList())
                                    {
                                        Thread.Sleep(2000); //延时操作

                                        string itemCarName = (itemCar == "1" ? "五座轿车"
                                                            : itemCar == "2" ? "SUV/MPV"
                                                            : itemCar == "3" ? "SUV"
                                                            : itemCar == "4" ? "MPV"
                                                            : "");

                                        string _TreeItems   = string.Format("{0}|{1}|{2}", model.CategoryIds, item.ParentId, itemCar);
                                        var    _compareData = dataList?.Where(_ => _.TreeItems == _TreeItems)?.FirstOrDefault();
                                        if (_compareData == null)
                                        {
                                            #region  步添加到产品库
                                            Service.OperationResult <string> createResult = client.CreateProductV2(
                                                new WholeProductInfo
                                            {
                                                Name                  = item.Name + itemCarName + item.CategorysName,
                                                DisplayName           = item.Name + itemCarName + item.CategorysName,
                                                Description           = model.Describe?.Replace("$1", item.CategorysName)?.Replace("$2", ""),
                                                PrimaryParentCategory = model.PrimaryParentCategory,
                                                ProductID             = model.ProdcutId, //Common.PinYinConverter.ConvertToFirstSpell(item.Name + itemCarName + item.CategorysName),
                                                VariantID             = null,
                                                Image_filename        = model.Image_filename,
                                                CatalogName           = "CarPAR",
                                                DefinitionName        = model.DefinitionName
                                            },
                                                userName,
                                                ChannelType.MenDian);

                                            if (createResult.Success && !string.IsNullOrWhiteSpace(createResult?.Result))
                                            {
                                                sqlInsertWhere.Add(string.Format(" ( N'{14}',N'{0}',N'{1}',N'{2}',{3},{4},{5},{6},{7},{8},N'{9}',{10},{11},{12},N'{13}',{15}) \r\n",
                                                                                 item.Name + itemCarName + item.CategorysName,
                                                                                 model.CategoryIds,
                                                                                 model.Describe?.Replace("$1", item.CategorysName)?.Replace("$2", ""),
                                                                                 model.Commission,
                                                                                 model.BeginPrice,
                                                                                 model.EndPrice,
                                                                                 model.BeginPromotionPrice,
                                                                                 model.EndPromotionPrice,
                                                                                 model.EveryDayNum,
                                                                                 item.ParentId,
                                                                                 model.RecommendCar,
                                                                                 itemCar,
                                                                                 model.IsDisable.GetHashCode(),
                                                                                 model.CreateTime,
                                                                                 createResult.Result, //产品ID
                                                                                 model.IsNotShow.GetHashCode()
                                                                                 ));
                                            }
                                            SyncProdcutLibraryLog.Add($"添加,操作人:{userName},ErrorMessage:{createResult.ErrorMessage},Exception:{createResult.Exception},ErrorCode:{createResult.ErrorCode},Result:{createResult.Result},Success:{createResult.Success},操作时间:{DateTime.Now.ToString()}");
                                            #endregion
                                        }
                                        else
                                        {
                                            #region  步修改产品库
                                            Service.OperationResult <bool> updateResult = client.UpdateProduct(
                                                new WholeProductInfo
                                            {
                                                Name                  = item.Name + itemCarName + item.CategorysName,
                                                DisplayName           = item.Name + itemCarName + item.CategorysName,
                                                Description           = model.Describe?.Replace("$1", item.CategorysName)?.Replace("$2", ""),
                                                PrimaryParentCategory = model.PrimaryParentCategory,
                                                ProductID             = _compareData.ProdcutId.Split('|')[0],
                                                VariantID             = _compareData.ProdcutId.Split('|')[1],
                                                Image_filename        = model.Image_filename,
                                                CatalogName           = "CarPAR",
                                                DefinitionName        = model.DefinitionName
                                            },
                                                userName,
                                                ChannelType.MenDian);

                                            if (updateResult.Success && updateResult.Result)
                                            {
                                                sqlUpdateWhere.Add(new SE_MDBeautyCategoryProductConfigModel()
                                                {
                                                    ProdcutId   = _compareData.ProdcutId,
                                                    PId         = _compareData.PId,
                                                    ProdcutName = item.Name + itemCarName + item.CategorysName,
                                                    Describe    = model.Describe?.Replace("$1", item.CategorysName)?.Replace("$2", ""),
                                                });
                                            }
                                            SyncProdcutLibraryLog.Add($"修改,操作人:{userName},ErrorMessage:{updateResult.ErrorMessage},Exception:{updateResult.Exception},ErrorCode:{updateResult.ErrorCode},ProdcutId:{_compareData.ProdcutId},Result:{updateResult.Result},Success:{updateResult.Success},操作时间:{DateTime.Now.ToString()}");
                                            #endregion
                                        }
                                    }
                                }
                                #endregion
                            }
                        }
                        else
                        {
                            SyncProdcutLibraryLog.Add($"遍历品牌: {model.Brands} 数据异常,请打开重试!,操作时间:{DateTime.Now.ToString()}");
                        }
                    }
                    #endregion

                    #region 拼接条件
                    if (sqlInsertWhere != null && sqlInsertWhere.Any())
                    {
                        dicSQL.Add("INSERT", sqlInsert + string.Join(",", sqlInsertWhere));
                    }

                    if (sqlUpdateWhere != null && sqlUpdateWhere.Any())
                    {
                        string _ProdcutName = " CASE PId ", _Describe = " CASE PId ";

                        foreach (var item in sqlUpdateWhere)
                        {
                            _ProdcutName += string.Format("WHEN {0} THEN N'{1}'", item.PId, item.ProdcutName);
                            _Describe    += string.Format("WHEN {0} THEN N'{1}'", item.PId, item.Describe);
                        }
                        _ProdcutName += " END ";
                        _Describe    += " END ";

                        dicSQL.Add("UPDATE", string.Format(sqlUpdate, string.Join(",", sqlUpdateWhere.Select(s => s.PId)), _ProdcutName, _Describe));
                    }
                    #endregion
                }
                else
                {
                    SyncProdcutLibraryLog.Add($"入口: dataTreeItems = null , Brands = {model.Brands} !,操作时间:{DateTime.Now.ToString()}");
                }

                CachingLogsHelp.AddOrGetExisting(SyncProdcutLibraryLog);
                return(dicSQL);
            }
        }
Example #51
0
 public static string JoinNonNullNonEmpty(string joinString, IEnumerable <string> objects) => string.Join(joinString, objects?.Where(s => !string.IsNullOrWhiteSpace(s)));
        /// <summary>
        /// Applies the modifications in the memory structures.
        /// </summary>
        protected override void Apply(SecurityContext context)
        {
            var relevantAcls = _acls?.Where(x => !_emptyAcls.Contains(x.EntityId)).ToArray() ?? new AclInfo[0];

            SecurityEntity.ApplyAclEditing(context, relevantAcls, _breaks, _unbreaks, _entriesToRemove, _emptyAcls);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="connection"></param>
        /// <param name="entities"></param>
        /// <param name="dbFields"></param>
        /// <param name="tableName"></param>
        /// <param name="qualifiers"></param>
        /// <param name="batchSize"></param>
        /// <param name="fields"></param>
        /// <param name="commandText"></param>
        /// <returns></returns>
        private static MergeAllExecutionContext CreateInternal(Type entityType,
                                                               IDbConnection connection,
                                                               IEnumerable <object> entities,
                                                               IEnumerable <DbField> dbFields,
                                                               string tableName,
                                                               IEnumerable <Field> qualifiers,
                                                               int batchSize,
                                                               IEnumerable <Field> fields,
                                                               string commandText)
        {
            var dbSetting       = connection.GetDbSetting();
            var identity        = (Field)null;
            var inputFields     = (IEnumerable <DbField>)null;
            var identityDbField = dbFields?.FirstOrDefault(f => f.IsIdentity);

            // Check the fields
            if (fields?.Any() != true)
            {
                fields = dbFields?.AsFields();
            }

            // Check the qualifiers
            if (qualifiers?.Any() != true)
            {
                var primary = dbFields?.FirstOrDefault(dbField => dbField.IsPrimary == true);
                qualifiers = primary?.AsField().AsEnumerable();
            }

            // Set the identity field
            identity = IdentityCache.Get(entityType)?.AsField() ??
                       FieldCache
                       .Get(entityType)?
                       .FirstOrDefault(field =>
                                       string.Equals(field.Name.AsUnquoted(true, dbSetting), identityDbField?.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) ??
                       identityDbField?.AsField();

            // Filter the actual properties for input fields
            inputFields = dbFields?
                          .Where(dbField =>
                                 fields.FirstOrDefault(field => string.Equals(field.Name.AsUnquoted(true, dbSetting), dbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) != null)
                          .AsList();

            // Exclude the fields not on the actual entity
            if (entityType.IsClassType() == false)
            {
                var entityFields = Field.Parse(entities?.FirstOrDefault());
                inputFields = inputFields?
                              .Where(field =>
                                     entityFields.FirstOrDefault(f => string.Equals(f.Name.AsUnquoted(true, dbSetting), field.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) != null)
                              .AsList();
            }

            // Variables for the context
            var multipleEntitiesFunc = (Action <DbCommand, IList <object> >)null;
            var singleEntityFunc     = (Action <DbCommand, object>)null;
            var identitySetterFunc   = (Action <object, object>)null;

            // Get if we have not skipped it
            if (identity != null)
            {
                identitySetterFunc = FunctionCache.GetDataEntityPropertySetterCompiledFunction(entityType, identity);
            }

            // Identity which objects to set
            if (batchSize <= 1)
            {
                singleEntityFunc = FunctionCache.GetDataEntityDbParameterSetterCompiledFunction(entityType,
                                                                                                string.Concat(entityType.FullName, StringConstant.Period, tableName, ".MergeAll"),
                                                                                                inputFields,
                                                                                                null,
                                                                                                dbSetting);
            }
            else
            {
                multipleEntitiesFunc = FunctionCache.GetDataEntityListDbParameterSetterCompiledFunction(entityType,
                                                                                                        string.Concat(entityType.FullName, StringConstant.Period, tableName, ".MergeAll"),
                                                                                                        inputFields,
                                                                                                        null,
                                                                                                        batchSize,
                                                                                                        dbSetting);
            }

            // Return the value
            return(new MergeAllExecutionContext
            {
                CommandText = commandText,
                InputFields = inputFields,
                BatchSize = batchSize,
                SingleDataEntityParametersSetterFunc = singleEntityFunc,
                MultipleDataEntitiesParametersSetterFunc = multipleEntitiesFunc,
                IdentityPropertySetterFunc = identitySetterFunc
            });
        }
Example #54
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="connection"></param>
        /// <param name="dbFields"></param>
        /// <param name="tableName"></param>
        /// <param name="qualifiers"></param>
        /// <param name="fields"></param>
        /// <param name="hints"></param>
        /// <param name="transaction"></param>
        /// <param name="statementBuilder"></param>
        /// <returns></returns>
        private static MergeExecutionContext <TEntity> CreateInternal <TEntity>(IDbConnection connection,
                                                                                IEnumerable <DbField> dbFields,
                                                                                string tableName,
                                                                                IEnumerable <Field> qualifiers,
                                                                                IEnumerable <Field> fields,
                                                                                string hints = null,
                                                                                IDbTransaction transaction         = null,
                                                                                IStatementBuilder statementBuilder = null)
            where TEntity : class
        {
            var typeOfEntity    = typeof(TEntity);
            var dbSetting       = connection.GetDbSetting();
            var identity        = (Field)null;
            var inputFields     = new List <DbField>();
            var identityDbField = dbFields?.FirstOrDefault(f => f.IsIdentity);

            // Set the identity field
            if (typeOfEntity.IsClassType())
            {
                identity = IdentityCache.Get <TEntity>()?.AsField() ??
                           FieldCache
                           .Get <TEntity>()?
                           .FirstOrDefault(field =>
                                           string.Equals(field.Name.AsUnquoted(true, dbSetting), identityDbField?.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) ??
                           identityDbField?.AsField();
            }

            // Filter the actual properties for input fields
            inputFields = dbFields?
                          .Where(dbField =>
                                 fields.FirstOrDefault(field => string.Equals(field.Name.AsUnquoted(true, dbSetting), dbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) != null)
                          .AsList();

            // Variables for the entity action
            var identityPropertySetter = (Action <TEntity, object>)null;

            // Get the identity setter
            if (typeOfEntity.IsClassType() == true && identity != null)
            {
                identityPropertySetter = FunctionCache.GetDataEntityPropertySetterCompiledFunction <TEntity>(identity);
            }

            // Identify the requests
            var mergeRequest = new MergeRequest(tableName,
                                                connection,
                                                transaction,
                                                fields,
                                                qualifiers,
                                                hints,
                                                statementBuilder);

            // Return the value
            return(new MergeExecutionContext <TEntity>
            {
                CommandText = CommandTextCache.GetMergeText(mergeRequest),
                InputFields = inputFields,
                ParametersSetterFunc = FunctionCache.GetDataEntityDbParameterSetterCompiledFunction <TEntity>(
                    string.Concat(typeof(TEntity).FullName, StringConstant.Period, tableName, ".Merge"),
                    inputFields?.AsList(),
                    null,
                    dbSetting),
                IdentityPropertySetterFunc = identityPropertySetter
            });
        }
Example #55
0
 public static IEnumerable <CodeFragment> FilterCallableSpecializations(IEnumerable <CodeFragment> fragments) =>
 fragments?.Where(IsCallableSpecialization);
Example #56
0
 public ContextChannelsPacket(IEnumerable <IChannel> channels)
 {
     Channels = channels?.Where(c => c != null) ?? throw new ArgumentNullException(nameof(channels));
 }
        private IEnumerable <IVehicle> FilterByBranchTags(IEnumerable <IVehicle> vehicles, IEnumerable <EVehicleBranchTag> validTags, Func <IVehicle, IVehicleTags> tagLocator, bool suppressLogging)
        {
            var filteredVehicles = vehicles?.Where(vehicle => tagLocator(vehicle)?[validTags] ?? true).AsParallel().ToList() ?? new List <IVehicle>();

            return(AssessFilterResult(filteredVehicles, validTags, suppressLogging));
        }
 public int CountExpiredElements(IEnumerable <string> keys)
 {
     return(keys?.Where(k => Get(k) == null).Count() ?? 0);
 }
Example #59
0
 public IEnumerable <Product> ByColor(IEnumerable <Product> products, Color color)
 {
     return(products?.Where(product => product.Color == color));
 }
Example #60
0
 public static IEnumerable <CodeFragment> FilterCallableDeclarations(IEnumerable <CodeFragment> fragments) =>
 fragments?.Where(IsCallableDeclaration);