コード例 #1
0
 private void RecycleNode(LinkedListNode <WaiterInfo> node)
 {
     Assumes.True(Monitor.IsEntered(this.syncObject));
     node.Value.Node = null;
     if (this.nodePool.Count < 10)
     {
         LinkedListNode <WaiterInfo?> nullableNode = node !;
         nullableNode.Value = null;
         this.nodePool.Push(nullableNode);
     }
 }
コード例 #2
0
        public void Dispose()
        {
            Assumes.True(_context.IsOnMainThread, "Must be on UI thread");

            if (_cookie != VSConstants.VSCOOKIE_NIL && _solution != null)
            {
                Verify.HResult(_solution.UnadviseSolutionEvents(_cookie));

                _cookie = VSConstants.VSCOOKIE_NIL;
            }
        }
コード例 #3
0
 /**
  * This should be overridden to extract correct message size in the case of lazy parsing.  Until this method is
  * implemented in a subclass of ChildMessage lazy parsing may have no effect.
  *
  * This default implementation is a safe fall back that will ensure it returns a correct value by parsing the message.
  *
  * @return
  */
 int getMessageSize()
 {
     if (Length != UNKNOWN_LENGTH)
     {
         return(Length);
     }
     maybeParse();
     Assumes.True(Length != UNKNOWN_LENGTH,
                  "Length field has not been set in %s after full parse.", this.GetType().Name);
     return(Length);
 }
コード例 #4
0
        protected override IJsonRpcMessageFormatter CreateFormatter()
        {
            Assumes.True(Formatter == Formatters.MessagePack);

            MessagePackFormatter         formatter = base.CreateFormatter() as MessagePackFormatter ?? new MessagePackFormatter();
            MessagePackSerializerOptions options   = MessagePackSerializerOptions.Value;

            formatter.SetMessagePackSerializerOptions(options);

            return(formatter);
        }
コード例 #5
0
        public GraphNode AddTopLevelGraphNode(
            IGraphContext graphContext,
            string projectPath,
            IDependencyViewModel viewModel)
        {
            Assumes.True(IsInitialized);

            GraphNodeId newNodeId = GetTopLevelGraphNodeId(projectPath, viewModel.OriginalModel.GetTopLevelId());

            return(DoAddGraphNode(newNodeId, graphContext, projectPath, parentNode: null, viewModel: viewModel));
        }
コード例 #6
0
            /// <summary>
            /// Reserves a read lock from a previously held lock.
            /// </summary>
            /// <returns>The releaser for the read lock.</returns>
            /// <exception cref="InvalidOperationException">Thrown if no lock is held by the caller.</exception>
            private ResourceReleaser AcquirePreexistingLockOrThrow()
            {
                if (!this.service.IsAnyLockHeld)
                {
                    Verify.FailOperation(Strings.InvalidWithoutLock);
                }

                AsyncReaderWriterResourceLock <TMoniker, TResource> .ResourceAwaiter awaiter = this.service.ReadLockAsync(CancellationToken.None).GetAwaiter();
                Assumes.True(awaiter.IsCompleted);
                return(awaiter.GetResult());
            }
コード例 #7
0
        private void RemoveFromContextIfPresent(string fullPath, IProjectLogger logger)
        {
            if (_paths.Contains(fullPath))
            {
                logger.WriteLine("Removing analyzer '{0}'", fullPath);
                Context.RemoveAnalyzerReference(fullPath);

                bool removed = _paths.Remove(fullPath);
                Assumes.True(removed);
            }
        }
コード例 #8
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Starts the given hc. </summary>
        ///
        /// <param name="hc">   The hc. </param>
        ///
        /// <returns>   True if it succeeds, false if it fails. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        public virtual bool Start(HostControl hc)
        {
            _host = hc;
            Console.WriteLine(_name + string.Intern(" Service Started."), Color.Yellow);

            Assumes.True(_timer != null, string.Intern("_timer is null"));
            _timer.AutoReset = true;
            _timer.Enabled   = true;
            _timer.Start();
            return(true);
        }
コード例 #9
0
        public void Dispose()
        {
            Assumes.True(_context.IsOnMainThread, "Must be on UI thread");

            if (_cookie != VSConstants.VSCOOKIE_NIL && _registerProjectTypes != null)
            {
                Verify.HResult(_registerProjectTypes.UnregisterProjectType(_cookie));
            }

            Dispose(disposing: true);
        }
コード例 #10
0
 /// <summary>
 /// Creates an authentication request to verify that a user controls
 /// some given Identifier.
 /// </summary>
 /// <param name="userSuppliedIdentifier">
 /// The Identifier supplied by the user.  This may be a URL, an XRI or i-name.
 /// </param>
 /// <param name="realm">
 /// The shorest URL that describes this relying party web site's address.
 /// For example, if your login page is found at https://www.example.com/login.aspx,
 /// your realm would typically be https://www.example.com/.
 /// </param>
 /// <returns>
 /// An authentication request object that describes the HTTP response to
 /// send to the user agent to initiate the authentication.
 /// </returns>
 /// <remarks>
 /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para>
 /// </remarks>
 /// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception>
 /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception>
 public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm)
 {
     Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
     Requires.NotNull(realm, "realm");
     try {
         var result = this.CreateRequests(userSuppliedIdentifier, realm).First();
         Assumes.True(result != null);
         return(result);
     } catch (InvalidOperationException ex) {
         throw ErrorUtilities.Wrap(ex, OpenIdStrings.OpenIdEndpointNotFound);
     }
 }
コード例 #11
0
ファイル: ContractNameServices.cs プロジェクト: ppease/vs-mef
        private static void WriteGenericTypeName(StringBuilder typeName, Type type, bool isDefinition, Queue <Type> genericTypeArguments, bool formatGenericName)
        {
            //
            // Writes generic type name, e.g. generic name and generic arguments
            //
            Assumes.True(type.GetTypeInfo().IsGenericType, "Expecting type to be a generic type");
            int    genericArity    = GetGenericArity(type);
            string genericTypeName = FindGenericTypeName(type.GetGenericTypeDefinition().Name);

            typeName.Append(genericTypeName);
            WriteTypeArgumentsString(typeName, genericArity, isDefinition, genericTypeArguments, formatGenericName);
        }
コード例 #12
0
            protected override ImageId ReadValue(JsonReader reader, JsonSerializer serializer)
            {
                Assumes.True(reader.TokenType == JsonToken.StartObject);

                var guid = ReadProperty <Guid>(reader, serializer);
                var id   = ReadProperty <long>(reader);

                Assumes.True(reader.Read());
                Assumes.True(reader.TokenType == JsonToken.EndObject);

                return(new ImageId(guid, (int)id));
            }
コード例 #13
0
            /// <summary>
            /// Deserializes a nonce from the return_to parameter.
            /// </summary>
            /// <param name="value">The base64-encoded value of the nonce.</param>
            /// <returns>The instantiated and initialized nonce.</returns>
            internal static CustomNonce Deserialize(string value)
            {
                Requires.NotNullOrEmpty(value, "value");

                byte[] nonce = MessagingUtilities.FromBase64WebSafeString(value);
                Assumes.True(nonce != null);
                DateTime creationDateUtc = new DateTime(BitConverter.ToInt64(nonce, 0), DateTimeKind.Utc);

                byte[] randomPart = new byte[NonceByteLength];
                Array.Copy(nonce, sizeof(long), randomPart, 0, NonceByteLength);
                return(new CustomNonce(creationDateUtc, randomPart));
            }
コード例 #14
0
        private static async Task <HttpContent> EnsureContentHasLengthAsync(HttpContent content)
        {
            if (content != null && !content.Headers.ContentLength.HasValue)
            {
                // Copy the content, which sets the content length.
                content = await CopyContentAsync(content, Stream.Null);

                Assumes.True(content.Headers.ContentLength.HasValue);
            }

            return(content);
        }
コード例 #15
0
        private static ModuleBuilder GetProxyModuleBuilder()
        {
            Assumes.True(Monitor.IsEntered(MetadataViewFactories));
            if (transparentProxyModuleBuilder == null)
            {
                // make a new assemblybuilder and modulebuilder
                var assemblyBuilder = CreateProxyAssemblyBuilder(typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes));
                transparentProxyModuleBuilder = assemblyBuilder.DefineDynamicModule("MetadataViewProxiesModule");
            }

            return(transparentProxyModuleBuilder);
        }
コード例 #16
0
        public async ValueTask <IReadOnlyList <ProjectAction> > GetUninstallActionsAsync(
            string projectId,
            PackageIdentity packageIdentity,
            bool removeDependencies,
            bool forceRemove,
            CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectId);
            Assumes.NotNull(packageIdentity);
            Assumes.False(packageIdentity.HasVersion);
            Assumes.NotNull(_state.SourceCacheContext);
            Assumes.NotNull(_state.ResolvedActions);
            Assumes.Null(_state.PackageIdentity);

            cancellationToken.ThrowIfCancellationRequested();

            return(await CatchAndRethrowExceptionAsync(async() =>
            {
                INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync <INuGetProjectContext>();
                (bool success, NuGetProject? project) = await TryGetNuGetProjectMatchingProjectIdAsync(projectId);

                Assumes.True(success);
                Assumes.NotNull(project);

                var projectActions = new List <ProjectAction>();
                var uninstallationContext = new UninstallationContext(removeDependencies, forceRemove);

                NuGetPackageManager packageManager = await _sharedState.PackageManager.GetValueAsync(cancellationToken);
                IEnumerable <NuGetProjectAction> actions = await packageManager.PreviewUninstallPackageAsync(
                    project,
                    packageIdentity.Id,
                    uninstallationContext,
                    projectContext,
                    cancellationToken);

                foreach (NuGetProjectAction action in actions)
                {
                    var resolvedAction = new ResolvedAction(project, action);
                    var projectAction = new ProjectAction(
                        CreateProjectActionId(),
                        projectId,
                        action.PackageIdentity,
                        action.NuGetProjectActionType,
                        implicitActions: null);

                    _state.ResolvedActions[projectAction.Id] = resolvedAction;

                    projectActions.Add(projectAction);
                }

                return projectActions;
            }));
        }
コード例 #17
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Initializes a new instance of the MicroServiceEcoSystem.BaseMicroService&lt;T&gt; class.
        /// </summary>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        public BaseMicroService()
        {
            double interval = 60000;

            _timer = new Timer(interval);
            Assumes.True(_timer != null, "_timer is null");

            _timer.Elapsed  += OnTick;
            _timer.AutoReset = true;
            _workerId        = Guid.NewGuid().ToString();
            _name            = nameof(T);
        }
コード例 #18
0
        public virtual void AddSubscriptions(AggregateCrossTargetProjectContext projectContext)
        {
            Requires.NotNull(projectContext, nameof(projectContext));
            Assumes.True(IsInitialized);

            foreach (ConfiguredProject configuredProject in projectContext.InnerConfiguredProjects)
            {
                Assumes.Present(configuredProject.Services.ProjectSubscription);

                SubscribeToConfiguredProject(configuredProject, configuredProject.Services.ProjectSubscription);
            }
        }
コード例 #19
0
            private void CheckForInitialized()
            {
                // We should have been initialized by our
                // owner before they called into us
                Assumes.True(IsInitialized);

                // If we failed to create a context, we treat it as a cancellation
                if (_contextAccessor == null)
                {
                    throw new OperationCanceledException();
                }
            }
コード例 #20
0
        public GraphNode AddGraphNode(
            IGraphContext graphContext, 
            string projectPath, 
            GraphNode parentNode, 
            IDependencyViewModel viewModel)
        {
            Assumes.True(IsInitialized);

            var modelId = viewModel.OriginalModel == null ? viewModel.Caption : viewModel.OriginalModel.Id;
            var newNodeId = GetGraphNodeId(projectPath, parentNode, modelId);
            return DoAddGraphNode(newNodeId, graphContext, projectPath, parentNode, viewModel);
        }
コード例 #21
0
        private LinkedListNode <WaiterInfo> GetNode(WaiterInfo info)
        {
            Assumes.True(Monitor.IsEntered(this.syncObject));
            if (this.nodePool.Count > 0)
            {
                LinkedListNode <WaiterInfo?>?node = this.nodePool.Pop();
                node.Value = info;
                return(node !);
            }

            return(new LinkedListNode <WaiterInfo>(info));
        }
コード例 #22
0
        public ImplicitProjectAction?Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
        {
            if (reader.TryReadNil())
            {
                return(null);
            }

            // stack overflow mitigation - see https://github.com/neuecc/MessagePack-CSharp/security/advisories/GHSA-7q36-4xx7-xcxf
            options.Security.DepthStep(ref reader);

            try
            {
                string?                id = null;
                PackageIdentity?       packageIdentity   = null;
                NuGetProjectActionType?projectActionType = null;

                int propertyCount = reader.ReadMapHeader();

                for (var propertyIndex = 0; propertyIndex < propertyCount; ++propertyIndex)
                {
                    switch (reader.ReadString())
                    {
                    case IdPropertyName:
                        id = reader.ReadString();
                        break;

                    case PackageIdentityPropertyName:
                        packageIdentity = PackageIdentityFormatter.Instance.Deserialize(ref reader, options);
                        break;

                    case ProjectActionTypePropertyName:
                        projectActionType = options.Resolver.GetFormatter <NuGetProjectActionType>().Deserialize(ref reader, options);
                        break;

                    default:
                        reader.Skip();
                        break;
                    }
                }

                Assumes.NotNullOrEmpty(id);
                Assumes.NotNull(packageIdentity);
                Assumes.True(projectActionType.HasValue);

                return(new ImplicitProjectAction(id, packageIdentity, projectActionType !.Value));
            }
            finally
            {
                // stack overflow mitigation - see https://github.com/neuecc/MessagePack-CSharp/security/advisories/GHSA-7q36-4xx7-xcxf
                reader.Depth--;
            }
        }
コード例 #23
0
ファイル: RabbitReceiver.cs プロジェクト: Sliborskii/Contour
        /// <summary>
        /// Builds a set of listeners constructing one listener for each URL in the connection string
        /// </summary>
        private void BuildListeners()
        {
            var reuseConnectionProperty = this.receiverOptions.GetReuseConnection();
            var reuseConnection         = reuseConnectionProperty.HasValue && reuseConnectionProperty.Value;

            this.logger.Trace(
                $"Building listeners of [{this.Configuration.Label}]:\r\n\t{string.Join("\r\n\t", this.receiverOptions.RabbitConnectionString.Select(url => $"Listener({this.Configuration.Label}): URL\t=>\t{url}"))}");

            foreach (var url in this.receiverOptions.RabbitConnectionString)
            {
                var source     = new CancellationTokenSource();
                var connection = this.connectionPool.Get(url, reuseConnection, source.Token);
                this.logger.Trace($"Using connection [{connection.Id}] at URL=[{url}] to resolve a listener");

                var topologyBuilder = new TopologyBuilder(connection.OpenChannel());
                var builder         = new SubscriptionEndpointBuilder(this.bus.Endpoint, topologyBuilder, this.Configuration);

                var endpointBuilder = this.Configuration.Options.GetEndpointBuilder();
                Assumes.True(endpointBuilder != null, "EndpointBuilder is null for [{0}].", this.Configuration.Label);

                var endpoint = endpointBuilder.Value(builder);

                var newListener = new Listener(
                    this.bus,
                    connection,
                    endpoint,
                    this.receiverOptions,
                    this.bus.Configuration.ValidatorRegistry);

                // There is no need to register another listener at the same URL and for the same source; consuming actions can be registered for a single listener
                var listener =
                    this.listeners.FirstOrDefault(
                        l =>
                        l.BrokerUrl == newListener.BrokerUrl &&
                        newListener.Endpoint.ListeningSource.Equals(l.Endpoint.ListeningSource));

                if (listener == null)
                {
                    listener = newListener;
                    this.listeners.Add(listener);
                }
                else
                {
                    // Check if an existing listener can be a substitute for a new one and if so just skip the new listeners
                    this.CheckIfCompatible(newListener);
                    listener = newListener;
                }

                // This event should be fired always, no matter if a listener already existed; this will ensure the event will be handled outside (in the bus)
                this.ListenerRegistered(this, new ListenerRegisteredEventArgs(listener));
            }
        }
コード例 #24
0
        private void RemoveFromContextIfPresent(string includePath, IProjectLogger logger)
        {
            string fullPath = _project.MakeRooted(includePath);

            if (_paths.Contains(fullPath))
            {
                // Remove from the context first so if Roslyn throws due to a bug
                // or other reason, that our state of the world remains consistent
                RemoveFromContext(fullPath, logger);
                bool removed = _paths.Remove(fullPath);
                Assumes.True(removed);
            }
        }
コード例 #25
0
        private async Task ServerOfferAsync()
        {
            var channel = await this.mx.OfferChannelAsync("serverOffer");

            var(r, w) = CreateStreamIO(channel);
            await w.WriteLineAsync("theserver");

            w.Close();
            string line = await r.ReadLineAsync();

            Assumes.True(line == "recv: theserver");
            r.Close();
        }
コード例 #26
0
        private void RemoveFromContextIfPresent(string includePath, IProjectLogger logger)
        {
            string fullPath = _project.MakeRooted(includePath);

            if (_paths.Contains(fullPath))
            {
                logger.WriteLine("Removing dynamic file '{0}'", fullPath);
                Context.RemoveDynamicFile(fullPath);

                bool removed = _paths.Remove(fullPath);
                Assumes.True(removed);
            }
        }
コード例 #27
0
        public async Task InitializeAsync(IAsyncServiceProvider asyncServiceProvider)
        {
            Assumes.Null(_registerProjectTypes);
            Assumes.True(_context.IsOnMainThread, "Must be on UI thread");

            _registerProjectTypes = await asyncServiceProvider.GetServiceAsync <SVsRegisterProjectTypes, IVsRegisterProjectTypes>();

            ((IVsProjectFactory)this).SetSite(new ServiceProviderToOleServiceProviderAdapter(ServiceProvider.GlobalProvider));

            Guid guid = GetType().GUID;

            Verify.HResult(_registerProjectTypes.RegisterProjectType(ref guid, this, out _cookie));
        }
コード例 #28
0
        /// <summary>
        /// Removes all synchronous tasks we applies to a dependent task, after the relationship is removed.
        /// </summary>
        /// <param name="child">The original dependent task</param>
        private void RemoveDependingSynchronousTaskFromChild(JoinableTask child)
        {
            Requires.NotNull(child, nameof(child));
            Assumes.True(Monitor.IsEntered(this.owner.Context.SyncContextLock));

            DependentSynchronousTask existingTaskTracking = this.dependingSynchronousTaskTracking;

            while (existingTaskTracking != null)
            {
                child.RemoveDependingSynchronousTask(existingTaskTracking.SynchronousTask);
                existingTaskTracking = existingTaskTracking.Next;
            }
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: AArnott/Nerdbank.Streams
        private async Task ServerOfferAsync()
        {
            MultiplexingStream.Channel?channel = await this.mx.OfferChannelAsync("serverOffer");

            (StreamReader r, StreamWriter w) = CreateStreamIO(channel);
            await w.WriteLineAsync("theserver");

            w.Close();
            string?line = await r.ReadLineAsync();

            Assumes.True(line == "recv: theserver");
            r.Close();
        }
コード例 #30
0
 /// <summary>
 /// Invoked when the remote party acknowledges bytes we previously transmitted as processed,
 /// thereby allowing us to consider that data removed from the remote party's "window"
 /// and thus enables us to send more data to them.
 /// </summary>
 /// <param name="bytesProcessed">The number of bytes processed by the remote party.</param>
 internal void OnContentProcessed(long bytesProcessed)
 {
     Requires.Range(bytesProcessed >= 0, nameof(bytesProcessed), "A non-negative number is required.");
     lock (this.SyncObject)
     {
         Assumes.True(bytesProcessed <= this.remoteWindowFilled);
         this.remoteWindowFilled -= bytesProcessed;
         if (this.remoteWindowFilled < this.remoteWindowSize)
         {
             this.remoteWindowHasCapacity.Set();
         }
     }
 }