private void PopulateProperties( GraphicStructure paletteStructure, IList<GraphicStructure> pixelStructures ) { Palette = new Palette( paletteStructure.Pixels, Palette.ColorDepth._16bit ); List<byte> pix = new List<byte>(); pixelStructures.ForEach( p => pix.AddRange( p.Pixels ) ); Pixels = pix.AsReadOnly(); }
public static void FillActiveUserFilesListView(IList<ActiveUserFile> activeUserFiles, ListView target) { target.Items.Clear(); target.Columns.Clear(); target.Columns.Add("File Name"); target.Columns.Add("Reference Computer"); target.Columns.Add("Memory Use"); target.Columns.Add("CPU Use"); target.Columns.Add("Description"); IList<String> images = new List<string>(); images.Add("TrendWinForm.Images.Icons.File_byJesse_48.png"); PopulateListViewImages(images, target); activeUserFiles.ForEach(auf => { var item = new ListViewItem(auf.ReferenceComputer.ToString()); item.Text = auf.FileName; item.SubItems.Add(auf.ReferenceComputer.Make + " " + auf.ReferenceComputer.Model); item.SubItems.Add(auf.MemoryUsage.ToString()); item.SubItems.Add(auf.CpuUsage.ToString()); item.SubItems.Add(auf.Description); item.ImageIndex = 0; target.Items.Add(item); }); }
private static string get_lines(IList<FinishedAndRawInventoryCounted> counteds) { var retVal = "Dell Part Number Available FG Qty Available RAW Qty\r\n"; counteds.ForEach( i => retVal += get_line(i) + "\r\n"); return retVal; }
protected IList<ICountryDetails> GetContryDetailsModel(IList<Country> countries) { var contryDetails = new List<ICountryDetails>(); countries.ForEach(c => contryDetails.Add(GetContryDetailsModel(c))); return contryDetails; }
/// <summary> /// Function to append errors in validation error dictionary. /// </summary> /// <param name="errorsDictionary">Errors dictionary</param> /// <param name="errors">List of errors</param> public static void Append(this Dictionary<string, string> errorsDictionary, IList<ErrorListItem> errors) { if (errors != null) { errors.ForEach(item => Append(errorsDictionary, item)); } }
private static bool AskOrBoolReturnHooks(CommandArgs args, IList<Func<CommandArgs, bool>> hooks) { bool ret = false; hooks.ForEach(delegate(Func<CommandArgs, bool> a){ ret |= a(args); }); return ret; }
/// <summary> /// Copies the validation errors. /// </summary> /// <param name="modelState">State of the model.</param> /// <param name="validationErrors">The validation errors.</param> public static void CopyValidationErrors(this ModelStateDictionary modelState, IList<ValidationError> validationErrors) { validationErrors.ForEach(error => modelState.AddModelError(error.Property, /* strValue, */ error.Message)); //string strValue = null; //if (error.AttemptedValue != null) // strValue = error.AttemptedValue.ToString(); }
private void AddBuildings(TreeViewItem projectItem, IList<Web.Models.Building> buildings) { buildings.ForEach(b => { var buildingItem = new TreeViewItem() { }; View1.Items.Add(projectItem); }); }
private static IEnumerable<NodeData> EncodeNodes( IList<ExplorationNode> nodes, Dictionary<ExplorationEdge, uint> edgeToId) { List<NodeData> nodeData = new List<NodeData>(); nodes.ForEach( (node) => nodeData.Add(new NodeData(node, edgeToId))); return nodeData.OrderBy((node) => node.NodeId); }
public IList<Token> Scan(IList<Token> tokens, Options options) { tokens.ForEach(token => token.Tag( new ITag[] { ScanOrdinal(token, options), ScanOrdinalDay(token) }.Where( x => x != null).ToList())); return tokens; }
private IDictionary<GenusTypeDto, PhotoDto> BuildGenusTypeDictionary(IList<GenusTypeDto> dtoList) { var dictionary = new Dictionary<GenusTypeDto, PhotoDto>(); dtoList.ForEach(x => { var photo = this.photosRepository.GetSingleForGenusType(x.Id); dictionary.Add(x, photo == null ? null : DtoFactory.Build(photo)); }); return dictionary; }
public OrderLine(Product product, int quantity, IList<Outcome> outcomes):this() { Product = product; Quantity = quantity; Price = product.Price; ProductName = product.Name; Outcomes = outcomes; outcomes.ForEach(x => x.OrderLine = this); Profit = Outcomes.Sum(outcome => outcome.Profit); SummWithDiscount = Outcomes.Sum(outcome => outcome.SummWithDiscount); }
/// <summary> /// Includes a style to the page with versioning. /// </summary> /// <param name="html">Reference to the HtmlHelper object</param> /// <param name="url">URL of the style file</param> public static IHtmlString IncludeStyle(this HtmlHelper html, IList <string> Wurls) { StringBuilder sb = new StringBuilder(); Wurls?.ForEach(s => sb.AppendLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + GetPathWithVersioning(s) + "\" />")); return(html.Raw(sb.ToString())); }
/// <summary> /// Resets the service and view model, and closes and removes and click-zone windows. /// </summary> private void ResetRecording() { _service.ResetRecording(true); _model.ResetActions(); _managedClickZoneViews?.ForEach(v => v.Close()); _managedClickZoneViews = new List <ClickZoneView>(); }
public static SwipeView SetItems(this SwipeView view, IList <SwipeItem> bottom = null, IList <SwipeItem> left = null, IList <SwipeItem> right = null, IList <SwipeItem> top = null) { bottom?.ForEach(item => view.BottomItems.Add(item)); left?.ForEach(item => view.LeftItems.Add(item)); right?.ForEach(item => view.RightItems.Add(item)); top?.ForEach(item => view.TopItems.Add(item)); return(view); }
/// <summary> /// Includes a style to the page with versioning. /// </summary> /// <param name="html">Reference to the HtmlHelper object</param> /// <param name="url">URL of the style file</param> public static IHtmlString IncludeStyle(this HtmlHelper html, IList <LinkEntry> Wurls) { StringBuilder sb = new StringBuilder(); Wurls?.ForEach(s => { s.Href = GetPathWithVersioning(s.Href); sb.AppendLine(s.GetTag()); }); return(html.Raw(sb.ToString())); }
void Dispose(bool _) { if (disposed) { return; } disposed = true; allocatedItems?.ForEach(t => Prj.GetItems(t).ToArray().ForEach(i => Prj.RemoveItem(i))); _sln.Dispose(); }
protected override IHost CreateHost(IHostBuilder builder) { var host = base.CreateHost(builder); var testSettings = host.Services.GetRequiredService <TestSettings>(); _userClaims?.ForEach(claim => testSettings.AddClaim(claim)); ExecutePostCreateActions(host); return(host); }
public void ParseResult(IList<string> lines) { lines.ForEach(l => { if (l.StartsWith("dangling commit ")) { var commit = new BareCommitResult(); commit.ParseResult(new List<string>() { l.Remove(0, l.LastIndexOf(" ", StringComparison.Ordinal) + 1)}); Commits.Add(commit); } }); }
// clear is important to avoid mem leaks of event handlers // TODO: is everything cleared correct or are there leftover references? // is this relevant here at all? // see also ResetMenuCommandSets()? public void RemoveAdditionalMainMenuItems() { _menuStrip.Items.Remove(_navigateToolStripMenuItem); _menuStrip.Items.Remove(_viewToolStripMenuItem); // don't forget to clear old associated menu items if (_itemsRegisteredWithMenuCommand != null) { _navigateMenuCommands?.ForEach(mc => mc.UnregisterMenuItems(_itemsRegisteredWithMenuCommand)); _viewMenuCommands?.ForEach(mc => mc.UnregisterMenuItems(_itemsRegisteredWithMenuCommand)); _itemsRegisteredWithMenuCommand.Clear(); } }
public InteractiveTests() { InitializeComponent(); _tests = AllTypes.InCurrentAssembly() .Where(x => x.IsConcrete() && x.IsAssignableTo<UiTest>()) .Select(x => (UiTest)Activator.CreateInstance(x)) .ToList(); _tests .ForEach(x => x.Owner = this); _tests.Select(x => x.Module) .Distinct() .ForEach(x => _moduleNames.Add(x)); _modules.DataSource = _moduleNames.ToList() ; }
public UserListResponse GetUsersList() { try { IList <User> users = UserRepository.FindAll(); users?.ForEach(user => user.ClearPassword()); UserListResponse userIndexResponse = new UserListResponse { Success = true }; userIndexResponse.Users = users; return(userIndexResponse); } catch (Exception e) { return(new UserListResponse { Success = false, Message = e.Message }); } }
public void UpdateAttributeOptionDisplayOrder(Product product, IList<SortItem> options) { if (product != null && options != null && options.Count > 0) { _session.Transact(session => { options.ForEach(item => { var option = session.Get<ProductOption>(item.Id); if (option == null) return; product.Options.Remove(option); product.Options.Insert(item.Order, option); }); session.Update(product); }); } }
public GraphicsStructureImage( IList<GraphicStructureList> lists ) { List<GraphicStructure> structs = new List<GraphicStructure>(); lists.ForEach( l => structs.AddRange( l.Structures ) ); PopulateProperties( structs[0], structs.Sub( 1 ) ); }
/// <summary> /// Initializes the drop item groups for this map. /// By default, we add money and random items. On event or special maps, this can be overwritten. /// </summary> protected virtual void InitializeDropItemGroups() { DefaultDropItemGroups.ForEach(this.mapDefinition.DropItemGroups.Add); }
protected void WriteStorageAccountList(IList<StorageModels.StorageAccount> storageAccounts) { List<PSStorageAccount> output = new List<PSStorageAccount>(); storageAccounts.ForEach(storageAccount => output.Add(PSStorageAccount.Create(storageAccount, this.StorageClient))); WriteObject(output, true); }
public ConnectionManager(IList <ConnectionEndpoint> endpoints, string inputQueueAddress, IRebusLoggerFactory rebusLoggerFactory, Func <IConnectionFactory, IConnectionFactory> customizer) { if (endpoints == null) { throw new ArgumentNullException(nameof(endpoints)); } if (rebusLoggerFactory == null) { throw new ArgumentNullException(nameof(rebusLoggerFactory)); } _log = rebusLoggerFactory.GetLogger <ConnectionManager>(); if (inputQueueAddress != null) { _log.Info("Initializing RabbitMQ connection manager for transport with input queue {queueName}", inputQueueAddress); } else { _log.Info("Initializing RabbitMQ connection manager for one-way transport"); } if (endpoints.Count == 0) { throw new ArgumentException("Please remember to specify at least one endpoints for a RabbitMQ server. You can also add multiple connection strings separated by ; or , which RabbitMq will use in failover scenarios"); } if (endpoints.Count > 1) { _log.Info("RabbitMQ transport has {count} endpoints available", endpoints.Count); } endpoints.ForEach(endpoint => { if (endpoint == null) { throw new ArgumentException("Provided endpoint collection should not contain null values"); } if (string.IsNullOrEmpty(endpoint.ConnectionString)) { throw new ArgumentException("null or empty value is not valid for ConnectionString"); } }); _connectionFactory = new ConnectionFactory { Uri = endpoints.First().ConnectionUri, //Use the first URI in the list for ConnectionFactory to pick the AMQP credentials, VirtualHost (if any) AutomaticRecoveryEnabled = true, NetworkRecoveryInterval = TimeSpan.FromSeconds(30), ClientProperties = CreateClientProperties(inputQueueAddress) }; if (customizer != null) { _connectionFactory = customizer(_connectionFactory); } _amqpTcpEndpoints = endpoints .Select(endpoint => { try { return(new AmqpTcpEndpoint(new Uri(endpoint.ConnectionString), ToSslOption(endpoint.SslSettings))); } catch (Exception exception) { throw new FormatException($"Could not turn the connection string '{endpoint.ConnectionString}' into an AMQP TCP endpoint", exception); } }) .ToList(); }
static void DerivePageCountFromPageRange(IList <Reference> references) => references.ForEach(reference => DerivePageCountFromPageRange(reference));
private void GetSubmoduleStatus(IList<GitItemStatus> status, string from, string to) { status.ForEach(item => { if (item.IsSubmodule) { item.SubmoduleStatus = Task.Factory.StartNew(() => { Patch patch = GetSingleDiff(from, to, item.Name, item.OldName, "", SystemEncoding, true); string text = patch != null ? patch.Text : ""; var submoduleStatus = GitCommandHelpers.GetSubmoduleStatus(text); if (submoduleStatus.Commit != submoduleStatus.OldCommit) { var submodule = submoduleStatus.GetSubmodule(this); submoduleStatus.CheckSubmoduleStatus(submodule); } return submoduleStatus; }); } }); }
public async Task Load(IList <Record> Spisok, CancellationToken token, IModel m) { HtmlNodeCollection nodes; HtmlNode root; HtmlDocument document2, hDocument; Record rec, rec2; //IEnumerable<Record> rec3; string text; MyEventArgs args = new MyEventArgs(); Random rnd = new Random(); StringBuilder SBDesc = new StringBuilder(); string tmpString; char searchChar1, searchChar2; //await GetDocument(webs); //text = hDocument.DocumentNode.SelectSingleNode("//div[@data-qa='vacancies-total-found']")?.InnerText ?? ""; //web = new HtmlWeb(); //document = web.Load(webs); args.Value = 0; args.Value2 = 0; Changed?.Invoke(this, args); await Task.Delay(100); Spisok.ForEach <Record>(s => s.Closed = true); hDocument = await GetDocument(webs); searchChar1 = '?'; searchChar2 = '='; text = hDocument.DocumentNode.SelectSingleNode("//span[@data-qa='vacancies-total-found']")?.InnerText ?? ""; text = Regex.Match(text, @"\d+").Value; if (!Int32.TryParse(text, out int _p)) { searchChar1 = '&'; searchChar2 = '='; text = hDocument.DocumentNode.SelectSingleNode("//h1[@data-qa='bloko-header-3']")?.InnerText ?? ""; text = Regex.Replace(text, @"<[^>]+>| ", "").Trim(); text = Regex.Replace(text, @" ", "").Trim(); text = Regex.Match(text, @"\d+").Value; if (!Int32.TryParse(text, out _p)) { throw new ArgumentException("Vacancy count error"); } } args.MaxValue = _p; _p = 0; nodes = hDocument.DocumentNode.SelectNodes("//div[@class='vacancy-serp-item' or @class='vacancy-serp-item vacancy-serp-item_premium']"); while (nodes != null) { foreach (HtmlNode node in nodes) { //text = node.SelectSingleNode(".//script[@data-name='HH/VacancyResponsePopup/VacancyResponsePopup']")?.Attributes["data-params"]?.Value ?? "0"; text = node.SelectSingleNode(".//a[@data-qa='vacancy-serp__vacancy_response']")?.Attributes["href"]?.Value ?? "0"; text = Regex.Match(text, @"(?<=vacancyId.*)\d+").Value; // теперь надо узнать есть ли уже такой Id в Spisok rec2 = null; //rec3 = null; rec2 = (Spisok as List <Record>).Find(c => c.Id == text); //rec3 = Spisok.Where(c => c.Id == text); //if (rec3.Count<Record>() == 0) if (rec2 == null) { // Новая запись rec = new Record { Name = node.SelectSingleNode(".//a[@class='bloko-link']")?.InnerText ?? "", link = node.SelectSingleNode(".//a[@class='bloko-link']")?.Attributes["href"].Value, Zp = node.SelectSingleNode(".//span[@data-qa='vacancy-serp__vacancy-compensation']")?.InnerText ?? "", Comp = node.SelectSingleNode(".//div[@class='vacancy-serp-item__meta-info-company']")?.InnerText ?? "", Town = node.SelectSingleNode(".//div[@data-qa='vacancy-serp__vacancy-address']")?.InnerText ?? "", Resp1 = node.SelectSingleNode(".//div[@data-qa='vacancy-serp__vacancy_snippet_responsibility']")?.InnerText ?? "", Req1 = node.SelectSingleNode(".//div[@data-qa='vacancy-serp__vacancy_snippet_requirement']")?.InnerText ?? "", Interes = null }; rec.Zp2 = ExtractZp(rec.Zp); tmpString = node.SelectSingleNode(".//span[@class='vacancy-serp-item__publication-date vacancy-serp-item__publication-date_long']")?.InnerText ?? ""; if (Regex.Match(tmpString, @"\d+").Length == 1) { tmpString = "0" + tmpString; } if (DateTime.TryParseExact(Regex.Replace(tmpString, @"\u00A0", " "), "dd MMMMM", null, DateTimeStyles.None, out DateTime tmpDate)) { rec.Dat = tmpDate; } else { rec.Dat = DateTime.Now; } rec.Id = text; rec.BeginingDate = DateTime.Now; rec.LastCheckDate = DateTime.Now; if (rec.Dat > DateTime.Now) { rec.Dat = rec.Dat.AddYears(-1); } rec.DaysLong = (rec.LastCheckDate - rec.Dat).TotalDays; // Случайная пауза. StartPause?.Invoke(this, args); await Task.Delay(rnd.Next(2000, 4000)); EndPause?.Invoke(this, args); document2 = await GetDocument(rec.link); if (document2 != null) { rec.Opt = document2.DocumentNode.SelectSingleNode("(//div[@class='bloko-gap bloko-gap_bottom'])[14]")?.InnerText ?? ""; root = document2.DocumentNode.SelectSingleNode("//div[@class='g-user-content' or @data-qa='vacancy-description']"); SBDesc.Clear(); foreach (HtmlNode node2 in root.DescendantsAndSelf()) { if (!node2.HasChildNodes) { text = node2.InnerText; if (!string.IsNullOrWhiteSpace(text)) { SBDesc.AppendLine(text); } } } rec.Desc = ConvertToFlowDocumentString(SBDesc.ToString(), new String[] { "Требования" }); } //rec.Desc = XamlWriter.Save(SBDesc.ToString()); //rec.Desc = SBDesc.ToString(); // Преобразовать SBDesc.ToString() во FlowDocument //yap.ForEach<AnaliseType>(p => p.count = spisok.Count(t => t.AllInfo().СontainsCI(p.Name) || t.AllInfo().СontainsCI(p.NameRus()))); rec.Sharp = rec.AllInfo().ContainsCI("C#") || rec.AllInfo().ContainsCI("С#") || rec.AllInfo().ContainsCI(".NET"); rec.JavaScript = rec.AllInfo().ContainsCI("JavaScript"); rec.SQL = rec.AllInfo().ContainsCI("SQL"); rec._1C = rec.AllInfo().ContainsCI("1C") || rec.AllInfo().ContainsCI("1С"); rec.Distant = rec.AllInfo().ContainsCI("удал"); rec.Closed = false; //SC.Post(new SendOrPostCallback(o => { Spisok.Add(rec); }), 1); Spisok.Add(rec); args.Value2++; } else { // Уже есть // rec2 = rec3.First<Record>(); if (string.IsNullOrWhiteSpace(rec2.Comp)) { rec2.Comp = node.SelectSingleNode(".//div[@class='vacancy-serp-item__meta-info-company']")?.InnerText ?? ""; } if (string.IsNullOrWhiteSpace(rec2.Town)) { rec2.Town = node.SelectSingleNode(".//div[@data-qa='vacancy-serp__vacancy-address']")?.InnerText ?? ""; } rec2.LastCheckDate = DateTime.Now; rec2.Closed = false; rec2.NewUpdates = false; if (rec2.Closed && (DateTime.Now - rec2.LastCheckDate).TotalHours < 36) { rec2.NewUpdates = true; } if (!rec2.Closed && (DateTime.Now - rec2.BeginingDate).TotalHours < 12) { rec2.NewUpdates = true; } if (rec2.BeginingDate < rec2.Dat) { rec2.DaysLong = (rec2.LastCheckDate - rec2.BeginingDate).TotalDays; } else { rec2.DaysLong = (rec2.LastCheckDate - rec2.Dat).TotalDays; } } //Dispatcher.Invoke(updProgress, new object[] { ProgressBar.ValueProperty, ++value }); //Pbprc = value / 350 * 100; args.Value++; Changed?.Invoke(this, args); token.ThrowIfCancellationRequested(); } // Случайная пауза. StartPause?.Invoke(this, args); await Task.Delay(rnd.Next(2000, 4000)); EndPause?.Invoke(this, args); hDocument = await GetDocument(webs + searchChar1 + "page" + searchChar2 + ++_p); nodes = hDocument.DocumentNode.SelectNodes("//div[@class='vacancy-serp-item' or @class='vacancy-serp-item vacancy-serp-item_premium']"); } args.Value = 0; args.Value2 = 0; Changed?.Invoke(this, args); await Task.Delay(100); }
public Rule(T defaultRule, IList <T> others) : this(defaultRule) { GuardArgument.ArgumentIsNotNull(others); others.ForEach(x => Strategies.Push(x)); }
/// <summary> /// Initializes a new instance of the <see cref="Entity"/> class with a name and a list of /// properties that are defined locally on the entity (and are not part of incoming associations). /// </summary> /// <param name="domainModel">The incoming <seealso cref="DomainModel"/></param> /// <param name="entityDefinition">The incoming <seealso cref="EntityDefinition"/></param> internal Entity(DomainModel domainModel, EntityDefinition entityDefinition) { DomainModel = domainModel; Schema = entityDefinition.Schema; Name = entityDefinition.Name; TableNameByDatabaseEngine = new Dictionary <DatabaseEngine, string>(entityDefinition.TableNames); Description = entityDefinition.Description?.Trim(); IsAbstract = entityDefinition.IsAbstract; IsDeprecated = entityDefinition.IsDeprecated; DeprecationReasons = entityDefinition.DeprecationReasons; _locallyDefinedProperties = entityDefinition.LocallyDefinedProperties.Select(x => new EntityProperty(x)) .ToList(); _identifiers = entityDefinition.Identifiers.Select(x => new EntityIdentifier(x)) .ToReadOnlyList(); // Assign entity references to the identifiers, properties _identifiers.ForEach(i => i.Entity = this); _locallyDefinedProperties.ForEach(p => p.Entity = this); _properties = new Lazy <IReadOnlyList <EntityProperty> >( () => { // All properties, identifying ones first var properties = IncomingAssociations.Where(a => a.IsIdentifying) .SelectMany(x => x.ThisAssociationProperties.Cast <DomainPropertyBase>()) .Concat(_locallyDefinedProperties.Where(p => p.IsIdentifying)) .Concat( IncomingAssociations.Where(a => !a.IsIdentifying) .SelectMany(x => x.ThisAssociationProperties)) .Concat(_locallyDefinedProperties.Where(p => !p.IsIdentifying)) .ToList(); var distinctProperties = properties .Distinct(ModelComparers.DomainPropertyNameOnly) .ToList() .AsReadOnly(); // Return the distinct set of EntityProperty instances, // constructing new EntityProperty instances for the "winning" AssociationProperty var entityProperties = distinctProperties.Select(dp => (dp as EntityProperty) ?? new EntityProperty(dp as AssociationProperty)) .ToList(); // Ensure back-references to the Entity are set entityProperties.ForEach(p => p.Entity = this); return(entityProperties); }); _nonIdentifyingProperties = new Lazy <IReadOnlyList <EntityProperty> >( () => Properties.Where(p => !p.IsIdentifying) .ToList() .AsReadOnly()); _derivedEntities = new Lazy <Entity[]>( () => { AssociationView[] associations; if (!DomainModel.AssociationViewsByEntityFullName.TryGetValue(FullName, out associations)) { return(new Entity[0]); } return(associations .Where(x => x.AssociationType == AssociationViewType.ToDerived) .Select(x => x.OtherEntity) .ToArray()); }); _propertyByName = new Lazy <IReadOnlyDictionary <string, EntityProperty> >( () => Properties.ToDictionary(x => x.PropertyName, x => x, StringComparer.InvariantCultureIgnoreCase)); _primaryIdentifier = new Lazy <EntityIdentifier>( () => _identifiers.SingleOrDefault(x => x.IsPrimary)); _alternateIdentifiers = new Lazy <IReadOnlyList <EntityIdentifier> >( () => _identifiers.Where(x => !x.IsPrimary) .ToList()); _baseAssociation = new Lazy <AssociationView>( () => { AssociationView[] associations; if (!DomainModel.AssociationViewsByEntityFullName.TryGetValue(FullName, out associations)) { return(null); } return(associations.SingleOrDefault(a => a.AssociationType == AssociationViewType.FromBase)); }); _isEntityExtension = new Lazy <bool>( () => EdFiStandardEntityAssociation != null); _extensions = new Lazy <Entity[]>( () => { AssociationView[] associations; if (!DomainModel.AssociationViewsByEntityFullName.TryGetValue(FullName, out associations)) { return(new Entity[0]); } return(associations .Where(x => x.AssociationType == AssociationViewType.ToExtension) .Select(x => x.OtherEntity) .ToArray()); }); _extensionAssociations = new Lazy <AssociationView[]>( () => { AssociationView[] associations; if (!DomainModel.AssociationViewsByEntityFullName.TryGetValue(FullName, out associations)) { return(new AssociationView[0]); } return(associations .Where(x => x.AssociationType == AssociationViewType.ToExtension) .ToArray()); }); _aggregateExtensionOneToOnes = new Lazy <AssociationView[]>( () => { return(NavigableOneToOnes.Where(a => a.ThisEntity.Schema != a.OtherEntity.Schema) .ToArray()); }); _aggregateExtensionChildren = new Lazy <AssociationView[]>( () => { return(NavigableChildren.Where(a => a.ThisEntity.Schema != a.OtherEntity.Schema) .ToArray()); }); _edFiStandardEntity = new Lazy <Entity>( () => { if (EdFiStandardEntityAssociation == null) { return(null); } return(EdFiStandardEntityAssociation.OtherEntity); }); _edFiStandardEntityAssociation = new Lazy <AssociationView>( () => IncomingAssociations .SingleOrDefault(a => a.AssociationType == AssociationViewType.FromCore) ); _childToAggregateRootIdentifierPropertyMappings = new Lazy <IReadOnlyList <PropertyMapping> >(() => BuildChildToAggregateRootPropertyMappings(this)); }
public static IList<GoodsDetail> GetItems(IList<int> ids) { var r = new List<GoodsDetail>(); if (ids != null && ids.Any()) { ids.ForEach(id => { var rData = Commodity.GetShopItemDetail(id); if (rData != null) { r.Add(new GoodsDetail { Picture = rData.Picture, Pictures = rData.Pictures, MarketPrice = rData.MarketPrice, Partners = rData.Partners, Price = rData.Price, Id = rData.Id, ItemTitle = rData.ItemTitle, Sales = rData.Sales }); } }); } return r; }
private static IDisposable MapIndexingInProgress(IList <IndexToWorkOn> indexesToWorkOn) { indexesToWorkOn.ForEach(x => x.Index.IsMapIndexingInProgress = true); return(new DisposableAction(() => indexesToWorkOn.ForEach(x => x.Index.IsMapIndexingInProgress = false))); }
public void Store(IList<MarkdownFile> files) { files.ForEach(Store); }
// GET: Book public ActionResult Index(string bookGenre, string searchString, string author, string bookPrice) { IList <BookViewModel> books = null; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:1786/api/"); var responseTask = client.GetAsync("booksearch"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync <IList <BookViewModel> >(); readTask.Wait(); books = readTask.Result; CreateDropdownData(books); if (!string.IsNullOrEmpty(searchString)) { var searchStringsTrimmed = TrimSearchKeyword(searchString); var idTitlestringDictionary = new Dictionary <string, string[]>(); books.ForEach(b => idTitlestringDictionary.Add(b.Id, b.Title.ToLower().Split(' '))); books = GetMatchedItems(idTitlestringDictionary, searchStringsTrimmed.ToArray(), books); } if (!string.IsNullOrEmpty(author)) { var authorStringsTrimmed = TrimSearchKeyword(author); var idAuthorDictionary = new Dictionary <string, string[]>(); foreach (var b in books) { //Trim "," from the author's names and save them in idAuthorDictionary char[] toTrim = { ',' }; var nameSplit = b.Author.ToLower().Split(' '); var nameArray = new List <string>(); nameSplit.ForEach(n => { nameArray.Add(n.TrimEnd(toTrim)); }); idAuthorDictionary.Add(b.Id, nameArray.ToArray()); } books = GetMatchedItems(idAuthorDictionary, authorStringsTrimmed.ToArray(), books); } if (!string.IsNullOrEmpty(bookGenre)) { books = books.Where(b => b.Genre.Equals(bookGenre)).ToList(); } if (!string.IsNullOrEmpty(bookPrice)) { var words = bookPrice.Split(' '); char[] toTrim = { '€' }; var fromPrice = Convert.ToDecimal(words[0].Trim(toTrim)); var toPrice = words.Length == 2 ? -99m : Convert.ToDecimal(words[2].Trim(toTrim)); books = toPrice < 0 ? books.Where(b => b.Price > fromPrice).ToList() : books.Where(b => b.Price > fromPrice && b.Price < toPrice).ToList(); } } else { books = Enumerable.Empty <BookViewModel>().ToList(); ModelState.AddModelError(string.Empty, "Web api error."); } } return(View(books)); }
public void AddEventForManyWithEmail(IUserEvent userEvent, IList <string> userEmails) { userEmails.ForEach(email => AddEventWithEmail(userEvent, email)); }
public void UpdateOnJavascriptContext(BridgeUpdater updater, IList <IJsCsGlue> values) { values?.ForEach(UpdateJavascriptValue); UpdateOnJavascriptContext(updater); }
public void AddEventForMany(IUserEvent userEvent, IList <string> userIds) { userIds.ForEach(id => AddEventWithId(userEvent, ObjectId.Parse(id))); }
public IList <Token> Scan(IList <Token> tokens, Options options) { tokens.ForEach(ApplyTags); return(tokens); }
private void AddPayloads(IO.StringWriter writer, IList <Payload> payloads) { payloads.ForEach(payload => AddFileCommand(writer, payload.SourceFile, payload.Name)); }
public void Reset() { _controls.ForEach(item => item.Reset()); BuildEditContext(); }
private static IDisposable MapIndexingInProgress(IList<IndexToWorkOn> indexesToWorkOn) { indexesToWorkOn.ForEach(x => x.Index.IsMapIndexingInProgress = true); return new DisposableAction(() => indexesToWorkOn.ForEach(x => x.Index.IsMapIndexingInProgress = false)); }
/// <summary> /// Assigns the persons list. /// </summary> /// <param name="presenter">The presenter.</param> /// <param name="projectPerson">The project person.</param> private void AssignPersonsList(ProjectPresenter presenter, IList<ProjectPersonListItem> projectPerson) { projectPerson.ForEach(p => presenter.Project.ProjectPersons.Add(this.MapProjectListItemToProjectPerson(p, presenter))); }
public IList<Token> Scan(IList<Token> tokens, Options options) { tokens.ForEach(ApplyTags); return tokens; }
private void UnpackResponsePackage(Guid requestId, Document zipDoc) { IList <DnsRequestSearchTerm> searchTerms = null; using (var db = new DataContext()) { using (var dbStream = zipDoc.GetStream(db)) { if (dbStream.Length <= 0) { return; } using (ZipInputStream zf = new ZipInputStream(dbStream)) { ZipEntry zipEntry = null; while ((zipEntry = zf.GetNextEntry()) != null) { if (!zipEntry.IsFile) { continue; } // Look for csv version first. Done if found. if (zipEntry.Name.ToLower().EndsWith("allrun_signature.csv")) { //searchTerms = GetSearchTerms(requestId, zf.GetInputStream(zipEntry)); searchTerms = GetSearchTerms(requestId, zf); break; } else if (zipEntry.Name.ToLower().EndsWith("allrun_signature.sas7bdat")) { //searchTerms = GetSASSearchTerms(requestId, zf.GetInputStream(zipEntry)); searchTerms = GetSearchTerms(requestId, zf); } } } } } using (var db = new DataContext()) { if (searchTerms != null) { // Store the first one only. IList <RequestSearchTerm> requestSearchTerms = new List <RequestSearchTerm>(); if (db.RequestSearchTerms.Where(t => t.RequestID == requestId).Count() <= 0) { searchTerms.ForEach(t => requestSearchTerms.Add(new RequestSearchTerm { RequestID = requestId, Type = (int)t.Type, DateFrom = t.DateFrom, DateTo = t.DateTo, NumberFrom = t.NumberFrom, NumberTo = t.NumberTo, NumberValue = t.NumberValue, StringValue = t.StringValue }) ); } db.RequestSearchTerms.AddRange(requestSearchTerms); db.SaveChanges(); } } }
private IList <Produto> FiltrarPreco(IList <Produto> produtos, int lojaId) { produtos.ForEach(p => p.Precos = p.Precos.Where(pp => pp.Loja.Id == lojaId).ToList()); return(produtos); }
public dtoFileDetail GetDetailFile(IList <Int32> UsersId, Int64 FileId, IDictionary <String, String> translateServiceCode) { dtoFileDetail FileInfo = new dtoFileDetail(); // 1. Col_Manager -> ColBaseCommunityFile (per le info sul file). // La proprietà IsInternal mi dice se appartiene ad un servizio o alla comunità. BaseCommunityFile File = Manager.Get <BaseCommunityFile>(FileId); FileInfo.FileName = File.Name; if (File.IsInternal) { FileInfo.ComService = "Service"; FileInfo.Path = ""; } else { FileInfo.ComService = File.CommunityOwner.Name; FileInfo.Path = File.FilePath; } FileInfo.Size = File.Size; FileInfo.LoadedBy = File.Owner.SurnameAndName; FileInfo.LoadedOn = File.CreatedOn; FileInfo.Downloads = File.Downloads; FileInfo.isInternal = File.IsInternal; // 2. da filelink recupero le info sui download (riferiti ad un singolo file) // //var x = (from f in Manager.GetAll<FileDownloadInfo>(f => (FilesIds.Contains(f.File.Id) && UsersIds.Contains(f.Downloader.Id))) // select new { Key = f.Downloader.Id.ToString() + "-" + f.File.Id.ToString() }); IList <Person> Users = Manager.GetAll <Person>(p => (UsersId.Contains(p.Id))).ToList(); FileInfo.DownDetails = new List <dtoUserDownInfo>(); Users.ForEach(delegate(Person prsn) { dtoUserDownInfo UDI = new dtoUserDownInfo(); UDI.downBy = prsn.SurnameAndName; UDI.downOnList = GetdtoDownInfos(prsn.Id, FileId, translateServiceCode); if (UDI.downOnList == null) { UDI.downOnList = new List <dtoDownInfo>(); } UDI.TotalDownload = UDI.downOnList.Count(); //Eventualmente metterlo "fuori" o toglierlo del tutto... FileInfo.DownDetails.Add(UDI); }); // 3. Prendere dalla View un iDictionary(String, String) -> Dictionary(Service.Code, ServiceTranslateName) // per tradurre i nomi dei servizi. // return(FileInfo); }
public IList<Token> Scan(IList<Token> tokens, Options options) { tokens.ForEach((token, nextToken) => token.Tag( new ITag[] { Scan(token, nextToken, options), ScanDay(token, nextToken, options), ScanMonth(token, nextToken, options), ScanYear(token, nextToken, options), }.Where( x => x != null).ToList())); return tokens; }
private void DeleteSourceMessages(CloudQueue sourceQueue, IList<CloudQueueMessage> inboundMessages, Stopwatch stopWatch) { inboundMessages.ForEach(inMsg => sourceQueue.DeleteMessage(inMsg)); this.LogInformation("Done deleting {0} messages from {1} queue. Elapsed {2}.", inboundMessages.Count, sourceQueue.Name, stopWatch.Elapsed); }
public void UpdateSpecificationAttributeDisplayOrder(IList<SortItem> options) { _session.Transact(session => options.ForEach(item => { var formItem = session.Get<ProductSpecificationAttribute>(item.Id); formItem.DisplayOrder = item.Order; session.Update(formItem); })); }
public IList<Token> Scan(IList<Token> tokens, Options options) { tokens.ForEach(token => { foreach (var scanner in _scanners) { var tag = scanner(token, options); if (tag != null) { token.Tag(tag); break; } } }); return tokens; }
protected override void Init() { var actionGrid = new Grid() { Padding = new Thickness(10), BackgroundColor = Color.Aquamarine }; actionGrid.AddChild(new Button() { Text = "Index desc", Command = new Command(() => IndexDesc()) }, 0, 0); actionGrid.AddChild(new Button() { Text = "All indexes equal 0", Command = new Command(() => listViews.ForEach(c => c.TabIndex = 0)) }, 1, 0); actionGrid.AddChild(new Button() { Text = "Negative indexes", Command = new Command(() => IndexNegative()) }, 2, 0); actionGrid.AddChild(new Button() { Text = "TabStops = True", Command = new Command(() => listViews.ForEach(c => c.IsTabStop = true)) }, 0, 1); actionGrid.AddChild(new Button() { Text = "TabStops = False", Command = new Command(() => listViews.ForEach(c => c.IsTabStop = false)) }, 1, 1); actionGrid.AddChild(new Button() { Text = "TabStops every second", Command = new Command(() => { for (int i = 0; i < listViews.Count; i++) { listViews[i].IsTabStop = i % 2 == 0; } }) }, 2, 1); var pickerStopped = new Picker { Title = $"[+] Picker - Tab stop enable", IsTabStop = true }; var pickerNotStopped = new Picker { Title = "[-] Picker - Tab stop disable", IsTabStop = false }; for (var i = 1; i < 3; i++) { pickerNotStopped.Items.Add("Sample Option " + i); pickerStopped.Items.Add("Sample Option " + i); } var stack = new StackLayout { Children = { actionGrid, pickerStopped, pickerNotStopped, new Button { Text = $"TabIndex 90", IsTabStop = true, TabIndex = 90 }, new Button { Text = $"TabIndex 100", IsTabStop = true, TabIndex = 100 }, new Button { Text = $"TabIndex 100", IsTabStop = true, TabIndex = 100 }, new Button { Text = $"TabIndex 90", IsTabStop = true, TabIndex = 90 }, new Button { Text = $"[+] Button - TabStop enable", IsTabStop = true }, new Button { Text = "Button - Non stop", IsTabStop = false }, new CheckBox { IsTabStop = true }, new CheckBox { IsTabStop = false }, new DatePicker { IsTabStop = true }, new DatePicker { IsTabStop = false }, new Editor { Text = $"[+] Editor - Tab stop enable", IsTabStop = true }, new Editor { Text = "Editor - Non stop", IsTabStop = false }, new Entry { Text = $"[+] Entry - Tab stop enable", IsTabStop = true }, new Entry { Text = "Entry - Non stop", IsTabStop = false }, new ProgressBar { IsTabStop = true, HeightRequest = 40, Progress = 80 }, new ProgressBar { IsTabStop = false, HeightRequest = 40, Progress = 40 }, new SearchBar { Text = $"[+] SearchBar - TabStop enable", IsTabStop = true }, new SearchBar { Text = "SearchBar - TabStop disable", IsTabStop = false }, new Slider { IsTabStop = true }, new Slider { IsTabStop = false }, new Stepper { IsTabStop = true }, new Stepper { IsTabStop = false }, new Switch { IsTabStop = true }, new Switch { IsTabStop = false }, new TimePicker { IsTabStop = true }, new TimePicker { IsTabStop = false }, } }; listViews = stack.Children; foreach (var item in listViews) { item.Focused += (_, e) => { BackgroundColor = e.VisualElement.IsTabStop ? Color.Transparent : Color.OrangeRed; Title = $"{e.VisualElement.TabIndex} - " + (e.VisualElement.IsTabStop ? "[+]" : "WRONG"); e.VisualElement.Scale = 0.7; }; item.Unfocused += (_, e) => { BackgroundColor = Color.Transparent; Title = string.Empty; e.VisualElement.Scale = 1; }; } IndexDesc(); Content = new ScrollView() { Content = stack }; }
public void AddEventForMany(IUserEvent userEvent, IList <ObjectId> userIds) { userIds.ForEach(id => AddEventWithId(userEvent, id)); }
/// <summary> /// Compresses the specified file. /// </summary> /// <typeparam name="T">Must be <see cref="IStringSectioned"/> and <see cref="ICompressed"/></typeparam> /// <param name="file">The file to compress.</param> /// <param name="ignoreSections">A dictionary indicating which entries to not compress, with each key being the section that contains the ignored /// entries and each item in the value being an entry to ignore</param> /// <param name="callback">The progress callback.</param> public static CompressionResult Compress( IList<IList<string>> sections, byte terminator, GenericCharMap charmap, IList<bool> allowedSections ) { int length = 0; sections.ForEach( s => length += charmap.StringsToByteArray( s, terminator ).Length ); byte[] result = new byte[length]; int[] lengths = new int[sections.Count]; int pos = 0; for( int section = 0; section < sections.Count; section++ ) { int oldPos = pos; if ( allowedSections == null || allowedSections[section] ) { CompressSection( charmap.StringsToByteArray( sections[section], terminator ), result, ref pos ); } else { byte[] secResult = charmap.StringsToByteArray( sections[section], terminator ); secResult.CopyTo( result, pos ); pos += secResult.Length; } lengths[section] = pos - oldPos; } return new CompressionResult( result.Sub( 0, pos - 1 ), lengths ); }
public void SetSslOptions(SslSettings ssl) { _amqpTcpEndpoints.ForEach(endpoint => { endpoint.Ssl = ToSslOption(ssl); }); }
protected override void ExecuteIndexingWork(IList<IndexToWorkOn> indexesToWorkOn, Etag synchronizationEtag) { indexesToWorkOn = context.Configuration.IndexingScheduler.FilterMapIndexes(indexesToWorkOn); var lastIndexedGuidForAllIndexes = indexesToWorkOn.Min(x => new ComparableByteArray(x.LastIndexedEtag.ToByteArray())).ToEtag(); var startEtag = CalculateSynchronizationEtag(synchronizationEtag, lastIndexedGuidForAllIndexes); context.CancellationToken.ThrowIfCancellationRequested(); var operationCancelled = false; TimeSpan indexingDuration = TimeSpan.Zero; List<JsonDocument> jsonDocs = null; var lastEtag = Etag.Empty; indexesToWorkOn.ForEach(x => x.Index.IsMapIndexingInProgress = true); try { jsonDocs = prefetchingBehavior.GetDocumentsBatchFrom(startEtag); if (Log.IsDebugEnabled) { Log.Debug("Found a total of {0} documents that requires indexing since etag: {1}: ({2})", jsonDocs.Count, startEtag, string.Join(", ", jsonDocs.Select(x => x.Key))); } context.ReportIndexingActualBatchSize(jsonDocs.Count); context.CancellationToken.ThrowIfCancellationRequested(); if (jsonDocs.Count <= 0) return; var sw = Stopwatch.StartNew(); lastEtag = DoActualIndexing(indexesToWorkOn, jsonDocs); indexingDuration = sw.Elapsed; } catch (OperationCanceledException) { operationCancelled = true; } finally { if (operationCancelled == false && jsonDocs != null && jsonDocs.Count > 0) { prefetchingBehavior.CleanupDocuments(lastEtag); prefetchingBehavior.UpdateAutoThrottler(jsonDocs, indexingDuration); } prefetchingBehavior.BatchProcessingComplete(); indexesToWorkOn.ForEach(x => x.Index.IsMapIndexingInProgress = false); } }
public void Reset() { _controls.ForEach(item => item.Reset()); }
public void UpdateDisplayOrder(IList<SortItem> options) { _session.Transact(session => options.ForEach(item => { var formItem = session.Get<Country>(item.Id); formItem.DisplayOrder = item.Order; session.Update(formItem); })); }
public void AddBusinessForManyWithEmail(IUserBusiness userBusiness, IList <string> userEmails) { userEmails.ForEach(email => AddBusinessWithEmail(userBusiness, email)); }