LogDebug() public method

public LogDebug ( ) : void
return void
        public async Task <ISingleResponse <ServiceEnvironmentStatus> > GetServiceStatusAsync(ServiceEnvironmentStatus entity)
        {
            Logger?.LogDebug("'{0}' has been invoked", nameof(GetServiceStatusAsync));

            var response = new SingleResponse <ServiceEnvironmentStatus>();

            try
            {
                response.Model = await Repository
                                 .GetServiceEnvironmentStatusAsync(entity);
            }
            catch (Exception ex)
            {
                response.SetError(Logger, ex);
            }

            return(response);
        }
Beispiel #2
0
        public async Task <ISingleResponse <OrderHeader> > GetOrderAsync(long id)
        {
            Logger?.LogDebug("{0} has been invoked", nameof(GetOrderAsync));

            var response = new SingleResponse <OrderHeader>();

            try
            {
                // Retrieve order by id
                response.Model = await DbContext.GetOrderAsync(new OrderHeader(id));
            }
            catch (Exception ex)
            {
                response.SetError(Logger, nameof(GetOrderAsync), ex);
            }

            return(response);
        }
Beispiel #3
0
        private void UnsubscribeAll()
        {
            lock (Sync)
            {
                if (!Subscribers.Any())
                {
                    return;
                }

                AbortStreaming();

                Logger?.LogDebug($"{GetType().Name}.{nameof(UnsubscribeAll)}: Removing all streams.  [thread: {Thread.CurrentThread.ManagedThreadId}]");
                Subscribers.Clear();
                StreamNames.Clear();

                OnProvidedStreamsChanged();
            }
        }
Beispiel #4
0
        protected internal void HandleStopEvent(Activity current, IOwinContext arg)
        {
            if (ShouldIgnoreRequest(arg.Request.Path.Value))
            {
                Logger?.LogDebug("HandleStopEvent: Ignoring path: {path}", arg.Request.Path.Value);
                return;
            }

            if (current.Duration.TotalMilliseconds > 0)
            {
                ITagContext tagContext = GetTagContext(arg);
                StatsRecorder
                .NewMeasureMap()
                .Put(responseTimeMeasure, current.Duration.TotalMilliseconds)
                .Put(serverCountMeasure, 1)
                .Record(tagContext);
            }
        }
Beispiel #5
0
        private async Task EnsureClientsCollectionCreated()
        {
            _clientUri = UriFactory.CreateDocumentCollectionUri(Database.Id, Constants.CollectionNames.Client);
            Logger?.LogDebug($"Clients URI: {_clientUri}");

            var partitionKeyDefinition = new PartitionKeyDefinition
            {
                Paths = { Constants.CollectionPartitionKeys.Client }
            };

            Logger?.LogDebug($"Client Partition Key: {partitionKeyDefinition}");

            var indexingPolicy = new IndexingPolicy
            {
                Automatic    = true,
                IndexingMode = IndexingMode.Consistent
            };

            Logger?.LogDebug($"Clients Indexing Policy: {indexingPolicy}");

            _clients = new DocumentCollection
            {
                Id             = Constants.CollectionNames.Client,
                PartitionKey   = partitionKeyDefinition,
                IndexingPolicy = indexingPolicy
            };
            Logger?.LogDebug($"Clients Collection: {_clients}");

            Logger?.LogDebug($"Ensure Clients (ID:{_clients.Id}) collection exists...");
            var clientsRequestOptions = new RequestOptions
            {
                OfferThroughput = GetRUsFor(CollectionName.Clients)
            };

            Logger?.LogDebug($"Clients Request Options: {clientsRequestOptions}");
            var clientResults = await DocumentClient.CreateDocumentCollectionIfNotExistsAsync(DatabaseUri,
                                                                                              _clients, clientsRequestOptions);

            Logger?.LogDebug($"{_clients.Id} Creation Results: {clientResults.StatusCode}");
            if (clientResults.StatusCode.EqualsOne(HttpStatusCode.Created, HttpStatusCode.OK))
            {
                _clients = clientResults.Resource;
            }
        }
        private void HandleMessage(Event message)
        {
            if (message == null)
            {
                Logger?.LogWarning($"下载器代理 {_options.AgentId} 接收到空消息");
                return;
            }
#if DEBUG
            Logger?.LogDebug($"下载器代理 {_options.AgentId} 接收到消息: {message}");
#endif

            try
            {
                switch (message.Type)
                {
                case Framework.DownloadCommand:
                {
                    if (message.IsTimeout(60))
                    {
                        break;
                    }

                    DownloadAsync(message.Data).ConfigureAwait(false).GetAwaiter();
                    break;
                }

                case Framework.ExitCommand:
                {
                    if (message.IsTimeout(6))
                    {
                        break;
                    }

                    if (message.Data == _options.AgentId)
                    {
                        StopAsync(default).ConfigureAwait(true).GetAwaiter();
                    }
                    else
                    {
                        Logger?.LogWarning($"下载器代理 {_options.AgentId} 收到错误的退出消息: {message}");
                    }

                    break;
                }
        protected internal void HandleStartEvent(HttpContext context)
        {
            if (ShouldIgnoreRequest(context.Request.Path))
            {
                Logger?.LogDebug("HandleStartEvent: Ignoring path: {path}", context.Request.Path.ToString());
                return;
            }

            if (active.Value != null)
            {
                Logger?.LogDebug("HandleStartEvent: Continuing existing span!");
                return;
            }

            ISpanContext traceContext = ExtractTraceContext(context);
            string spanName = ExtractSpanName(context);

            ISpan span;
            if (traceContext != null)
            {
                Logger?.LogDebug("HandleStartEvent: Found parent span {parent}", traceContext.ToString());
                span = Tracer.SpanBuilderWithRemoteParent(spanName, traceContext)
                    .StartSpan();
            }
            else
            {
                span = Tracer.SpanBuilder(spanName)
                    .StartSpan();
            }

            span.PutServerSpanKindAttribute()
                .PutHttpUrlAttribute(context.Request.GetDisplayUrl())
                .PutHttpMethodAttribute(context.Request.Method.ToString())
                .PutHttpPathAttribute(context.Request.Path.ToString())
                .PutHttpHostAttribute(context.Request.Host.ToString());

            if (context.Request.Headers != null)
            {
                span.PutHttpRequestHeadersAttribute(AsList(context.Request.Headers));
            }

            active.Value = new SpanContext(span, AsyncLocalContext.CurrentSpan);
            AsyncLocalContext.CurrentSpan = span;
        }
Beispiel #8
0
        /// <summary>
        /// Starts the service listener if it is in a stopped state.
        /// </summary>
        /// <param name="servicePort">The port used to listen on.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        /// <exception cref="ArgumentOutOfRangeException">servicePort - Port must be less then " + IPEndPoint.MaxPort + " and more then " + IPEndPoint.MinPort</exception>
        /// <exception cref="InvalidOperationException">Tcp listener is already active and must be stopped before starting</exception>
        public bool Start(int servicePort)
        {
            if (servicePort > IPEndPoint.MaxPort || servicePort < IPEndPoint.MinPort)
            {
                throw new ArgumentOutOfRangeException(nameof(servicePort),
                                                      "Port must be less then " + IPEndPoint.MaxPort + " and more then " + IPEndPoint.MinPort);
            }

            if (IsActive)
            {
                throw new InvalidOperationException(
                          "Tcp listener is already active and must be stopped before starting");
            }

            if (InterfaceAddress == null)
            {
                var ex = new InvalidOperationException("Unable to set interface address");
                Logger?.LogDebug(ex, "Unable to set interface address for TCP {Port}", servicePort);
                throw ex;
            }

            try
            {
                Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                Socket.Bind(new IPEndPoint(InterfaceAddress, servicePort));
                Socket.ReceiveTimeout = ReceiveTimeout;
                Socket.SendTimeout    = SendTimeout;
                Socket.Listen(ListenBacklog);

                IsActive = true;
                Thread   = new Thread(StartTcpListening);
                Thread.Start();

                Logger?.LogInformation("Listener started for TCP requests on {LocalEndPoint}", Socket.LocalEndPoint);
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex, "Listener failed to to start on TCP {ServicePort}", servicePort);
                return(false);
            }

            return(true);
        }
Beispiel #9
0
        public override void Post(SpeechIdentifier.PostCallback callback)
        {
            if (IsSessionOpen && !IsSessionClosing)
            {
                IdentifyResults.Clear();

                Uri uri = Configuration.Server.BuildEndpoint(URI_PATH_PROCESS);

                Logger?.LogDebug("SpeechIdentifier_HttpClient_Version1.Post(callback): URI: " + uri.ToString());

                using (var request = BuildRequest(CallMode.Process, uri))
                {
                    var task = mHttpClient.SendAsync(request).ContinueWith((requestTask) => {
                        if (requestTask.IsFaulted)
                        {
                            IdentifyResult = SpeechIdentifier.Result.Timeout;
                            Logger?.LogError(requestTask.Exception);
                            callback?.Invoke(IdentifyResult);
                            return;
                        }
                        HandleResponse(CallMode.Process, request, requestTask.Result).ContinueWith((responseTask) => {
                            if (responseTask.IsFaulted)
                            {
                                IdentifyResult = SpeechIdentifier.Result.Timeout;
                                Logger?.LogError(responseTask.Exception);
                                callback?.Invoke(IdentifyResult);
                                return;
                            }
                            callback?.Invoke(IdentifyResult);
                        });
                    });

                    if (task.IsFaulted)
                    {
                        IdentifyResult = SpeechIdentifier.Result.Timeout;
                        Logger?.LogError(task.Exception);
                        callback?.Invoke(IdentifyResult);
                    }

                    return;
                }
            }
            callback?.Invoke(IdentifyResult = SpeechIdentifier.Result.Invalid);
        }
Beispiel #10
0
        public override bool Cancel(string reason)
        {
            if (IsSessionOpen && !IsSessionClosing)
            {
                IsSessionClosing = true;
                IdentifyResults.Clear();
                Content.Clear();

                if (string.IsNullOrEmpty(reason))
                {
                    reason = "Unknown";
                }
                else
                {
                    reason = reason.Replace(' ', '-').Substring(0, System.Math.Min(reason.Length, 64));
                }

                Uri uri = Configuration.Server.BuildEndpoint(URI_PATH_CANCEL, reason);

                Logger?.LogDebug("SpeechIdentifier_HttpClient_Version1.Cancel(): URI: " + uri.ToString());

                using (var request = BuildRequest(CallMode.Cancel, uri))
                {
                    try
                    {
                        var responseTask = mHttpClient.SendAsync(request);

                        responseTask.RunSynchronously();

                        var resultTask = HandleResponse(CallMode.Cancel, request, responseTask.Result);

                        resultTask.RunSynchronously();

                        return(resultTask.Result);
                    }
                    catch (HttpRequestException ex)
                    {
                        IdentifyResult = SpeechIdentifier.Result.Timeout;
                        Logger?.LogError(ex);
                    }
                }
            }
            return(false);
        }
Beispiel #11
0
        /// <summary>
        /// Determines the file size of the given file
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public async Task <long> GetFileSizeAsync(string fileName)
        {
            EnsureLoggedIn();
            Logger?.LogDebug($"[FtpClient] Getting file size for {fileName}");
            var sizeResponse = await SendCommandAsync(new FtpCommandEnvelope
            {
                FtpCommand = FtpCommand.SIZE,
                Data       = fileName
            });

            if (sizeResponse.FtpStatusCode != FtpStatusCode.FileStatus)
            {
                throw new FtpException(sizeResponse.ResponseMessage);
            }

            long fileSize = long.Parse(sizeResponse.ResponseMessage.Substring(4));

            return(fileSize);
        }
Beispiel #12
0
        /// <summary>
        /// Initializes a new UnitOfWork instance
        /// </summary>
        /// <returns>The new UnitOfWork instance</returns>
        public IUnitOfWorkBase InitNewUnitOfWork()
        {
            ThrowIfDisposingOrDisposed();

            int newUowID = GetNextFreeUowID();
            var uow      = InitNewUnitOfWork(newUowID);

            if (uow == null)
            {
                Logger?.LogError("InitNewUnitOfWork from {type} returned null.", this.GetType());
            }
            else
            {
                Logger?.LogDebug("New UnitOfWork ({uow.id}, {uow.type}) initialized by {dbCtx.type}.", uow.UowId, uow.GetType(), this.GetType());
            }
            RegisterUnitOfWork(uow);

            return(uow);
        }
Beispiel #13
0
 public override Task TakeMeasurementAsync()
 {
     if (CurrentState == SensorStateEnum.Initialized)
     {
         _lastTemperatureCelsius = _cpuTemperature.Temperature.Celsius;
         if (double.IsNaN(_lastTemperatureCelsius))
         {
             CurrentState            = SensorStateEnum.Error;
             _lastTemperatureCelsius = double.NaN;
         }
         else
         {
             _lastTemperatureCelsius = Math.Round(_lastTemperatureCelsius, 2);
         }
     }
     Logger?.LogDebug($"{DateTimeOffset.Now}:HealthSensor: reading");
     Logger?.LogInformation($"CPU Temperature {_lastTemperatureCelsius}");
     return(Task.FromResult(_lastTemperatureCelsius));
 }
Beispiel #14
0
 public Task HandleAsync(Message message)
 {
     Logger?.LogDebug("Handing {MessageType} with ordered shell handler.", message.Header.MessageType);
     currentTask = new Task <TResult?>((state) =>
     {
         taskDepth++;
         var previousTask   = (Task <TResult?>?)state;
         var previousResult = previousTask?.Result;
         var currentResult  = HandleAsync(message, previousResult).Result;
         taskDepth--;
         if (taskDepth == 0)
         {
             currentTask = null;
         }
         return(currentResult);
     }, currentTask);
     currentTask.Start();
     return(currentTask);
 }
        protected internal void HandleStopEvent(HttpWebRequest request, HttpStatusCode statusCode, WebHeaderCollection headers)
        {
            if (!Pending.TryRemove(request, out var span))
            {
                Logger?.LogDebug("HandleStopEvent: Missing span context");
                return;
            }

            if (span != null)
            {
                span.PutHttpStatusCodeAttribute((int)statusCode);
                if (headers != null)
                {
                    span.PutHttpResponseHeadersAttribute(headers);
                }

                span.End();
            }
        }
Beispiel #16
0
        /// <summary>
        /// Produces a data socket using Extended Passive mode
        /// </summary>
        /// <returns></returns>
        internal async Task <Socket> ConnectDataSocketAsync()
        {
            Logger?.LogDebug("[FtpClient] Connecting to a data socket");
            var epsvResult = await SendCommandAsync(FtpCommand.EPSV);

            if (epsvResult.FtpStatusCode != FtpStatusCode.EnteringExtendedPassive)
            {
                throw new FtpException(epsvResult.ResponseMessage);
            }

            var passivePortNumber = epsvResult.ResponseMessage.ExtractEpsvPortNumber();

            if (!passivePortNumber.HasValue)
            {
                throw new FtpException("Could not detmine EPSV data port");
            }


            Socket socket = null;

            try
            {
                Logger?.LogDebug($"Connecting data socket, {Configuration.Host}:{passivePortNumber.Value}");

                var ipEndpoint = await dnsResolver.ResolveAsync(Configuration.Host, passivePortNumber.Value, Configuration.IpVersion);

                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    ReceiveTimeout = Configuration.TimeoutSeconds * 1000
                };
                socket.Connect(ipEndpoint);

                return(socket);
            }
            catch (Exception ex)
            {
                if (socket != null && socket.Connected)
                {
                    socket.Shutdown(SocketShutdown.Both);
                }
                throw new FtpException("Can't connect to remote server", ex);
            }
        }
        public async Task <IListResponse <ServiceWatcherItemDto> > GetActiveServiceWatcherItemsAsync()
        {
            Logger?.LogDebug("'{0}' has been invoked", nameof(GetActiveServiceWatcherItemsAsync));

            var response = new ListResponse <ServiceWatcherItemDto>();

            try
            {
                response.Model = await DbContext.GetActiveServiceWatcherItems().ToListAsync();

                Logger?.LogInformation("The service watch items were loaded successfully");
            }
            catch (Exception ex)
            {
                response.SetError(Logger, nameof(GetActiveServiceWatcherItemsAsync), ex);
            }

            return(response);
        }
Beispiel #18
0
        private void EnableReloading()
        {
            if (Settings.ReloadSettings.ConfigMaps && !Polling)
            {
                switch (Settings.ReloadSettings.Mode)
                {
                case ReloadMethods.Event:
                    ConfigMapWatcher = K8sClient.WatchNamespacedConfigMapAsync(
                        Settings.Name,
                        Settings.Namespace,
                        onEvent: (eventType, item) =>
                    {
                        Logger?.LogInformation("Recieved {eventType} event for ConfigMap {configMapName} with {entries} values", eventType.ToString(), Settings.Name, item?.Data?.Count);
                        switch (eventType)
                        {
                        case WatchEventType.Added:
                        case WatchEventType.Modified:
                        case WatchEventType.Deleted:
                            ProcessData(item);
                            break;

                        default:
                            Logger?.LogDebug("Event type {eventType} is not supported, no action has been taken", eventType);
                            break;
                        }
                    },
                        onError: (exception) =>
                    {
                        Logger?.LogCritical(exception, "ConfigMap watcher on {namespace}.{name} encountered an error!", Settings.Namespace, Settings.Name);
                    },
                        onClosed: () => { Logger?.LogInformation("ConfigMap watcher on {namespace}.{name} connection has closed", Settings.Namespace, Settings.Name); }).GetAwaiter().GetResult();
                    break;

                case ReloadMethods.Polling:
                    StartPolling(Settings.ReloadSettings.Period);
                    break;

                default:
                    Logger?.LogError("Unsupported reload method!");
                    break;
                }
            }
        }
Beispiel #19
0
        /// <summary>
        /// Sends a command to the FTP server, and returns the response
        /// </summary>
        /// <param name="envelope"></param>
        /// <returns></returns>
        public async Task <FtpResponse> SendCommandAsync(FtpCommandEnvelope envelope)
        {
            await commandSemaphore.WaitAsync();

            if (HasResponsePending())
            {
                await GetResponseAsync();
            }

            string commandString = envelope.GetCommandString();

            Logger?.LogDebug($"[FtpClient] Sending command: {commandString}");
            commandSocket.Send(commandString.ToAsciiBytes());

            var response = await GetResponseAsync();

            commandSemaphore.Release();
            return(response);
        }
Beispiel #20
0
        protected virtual IMessage DoReceive(CancellationToken cancellationToken = default)
        {
            var interceptorList = Interceptors;
            Stack <IChannelInterceptor> interceptorStack = null;

            try
            {
                Logger?.LogTrace("PreReceive on channel '" + this + "'");
                if (interceptorList.Count > 0)
                {
                    interceptorStack = new Stack <IChannelInterceptor>();

                    if (!interceptorList.PreReceive(this, interceptorStack))
                    {
                        return(null);
                    }
                }

                var message = DoReceiveInternal(cancellationToken);

                if (message == null)
                {
                    Logger?.LogTrace("PostReceive on channel '" + ServiceName + "', message is null");
                }
                else
                {
                    Logger?.LogDebug("PostReceive on channel '" + ServiceName + "', message: " + message);
                }

                if (interceptorStack != null && message != null)
                {
                    message = interceptorList.PostReceive(message, this);
                }

                interceptorList.AfterReceiveCompletion(message, this, null, interceptorStack);
                return(message);
            }
            catch (Exception ex)
            {
                interceptorList.AfterReceiveCompletion(null, this, ex, interceptorStack);
                throw;
            }
        }
Beispiel #21
0
        protected internal virtual void HandleAfterActionEvent()
        {
            var spanContext = active.Value;

            if (spanContext == null)
            {
                Logger?.LogDebug("HandleAfterActionEvent: Missing span context");
                return;
            }

            IScope scope = spanContext.ActiveScope;

            if (scope != null)
            {
                scope.Dispose();
            }

            active.Value = null;
        }
        public async Task <ISingleResponse <Customer> > GetCustomer(string CustomerCode)
        {
            //throw new NotImplementedException();
            Logger?.LogDebug("{0} has been invoked", nameof(GetCustomer));

            var response = new SingleResponse <Customer>();

            try
            {
                // Retrieve order by id
                response.Model = await customerRepository.GetCustomer(CustomerCode);
            }
            catch (Exception ex)
            {
                response.SetError(ex, Logger);
            }

            return(response);
        }
Beispiel #23
0
        public async Task <ISingleResponse <Branch> > GetBranchByBranchCodeAsync(string branchCode)
        {
            //throw new NotImplementedException();
            Logger?.LogDebug("{0} has been invoked", nameof(GetBranchByBranchCodeAsync));

            var response = new SingleResponse <Branch>();

            try
            {
                // Retrieve order by id
                response.Model = await branchRepository.GetBranchByBranchCodeAsync(branchCode);
            }
            catch (Exception ex)
            {
                response.SetError(ex, Logger);
            }

            return(response);
        }
        public async Task <ISingleResponse <Order> > GetOrderAsync(Int64 id)
        {
            Logger?.LogDebug("{0} has been invoked", nameof(GetOrderAsync));

            var response = new SingleResponse <Order>();

            try
            {
                // Retrieve order by id
                response.Model = await SalesRepository
                                 .GetOrderAsync(new Order(id));
            }
            catch (Exception ex)
            {
                response.SetError(ex, Logger);
            }

            return(response);
        }
        protected internal void HandleStartEvent(HttpRequestMessage request)
        {
            if (ShouldIgnoreRequest(request.RequestUri.AbsolutePath))
            {
                Logger?.LogDebug("HandleStartEvent: Ignoring path: {path}", request.RequestUri.AbsolutePath);
                return;
            }

            if (request.Properties.TryGetValue(SPANCONTEXT_KEY, out object context))
            {
                Logger?.LogDebug("HandleStartEvent: Continuing existing span!");
                return;
            }

            string spanName = ExtractSpanName(request);

            var    parentSpan = GetCurrentSpan();
            ISpan  started;
            IScope scope;

            if (parentSpan != null)
            {
                scope = Tracer.SpanBuilderWithExplicitParent(spanName, parentSpan)
                        .StartScopedSpan(out started);
            }
            else
            {
                scope = Tracer.SpanBuilder(spanName)
                        .StartScopedSpan(out started);
            }

            request.Properties.Add(SPANCONTEXT_KEY, new SpanContext(started, scope));

            started.PutClientSpanKindAttribute()
            .PutHttpRawUrlAttribute(request.RequestUri.ToString())
            .PutHttpMethodAttribute(request.Method.ToString())
            .PutHttpHostAttribute(request.RequestUri.Host, request.RequestUri.Port)
            .PutHttpPathAttribute(request.RequestUri.AbsolutePath)
            .PutHttpRequestHeadersAttribute(request.Headers.ToList());

            InjectTraceContext(request, parentSpan);
        }
Beispiel #26
0
        public virtual IUserDataClient Unsubscribe <TEventArgs>(string listenKey, Action <TEventArgs> callback)
            where TEventArgs : UserDataEventArgs
        {
            Logger?.LogDebug($"{nameof(UserDataClient)}.{nameof(Unsubscribe)}: \"{listenKey}\" (callback: {(callback == null ? "no" : "yes")}).  [thread: {Thread.CurrentThread.ManagedThreadId}]");

            var type = typeof(TEventArgs);

            if (callback != null)
            {
                if (type == typeof(AccountUpdateEventArgs))
                {
                    // ReSharper disable once InconsistentlySynchronizedField
                    Unsubscribe(listenKey, callback as Action <AccountUpdateEventArgs>, _accountUpdateSubscribers);
                }
                else if (type == typeof(OrderUpdateEventArgs))
                {
                    // ReSharper disable once InconsistentlySynchronizedField
                    Unsubscribe(listenKey, callback as Action <OrderUpdateEventArgs>, _orderUpdateSubscribers);
                }
                else if (type == typeof(AccountTradeUpdateEventArgs))
                {
                    // ReSharper disable once InconsistentlySynchronizedField
                    Unsubscribe(listenKey, callback as Action <AccountTradeUpdateEventArgs>, _accountTradeUpdateSubscribers);
                }
                else
                {
                    Unsubscribe(listenKey, callback as Action <UserDataEventArgs>, null);
                }
            }
            else
            {
                // ReSharper disable once InconsistentlySynchronizedField
                Unsubscribe(listenKey, null, _accountUpdateSubscribers);
                // ReSharper disable once InconsistentlySynchronizedField
                Unsubscribe(listenKey, null, _orderUpdateSubscribers);
                // ReSharper disable once InconsistentlySynchronizedField
                Unsubscribe(listenKey, null, _accountTradeUpdateSubscribers);
                Unsubscribe <UserDataEventArgs>(listenKey, null, null);
            }

            return(this);
        }
Beispiel #27
0
        private void HandleMessage(string message)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                Logger?.LogWarning($"下载器代理 {_options.AgentId} 接收到空消息");
                return;
            }
#if DEBUG
            Logger?.LogDebug($"下载器代理 {_options.AgentId} 接收到消息: {message}");
#endif

            try
            {
                var commandMessage = message.ToCommandMessage();

                if (commandMessage == null)
                {
                    Logger?.LogWarning($"下载器代理 {_options.AgentId} 接收到非法消息: {message}");
                    return;
                }

                switch (commandMessage.Command)
                {
                case Framework.DownloadCommand:
                {
                    Download(commandMessage.Message).ConfigureAwait(false).GetAwaiter();
                    break;
                }

                case Framework.ExitCommand:
                {
                    if (commandMessage.Message == _options.AgentId)
                    {
                        StopAsync(default).ConfigureAwait(true).GetAwaiter();
                    }
                    else
                    {
                        Logger?.LogWarning($"下载器代理 {_options.AgentId} 收到错误的退出消息: {message}");
                    }

                    break;
                }
Beispiel #28
0
        public async Task <IActionResult> GetTransactions()
        {
            Logger?.LogDebug("'{0}' has been invoked", nameof(GetTransactions));

            var response = new ListResponse <Transaction>();

            try
            {
                var data = await GetAllTransactions();

                response.Model   = data;
                response.Message = $"Total of Transactions: {data.Count()}";
            }
            catch (Exception ex)
            {
                ResponseError(response, ex, nameof(GetTransactions));
            }

            return(response.ToHttpResponse());
        }
Beispiel #29
0
        public override async Task PublishAsync(CancellationToken cancellationToken)
        {
            var data          = GetTelemetry();
            var messageString = JsonConvert.SerializeObject(data);

            Logger?.LogDebug($"Telemetry message: {messageString}");
            var encodedText = Encoding.UTF8.GetBytes($"{messageString}{_separator}");

            try
            {
                await _fileStream.WriteAsync(encodedText, 0,
                                             encodedText.Length, cancellationToken);

                await _fileStream.FlushAsync(cancellationToken);
            }
            catch (ObjectDisposedException e)
            {
                Logger.LogCritical(e.Message);
            }
        }
        /// <summary>
        /// Removes cached item by cachekey's prefix async.
        /// </summary>
        /// <remarks>
        /// Before using the method , you should follow this link
        /// https://github.com/memcached/memcached/wiki/ProgrammingTricks#namespacing
        /// and confirm that you use the namespacing when you set and get the cache.
        /// </remarks>
        /// <param name="prefix">Prefix of CacheKey.</param>
        /// <returns></returns>
        public override async Task BaseRemoveByPrefixAsync(string prefix)
        {
            ArgumentCheck.NotNullOrWhiteSpace(prefix, nameof(prefix));

            var oldPrefixKey = _memcachedClient.Get(prefix)?.ToString();

            var newValue = DateTime.UtcNow.Ticks.ToString();

            Logger?.LogDebug("RemoveByPrefixAsync : prefix = {0}", prefix);

            if (oldPrefixKey.Equals(newValue))
            {
                newValue = string.Concat(newValue, new Random().Next(9).ToString());
            }
            await _memcachedClient.StoreAsync(
                Enyim.Caching.Memcached.StoreMode.Set,
                this.HandleCacheKey(prefix),
                newValue,
                new TimeSpan(0, 0, 0));
        }