public DisableAndEnableButtons() { _modules = CreateMenuElementGroup() ; _toolbar = CreateMenuElements(); AddAction("Enable Toolbar", () => _toolbar.ForEach(x => x.Enable())); AddAction("Disable Toolbar", () => _toolbar.ForEach(x => x.Disable())); }
public ActionResult Create([Bind(Include = "AuditId,ProjectId,ServiceType,PlannedDate,Status,Auditors,Result")] Audit createdAudit, IEnumerable <HttpPostedFileBase> uploads) { if (ModelState.IsValid) { if (createdAudit.Status.Equals(AuditStatuses.Closed) || createdAudit.Status.Equals(AuditStatuses.Passed)) { createdAudit.LastAuditDate = DateTime.Today; } uploads?.ForEach(upload => { if (upload == null || upload.ContentLength == 0) { return; } var file = new File { FileName = System.IO.Path.GetFileName(upload.FileName), ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { file.Content = reader.ReadBytes(upload.ContentLength); } createdAudit.Files.Add(file); }); db.Audits.Add(createdAudit); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.ProjectId = new SelectList(db.Projects, "ProjectId", "Name", createdAudit.ProjectId); return(View(createdAudit)); }
public Room(string uid, IEnumerable <string> neighbors, Component lamp, IDaylightService daylightService, IConcurrencyProvider concurrencyProvider, ILogger logger, AreaDescriptor areaDescriptor, MotionConfiguration motionConfiguration, IEnumerable <IEventDecoder> eventsDecoders) { Uid = uid ?? throw new ArgumentNullException(nameof(uid)); Neighbors = neighbors ?? throw new ArgumentNullException(nameof(neighbors)); Lamp = lamp ?? throw new ArgumentNullException(nameof(lamp)); if (areaDescriptor.WorkingTime == WorkingTime.DayLight) { _turnOnConditionsValidator.WithCondition(ConditionRelation.And, new IsDayCondition(daylightService)); } else if (areaDescriptor.WorkingTime == WorkingTime.AfterDusk) { _turnOnConditionsValidator.WithCondition(ConditionRelation.And, new IsNightCondition(daylightService)); } _turnOnConditionsValidator.WithCondition(ConditionRelation.And, new IsEnabledAutomationCondition(this)); _turnOffConditionsValidator.WithCondition(ConditionRelation.And, new IsEnabledAutomationCondition(this)); _turnOffConditionsValidator.WithCondition(ConditionRelation.And, new IsTurnOffAutomaionCondition(this)); _logger = logger; _motionConfiguration = motionConfiguration; _concurrencyProvider = concurrencyProvider; _eventsDecoders = eventsDecoders; AreaDescriptor = areaDescriptor; _TurnOffTimeOut = new Timeout(AreaDescriptor.TurnOffTimeout, _motionConfiguration.TurnOffPresenceFactor); _eventsDecoders?.ForEach(decoder => decoder.Init(this)); }
/// <summary> /// To extract prepared raw-data. /// </summary> /// <param name="data">Any object data which is ready for this IObjHandler.</param> /// <returns>Final part of sln data.</returns> public override string Extract(object data) { var sb = new StringBuilder(); sb.AppendLine($"{SP}GlobalSection(NestedProjects) = preSolution"); bool hasDep = false; folders?.ForEach(p => { if (p.header.parent?.Value != null) { sb.AppendLine($"{SP}{SP}{p.header.pGuid} = {p.header.parent.Value?.header.pGuid}"); hasDep = true; } }); pItems?.ForEach(p => { if (p.parent?.Value != null) { sb.AppendLine($"{SP}{SP}{p.pGuid} = {p.parent.Value?.header.pGuid}"); hasDep = true; } }); if (!hasDep) { return(String.Empty); } sb.Append($"{SP}EndGlobalSection"); return(sb.ToString()); }
public static void SendEmail( IEnumerable<string> toAddresses, string fromAddress, string subject, string body) { if (!toAddresses.Any() || string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(body)) { throw new ArgumentNullException("SendEmail", "Invalid email request"); } if (string.IsNullOrEmpty(fromAddress)) { fromAddress = ConfigurationManager.AppSettings["Email.DefaultFrom"]; } var message = new MailMessage(); toAddresses.ForEach(message.To.Add); message.From = new MailAddress(fromAddress); message.Subject = subject; message.Body = body; message.BodyEncoding = Encoding.UTF8; string host = ConfigurationManager.AppSettings["Email.Host"]; int port = int.Parse(ConfigurationManager.AppSettings["Email.Port"]); SmtpClient client = new SmtpClient(host, port); client.Send(message); }
public static dynamic CreateToken(SecurityKey key, IdentityUser user, IEnumerable <string> roles = null, IEnumerable <Claim> claims = null, TimeSpan?lifespan = null) { var tokenClaims = new List <Claim> { new Claim(JwtRegisteredClaimNames.NameId, user.UserName) }; roles?.ForEach(rol => tokenClaims.Add(new Claim(ClaimTypes.Role, rol))); claims?.ForEach(val => tokenClaims.Add(val)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescription = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(tokenClaims), Expires = DateTime.UtcNow.Add(lifespan ?? TimeSpan.FromDays(1)), SigningCredentials = credentials }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescription); return(new { AccessToken = tokenHandler.WriteToken(token), Expired = token.ValidTo, RefreshToken = CreateGenericToken() }); }
internal CommandMediator( Window window, Interaction interaction, bool bindCancelToClose ) { Contract.Requires( window != null ); this.window = window; this.window.Closing += OnWindowClosing; if ( interaction == null ) return; commands = interaction.Commands; commands.ForEach( c => c.Executed += OnExecuted ); if ( !bindCancelToClose ) return; // determine if behavior is already applied var behaviors = System.Windows.Interactivity.Interaction.GetBehaviors( this.window ); var behavior = behaviors.OfType<WindowCloseBehavior>().FirstOrDefault(); // add behavior which can support binding the cancel command to the window close button (X) if ( behavior == null ) { behavior = new WindowCloseBehavior(); behaviors.Add( behavior ); } behavior.CloseCommand = interaction.CancelCommand; }
/// <summary> /// Initializes a new instance of the <see cref="PluginManager"/> class. /// </summary> /// <param name="Repositories">The repositories.</param> /// <param name="Bootstrapper">The bootstrapper.</param> public PluginManager(IEnumerable<string> Repositories, IBootstrapper Bootstrapper) { Contract.Requires<ArgumentNullException>(Repositories != null, "Repositories"); this.Bootstrapper = Bootstrapper; PackageRepositories = Repositories.ForEach(x => PackageRepositoryFactory.Default.CreateRepository(x)); Initialize(); }
public void SaveEvents(IEnumerable<IAggregateRootEvent> events) { lock(_lockObject) { events.ForEach(e => _events.Add(e)); } }
protected CommandResult SaveEnumerable( IEnumerable<object> models ) { try { var list = new BulkPersist( true, false, models ); var body = list.ToString(); var result = Post( body ); var updates = result.GetResultAs<SaveResponse[]>().ToDictionary( x => x.Id, x => x.Revision ); models .ForEach( x => { var documentId = x.GetDocumentIdAsJson(); string newRev = null; if ( updates.TryGetValue( documentId, out newRev ) ) { x.SetDocumentRevision( newRev ); } } ); return result; } catch ( Exception ex ) { throw Exception( ex, "An exception occurred trying to save a collection documents at {0}. \r\n\t {1}", Uri.ToString(), ex ); } }
public static C AttachPriorityPartition <C>(this C pipeline , IEnumerable <SenderPartitionConfig> config) where C : IPipelineChannelOutgoing <IPipeline> { config?.ForEach((p) => pipeline.AttachPriorityPartition(p)); return(pipeline); }
private void Check(IEnumerable<Tuple<int, int, int>> gen) { gen.ForEach(t => { var len = t.Item1; var win = t.Item2; var step = t.Item3; var af = Source.FromEnumerator(() => Enumerable.Range(0, int.MaxValue).Take(len).GetEnumerator()) .Sliding(win, step) .RunAggregate(new List<IEnumerable<int>>(), (ints, e) => { ints.Add(e); return ints; }, Materializer); var input = Enumerable.Range(0, int.MaxValue).Take(len).ToList(); var cf = Source.FromEnumerator(() => Sliding(input, win, step).GetEnumerator()) .RunAggregate(new List<IEnumerable<int>>(), (ints, e) => { ints.Add(e); return ints; }, Materializer); af.Wait(TimeSpan.FromSeconds(30)).Should().BeTrue(); cf.Wait(TimeSpan.FromSeconds(30)).Should().BeTrue(); af.Result.ShouldAllBeEquivalentTo(cf.Result); }); }
private static string CreateMessage(object message, IEnumerable<Type> handlerTypes) { var exceptionMessage = "There are multiple handlers registered for the message type:{0}.\nIf you are getting this because you have registered a listener as a test spy have your listener implement ISynchronousBusMessageSpy and the exception will disappear" .FormatWith(message.GetType()); handlerTypes.ForEach(handlerType => exceptionMessage += "{0}{1}".FormatWith(Environment.NewLine, handlerType.FullName)); return exceptionMessage; }
private void UpdateChain(IEnumerable<IFilter> filter, bool attach) { if (filter != null) { if (attach) { filter.ForEach(f => f.RequireReaccept += filter_RequireReaccept); filter.ForEach(f => f.RequirePartialReaccept += filter_RequirePartialReaccept); } else { filter.ForEach(f => f.RequireReaccept -= filter_RequireReaccept); filter.ForEach(f => f.RequirePartialReaccept -= filter_RequirePartialReaccept); } } }
/// <summary> /// Includes a script to the page with versioning. /// </summary> /// <param name="html">Reference to the HtmlHelper object</param> /// <param name="url">URL of the script file</param> public static IHtmlString IncludeScript(this HtmlHelper html, IEnumerable <string> urls) { StringBuilder sb = new StringBuilder(); urls?.ForEach(s => sb.AppendLine("<script src=\"" + GetPathWithVersioning(s) + "\" type=\"text/javascript\"></script>")); return(html.Raw(sb.ToString())); }
public void RegisterDeasy(IEnumerable<AttributeInfo<DeasyAttribute>> deasyList) { deasyList.ForEach(d => { Register(d); }); }
protected Action<object> SetupProxy(Type eventType, IEnumerable<Type> constraintHandlerTypes = null) { ids = new ConcurrentBag<string>(); events = new ConcurrentBag<object>(); typeName = eventType.FullName; typeNames = new[] { typeName }.Select(t => new EventType { Type = t }).ToList(); Action<object> handler = null; WhenCalling<ITypeFinder>(x => x.ListEventTypes()).Return(new[] { eventType }); WhenCalling<ITypeFinder>(x => x.GetEventType(Arg<string>.Is.Anything)).Return(eventType); if (constraintHandlerTypes != null) constraintHandlerTypes.ForEach(t => Register(Activator.CreateInstance((Type) t))); WhenCalling<ITypeFinder>(x => x.GetConstraintHandlerTypes(Arg<Type>.Is.Anything)) .Return(constraintHandlerTypes != null ? constraintHandlerTypes : Enumerable.Empty<Type>()); WhenCalling<IEventAggregator>(x => x.Subscribe(Arg<Action<object>>.Is.Anything)).Callback<Action<object>>(h => { handler = h; return true; }); WhenAccessing<IRequest, IPrincipal>(x => x.User).Return(Thread.CurrentPrincipal); var client = new Client(events); WhenCalling<IHubConnectionContext<dynamic>>(x => x.Client(Arg<string>.Is.Anything)).Return(client); WhenAccessing<IHubContext, IHubConnectionContext<dynamic>>(x => x.Clients).Return(Get<IHubConnectionContext<dynamic>>()); Mock<IConnectionManager>(); WhenCalling<IConnectionManager>(x => x.GetHubContext<EventAggregatorProxyHub>()).Return(Get<IHubContext>()); eventProxy = new EventProxy(); return handler; }
public bool SendMessage(string subject, string body, IEnumerable<string> recepients) { var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(UserName, Password) }; using (var message = new MailMessage { Subject = subject, Body = body, }) { message.From = new MailAddress(FromAddress, FromName); message.IsBodyHtml = true; recepients.ForEach(x => message.To.Add(new MailAddress(x))); try { smtp.Send(message); } catch (Exception) { //TODO: shouild be logged return false; } } return true; }
private static void SetDefaultValues <TModel>(IEnumerable <TModel> model) where TModel : class, IBaseModel { model?.ForEach(item => { SetValues(item); }); }
public void AddChange(uint id, IEnumerable<RelationName> relations) { if (this.relations.ContainsKey(id) == false) this.relations.Add(id, new List<RelationName>()); relations.ForEach( (RelationName relation) => this.relations[id].Add(relation)); }
private static Paragraph GenerateParagraph(IEnumerable <ContentPart> contentParts) { var paragraph = new Paragraph(); contentParts?.ForEach(c => { switch (c.Type) { case "text": paragraph.Inlines.Add(c.Text); break; case "url": var hyperlink = new Hyperlink { Inlines = { new Run(c.Text) }, NavigateUri = new Uri(c.Url) }; hyperlink.Click += OnClickHyperlink; paragraph.Inlines.Add(hyperlink); break; } }); return(paragraph); }
private void SetReferenceDescriptionFieldValues <TModel>(IEnumerable <TModel> model) where TModel : class, IBaseModel { model?.ForEach(item => { SetReferenceDescriptionFieldValues(item); }); }
public MigrationsManager(IEnumerable<IMigrateSchema> schemas, IRunMigrations runner) { schemas.MustNotBeNull(); schemas.ForEach(s => s.Runner = runner); _schemas = Sort(schemas); _runner = runner; }
protected void SetModelStateErrors(IEnumerable<IValidationError> errors) { if (errors != null) { errors.ForEach(e => { ModelState.AddModelError(e.Property, e.ErrorMessage); }); } }
public static Type Create(Type parent, IEnumerable<Type> interfaces) { var proxy = module.DefineType(moduleName + '.' + parent.Name, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoLayout, parent); interfaces.ForEach( @interface => { proxy.AddInterfaceImplementation(@interface); @interface.GetMethods().ForEach(method => method.ImplementIn(proxy)); }); proxy.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .ForEach( constructor => { switch (constructor.Attributes & MethodAttributes.MemberAccessMask) { case MethodAttributes.Family: case MethodAttributes.Public: case MethodAttributes.FamORAssem: constructor.ImplementIn(proxy); break; } }); return proxy.CreateType(); }
private void UpdateProfileDescriptionProperties <TModel>(IEnumerable <Person> profiles, IEnumerable <TModel> model) where TModel : class, IBaseModel { model?.ForEach(item => { UpdateProfileDescription(profiles, item); }); }
public Trigger(string[] contexts, Type listenerType, MethodInfo method, IEnumerable <string> dependentContexts) { ListenerType = listenerType; Method = method; contexts.ForEach(c => masterPendingContexts.Add(new PendingContext(c))); // DependentContexts = dependentContexts?.ToList() ?? new List<string>(); dependentContexts?.ForEach(c => masterPendingContexts.Add(new DependentPendingContext(c))); }
public async Task<IUICommand> ShowDialogAsync(string content, string title, IEnumerable<UICommand> commands, uint defaultCommandIndex) { var showDialog = new MessageDialog(content, title); commands.ForEach(c => showDialog.Commands.Add(c)); showDialog.DefaultCommandIndex = defaultCommandIndex; return await showDialog.ShowAsync(); }
/// <summary> /// Loads modules from the specified files. /// </summary> /// <param name="files">The names of the files to load modules from.</param> public void LoadModules(IEnumerable<string> files) { files.ForEach(file => { var rubyModule = new RubyModule(_engine, file); Kernel.Load(rubyModule); }); }
/// <summary> /// Adds the client server groups. /// </summary> /// <param name="clientDatabaseId">The client database id.</param> /// <param name="serverGroups">The server groups.</param> public void AddClientServerGroups(uint clientDatabaseId, IEnumerable<uint> serverGroups) { lock (Container.lockGetClientServerGroups) { serverGroups.ForEach(m => QueryRunner.AddClientToServerGroup(m, clientDatabaseId)); Container.ClientServerGroupList.Remove(clientDatabaseId); } }
protected virtual void UpdateCompletenessForRecords(IEnumerable <Guid> recordIds, string schemaName, int completeness, string resultColumn) { recordIds?.ForEach((id => { var item = new CompletenessItem(id, schemaName, completeness, resultColumn); _completenessItems.Add(item); })); }
public void Subscribe(IEnumerable<SubscriptionDto> subscriptions, bool reconnected) { if (reconnected) eventProxy.UnsubscribeConnection(Context.ConnectionId); subscriptions .ForEach(s => eventProxy.Subscribe(Context, s.Type, s.GenericArguments ?? new string[0], s.Constraint, s.ConstraintId)); }
public static void RegisterGlobalFilters(GlobalFilterCollection filters, IEnumerable<object> otherFilters = null) { filters.Add(new HandleErrorAttribute()); otherFilters = otherFilters ?? new object[0]; otherFilters.ForEach(filters.Add); }
private static void EnsureValidAspects(IEnumerable<AspectMap> aspectsMap) { aspectsMap.ForEach(aspectMap => { aspectMap.Aspects.ForEach(aspectDefinition => { AspectValidator.ValidateAspect(aspectDefinition.Aspect, aspectMap); }); }); }
public async Task Initialize_ShouldCallInnerIntialize( IEnumerable<Mock<IInitializable>> mockInitializable ) { //arrange mockInitializable.ForEach(m => m.Setup(mm => mm.Initialize(It.IsAny<CancellationToken>())) .ReturnsDefaultTask() .Verifiable()) .ToArray(); var sut = new CompositeParallelInitializable(mockInitializable.Select(m => m.Object)); //act await sut.Initialize(CancellationToken.None); //assert mockInitializable.ForEach(m => m.Verify()).ToArray(); }
public static double CalculateExtractedSugarPoints(IEnumerable<RecipeFermentable> fermentables, double batchSize, double extractionEfficiency) { var totalPoints = 0d; fermentables.ForEach(f => totalPoints += (double)(f.Amount*f.Base.PPG)); return (totalPoints/batchSize)*(extractionEfficiency); }
public void FillCities(IEnumerable<string> cities) { cities.ForEach(o => { fromBox.Items.Add(o); toBox.Items.Add(o); }); }
public RenderTarget(DesignerView parent, IMapModel mapModel = null, IEnumerable <IMapModel> childItems = null) { Debug.Assert(parent != null); _parent = parent; MapModel = mapModel; childItems?.ForEach(item => Targets.Add(new RenderTarget(parent, item))); }
public static void RegisterGlobalFilters( GlobalFilterCollection filters, IEnumerable <object> otherFilters = null) { filters.Add(new HandleErrorAttribute()); otherFilters?.ForEach(filters.Add); }
public void Update(IEnumerable <ServiceComponent> entities) { RetryableOperation.Invoke(ExceptionPolicies.General, () => { entities?.ForEach(f => _serviceComponentRepository.Update(f)); _unitOfWork.Save(); }); }
public MapViewTreeNode(string text = null, IMapModel mapModel = null, IEnumerable <IMapModel> childItems = null) { StaticText = text; MapModel = mapModel; childItems?.ForEach(item => Nodes.Add(new MapViewTreeNode(mapModel: item))); Update(); }
/// <summary> /// Resets item rank and match status. /// </summary> /// <param name="items">Items.</param> public void ResetItems(IEnumerable <IMatchItem> items) { items?.ForEach(i => { i.Rank = 0; i.Matched = true; }); }
public MarketDataEntry(DateTime date, IEnumerable<string> candleKeys) { if (candleKeys == null) throw new ArgumentNullException(nameof(candleKeys)); Date = date; Candles = new Dictionary<string, bool>(); candleKeys.ForEach(c => Candles[c] = false); }
public void SetWords(Text text, IEnumerable<string> words) { if (text == null) throw new ArgumentNullException(nameof(text)); if (words == null) throw new ArgumentNullException(nameof(words)); EnsureSaved(text); var wordsSet = _redisClient.Sets[GetWordsSetId(text.Id)]; words.ForEach(wordsSet.Add); }
public NodeHealthMonitor( INodeConfiguration configuration, IEnumerable<INodeHealthBroadcaster> broadcasters ) { Observers = new ObserverCollection<NodeHealth>(); Configuration = configuration; UpdateTimer = new Timer( Configuration.HealthMonitorFrequency.TotalMilliseconds ); UpdateTimer.Elapsed += UpdateHealth; broadcasters .ForEach( x => Subscribe( x ) ); }
/// <summary> /// Will call the add method on a list via reflection to add the items /// </summary> /// <param name="items">Items to add to the list</param> /// <param name="list">The list to call the add method on</param> public static void CallAddMethod(IEnumerable<object> items, object list) { MethodInfo addMethod = list.GetType().GetMethod("Add"); items.ForEach(x => { addMethod.Invoke(list, new object[] { x }); }); }
public static void AddRange <T>(this ICollection <T> collection, IEnumerable <T> values) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } values?.ForEach(collection.Add); }
/// <summary> /// Filling the DataTable from IEnumerable /// </summary> /// <typeparam name="T">type of item from enumerable/typeparam> /// <param name="dt">DataTable</param> /// <param name="source">items of data</param> /// <param name="rowGen">generator for DataRow </param> /// <returns></returns> public static DataTable Fill <T>(this DataTable dt, IEnumerable <T> source, Func <T, object[]> rowGen = null) { if (dt == null) { return(dt); } source?.ForEach(t => dt.Rows.Add(rowGen?.Invoke(t) ?? new object[] { t })); return(dt); }
private void SetStatus(IEnumerable<IExecutableTask> executableTasks, Action<IHaveExecutionStatus, IExecutableTask> action) { _session.Transact(session => executableTasks.ForEach(task => { action(task.Entity, task); session.Update(task.Entity); })); }
public TenantCmdletMockTests(ITestOutputHelper output) { TestExecutionHelpers.SetUpSessionAndProfile(); XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output)); AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory(); ((MockTokenAuthenticationFactory)AzureSession.Instance.AuthenticationFactory).TokenProvider = (account, environment, tenant) => new MockAccessToken { UserId = "*****@*****.**", LoginType = LoginType.OrgId, AccessToken = "bbb", TenantId = tenant }; commandRuntimeMock.Setup(f => f.WriteObject(It.IsAny <object>(), It.IsAny <bool>())).Callback( (Object o, bool enumerateCollection) => { if (enumerateCollection) { IEnumerable <object> objects = o as IEnumerable <object>; objects?.ForEach(e => OutputPipeline.Add(e)); } else { OutputPipeline.Add(o); } }); cmdlet = new GetAzureRMTenantCommandMock() { CommandRuntime = commandRuntimeMock.Object, }; var sub = new AzureSubscription() { Id = Guid.NewGuid().ToString(), Name = "Test subscription" }; defaultContext = new AzureContext(sub, new AzureAccount() { Id = "*****@*****.**", Type = AzureAccount.AccountType.User }, AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud], new AzureTenant() { Id = Guid.NewGuid().ToString() }); var profile = new AzureRmProfile(); profile.DefaultContext = defaultContext; cmdlet.profileClient = new RMProfileClient(profile); cmdlet.profileClient.SubscriptionAndTenantClient = mockSubscriptionClient.Object; }
public BoundYieldStatement(int index, BoundExpression valueExpression, BoundExpression keyExpression, IEnumerable <TryCatchEdge> tryScopes = null) { Debug.Assert(index > 0); YieldIndex = index; YieldedValue = valueExpression; YieldedKey = keyExpression; tryScopes?.ForEach(ts => ContainingTryScopes.AddLast(ts)); }
public static IList <T> AddRange <T>(this IList <T> list, IEnumerable <T> enumerable) { if (list == null) { throw new ArgumentNullException(nameof(list)); } enumerable?.ForEach(list.Add); return(list); }
public static void FullText( this IEnumerable <SiteMenuElement> self, Context context, StringBuilder fullText) { self?.ForEach(o => fullText .Append(" ") .Append(o.Title)); }
/// <summary> /// Includes a script to the page with versioning. /// </summary> /// <param name="html">Reference to the HtmlHelper object</param> /// <param name="url">URL of the script file</param> public static IHtmlString IncludeScript(this HtmlHelper html, IEnumerable <ScriptEntry> urls) { StringBuilder sb = new StringBuilder(); urls?.ForEach(s => { s.Src = GetPathWithVersioning(s.Src); sb.AppendLine(s.GetTag()); }); return(html.Raw(sb.ToString())); }
private void UpdateFailedAttemptsHeader(IEnumerable <IBrokerMessage> messages, int attempt) => messages?.ForEach(msg => { if (attempt == 0) { msg.Headers.Remove(MessageHeader.FailedAttemptsKey); } else { msg.Headers.AddOrReplace(MessageHeader.FailedAttemptsKey, attempt); } });
private static void AddElement(XNamespace ns, XElement queryLog, string elementName, IEnumerable <XAttribute> attributes = null) { if (queryLog.Elements().Any(e => e.Name.LocalName == elementName)) { return; } var newElement = new XElement(ns + elementName); attributes?.ForEach(x => newElement.SetAttributeValue(x.Name, x.Value)); queryLog.AddFirst(newElement); }
public static void RegisterGlobalFilters( GlobalFilterCollection filters, IEnumerable <object> otherFilters = null) { filters.Add(new HttpThrottleFilter( Settings.ThrottleLimitPerSecond, Settings.ThrottleLimitPerMinute, Settings.ThrottleLimitPerHour, Settings.ThrottleLimitPerDay, Settings.ThrottleIpWhitelist)); filters.Add(new HandleErrorAttribute()); otherFilters?.ForEach(filters.Add); }
private IEnumerable <int> GetProfileIdsFromModel <TModel>(IEnumerable <TModel> model) where TModel : class, IBaseModel { var ids = new List <int>(); model?.ForEach(item => { var result = GetProfileIds(item); if ((result?.Count() ?? 0) > 0) { ids.AddRange(result); } }); return(ids); }
/// <summary> /// Fixed: /// </summary> public PermissionCollection(long referenceId, IEnumerable <string> permissions) { permissions?.ForEach(line => { var parts = line.Split(','); if (parts.Count() == 3) { Add(new PermissionModel( referenceId, parts[0] == "Dept" ? parts[1].ToInt() : 0, parts[0] == "Group" ? parts[1].ToInt() : 0, parts[0] == "User" ? parts[1].ToInt() : 0, (Permissions.Types)parts[2].ToLong())); } }); }
/// <summary> /// Forms hierarchy filter items collection from sheet's hierarchy settings. /// </summary> /// <param name="sheet"></param> /// <param name="hierarchyRowIds"></param> /// <returns></returns> public static IEnumerable <HierarchyFilterItem> FormHierarchyFilter(this Sheet sheet, IEnumerable <Guid> hierarchyRowIds) { var hierarchyFilter = new List <HierarchyFilterItem>(); int index = 0; IEnumerable <HierarchySettingItem> sheetHierarchyList = sheet.GetHierarchyItems(); hierarchyRowIds?.ForEach(hierarchyId => { hierarchyFilter.Add(new HierarchyFilterItem { Value = hierarchyId, ColumnPath = sheetHierarchyList.ElementAt(index).ColumnPath }); index++; }); return(hierarchyFilter); }