CompleterResult GetImplementations()
        {
            Func <Func <string, string>, string, Func <CompleterError>, Either <CompleterError, string> > getImplementation = (getImpl, interfaceName, check) => {
                var interfaceType = model.Compilation.GetTypeByMetadataName(interfaceName);
                if (type.AllInterfaces.Contains(interfaceType))
                {
                    var error = check.With(x => x());
                    if (error != null)
                    {
                        return(error);
                    }
                    return(string.Empty);
                }
                return(getImpl(type.Name).AddTabs(1));
            };
            const string IDataErrorInfoName = "System.ComponentModel.IDataErrorInfo";
            Func <string, string, string> getIDataErrorInfoPropertyImplementation = (implementation, name) =>
                                                                                    type.Properties().Any(m => (m.Name == IDataErrorInfoName + "." + name) || (m.DeclaredAccessibility == Microsoft.CodeAnalysis.Accessibility.Public && m.Name == name))
                     ? null
                     : implementation;
            var iDataErrorInfoType          = model.Compilation.GetTypeByMetadataName(IDataErrorInfoName);
            var dataErrorInfoImplementation = type.AllInterfaces.Contains(iDataErrorInfoType)
                ? (
                getIDataErrorInfoPropertyImplementation(DataErrorInfoErrorImplementation, "Error")
                +
                getIDataErrorInfoPropertyImplementation(DataErrorInfoIndexerImplementation, "this[]")
                ) : null;
            Func <CompleterError> checkRaisePropertyChangedMethod = () => {
                Func <CompleterError> error     = () => CompleterError.CreateForTypeName(type, Messages.POCO_RaisePropertyChangedMethodNotFound.Format(type.Name));
                var raisePropertyChangedMethods = methods.GetValueOrDefault("RaisePropertyChanged", ImmutableArray <IMethodSymbol> .Empty);
                if (raisePropertyChangedMethods.IsEmpty)
                {
                    return(error());
                }
                var raisePropertyChangedMethod = raisePropertyChangedMethods.FirstOrDefault(method => {
                    if (method.Parameters.Length != 1)
                    {
                        return(false);
                    }
                    var parameter = method.Parameters.Single();
                    return(parameter.RefKind == RefKind.None && parameter.Type.SpecialType == SpecialType.System_String);
                });
                if (raisePropertyChangedMethod == null)
                {
                    return(error());
                }
                return(null);
            };

            return(new[] {
                getImplementation(INPCImplemetation, "System.ComponentModel.INotifyPropertyChanged", checkRaisePropertyChangedMethod),
                getImplementation(ParentViewModelImplementation, "DevExpress.Mvvm.ISupportParentViewModel", null),
                getImplementation(SupportServicesImplementation, "DevExpress.Mvvm.ISupportServices", null),
                dataErrorInfoImplementation,
            }
                   .AggregateEither(errors => errors.ToImmutableArray(), values => values.ConcatStringsWithNewLines()));
        }
        public ComposableCatalog AddPart(ComposablePartDefinition partDefinition)
        {
            Requires.NotNull(partDefinition, nameof(partDefinition));

            var parts = this.parts.Add(partDefinition);

            if (parts == this.parts)
            {
                // This part is already in the catalog.
                return(this);
            }

            var exportsByContract = this.exportsByContract;

            foreach (var exportDefinition in partDefinition.ExportedTypes)
            {
                var list = exportsByContract.GetValueOrDefault(exportDefinition.ContractName, ImmutableList.Create <ExportDefinitionBinding>());
                exportsByContract = exportsByContract.SetItem(exportDefinition.ContractName, list.Add(new ExportDefinitionBinding(exportDefinition, partDefinition, default(MemberRef))));
            }

            foreach (var exportPair in partDefinition.ExportingMembers)
            {
                var member = exportPair.Key;
                foreach (var export in exportPair.Value)
                {
                    var list = exportsByContract.GetValueOrDefault(export.ContractName, ImmutableList.Create <ExportDefinitionBinding>());
                    exportsByContract = exportsByContract.SetItem(export.ContractName, list.Add(new ExportDefinitionBinding(export, partDefinition, member)));
                }
            }

            return(new ComposableCatalog(parts, exportsByContract, this.DiscoveredParts, this.Resolver));
        }
Example #3
0
        private static void AnalyzeCall(SyntaxNodeAnalysisContext context)
        {
            var call = context.Node as InvocationExpressionSyntax;

            if (call == null)
            {
                return;
            }

            var methodSymbol = SymbolHelpers.GetCalledMethodSymbol(call, context);

            if (methodSymbol == null)
            {
                return;
            }

            var methodFullName =
                string.Concat(methodSymbol.ContainingType.GetFullName(), ".", methodSymbol.GetDecoratedName());

            var descriptor = DiagnosticsMap.GetValueOrDefault(methodFullName);

            if (descriptor == null)
            {
                return;
            }

            if (call.Parent is ExpressionStatementSyntax)
            {
                var diagnostic = Diagnostic.Create(descriptor, call.GetLocation(), call.ToString());
                context.ReportDiagnostic(diagnostic);
            }
        }
Example #4
0
        private void ProcessItem(T item)
        {
            var hashCode = item.GetHashCode();

            if (_mainStore.ContainsKey(hashCode))
            {
                var al = _mainStore.GetValueOrDefault(hashCode);

                _mainStore = _mainStore.SetItem(hashCode, ++al);

                foreach (var subItem in _storeValues.Where(subItem => subItem.obj.Equals(item)))
                {
                    subItem.Count++;
                    break;
                }
            }
            else
            {
                _mainStore = _mainStore.SetItem(hashCode, 1);

                _storeValues = _storeValues.Add(new jcAnalyticsGroupItem <T> {
                    Count = 1, obj = item
                });
            }
        }
Example #5
0
    public void OnPacket(object sender, PacketReader reader)
    {
        RecvOp             op      = (RecvOp)reader.Read <ushort>();
        IPacketHandler <T> handler = Handlers.GetValueOrDefault(op);

        handler?.Handle(sender as T, reader);
    }
        private ISet <KindAndKey> ComputeChangedItemsForFullDataSet(
            ImmutableDictionary <DataKind, ImmutableDictionary <String, ItemDescriptor> > oldDataMap,
            ImmutableDictionary <DataKind, ImmutableDictionary <String, ItemDescriptor> > newDataMap
            )
        {
            ISet <KindAndKey> affectedItems = new HashSet <KindAndKey>();
            var emptyDict = ImmutableDictionary.Create <string, ItemDescriptor>();

            foreach (var kind in DataModel.AllDataKinds)
            {
                var oldItems = oldDataMap.GetValueOrDefault(kind, emptyDict);
                var newItems = newDataMap.GetValueOrDefault(kind, emptyDict);
                var allKeys  = oldItems.Keys.ToImmutableHashSet().Union(newItems.Keys);
                foreach (var key in allKeys)
                {
                    var hasOldItem = oldItems.TryGetValue(key, out var oldItem);
                    var hasNewItem = newItems.TryGetValue(key, out var newItem);
                    if (!hasOldItem && !hasNewItem)
                    {
                        continue; // shouldn't be possible due to how we computed allKeys
                    }
                    if (!hasOldItem || !hasNewItem || (oldItem.Version < newItem.Version))
                    {
                        _dependencyTracker.AddAffectedItems(affectedItems, new KindAndKey(kind, key));
                    }
                    // Note that comparing the version numbers is sufficient; we don't have to compare every detail of the
                    // flag or segment configuration, because it's a basic underlying assumption of the entire LD data model
                    // that if an entity's version number hasn't changed, then the entity hasn't changed (and that if two
                    // version numbers are different, the higher one is the more recent version).
                }
            }
            return(affectedItems);
        }
Example #7
0
        public void OnPacket(object sender, Packet packet)
        {
            PacketReader       reader  = packet.Reader();
            ushort             op      = reader.ReadUShort();
            IPacketHandler <T> handler = handlers.GetValueOrDefault((RecvOp)op);

            handler?.Handle(sender as T, reader);
        }
        public PropertyAccessor GetPropertyAccessor(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(propertyInfo));
            }

            return(_properties.GetValueOrDefault(propertyInfo));
        }
        public IImmutableSet <ProjectId> GetProjectsThatThisProjectDirectlyDependsOn(ProjectId projectId)
        {
            if (projectId == null)
            {
                throw new ArgumentNullException(nameof(projectId));
            }

            return(_referencesMap.GetValueOrDefault(projectId, ImmutableHashSet <ProjectId> .Empty));
        }
        private ImmutableHashSet <ProjectId> GetProjectsThatDirectlyDependOnThisProject_NoLock(ProjectId projectId)
        {
            if (_lazyReverseReferencesMap == null)
            {
                _lazyReverseReferencesMap = this.ComputeReverseReferencesMap();
                ValidateReverseReferences(_projectIds, _referencesMap, _lazyReverseReferencesMap);
            }

            return(_lazyReverseReferencesMap.GetValueOrDefault(projectId, ImmutableHashSet <ProjectId> .Empty));
        }
Example #11
0
    public void OnPacket(object?sender, IByteReader reader)
    {
        ushort            op      = reader.Read <ushort>();
        PacketHandler <T>?handler = handlers.GetValueOrDefault(op);

        if (sender is T session)
        {
            handler?.Handle(session, reader);
        }
    }
        IEnumerable <CodeFixProvider> GetApplicableFixProviders(Project project, ImmutableArray <Diagnostic> diagnostics)
        {
            var codeFixProviders = cache.GetAllCodeFixProviders(project);

            return(diagnostics
                   .Select(y => y.Id)
                   .Distinct()
                   .SelectMany(x => ImmutableDictionary.GetValueOrDefault(codeFixProviders, x, EmptyCodeFixProviderList))
                   .Distinct());
        }
        public void Update(string key, IReplicatedData delta)
        {
            // bump the counter for each update
            var version = _deltaCounter.GetValueOrDefault(key, 0L) + 1;

            _deltaCounter = _deltaCounter.SetItem(key, version);

            var deltaEntriesForKey = _deltaEntries.GetValueOrDefault(key, ImmutableSortedDictionary <long, IReplicatedData> .Empty);

            _deltaEntries = _deltaEntries.SetItem(key, deltaEntriesForKey.SetItem(version, delta));
        }
Example #14
0
        private ImmutableDictionary <SymbolicValue, SymbolicValueConstraints> AddConstraintForSymbolicValue(SymbolicValue symbolicValue,
                                                                                                            SymbolicValueConstraint constraint, ImmutableDictionary <SymbolicValue, SymbolicValueConstraints> constraintMap)
        {
            var constraints = constraintMap.GetValueOrDefault(symbolicValue);

            var updatedConstraints = constraints != null
                ? constraints.WithConstraint(constraint)
                : SymbolicValueConstraints.Create(constraint);

            return(constraintMap.SetItem(symbolicValue, updatedConstraints));
        }
Example #15
0
        async Task <IImmutableDictionary <string, IModuleIdentity> > GetModuleIdentitiesAsync(Diff diff)
        {
            // System modules have different module names and identity names. We need to convert module names to module identity names
            // and vice versa, to make sure the right values are being used.
            // TODO - This will fail if the user adds modules with the same module name as a system module - for example a module called
            // edgeHub. We might have to catch such cases and flag them as error (or handle them in some other way).
            IEnumerable <string> updatedModuleIdentites = diff.AddedOrUpdated.Select(m => ModuleIdentityHelper.GetModuleIdentityName(m.Name));
            IEnumerable <string> removedModuleIdentites = diff.Removed.Select(m => ModuleIdentityHelper.GetModuleIdentityName(m));

            List <Module> modules = (await this.serviceClient.GetModules()).ToList();

            ImmutableDictionary <string, Module> modulesDict = modules.ToImmutableDictionary(p => p.Id);

            IEnumerable <string> createIdentities = updatedModuleIdentites.Where(m => !modulesDict.ContainsKey(m));
            IEnumerable <string> removeIdentities = removedModuleIdentites.Where(
                m => modulesDict.ContainsKey(m) &&
                string.Equals(modulesDict.GetValueOrDefault(m).ManagedBy, Constants.ModuleIdentityEdgeManagedByValue, StringComparison.OrdinalIgnoreCase));

            // Update any identities that don't have SAS auth type or where the keys are null (this will happen for single device deployments,
            // where the identities of modules are created, but the auth keys are not set).
            IEnumerable <Module> updateIdentities = modules.Where(
                m => m.Authentication == null ||
                m.Authentication.Type != AuthenticationType.Sas ||
                m.Authentication.SymmetricKey == null ||
                (m.Authentication.SymmetricKey.PrimaryKey == null && m.Authentication.SymmetricKey.SecondaryKey == null))
                                                    .Select(
                m =>
            {
                m.Authentication = new AuthenticationMechanism
                {
                    Type = AuthenticationType.Sas
                };
                return(m);
            }).ToList();

            List <Module> updatedModulesIndentity            = (await this.UpdateServiceModulesIdentityAsync(removeIdentities, createIdentities, updateIdentities)).ToList();
            ImmutableDictionary <string, Module> updatedDict = updatedModulesIndentity.ToImmutableDictionary(p => p.Id);

            IEnumerable <IModuleIdentity> moduleIdentities;

            moduleIdentities = updatedModulesIndentity.Concat(modules.Where(p => !updatedDict.ContainsKey(p.Id))).Select(
                p =>
            {
                string connectionString = this.GetModuleConnectionString(p);
                return(new ModuleIdentity(
                           this.iothubHostName,
                           this.deviceId,
                           p.Id,
                           new ConnectionStringCredentials(connectionString)));
            });

            return(moduleIdentities.ToImmutableDictionary(m => ModuleIdentityHelper.GetModuleName(m.ModuleId)));
        }
Example #16
0
 public static T Apply <T>(this ImmutableDictionary <string, T> subst, T value) where T : IUnifiable <T>
 => value.Rewrite(
     x =>
 {
     var name = x.AsVariable();
     if (name != null)
     {
         return(subst.GetValueOrDefault(name, x));
     }
     return(x);
 }
     );
Example #17
0
        public static ImmutableDictionary <SymbolicValue, SymbolicValueConstraints> AddConstraintForSymbolicValue(
            this ImmutableDictionary <SymbolicValue, SymbolicValueConstraints> constraintMap,
            SymbolicValue symbolicValue, SymbolicValueConstraint constraint)
        {
            var constraints = ImmutableDictionary.GetValueOrDefault(constraintMap, symbolicValue);

            var updatedConstraints = constraints != null
                ? constraints.WithConstraint(constraint)
                : SymbolicValueConstraints.Create(constraint);

            return(constraintMap.SetItem(symbolicValue, updatedConstraints));
        }
Example #18
0
        private ImmutableDictionary <SymbolicValue, SymbolicValueConstraints> RemoveConstraintForSymbolicValue(SymbolicValue symbolicValue,
                                                                                                               SymbolicValueConstraint constraint, ImmutableDictionary <SymbolicValue, SymbolicValueConstraints> constraintMap)
        {
            var constraints = constraintMap.GetValueOrDefault(symbolicValue);

            if (constraints == null)
            {
                return(constraintMap);
            }

            var updatedConstraints = constraints.WithoutConstraint(constraint);

            return(constraintMap.SetItem(symbolicValue, updatedConstraints));
        }
Example #19
0
        public void Include <T>(params Expression <Func <T, Object> >[] retrievals)
        {
            if (retrievals == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(retrievals));
            }

            Logger.Debug(
                "Including {Type} {@Retrievals}",
                typeof(T),
                retrievals
                );

            if (!retrievals.Any())
            {
                return;
            }

            var retrievalsWithIncludes = IncludeInjectingVisitor.Instance.Visit(
                new ReadOnlyCollection <Expression>(retrievals)
                );

            Logger.Debug(
                "Retrievals with includes for {Type}: {@Retrievals}",
                typeof(T),
                retrievalsWithIncludes
                );

            _retrievals = _retrievals.SetItem(
                typeof(T),
                _retrievals.GetValueOrDefault(
                    typeof(T),
                    CreateExpressionHashSet()
                    )
                .Union(retrievalsWithIncludes)
                );
        }
Example #20
0
        private PropertyAccessor TryGetClientObjectAccessor(Parameter parameter)
        {
            var result = Mappings.GetValueOrDefault(parameter.PropertyAccessor);

            if (result == null)
            {
                Logger.Information(
                    "Parameter {Parameter} is not mapped to any {ClientObjectType} property.",
                    parameter,
                    ClientObjectType
                    );
            }

            return(result);
        }
Example #21
0
        public override int Partition(string stream, byte[] key, byte[] value, IMetadata metadata)
        {
            var partitionsCount = metadata.StreamPartitionCount(stream);

            if (partitionsCount == 0)
            {
                return(0);
            }

            lock (counter)
            {
                var currentCount = counter.GetValueOrDefault(stream, 0);
                counter = counter.SetItem(stream, currentCount + 1);
                return(counter[stream] % partitionsCount);
            }
        }
Example #22
0
 public void Add(
     IDependencyResolverAdder dependencyResolverAdder,
     ITestProbeActorCreator testProbeActorCreator,
     ITestProbeCreator testProbeCreator,
     IResolvedTestProbeStore resolvedTestProbeStore,
     IChildWaiter childWaiter,
     TestKitBase testKit,
     ImmutableDictionary <Type, ImmutableDictionary <Type, Func <object, object> > > handlers) =>
 dependencyResolverAdder.Add(testKit, actorType =>
 {
     ImmutableDictionary <Type, Func <object, object> > actorHandlers = handlers.GetValueOrDefault(actorType, null);
     ITestProbeActor probeActor = testProbeActorCreator.Create(testProbeCreator, testKit, actorHandlers);
     resolvedTestProbeStore.ResolveProbe(probeActor.ActorPath, actorType, probeActor.TestProbe, probeActor.PropsSupervisorStrategy);
     childWaiter.ResolvedChild();
     return(probeActor.Actor);
 });
Example #23
0
        ImmutableHashSet <string> GetSequenceColumns(PostgreSqlObjectName tableName)
        {
            const string sql = @"select s.relname as SequenceName, n.nspname as SchemaName, t.relname as TableName, a.attname as ColumnName
from pg_class s
  join pg_depend d on d.objid=s.oid and d.classid='pg_class'::regclass and d.refclassid='pg_class'::regclass
  join pg_class t on t.oid=d.refobjid
  join pg_namespace n on n.oid=t.relnamespace
  join pg_attribute a on a.attrelid=t.oid and a.attnum=d.refobjsubid
where s.relkind='S' and d.deptype='a'";

            if (m_SequenceColumns == null)
            {
                using (var con = new NpgsqlConnection(m_ConnectionBuilder.ConnectionString))
                {
                    con.Open();

                    using (var cmd = new NpgsqlCommand(sql, con))
                    {
                        using (var reader = cmd.ExecuteReader())
                        {
                            var result = new Dictionary <PostgreSqlObjectName, HashSet <string> >();
                            while (reader.Read())
                            {
                                var schemaTableName = new PostgreSqlObjectName(reader.GetString(reader.GetOrdinal("SchemaName")), reader.GetString(reader.GetOrdinal("TableName")));
                                var columnName      = reader.GetString(reader.GetOrdinal("ColumnName"));

                                if (result.TryGetValue(schemaTableName, out var identityColumns))
                                {
                                    identityColumns.Add(columnName);
                                }
                                else
                                {
                                    identityColumns = new HashSet <string>()
                                    {
                                        columnName
                                    };
                                    result.Add(schemaTableName, identityColumns);
                                }
                            }
                            m_SequenceColumns = result.ToImmutableDictionary(x => x.Key, x => x.Value.ToImmutableHashSet(StringComparer.OrdinalIgnoreCase));
                        }
                    }
                }
            }
            return(m_SequenceColumns.GetValueOrDefault(tableName, ImmutableHashSet <string> .Empty));
        }
        private ExchangeQuality CheckPrimaryStatusAndSwitchIfNeeded(string assetPairId,
                                                                    ImmutableDictionary <string, ExchangeQuality> exchangeQualities)
        {
            var primaryExchange         = _primaryExchanges.GetOrDefault(assetPairId);
            var originalPrimaryExchange = primaryExchange;

            var primaryQuality = primaryExchange == null ? null : exchangeQualities.GetValueOrDefault(primaryExchange);

            if (primaryQuality == null)
            {
                var result = SwitchPrimaryExchange(assetPairId, null, exchangeQualities,
                                                   newPrimary =>
                                                   $"{newPrimary.ExchangeName} has been chosen as an initial primary exchange for {assetPairId}. " +
                                                   $"It has error state \"{newPrimary.ErrorState}\" and hedging preference \"{newPrimary.HedgingPreference}\".");
                return(result);
            }

            var primaryPreference = primaryQuality.HedgingPreference;
            var primaryError      = primaryQuality.ErrorState;

            switch (primaryError)
            {
            case ExchangeErrorStateDomainEnum.Valid when primaryPreference > 0:
                return(primaryQuality);

            case ExchangeErrorStateDomainEnum.Outlier when primaryPreference > 0:
                _alertService.AlertRiskOfficer(assetPairId,
                                               $"Primary exchange {primaryExchange} for {assetPairId} is an outlier. Skipping price update.", EventTypeEnum.OutlierDetected);
                return(primaryQuality);

            case ExchangeErrorStateDomainEnum.Broken when primaryPreference > 0:
                _alertService.AlertRiskOfficer(assetPairId,
                                               $"Primary exchange {primaryExchange} for {assetPairId} is broken. Skipping price update.", EventTypeEnum.OutlierDetected);
                return(primaryQuality);

            default:
                primaryQuality = SwitchPrimaryExchange(assetPairId, primaryQuality, exchangeQualities,
                                                       newPrimary =>
                                                       $"Primary exchange {originalPrimaryExchange} for {assetPairId} was changed.\r\n" +
                                                       $"It had error state \"{primaryError}\" and hedging preference \"{primaryPreference}\".\r\n" +
                                                       $"New primary exchange: \"{newPrimary.ExchangeName}\". It has error state \"{newPrimary.ErrorState}\" and hedging preference \"{newPrimary.HedgingPreference}\".");
                return(primaryQuality);
            }
        }
Example #25
0
        public static Glyph?GetGlyph(this CompletionItem completionItem)
        {
            var tags = completionItem.Tags;

            for (var index = 0; index < tags.Length; index++)
            {
                var tag   = tags[index];
                var inner = Dictionary.GetValueOrDefault(tag);
                if (inner != null)
                {
                    if (inner.TryGetValue(string.Empty, out var glyph) ||
                        (index + 1 < tags.Length && inner.TryGetValue(tags[index + 1], out glyph)))
                    {
                        return(glyph);
                    }
                }
            }

            return(null);
        }
Example #26
0
        /// <summary>
        ///     Dispatch an action
        /// </summary>
        /// <param name="action"></param>
        public async Task Dispatch(IAction <TActionType> action)
        {
            await Task.Factory.StartNew(() =>
            {
                var targetReducer = _reducers.GetValueOrDefault(action.Type, null);

                if (targetReducer.IsDefault())
                {
                    _errorHandler(States.LastOrDefault().Key, action, new Exception($"Failed to find a reducer for action type: {action.Type}"));

                    throw new ReducerMatchException <TActionType>(action.Type);
                }

                TState updatedState;

                try
                {
                    // Update the state
                    updatedState = targetReducer(CurrentState, action);
                }
                catch (Exception e)
                {
                    _errorHandler(States.LastOrDefault().Key, action, e);

                    throw;
                }

                // Run updated state through middleware
                updatedState = _middleware(updatedState);

                // Add new state to list of states
                States = States.Add(new KeyValuePair <TState, DateTime>(updatedState, DateTime.Now)).TakeLast(StatesCountLimit).ToImmutableList();

                // Set the current state
                CurrentState = States.Last().Key;

                EventHandler(this, CurrentState);
            });
        }
Example #27
0
        public static void AddPropertyOverride(
            this Dictionary <string, string> properties,
            string propertyName,
            string userOverrideValue,
            ImmutableDictionary <string, string> propertyOverrides,
            ILogger logger)
        {
            var overrideValue = propertyOverrides.GetValueOrDefault(propertyName);

            if (!string.IsNullOrEmpty(userOverrideValue))
            {
                // If the user set the option, we should use that.
                properties.Add(propertyName, userOverrideValue);
                logger.LogDebug($"'{propertyName}' set to '{userOverrideValue}' (user override)");
            }
            else if (!string.IsNullOrEmpty(overrideValue))
            {
                // If we have a custom environment value, we should use that.
                properties.Add(propertyName, overrideValue);
                logger.LogDebug($"'{propertyName}' set to '{overrideValue}'");
            }
        }
Example #28
0
            public async Task Invoke(IDictionary <string, object> environment, IDictionary <string, string> keys)
            {
                var completed = new TaskCompletionSource <bool>();

                try
                {
                    var request = new OwinRequest(environment);

                    var handler = _handlers.GetValueOrDefault(request.Method, AsyncHttpRequestHandler.Null);

                    keys = keys.ToDictionary(k => k.Key, v => WebUtility.UrlDecode(v.Value));

                    await ExecuteAsync(environment, keys, request, handler).ConfigureAwait(false);

                    completed.TrySetResult(true);
                }
                catch (Exception ex)
                {
                    completed.TrySetException(ex);

                    throw;
                }
            }
Example #29
0
 /// <summary>
 /// Gets the status of the specified worker.
 /// </summary>
 public WorkerStatus GetStatus(string workerId)
 {
     return(_status.GetValueOrDefault(workerId, WorkerStatus.Available));
 }
Example #30
0
 public override long VersionAt(UniqueAddress node) => Versions.GetValueOrDefault(node, 0L);
        private static void HandleSyntaxTreeAnalysis(SyntaxTreeAnalysisContext context, ImmutableDictionary<string, ReportDiagnostic> specificDiagnosticOptions)
        {
            var syntaxRoot = context.Tree.GetRoot(context.CancellationToken);

            foreach (var trivia in syntaxRoot.DescendantTrivia().Where(trivia => trivia.IsKind(SyntaxKind.SingleLineCommentTrivia)))
            {
                if (trivia.ToString().StartsWith("////", StringComparison.Ordinal))
                {
                    // ignore commented out code
                    continue;
                }

                int triviaIndex;
                var triviaList = TriviaHelper.GetContainingTriviaList(trivia, out triviaIndex);

                if (!IsOnOwnLine(triviaList, triviaIndex))
                {
                    // ignore comments after other code elements.
                    continue;
                }

                if (IsPartOfFileHeader(triviaList, triviaIndex))
                {
                    // ignore comments that are part of the file header.
                    continue;
                }

                var trailingBlankLineCount = GetTrailingBlankLineCount(triviaList, ref triviaIndex);
                if (trailingBlankLineCount == 0)
                {
                    // ignore comments that are not followed by a blank line
                    continue;
                }
                else if (trailingBlankLineCount > 1)
                {
                    if (specificDiagnosticOptions.GetValueOrDefault(SA1507CodeMustNotContainMultipleBlankLinesInARow.DiagnosticId, ReportDiagnostic.Default) != ReportDiagnostic.Suppress)
                    {
                        // ignore comments that are followed by multiple blank lines -> the multiple blank lines will be reported by SA1507
                        continue;
                    }
                }
                else
                {
                    if (triviaIndex < triviaList.Count)
                    {
                        switch (triviaList[triviaIndex].Kind())
                        {
                        case SyntaxKind.SingleLineCommentTrivia:
                        case SyntaxKind.SingleLineDocumentationCommentTrivia:
                        case SyntaxKind.MultiLineCommentTrivia:
                        case SyntaxKind.MultiLineDocumentationCommentTrivia:
                            // ignore a single blank line in between two comments.
                            continue;
                        }
                    }
                }

                var diagnosticSpan = TextSpan.FromBounds(trivia.SpanStart, trivia.SpanStart + 2);
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.Create(context.Tree, diagnosticSpan)));
            }
        }