public LambdaPropertyEngine(Func <PropertyInfo, Json, Object> deserialize, Func <Object, Json> serialize) { deserialize.AssertNotNull(); _deserialize = (pi, j) => deserialize(pi, j); serialize.AssertNotNull(); _serialize = (o, j) => serialize(j); }
/// <summary> /// Writes the items in <paramref name="this"/> to <paramref name="csvWriter"/>. /// </summary> /// <remarks> /// <para> /// Property values are obtained via reflection. /// </para> /// </remarks> /// <typeparam name="T"> /// The type of the items to be written to <paramref name="csvWriter"/>. /// </typeparam> /// <param name="this"> /// The items to write. /// </param> /// <param name="csvWriter"> /// The <see cref="CsvWriter"/>. /// </param> /// <param name="writeHeaderRecord"> /// If <see langword="true"/>, a header record will first be written to <paramref name="csvWriter"/>, which is comprised of all specified property names. /// </param> /// <param name="propertyNames"> /// The names of public properties in <typeparamref name="T"/> that should be written to <paramref name="csvWriter"/>. /// </param> /// <param name="objectToStringConverter"> /// Provides a means of converting items in <paramref name="this"/> to <see cref="String"/>s. /// </param> /// <returns> /// The number of items written. /// </returns> public static int WriteCsv <T>(this IEnumerable <T> @this, CsvWriter csvWriter, bool writeHeaderRecord, string[] propertyNames, Func <object, string> objectToStringConverter) { objectToStringConverter.AssertNotNull("objectToStringConverter"); propertyNames.AssertNotNull("propertyNames"); var propertyInfos = new PropertyInfo[propertyNames.Length]; // get and cache all property infos that we'll need below for (var i = 0; i < propertyNames.Length; ++i) { exceptionHelper.ResolveAndThrowIf(propertyNames[i] == null, "nullPropertyName"); var propertyInfo = typeof(T).GetRuntimeProperty(propertyNames[i]); exceptionHelper.ResolveAndThrowIf(propertyInfo == null, "propertyNotFound", propertyNames[i], typeof(T).FullName); propertyInfos[i] = propertyInfo; } // if a header is requested, just return the property names var header = writeHeaderRecord ? propertyNames : null; // convert each object to a record by obtaining each property value and running it through the objectToStringConverter Func <T, IEnumerable <string> > objectToRecordConverter = o => { var record = new string[propertyNames.Length]; for (var i = 0; i < propertyInfos.Length; ++i) { record[i] = objectToStringConverter(propertyInfos[i].GetValue(o, null)); } return(record); }; return(@this.WriteCsv(csvWriter, header, objectToRecordConverter)); }
public override bool IterWhile(Func <Leaf <TValue>, bool> action) { #if ASSERTS action.AssertNotNull(); #endif if (!First.IterWhile(action)) { return(false); } if (Second == null) { return(true); } if (!Second.IterWhile(action)) { return(false); } if (Third == null) { return(true); } if (!Third.IterWhile(action)) { return(false); } if (Fourth == null) { return(true); } return(Fourth.IterWhile(action)); }
public static TResult SelectLast <TSource, TResult>(this IEnumerable <TSource> source, Func <TSource, TResult> selector) { source.AssertNotNull("source"); selector.AssertNotNull("selector"); return(source.Select(selector).LastOrDefault()); }
/// <summary> /// Queues the specified work to run on the thread pool. /// </summary> /// <param name="function">The work to execute asynchronously</param> public void RunTask(Func <Task> function, bool validateConnected) { long taskId; function.AssertNotNull(nameof(function)); if (cancellationToken.IsCancellationRequested) { return; } if (validateConnected && MgmtSession.Instance.Context == null) { throw new PSInvalidOperationException(Resources.RunConnectSecMgmtAccount); } taskId = totalTaskCount; Interlocked.Increment(ref totalTaskCount); taskCounter.AddCount(); if (Interlocked.Read(ref activeTaskCount) < maxConcurrency) { RunConcurrentTaskAsync(taskId, function()); } else { taskQueue.Enqueue(new Tuple <long, Func <Task> >(taskId, function)); } }
public void Derived_Parameter_Matches(Type _, Func <Type, bool> criteria, int expectedCount) { // We do not care what the Type was, per se, but the Cases should furnish something. _.AssertNotNull(); bool TryReportParameterTypes(IEnumerable <Type> reportedTypes) { OutputHelper.WriteLine( $"Reporting {expectedCount} expected " // ReSharper disable once PossibleNullReferenceException + $"types: {Join(", ", reportedTypes.Select(x => $"'{x.FullName} : {x.BaseType.FullName}'"))}" ); return(true); } var parameterTypes = ParameterTypes.ToArray(); try { parameterTypes.Where(criteria.AssertNotNull()).AssertEqual(expectedCount, x => x.Count()) .AssertTrue(TryReportParameterTypes); } catch (Exception ex) { OutputHelper.WriteLine("Failed to verify derived Parameter matches."); parameterTypes.AssertTrue(TryReportParameterTypes); throw; } }
public static TypeRule Rule(this Func <Type, bool> t) { t.AssertNotNull(); IDisposable _; return(Rule(t, out _)); }
/// <summary> /// Returns the maximal element of a sequence based on a specified projection and comparer for projected /// values. /// </summary> /// <remarks> /// If more than one element has the maximal projected value, the first one encountered will be returned. This /// overload uses the default comparer for the projected type. This operator uses immediate execution, but only /// buffers a single result (the current maximal element). /// </remarks> /// <typeparam name="TSource">The type of source sequence.</typeparam> /// <typeparam name="TKey">The type of projected element.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="selector">A transform function to apply to each element.</param> /// <param name="comparer">A comparer used to compare projected values.</param> /// <returns>The maximal element, according to the projection.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException"><paramref name="selector"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException"><paramref name="comparer"/> is <see langword="null"/>.</exception> /// <exception cref="InvalidOperationException"><paramref name="source"/> is empty.</exception> public static TSource MaxBy <TSource, TKey>( this IEnumerable <TSource> source, Func <TSource, TKey> selector, IComparer <TKey> comparer) { source.AssertNotNull("source"); selector.AssertNotNull("selector"); comparer.AssertNotNull("comparer"); using (IEnumerator <TSource> sourceIterator = source.GetEnumerator()) { if (!sourceIterator.MoveNext()) { throw new InvalidOperationException("The sequence is empty."); } var max = sourceIterator.Current; var maxKey = selector(max); while (sourceIterator.MoveNext()) { var candidate = sourceIterator.Current; var candidateProjected = selector(candidate); if (comparer.Compare(candidateProjected, maxKey) > 0) { max = candidate; maxKey = candidateProjected; } } return(max); } }
public static Task <OperationResult <T> > RequireAsync <T>(this OperationResult <T> currentOperationResult, AsyncPredicate <OperationResult <T> > condition, Func <OperationResult <T>, IOperationError> errorBuilder) => currentOperationResult .DoWhenAsync(async x => !await condition.AssertNotNull(nameof(condition)) .Invoke(x), x => OperationResult <T> .FromError( errorBuilder.AssertNotNull(nameof(errorBuilder)) .Invoke(x)));
public static OperationResult <TNext> ContinueOnSuccess <TPrev, TNext>(this OperationResult <TPrev> prevOperationResult, Func <TPrev, OperationResult <TNext> > nextOperation) => prevOperationResult.AssertNotNull(nameof(prevOperationResult)) .IsSuccess ? prevOperationResult .Continue(x => nextOperation.AssertNotNull(nameof(nextOperation)) .Invoke(prevOperationResult.Value)) : prevOperationResult.AsFailure <TNext>();
public LambdaTypeEngine(Func <Json, Object> deserialize, Func <Object, Json> serialize) { deserialize.AssertNotNull(); _deserialize = (t, j) => deserialize(j); serialize.AssertNotNull(); _serialize = (o, j) => serialize(j); }
public static string ReplaceCodes(string expression, Func <string, string> codeReplacement) { expression.AssertNotNull(nameof(expression)); codeReplacement.AssertNotNull(nameof(codeReplacement)); var codes = GetCodes(expression); var replacementByCode = new Dictionary <string, string>(codes.Count, StringComparer.OrdinalIgnoreCase); var pattern = new StringBuilder(); foreach (var code in codes.OrderByDescending(i => i.Length)) { replacementByCode.Add(code, codeReplacement(code)); if (pattern.Length > 0) { pattern.Append("|"); } // (?<n1>code) pattern.Append("(").Append(Regex.Escape(code)).Append(")"); } return(Regex.Replace(expression, pattern.ToString(), match => replacementByCode[match.Value], RegexOptions.IgnoreCase)); }
/// <summary> /// Registers with a context. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="container">The container.</param> /// <param name="contextBasedFactory">The context based factory.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="contextBasedFactory"/> is <see langword="null"/>. /// </exception> public static void RegisterWithContext <TService>( this Container container, Func <DependencyContext, TService> contextBasedFactory) where TService : class { contextBasedFactory.AssertNotNull("contextBasedFactory"); Func <TService> rootFactory = () => { return(contextBasedFactory(DependencyContext.Root)); }; container.Register <TService>(rootFactory, Lifestyle.Transient); // Allow the Func<DependencyContext, TService> to be // injected into parent types. container.ExpressionBuilding += (sender, e) => { if (e.RegisteredServiceType != typeof(TService)) { var rewriter = new DependencyContextRewriter { ServiceType = e.RegisteredServiceType, ContextBasedFactory = contextBasedFactory, RootFactory = rootFactory, Expression = e.Expression }; e.Expression = rewriter.Visit(e.Expression); } }; }
public static OperationResult <T> Require <T>(this OperationResult <T> currentOperationResult, Predicate <OperationResult <T> > condition, Func <OperationResult <T>, IOperationError> errorBuilder) => currentOperationResult .DoWhen(x => !condition.AssertNotNull(nameof(condition)) .Invoke(x), x => OperationResult <T> .FromError( errorBuilder.AssertNotNull(nameof(errorBuilder)) .Invoke(x)));
public static Task <OperationResult> RequireAsync(this OperationResult currentOperationResult, AsyncPredicate <OperationResult> condition, Func <OperationResult, IOperationError> errorBuilder) => currentOperationResult .DoWhenAsync(async(FunctionalResults.OperationResult x) => !await condition.AssertNotNull(nameof(condition)) .Invoke((FunctionalResults.OperationResult)x), (FunctionalResults.OperationResult x) => (FunctionalResults.OperationResult)FunctionalResults.OperationResult.FromError( errorBuilder.AssertNotNull(nameof(errorBuilder)) .Invoke((FunctionalResults.OperationResult)x)));
public static OperationResult Require(this OperationResult currentOperationResult, Predicate condition, Func <IOperationError> errorBuilder) => currentOperationResult .DoWhen(() => !condition.AssertNotNull(nameof(condition)) .Invoke(), () => OperationResult.FromError( errorBuilder.AssertNotNull(nameof(errorBuilder)) .Invoke()));
public async Task ExecuteAsync(PostId postId, DateTime now, Func <Task> potentialRemovalOperation) { postId.AssertNotNull("postId"); now.AssertUtc("now"); potentialRemovalOperation.AssertNotNull("potentialRemovalOperation"); var queuedCollectionId = await this.tryGetPostQueueId.ExecuteAsync(postId, now); if (queuedCollectionId == null) { await potentialRemovalOperation(); } else { var weeklyReleaseSchedule = await this.getWeeklyReleaseSchedule.ExecuteAsync(queuedCollectionId); using (var transaction = TransactionScopeBuilder.CreateAsync()) { await potentialRemovalOperation(); await this.defragmentQueue.ExecuteAsync(queuedCollectionId, weeklyReleaseSchedule, now); transaction.Complete(); } } }
/// <summary> /// Initializes a new instance of the <see cref="FilterRegistration{TFilter}"/> class. /// </summary> /// <param name="order">The order value for determining the order of execution of filters.</param> /// <param name="factory">The filter factory.</param> public FilterRegistration(int order, Func <IServiceProvider, TFilter> factory) { factory.AssertNotNull(nameof(factory)); Order = order; Factory = factory; }
public static PropertyRule Rule(this Func <PropertyInfo, bool> pi) { pi.AssertNotNull(); IDisposable _; return(Rule(pi, out _)); }
public RegisterationHandle(StateService owner, Func <IStateService, Task> saveTaskFactory) { owner.AssertNotNull(nameof(owner)); saveTaskFactory.AssertNotNull(nameof(saveTaskFactory)); _owner = owner; _saveTaskFactory = saveTaskFactory; }
private void UnregisterSaveCallback(Func <IStateService, Task> saveTaskFactory) { saveTaskFactory.AssertNotNull(nameof(saveTaskFactory)); lock (_sync) { _saveCallbacks.Remove(saveTaskFactory); } }
public MappedObservableCollection(IList <TFrom> source, Func <TFrom, TTo> mapper) : base(new ObservableCollection <TTo>()) { source.AssertNotNull(nameof(source)); mapper.AssertNotNull(nameof(mapper)); SyncAgent = new ListSyncManager <TFrom, TTo>(source, Items, mapper); }
public MainViewModel( Func <ExerciseProgramsViewModel> exerciseProgramsViewModelFactory) { exerciseProgramsViewModelFactory.AssertNotNull(nameof(exerciseProgramsViewModelFactory)); this.router = new RoutingState(); this.exerciseProgramsViewModelFactory = exerciseProgramsViewModelFactory; }
/// <summary> /// Initializes a new instance of the <see cref="DelegateEqualityComparer{T}"/> class. /// </summary> /// <param name="comparer">The comparer.</param> /// <param name="hash">The hash.</param> public DelegateEqualityComparer(Func <T, T, bool> comparer, Func <T, int> hash) { comparer.AssertNotNull("comparer"); hash.AssertNotNull("hash"); this.comparer = comparer; this.hash = hash; }
public MainViewModel( Func<ExerciseProgramsViewModel> exerciseProgramsViewModelFactory) { exerciseProgramsViewModelFactory.AssertNotNull(nameof(exerciseProgramsViewModelFactory)); this.router = new RoutingState(); this.exerciseProgramsViewModelFactory = exerciseProgramsViewModelFactory; }
/// <summary> /// Initializes a new instance of the <see cref="CapturePayment"/> class. /// </summary> /// <param name="paymentGateway">The payment gateway to use for capturing payments.</param> /// <param name="acquireAuthorizationCallFunction">The function to call to obtain the authorization code.</param> public CapturePayment(IPaymentGateway paymentGateway, Func <string> acquireAuthorizationCallFunction) { paymentGateway.AssertNotNull(nameof(paymentGateway)); acquireAuthorizationCallFunction.AssertNotNull(nameof(acquireAuthorizationCallFunction)); this.PaymentGateway = paymentGateway; this.AcquireInput = acquireAuthorizationCallFunction; }
public static PropertyRule Rule(this Func <PropertyInfo, bool> pi, out IDisposable unreg) { pi.AssertNotNull(); var rule = new PropertyRule(pi); Repository.Rules.Add(rule); unreg = new DisposableAction(() => Repository.Rules.Remove(rule)); return(rule); }
public static async ValueTask <T?> AggregateAsync <T>(this IAsyncEnumerable <T>? @this, T initialValue, Func <T, T, T> aggregator, CancellationToken token = default) { aggregator.AssertNotNull(nameof(aggregator)); var result = initialValue; await @this.DoAsync(item => result = aggregator(result !, item), token : token); return(result); }
public StaticLicenseSource(StaticLicenseConfiguration configuration, Func <HttpClient> httpClientFactory) { configuration.AssertNotNull(nameof(configuration)); httpClientFactory.AssertNotNull(nameof(httpClientFactory)); HttpClientFactory = httpClientFactory; _codeByUrl = CreateCodeByUrl(configuration.ByUrl); _urlByCode = CreateUrlByCode(configuration.ByCode); }
public static TypeRule Rule(this Func <Type, bool> t, out IDisposable unreg) { t.AssertNotNull(); var rule = new TypeRule(t); Repository.Rules.Add(rule); unreg = new DisposableAction(() => Repository.Rules.Remove(rule)); return(rule); }
public static AsyncCommandBuilder <T> Attach <T>(this IAsyncCommand <T> command, Func <T, Task> handler) { command.AssertNotNull(nameof(command)); handler.AssertNotNull(nameof(handler)); command.Handler = handler; return(new AsyncCommandBuilder <T>(command)); }
private void InitializeCore( BaseControlFlowGraph source, Func<ControlFlowBlock, bool> vertexFilter, Func<ControlFlowEdge, bool> edgeFilter, Action<ControlFlowEdge, ViewOfControlFlowGraph> onAlienEdge) { Source = source.AssertNotNull(); HookUpVertexPostprocessors(); _vertexFilter = vertexFilter.AssertNotNull(); _edgeFilter = edgeFilter.AssertNotNull(); _cachedVertices = _hardcodedVertices != null ? null : source.Vertices.Where(_vertexFilter).ToList(); (_cachedVertices ?? _hardcodedVertices.AsEnumerable()).ForEach(OnVertexAdded); ReadOnlyCollection<ControlFlowEdge> alienEdges = null; if (_hardcodedEdges != null) { var edgeVertices = _hardcodedEdges.SelectMany(e => new []{e.Source, e.Target}).ToHashSet(); edgeVertices.ExceptWith(_cachedVertices ?? _hardcodedVertices.AsEnumerable()); edgeVertices.AssertEmpty(); } else { _edgeFilter = e => edgeFilter(e) && _vertexFilter(e.Source) && _vertexFilter(e.Target); var relatedEdges = source.Edges(_vertexFilter, null).Concat(source.Edges(null, _vertexFilter)).Distinct(); var parts = relatedEdges.GroupBy(e => _edgeFilter(e)).ToDictionary(g => g.Key, g => g.AsEnumerable()); _cachedEdges = (parts.GetOrDefault(true, Seq.Empty<ControlFlowEdge>)).ToList(); alienEdges = parts.GetOrDefault(false, Seq.Empty<ControlFlowEdge>).ToReadOnly(); } (_cachedEdges ?? _hardcodedEdges.AsEnumerable()).ForEach(OnEdgeAdded); Action<ControlFlowBlock> cacheVertex = v => { if (_cachedVertices != null) _cachedVertices.Add(v); else throw AssertionHelper.Fail(); }; Action<ControlFlowBlock> uncacheVertex = v => { if (_cachedVertices != null) _cachedVertices.Remove(v); else _hardcodedVertices.Remove(v); }; source.VertexAdded += v => { if (_vertexFilter(v)) { cacheVertex(v); OnVertexAdded(v); } }; source.VertexRemoved += v => { if (_vertexFilter(v)) { uncacheVertex(v); OnVertexRemoved(v); } }; Action<ControlFlowEdge> cacheEdge = e => { if (_cachedEdges != null) _cachedEdges.Add(e); else throw AssertionHelper.Fail(); }; Action<ControlFlowEdge> uncacheEdge = e => { if (_cachedEdges != null) _cachedEdges.Remove(e); else _hardcodedEdges.Remove(e); }; source.EdgeAdded += e => { if (_edgeFilter(e)) { cacheEdge(e); OnEdgeAdded(e); } }; source.EdgeRemoved += e => { if (_edgeFilter(e)) { uncacheEdge(e); OnEdgeRemoved(e); } }; __vertices = new VirtualList<ControlFlowBlock>( () => (_hardcodedVertices ?? (IEnumerable<ControlFlowBlock>)_cachedVertices).Concat(_eigenVertices), (i, v) => { if (_eigenVertices.Contains(v)) { // do nothing - the vertex has just been created by AddEigenVertex } else { _vertexFilter(v).AssertTrue(); (_cachedVertices != null && i == _cachedVertices.Count()).AssertTrue(); Source.AddVertex(v); } }, (i, v) => { _vertexFilter(v).AssertTrue(); throw AssertionHelper.Fail(); }, i => { if (i < _cachedEdges.Count()) { var v = _cachedVertices[i]; Source.RemoveVertex(v); } else { throw AssertionHelper.Fail(); } }); __edges = new VirtualList<ControlFlowEdge>( () => (_hardcodedEdges ?? (IEnumerable<ControlFlowEdge>)_cachedEdges).Concat(_eigenEdges), (i, e) => { if (_eigenEdges.Contains(e)) { // do nothing - the edge has just been created by AddEigenEdge } else { _edgeFilter(e).AssertTrue(); (_cachedEdges != null && i == _cachedEdges.Count()).AssertTrue(); Source.AddEdge(e); } }, (i, e) => { _edgeFilter(e).AssertTrue(); throw AssertionHelper.Fail(); }, i => { if (i < _cachedEdges.Count()) { var e = _cachedEdges[i]; Source.RemoveEdge(e); } else { var e = _eigenEdges[i - _cachedEdges.Count()]; _eigenEdges.Remove(e); } }); try { _allowAutoCreateStartAndFinish = true; alienEdges.ForEach(e => onAlienEdge(e, this)); } finally { _allowAutoCreateStartAndFinish = false; } }
protected Rule(Func<Type, bool> type) { type.AssertNotNull(); Filter = mi => mi is Type && type(mi.AssertCast<Type>()); Hash = new Dictionary<Object, Object>(); }
protected Rule(Func<PropertyInfo, bool> property) { property.AssertNotNull(); Filter = mi => mi is PropertyInfo && property(mi.AssertCast<PropertyInfo>()); Hash = new Dictionary<Object, Object>(); }
public TypeRule(Func<Type, bool> filter) { Filter = filter.AssertNotNull(); }
/// <summary> /// Asynchronously writes all rows in <paramref name="this"/> to <paramref name="csvWriter"/>. /// </summary> /// <remarks> /// </remarks> /// <param name="this"> /// The <see cref="DataTable"/>. /// </param> /// <param name="csvWriter"> /// The <see cref="CsvWriter"/>. /// </param> /// <param name="writeHeaderRecord"> /// If <see langword="true"/>, a header record will also be written, which will be comprised of the column names defined for <paramref name="this"/>. /// </param> /// <param name="maximumRows"> /// The maximum number of rows from <paramref name="this"/> that should be written to <paramref name="csvWriter"/>. /// </param> /// <param name="objectToStringConverter"> /// Provides a means of converting values in the <see cref="DataRow"/>s to <see cref="String"/>s. /// </param> /// <returns> /// The actual number of rows from <paramref name="this"/> written to <paramref name="csvWriter"/>. /// </returns> public async static Task<int> WriteCsvAsync(this DataTable @this, CsvWriter csvWriter, bool writeHeaderRecord, int? maximumRows, Func<object, string> objectToStringConverter) { @this.AssertNotNull("@this"); csvWriter.AssertNotNull("csvWriter"); objectToStringConverter.AssertNotNull("objectToStringConverter"); var num = 0; if (writeHeaderRecord) { var columnNames = new string[@this.Columns.Count]; for (var i = 0; i < columnNames.Length; ++i) { columnNames[i] = @this.Columns[i].ColumnName; } await csvWriter.WriteRecordAsync(columnNames).ConfigureAwait(false); } var maximum = maximumRows.GetValueOrDefault(int.MaxValue); var buffer = new DataRecord[16]; var bufferOffset = 0; foreach (DataRow row in @this.Rows) { var record = new DataRecord(); for (var i = 0; i < row.ItemArray.Length; ++i) { record.Add(objectToStringConverter(row.ItemArray[i])); } buffer[bufferOffset++] = record; if (bufferOffset == buffer.Length) { // buffer full await csvWriter.WriteRecordsAsync(buffer, 0, buffer.Length).ConfigureAwait(false); bufferOffset = 0; } if (++num == maximum) { break; } } // write any outstanding data in buffer await csvWriter.WriteRecordsAsync(buffer, 0, bufferOffset).ConfigureAwait(false); return num; }
public Codebase Redirect(Func<MethodBase, bool> filter, Func<MethodBase, ReadOnlyCollection<Expression>, MethodBase> map_m, Func<MethodBase, ReadOnlyCollection<Expression>, IEnumerable<Expression>> map_args) { _redirects.Add(filter.AssertNotNull(), Tuple.New(map_m.AssertNotNull(), map_args.AssertNotNull())); return this; }
public Codebase Special(Func<MethodBase, bool> filter) { _special.Add(filter.AssertNotNull()); return this; }
public Codebase OptOut(Func<MethodBase, bool> filter) { _optOut.Add(filter.AssertNotNull()); return this; }
protected Rule(Func<MemberInfo, bool> member) { Filter = member.AssertNotNull(); Hash = new Dictionary<Object, Object>(); }