private static Lifetime GetLifetime(IImmutableList <AttributeData> attributes) { if (attributes.Any(a => a.AttributeClass?.Name == "InjectSingletonAttribute")) { return(Lifetime.Singleton); } if (attributes.Any(a => a.AttributeClass?.Name == "InjectScopedAttribute")) { return(Lifetime.Scoped); } if (attributes.Any(a => a.AttributeClass?.Name == "InjectTransientAttribute")) { return(Lifetime.Transient); } var injectAttribute = attributes.FirstOrDefault(a => a.AttributeClass?.Name == "InjectAttribute"); if (injectAttribute == null) { return(Lifetime.None); } var injectArg = injectAttribute.ConstructorArguments.FirstOrDefault(); if (injectArg.IsNull || injectArg.Kind != TypedConstantKind.Enum || injectArg.Type?.ToString() != "Microsoft.Extensions.DependencyInjection.ServiceLifetime") { return(Lifetime.None); } return(injectArg.Value switch { 1 => Lifetime.Scoped, 2 => Lifetime.Transient, // 0 (singleton) or others _ => Lifetime.Singleton, });
private static string GetCandidateAlert(CheckInOutRequest request, IImmutableList <CheckInOutCandidate> checkInOutCandidates, out AlertLevel level) { var text = ""; level = AlertLevel.Info; if (request.CheckType != CheckType.CheckOut) { return(text); } if (checkInOutCandidates.Any(predicate: c => !c.MayLeaveAlone)) { text = "Kinder mit gelbem Hintergrund dürfen nicht alleine gehen"; level = AlertLevel.Warning; } if (!checkInOutCandidates.Any(predicate: c => c.HasPeopleWithoutPickupPermission)) { return(text); } text = "Bei Kindern mit rotem Hintergrund gibt es Personen, die nicht abholberechtigt sind"; level = AlertLevel.Danger; return(text); }
private static IEnumerable <SyntaxNode> AffectedExpressions(SyntaxNode node) { return(node .DescendantNodesAndSelf() .Where(n => SideEffectExpressions.Any(s => s.Kinds.Any(n.IsKind))) .Select(n => SideEffectExpressions.Single(s => s.Kinds.Any(n.IsKind)).AffectedExpression(n))); }
private LogItemViewModel header( GroupId groupId, IImmutableList <IThreadSafeTimeEntry> group, LogItemVisualizationIntent visualizationIntent, int indexInLog, int dayInLog, int daysInThePast) { var sample = group.First(); return(new LogItemViewModel( groupId: groupId, representedTimeEntriesIds: group.Select(timeEntry => timeEntry.Id).ToArray(), visualizationIntent: visualizationIntent, isBillable: sample.Billable, isActive: sample.Project?.Active ?? true, description: sample.Description, duration: DurationAndFormatToString.Convert( TimeSpan.FromSeconds(group.Sum(timeEntry => timeEntry.Duration ?? 0)), durationFormat), projectName: sample.Project?.DisplayName(), projectColor: sample.Project?.Color, clientName: sample.Project?.Client?.Name, taskName: sample.Task?.Name, hasTags: sample.Tags.Any(), needsSync: group.Any(timeEntry => timeEntry.SyncStatus == SyncStatus.SyncNeeded), canSync: group.All(timeEntry => timeEntry.SyncStatus != SyncStatus.SyncFailed), isInaccessible: sample.IsInaccessible, indexInLog: indexInLog, dayInLog: dayInLog, daysInThePast: daysInThePast, projectIsPlaceholder: sample.Project?.IsPlaceholder() ?? false, taskIsPlaceholder: sample.Task?.IsPlaceholder() ?? false)); }
internal DropFunctionsCommand(IImmutableList <EntityName> functionNames) { if (!functionNames.Any()) { throw new ArgumentException("Empty", nameof(functionNames)); } FunctionNames = functionNames; }
internal DropTablesCommand(IImmutableList <EntityName> tableNames) { if (!tableNames.Any()) { throw new ArgumentNullException(nameof(tableNames), "At least one table name is needed"); } TableNames = tableNames.OrderBy(n => n.Name).ToImmutableArray(); }
public void SetItems(IImmutableList <TModel> items) { var sections = ImmutableList <TSection> .Empty; if (items != null && items.Any()) { var newSection = new TSection(); newSection.Initialize(default, items);
public DataFiles(DataFile dataFile, EventDirectory parent) { Name = dataFile.Name; IsIgnored = _ignoredFiles.Any(item => item == dataFile.NameWithExtension); IsValid = GetIsValid(dataFile.Name, parent); Parent = parent; Files = new DataFile[] { dataFile }.ToImmutableList(); }
private static Result InvalidStateCheck(IImmutableList <Speed> averagesPerActivity) { if (!averagesPerActivity.Any()) { return(Result.Failure("Constructor argument list of averages should not be empty.")); } return(Result.Ok()); }
public GradientColorBuilder Add(GradientColorByValue gradientColor) { if (_gradientColorList.Any(item => item.Value == gradientColor.Value)) { throw new InvalidOperationException($"Gradient color value ({gradientColor.Value}) is already defined"); } return(ShallowClone(_gradientColorList.Add(gradientColor))); }
private static IImmutableList <Event> RequireAtLeastOneEvent(IImmutableList <Event> events) { if (!events.Any()) { throw new ArgumentException("A commit must at least contain one event.", nameof(events)); } return(events); }
/// <summary> /// For a list of strings, tries to parse those strings into instance of the supplied types. /// </summary> /// <param name="args">The input to be parsed, supplied as a list of string arguments</param> /// <param name="types">The types of which instances will be attempted to be created from the input.</param> /// <param name="errorOnRemainingArgs">Whether it is an error if the arguments weren't fully consumed.</param> /// <returns>A parsing result object. On success that will contain a list of objects with the same length /// and same types as supplied in <paramref name="types"/></returns> /// <exception cref="MissingParserException">If there was no parser found for one of the supplied types. /// You must register a parser using <see cref="AddArgumentParser{T}"/> for each type.</exception> /// <exception cref="InvalidOperationException">If the requested types cannot be parsed, /// because their types or respective parsers are not implemented correctly.</exception> public async Task <ArgsParseResult <List <object> > > ParseRaw( IImmutableList <string> args, IEnumerable <Type> types, bool errorOnRemainingArgs = false) { IImmutableList <string> allRemainingArgs = args; var results = new List <object>(); bool success = true; var failures = new List <Failure>(); foreach (var type in types) { Type?queryType = type.IsGenericType ? type.BaseType : type; if (queryType == null || queryType.IsGenericType) { throw new InvalidOperationException($"generic type {type} need a non-generic base type"); } if (!_parsers.TryGetValue(queryType, out IArgumentParser? parser)) { throw new MissingParserException(typeWithoutParser: type); } Debug.Assert(parser != null, "try-get succeeded and the dictionary does not contain null values"); Type[] genericTypes = type.IsGenericType ? type.GenericTypeArguments : Array.Empty <Type>(); ArgsParseResult <object> parseResult; try { parseResult = await parser.Parse(allRemainingArgs, genericTypes); } catch (ArgumentOutOfRangeException) { failures.Add(new Failure(ErrorRelevanceConfidence.Unlikely, "too few arguments")); success = false; break; } failures.AddRange(parseResult.Failures); if (parseResult.SuccessResult != null) { Success <object> successResult = parseResult.SuccessResult.Value; results.Add(successResult.Result); allRemainingArgs = successResult.RemainingArgs; } else { success = false; break; } } if (success && errorOnRemainingArgs && allRemainingArgs.Any()) { success = false; failures.Add(new Failure(ErrorRelevanceConfidence.Unlikely, "too many arguments")); } return(success ? ArgsParseResult <List <object> > .Success(failures.ToImmutableList(), results, allRemainingArgs) : ArgsParseResult <List <object> > .Failure(failures.ToImmutableList())); }
public Part(string server, Prefix prefix, IImmutableList<string> destinations) { if (String.IsNullOrWhiteSpace(server)) throw new ArgumentException("Null or whitespace string", "server"); if (prefix == null) throw new ArgumentNullException("prefix"); if (destinations == null) throw new ArgumentNullException("destinations"); if (destinations.Count == 0 || destinations.Any(c => String.IsNullOrWhiteSpace(c))) throw new ArgumentException("Empty destination list or list contains an empty element.", "destinations"); this.server = server; this.prefix = prefix; this.destinations = destinations; this.ircMessage = Common.CreateIrcMessageFormat(this.Prefix, Part.CanonicalCommand, "{0}", this.Destinations); }
public List(string server, Prefix prefix, IImmutableList<string> channels) { if (String.IsNullOrWhiteSpace(server)) throw new ArgumentException("Null or whitespace string", "server"); if (prefix == null) throw new ArgumentNullException("prefix"); if (channels == null) throw new ArgumentNullException("channels"); if (channels.Count == 0 || channels.Any(c => String.IsNullOrWhiteSpace(c))) throw new ArgumentException("Empty channel list or list contains an empty element.", "channels"); this.server = server; this.prefix = prefix; this.channels = channels; this.ircMessage = Common.CreateIrcMessageFormat(prefix, List.CanonicalCommand, "{0}", String.Join(",", this.Channels)); }
public Message(string server, Prefix prefix, string command, IImmutableList<string> parameters) { if (String.IsNullOrWhiteSpace(server)) throw new ArgumentException("String null or empty", "server"); if (prefix == null) throw new ArgumentNullException("prefix"); if (String.IsNullOrWhiteSpace(command)) throw new ArgumentException("String null or empty", "command"); if (parameters == null) throw new ArgumentNullException("parameters"); if (parameters.Any(s => String.IsNullOrWhiteSpace(s))) throw new ArgumentException("Empty or null parameter", "parameters"); this.server = server; this.prefix = prefix; this.command = command; this.parameters = parameters; }
public void AddDocumentBatch(long timeStamp, IImmutableList <Block> blocks) { if (_initialized == null) { throw new InvalidOperationException("InitializeAsync hasn't been called"); } if (blocks.Any()) { _initialized.Fat.AddDocumentBatch(timeStamp, blocks); _isDirty = true; } }
public Join(string server, Prefix prefix, IImmutableList<string> channels, Maybe<IImmutableList<string>> keys) { if (String.IsNullOrWhiteSpace(server)) throw new ArgumentException("Null or whitespace string", "server"); if (prefix == null) throw new ArgumentNullException("prefix"); if (channels == null) throw new ArgumentNullException("channels"); if (channels.Count == 0 || channels.Any(c => String.IsNullOrWhiteSpace(c))) throw new ArgumentException("Empty channel list or list contains an empty element.", "channels"); if (keys.HasValue && keys.Value.Count != 0 && (keys.Value.Count != channels.Count || keys.Value.Any(k => String.IsNullOrWhiteSpace(k)))) throw new ArgumentException("Non-empty key list contains an empty element or doesn't have the same number of elements as the channel list.", "keys"); this.server = server; this.prefix = prefix; this.channels = channels; this.keys = keys.DefaultIfEmpty(ImmutableList<string>.Empty).Single(); this.ircMessage = Common.CreateIrcMessageFormat(prefix, Join.CanonicalCommand, "{0} {1}", String.Join(",", this.Channels), String.Join(",", this.Keys)); }
public AlterTablesRetentionPolicyCommand( IEnumerable <EntityName> tableNames, JsonDocument policy) : base(policy) { TableNames = tableNames .OrderBy(t => t.Name) .ToImmutableArray(); if (!TableNames.Any()) { throw new ArgumentOutOfRangeException( nameof(tableNames), "Should contain at least one table name"); } }
public async Task <bool> UpdateNoSqlAsync(IImmutableList <BookChangeInfo> booksToUpdate) { if (_noSqlContext == null || !booksToUpdate.Any()) { return(false); } foreach (var bookToUpdate in booksToUpdate) { switch (bookToUpdate.State) { case EntityState.Deleted: { var noSqlBook = await _noSqlContext.FindAsync <BookListNoSql>(bookToUpdate.BookId); _noSqlContext.Remove(noSqlBook); break; } case EntityState.Modified: { //Note: You need to read the actual Cosmos entity because of the extra columns like id, _rid, etc. //Version 3 might make attach work https://github.com/aspnet/EntityFrameworkCore/issues/13633 var noSqlBook = await _noSqlContext.FindAsync <BookListNoSql>(bookToUpdate.BookId); var update = await _sqlContext.Set <Book>() .ProjectTo <BookListNoSql>(SqlToNoSqlMapper) .SingleAsync(x => x.BookId == bookToUpdate.BookId); SqlToNoSqlMapper.CreateMapper().Map(update, noSqlBook); break; } case EntityState.Added: var newBook = await _sqlContext.Set <Book>() .ProjectTo <BookListNoSql>(SqlToNoSqlMapper) .SingleAsync(x => x.BookId == bookToUpdate.BookId); _noSqlContext.Add(newBook); break; default: throw new ArgumentOutOfRangeException(); } } return(true); }
private void RemoveOperation(IWampRpcOperation operation) { lock (mLock) { RaiseCalleeUnregistering(operation); mOperations = mOperations.Remove(operation); RaiseCalleeUnregistered(operation); if (!mOperations.Any()) { RaiseEmpty(); } } }
private async Task <T> ExecuteHttpRequest <T>(Method httpMethod, string url, object body, IImmutableList <Parameter> parameters) { if (url == null) { url = string.Empty; } if (!string.IsNullOrEmpty(url) && url.StartsWith('/')) { url = url.Substring(1); } try { var request = new RestRequest(url, httpMethod); if (parameters != null && parameters.Any()) { parameters.ForEach(x => request.AddParameter(x)); } if (body != null) { BuildContent(request, body); } PrepareRequest(request); var response = await _restClient.ExecuteAsync(request); LogHttpRequest(response); if ((int)response.StatusCode < 200 || (int)response.StatusCode >= 300) { throw new HttpClientException(response.StatusCode, response.Content); } return((T)BuildResponse <T>(response)); } catch (Exception ex) { HandleException(ex); throw; } }
private void PrintHelpEntries(IImmutableList <HelpEntry> helpEntries, string entriesHeader) { if (!helpEntries.Any()) { return; } _sysConsole .WriteLine() .WriteLine(entriesHeader) .WriteLine(); var firstColumnWidth = helpEntries.Select(x => x.ArgumentName?.Length ?? 0).Max() + 3; helpEntries .ForEach(x => _sysConsole.WriteLine($" {x.ArgumentName?.PadRight(firstColumnWidth)}{x.HelpText}")); }
private static string RenderAssetInContent(string content, IImmutableList <Asset> assets) { if (assets.Any()) { var builder = new StringBuilder(content); foreach (var asset in assets) { builder.Replace(asset.SourceUri.ToString(), '/' + asset.FilePath); } return(builder.ToString()); } else { return(content); } }
public bool UpdateNoSql(IImmutableList <BookChangeInfo> booksToUpdate) { if (_noSqlContext == null || !booksToUpdate.Any()) { return(false); } foreach (var bookToUpdate in booksToUpdate) { switch (bookToUpdate.State) { case EntityState.Deleted: { var noSqlBook = _noSqlContext.Find <BookListNoSql>(bookToUpdate.BookId); _noSqlContext.Remove(noSqlBook); break; } case EntityState.Modified: { var noSqlBook = _noSqlContext.Find <BookListNoSql>(bookToUpdate.BookId); var update = _sqlContext.Set <Book>() .ProjectTo <BookListNoSql>(SqlToNoSqlMapper) .Single(x => x.BookId == bookToUpdate.BookId); SqlToNoSqlMapper.CreateMapper().Map(update, noSqlBook); break; } case EntityState.Added: var newBook = _sqlContext.Set <Book>() .ProjectTo <BookListNoSql>(SqlToNoSqlMapper) .Single(x => x.BookId == bookToUpdate.BookId); _noSqlContext.Add(newBook); break; default: throw new ArgumentOutOfRangeException(); } } return(true); }
public override void VisitClassDeclaration(ClassDeclarationSyntax node) { IImmutableList <ITypeSymbol> baseTypes = SemanticModel.GetAllBaseTypeSymbols(node); bool isController = baseTypes.Any(t => t.Equals(KnownTypes.Controller)); if (!isController) { return; } IImmutableList <AttributeUsageInfo> attributeInfo = SemanticModel.GetAttributeInfo(node.AttributeLists); bool isVersioned = attributeInfo.Any(info => info.AttributeType.Equals(KnownTypes.ApiVersionAttribute)); if (!isVersioned) { return; } base.VisitClassDeclaration(node); }
public override async Task <ArgsParseResult <Optional> > Parse( IImmutableList <string> args, Type[] genericTypes) { if (genericTypes.Length != 1) { throw new ArgumentException($"Only expected 1 generic argument for {typeof(Optional)}, " + $"but got {genericTypes.Length}"); } var type = typeof(Optional <>).MakeGenericType(genericTypes[0]); ConstructorInfo?constructor = type.GetConstructor(new[] { typeof(bool), genericTypes[0] }); if (constructor == null) { throw new InvalidOperationException($"{type} needs a constructor (bool present, T value)."); } if (!args.Any()) { var optional = (Optional)constructor.Invoke(new object?[] { false, null }); return(ArgsParseResult <Optional> .Success(optional, args)); } ArgsParseResult <List <object> > parseResult = await _argsParser.ParseRaw(args, genericTypes); if (parseResult.SuccessResult != null) { Success <List <object> > success = parseResult.SuccessResult.Value; var optional = (Optional)constructor.Invoke(new[] { true, success.Result[0] }); return(ArgsParseResult <Optional> .Success(parseResult.Failures, optional, success.RemainingArgs)); } else { var optional = (Optional)constructor.Invoke(new object?[] { false, null }); return(ArgsParseResult <Optional> .Success(parseResult.Failures, optional, args)); } }
private bool ContainsSource(IDocumentSource source) { return(indexers.Any(indexer => indexer.Source == source)); }
private static bool HasMembersAndAllAreStatic(IImmutableList<ISymbol> members) { return members.Any() && members.All(member => member.IsStatic); }
private static bool HasMembersAndAllAreStatic(IImmutableList <ISymbol> members) { return(members.Any() && members.All(member => member.IsStatic)); }
/// <summary> /// This MUST be called before SavChanges. It finds any Book changes /// </summary> /// <returns>true if there are BookChanges that need projecting to NoSQL database</returns> public bool FindBookChangesToProjectToNoSql(SqlDbContext sqlContext) { _bookChanges = BookChangeInfo.FindBookChanges(sqlContext.ChangeTracker.Entries().ToList(), sqlContext); return(_bookChanges.Any()); }