internal async Task <IRoutingTable> UpdateRoutingTableAsync(AccessMode mode,
                                                                    string database, Bookmark bookmark)
        {
            if (database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }

            _logger?.Debug("Updating routing table for database '{0}'.", database);

            var existingTable = RoutingTableFor(database);

            if (existingTable == null)
            {
                existingTable = new RoutingTable(database, Enumerable.Empty <Uri>());
            }

            var hasPrependedInitialRouters = false;

            if (existingTable.IsReadingInAbsenceOfWriter(mode))
            {
                var uris = _initialServerAddressProvider.Get();
                await PrependRoutersAsync(existingTable, uris).ConfigureAwait(false);

                hasPrependedInitialRouters = true;
            }

            var triedUris       = new HashSet <Uri>();
            var newRoutingTable = await UpdateRoutingTableAsync(existingTable, mode, database, bookmark, triedUris)
                                  .ConfigureAwait(false);

            if (newRoutingTable != null)
            {
                return(newRoutingTable);
            }

            if (!hasPrependedInitialRouters)
            {
                var uris = _initialServerAddressProvider.Get();
                uris.ExceptWith(triedUris);
                if (uris.Count != 0)
                {
                    await PrependRoutersAsync(existingTable, uris).ConfigureAwait(false);

                    newRoutingTable = await UpdateRoutingTableAsync(existingTable, mode, database, bookmark)
                                      .ConfigureAwait(false);

                    if (newRoutingTable != null)
                    {
                        return(newRoutingTable);
                    }
                }
            }

            // We tried our best however there is just no cluster.
            // This is the ultimate place we will inform the user that a new driver to be created.
            throw new ServiceUnavailableException(
                      "Failed to connect to any routing server. " +
                      "Please make sure that the cluster is up and can be accessed by the driver and retry.");
        }
 private void LogSuccess(IDictionary <string, object> meta)
 {
     if (_logger != null && _logger.IsDebugEnabled())
     {
         _logger?.Debug(MessagePattern, new SuccessMessage(meta));
     }
 }
        // "main" scene constructor. The constructor is called by the server when the scene is created.
        //
        public Main(ISceneHost scene)
        {
            _scene = scene;
            _env = _scene.GetComponent<IEnvironment>();
            _log = _scene.GetComponent<ILogger>();
            _log.Debug("server", "starting configuration");

            // we configure the functions that will be called by the Connecting, Connected and Disconnected events.
            // Connecting is called when a client tries to connect to the server. Please use this event to prevent player form accessing the server.
            // Connected is called when a client is already connected.
            // Disconnected is called when a client is already disconnected.
            _scene.Connecting.Add(OnConnecting);
            _scene.Connected.Add(OnConnected);
            _scene.Disconnected.Add(OnDisconnect);

            // We configure the routes and procedure the client can use.
            // A route is used for "one-shot" messages that don't need response such as position updates.
            // Produres send a response to the client. It's better to use them when client have to wait for a response from the server such as being hit.
            // Procedures use more bandwidth than regular routes.
            //
            // In our case, the server mostly has procedures as the client always needs to wait for a response from the server since it controls the game.
            _scene.AddProcedure("play", OnPlay);
            _scene.AddProcedure("click", OnClick);
            _scene.AddProcedure("update_leaderBoard", OnUpdateLeaderBoard);

            // this route is only used by the client to disconnect from the game (not the server) because it doesn't have to wait for the server to stop playing.
            _scene.AddRoute("exit", OnExit);

            //The starting and shutdown event are called when the scene is launched and shut down. these are useful if you need to initiate the server logic or save the game state before going down.
            _scene.Starting.Add(OnStarting);
            _scene.Shuttingdown.Add(OnShutdown);

            _log.Debug("server", "configuration complete");
        }
Exemple #4
0
        /// <inheritdoc />
        public void Authorize(IApiAuthParams @params)
        {
            // подключение браузера через прокси
            if (@params.Host != null)
            {
                _logger?.Debug(message: "Настройка прокси");

                Browser.Proxy = WebProxy.GetProxy(host: @params.Host,
                                                  port: @params.Port,
                                                  proxyLogin: @params.ProxyLogin,
                                                  proxyPassword: @params.ProxyPassword);

                RestClient.Proxy = Browser.Proxy;
            }

            // если токен не задан - обычная авторизация
            if (@params.AccessToken == null)
            {
                AuthorizeWithAntiCaptcha(authParams: @params);

                // Сбросить после использования
                @params.CaptchaSid = null;
                @params.CaptchaKey = "";
            }

            // если токен задан - авторизация с помощью токена полученного извне
            else
            {
                TokenAuth(accessToken: @params.AccessToken, userId: @params.UserId, expireTime: @params.TokenExpireTime);
            }

            _ap = @params;
            _logger?.Debug(message: "Авторизация прошла успешно");
        }
        public static async Task Set <T>(this IDistributedCache cache,
                                         string key,
                                         T item,
                                         ILogger?logger = default,
                                         CancellationToken cancellationToken = default) where T : class
        {
            try
            {
                var json = JsonSerializer.Serialize(item);

                var options = new DistributedCacheEntryOptions();

                await cache.SetStringAsync(key, json, options, cancellationToken);
            }
            catch (TaskCanceledException ex)
            {
                logger?.Debug(ex, "Cache timed out");
            }
            catch (OperationCanceledException ex)
            {
                logger?.Debug(ex, "Cache timed out");
            }
            catch (Exception ex)
            {
                logger?.Debug(ex, "Could not set cache");
            }
        }
        public IObservable <IOnPremiseConnectorRequest> OnRequestReceived(Guid linkId, string connectionId, bool autoAck)
        {
            return(CreateConsumerObservable <OnPremiseConnectorRequest>($"{_REQUEST_QUEUE_PREFIX}{linkId}", autoAck, (request, deliveryTag) =>
            {
                if (autoAck)
                {
                    return;
                }

                switch (request.AcknowledgmentMode)
                {
                case AcknowledgmentMode.Auto:
                    lock (_model)
                    {
                        _model.BasicAck(deliveryTag, false);
                    }

                    _logger?.Debug("Request was automatically acknowledged. request-id={RequestId}", request.RequestId);
                    break;

                case AcknowledgmentMode.Default:
                case AcknowledgmentMode.Manual:
                    request.AcknowledgeId = deliveryTag.ToString();
                    request.AcknowledgeOriginId = _originId;
                    _logger?.Verbose("Request acknowledge id was set. request-id={RequestId}, acknowledge-id={AcknowledgeId}", request.RequestId, request.AcknowledgeId);
                    break;
                }
            }));
        }
 public void DebugWrite(ILogger logger)
 {
     if (logger == null) throw new ArgumentNullException("logger");
     logger.Debug("TestFileCollection.UnitTestProvider = {0}".FormatWith(UnitTestProvider));
     logger.Debug("TestFileCollection.MSTestVersion = {0}".FormatWith(MSTestVersion));
     logger.Debug("TestFileCollection.TestAssembly = {0}".FormatWith(TestAssemblyFullName));
 }
Exemple #8
0
        public async Task Start()
        {
            await _tcpSocketClient.ConnectAsync(_uri, _encryptionManager.UseTls).ConfigureAwait(false);

            IsOpen = true;
            _logger?.Debug($"~~ [CONNECT] {_uri}");

            var version = await DoHandshake().ConfigureAwait(false);

            switch (version)
            {
            case ProtocolVersion.Version1:
                _logger?.Debug("S: [HANDSHAKE] 1");

                var formatV1 = new PackStreamMessageFormatV1(_tcpSocketClient, _logger);
                _writer = formatV1.Writer;
                _reader = formatV1.Reader;
                break;

            case ProtocolVersion.NoVersion:
                throw new NotSupportedException("The Neo4j server does not support any of the protocol versions supported by this client. " +
                                                "Ensure that you are using driver and server versions that are compatible with one another.");

            case ProtocolVersion.Http:
                throw new NotSupportedException("Server responded HTTP. Make sure you are not trying to connect to the http endpoint " +
                                                $"(HTTP defaults to port 7474 whereas BOLT defaults to port {GraphDatabase.DefaultBoltPort})");

            default:
                throw new NotSupportedException("Protocol error, server suggested unexpected protocol version: " + version);
            }
        }
        public Connection(IPAddress address, TransportConfig config, ILogger logger)
        {
            Endpoint = address;
            _config = config;
            _logger = logger;
            _tcpClient = new TcpClient();
            _tcpClient.Connect(address, _config.Port);

            Stream stream = _tcpClient.GetStream();
            #if DEBUG_STREAM
            stream = new DebugStream(stream);
            #endif

            _outputStream = stream;
            _inputStream = stream;

            for (byte idx = 0; idx < STREAMID_MAX; ++idx)
            {
                _availableStreamIds.Push(idx);
                _requestStates[idx].Lock = new object();
            }

            _logger.Debug("Ready'ing connection for {0}", Endpoint);
            GetOptions();
            ReadifyConnection();
            _logger.Debug("Connection to {0} is ready", Endpoint);
        }
Exemple #10
0
        internal void SyncNext()
        {
            var oldSyncSource = CurrentSyncSource;

            // At this point the current sync source either doesn't have the next announcement
            // or has none at all.
            CurrentSyncSource = null;

            // Try and find a peer with an anouncement that corresponds to the next block we need.
            foreach (var p in _peers.Where(p => p.AnyStashed && p != oldSyncSource))
            {
                if (p.SyncNextAnnouncement())
                {
                    CurrentSyncSource = p;

                    FireSyncStateChanged(true);
                    _logger?.Debug($"Catching up with {p}.");

                    return;
                }
            }

            if (CurrentSyncSource != null)
            {
                _logger?.Error($"The current sync source {CurrentSyncSource} is not null even though sync should be finished.");
            }

            FireSyncStateChanged(false);

            _logger?.Debug("Catched up all peers.");
        }
Exemple #11
0
 /// <inheritdoc />
 public void LogDebug <T>(T value)
 {
     if (IsDebugLoggingEnabled)
     {
         _logger?.Debug(value);
     }
 }
Exemple #12
0
        /// <summary>
        ///     Danger! Danger, Will Robinson!
        /// </summary>
        private static void RemoveAllExistingNamespaceElements(Func<NamespaceManager> namespaceManager, ILogger logger)
        {
            logger.Debug("Removing all existing namespace elements. IMPORTANT: This should only be done in your regression test suites.");

            var queueDeletionTasks = namespaceManager().GetQueues()
                                                       .Select(q => q.Path)
                                                       .Select(queuePath => Task.Run(async delegate
                                                                                           {
                                                                                               logger.Debug("Deleting queue {0}", queuePath);
                                                                                               await namespaceManager().DeleteQueueAsync(queuePath);
                                                                                           }))
                                                       .ToArray();

            var topicDeletionTasks = namespaceManager().GetTopics()
                                                       .Select(t => t.Path)
                                                       .Select(topicPath => Task.Run(async delegate
                                                                                           {
                                                                                               logger.Debug("Deleting topic {0}", topicPath);
                                                                                               await namespaceManager().DeleteTopicAsync(topicPath);
                                                                                           }))
                                                       .ToArray();

            var allDeletionTasks = new Task[0]
                .Union(queueDeletionTasks)
                .Union(topicDeletionTasks)
                .ToArray();
            Task.WaitAll(allDeletionTasks);
        }
Exemple #13
0
        private Assembly LoadAssembly()
        {
            if (_configuration.CustomCodeAssemblyPath == null)
            {
                return(null);
            }

            try
            {
                _logger?.Debug("Trying to load custom code assembly. assembly-path={CustomCodeAssemblyPath}", _configuration.CustomCodeAssemblyPath);
                var assembly = Assembly.LoadFrom(_configuration.CustomCodeAssemblyPath);

                _logger?.Information("Successfully loaded custom code assembly from {CustomCodeAssemblyPath}", _configuration.CustomCodeAssemblyPath);

                return(assembly);
            }
            catch (Exception ex)
            {
                _logger?.Error(ex, "There was an error loading the custom code assembly. assembly-path={CustomCodeAssemblyPath}", _configuration.CustomCodeAssemblyPath);
                _configuration.CustomCodeAssemblyPath = null;
                _assembly = null;
            }

            return(null);
        }
Exemple #14
0
        public static bool PublishQueuedItems(Item triggerItem, Database[] targets, ILogger logger = null)
        {
            if (ManuallyAddedCandidates.Count == 0)
            {
                return(false);
            }

            foreach (var database in targets)
            {
                var suffix = ManuallyAddedCandidates.Count == 1 ? string.Empty : "s";
                logger?.Debug($"> Publishing {ManuallyAddedCandidates.Count} synced item{suffix} in queue to {database.Name}");

                var publishOptions = new PublishOptions(triggerItem.Database, database, PublishMode.SingleItem, triggerItem.Language, DateTime.UtcNow)
                {
                    RootItem = triggerItem, CompareRevisions = false, RepublishAll = true
                };

                var result = new Publisher(publishOptions, triggerItem.Database.Languages).PublishWithResult();

                logger?.Debug($"> Published synced items to {database.Name} (New: {result.Statistics.Created}, Updated: {result.Statistics.Updated}, Deleted: {result.Statistics.Deleted} Skipped: {result.Statistics.Skipped})");
            }

            // clear the queue after we publish
            while (ManuallyAddedCandidates.Count > 0)
            {
                ID fake;
                ManuallyAddedCandidates.TryDequeue(out fake);
            }

            return(true);
        }
Exemple #15
0
        public Connection(IPAddress address, TransportConfig config, ILogger logger, IInstrumentation instrumentation)
        {
            Endpoint = address;
            _config = config;
            _logger = logger;
            _instrumentation = instrumentation;
            _tcpClient = new TcpClient();
            _tcpClient.Connect(address, _config.Port);
            _streaming = config.Streaming;

            for (byte idx = 0; idx < MAX_STREAMID; ++idx)
            {
                _availableStreamIds.Push(idx);
            }

            _socket = _tcpClient.Client;

            // start a new read task
            Task.Factory.StartNew(ReadNextFrameHeader, _cancellation.Token);

            // readify the connection
            _logger.Debug("Readyfying connection for {0}", Endpoint);
            //GetOptions();
            ReadifyConnection();
            _logger.Debug("Connection to {0} is ready", Endpoint);
        }
        private void FtpClientOnLogEvent(FtpTraceLevel level, string message)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                return;
            }

            int indexOf = message.IndexOf("at System.Net.Sockets.Socket", StringComparison.Ordinal);

            if (indexOf >= 0)
            {
                message = message.Substring(0, indexOf).Trim();
            }

            const string messageTemplate = "{FtpMessage}";

            switch (level)
            {
            case FtpTraceLevel.Info:
                _logger?.Debug(messageTemplate, message);
                break;

            case FtpTraceLevel.Error:
                _logger?.Warning(messageTemplate, message);
                break;

            case FtpTraceLevel.Verbose:
                _logger?.Debug(messageTemplate, message);
                break;

            case FtpTraceLevel.Warn:
                _logger?.Warning(messageTemplate, message);
                break;
            }
        }
Exemple #17
0
        public Connection(IPAddress address, TransportConfig config, ILogger logger)
        {
            Endpoint = address;
            _config = config;
            _logger = logger;
            _tcpClient = new TcpClient();
            _tcpClient.Connect(address, _config.Port);
            _streaming = config.Streaming;

            Stream stream = _tcpClient.GetStream();
            #if DEBUG_STREAM
            stream = new DebugStream(stream);
            #endif

            _outputStream = stream;
            _inputStream = stream;

            for (byte idx = 0; idx < MAX_STREAMID; ++idx)
            {
                _availableStreamIds.Push(idx);
            }

            // start a new read task
            Task.Factory.StartNew(ReadNextFrameHeader, _cancellation.Token);

            // readify the connection
            _logger.Debug("Readyfying connection for {0}", Endpoint);
            GetOptions();
            ReadifyConnection();
            _logger.Debug("Connection to {0} is ready", Endpoint);
        }
Exemple #18
0
        internal IEnumerable <ArtistQueryResult> GetMatchingArtists(string loweredSearch)
        {
            log?.Debug($"searching for artist {loweredSearch} in style {MusicStyle.ToString()}");
            var artists = MusicDb.ArtistStyles
                          .Where(x1 => x1.StyleId == MusicStyle)
                          .Select(x2 => x2.Artist).ToArray();

            if (prefixMatch)
            {
                artists = artists.Where(x => prefixMatchAnyWord(x.Name, loweredSearch)).ToArray();
                log?.Debug($"found {artists.Count()} with prefix {loweredSearch}");
            }
            else
            {
                //artists = artists
                //    .Where(x => x.Name.Contains(loweredSearch, StringMatchingOptions.IgnoreNonAlphaNumerics | StringMatchingOptions.IgnoreAccents))
                //    ;
                artists = artists
                          .Where(x => x.Name.Contains(loweredSearch, CultureInfo.CurrentCulture, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols))
                          .ToArray();
                log?.Debug($"found {artists.Count()} containing {loweredSearch}");
            }

            return(artists.Select(x => new ArtistQueryResult
            {
                Artist = new SearchKey
                {
                    Key = x.Id,
                    Name = x.Name
                },
            }));
        }
Exemple #19
0
        /// <summary>
        /// Suggested block validation runs basic checks that can be executed before going through the expensive EVM processing.
        /// </summary>
        /// <param name="block">A block to validate</param>
        /// <returns><value>True</value> if the <paramref name="block"/> is valid, otherwise <value>False</value></returns>
        public bool ValidateSuggestedBlock(Block block)
        {
            Transaction[] txs         = block.Transactions;
            IReleaseSpec  releaseSpec = _specProvider.GetSpec(block.Number);

            for (int i = 0; i < txs.Length; i++)
            {
                if (!_txValidator.IsWellFormed(txs[i], releaseSpec))
                {
                    if (_logger.IsDebug)
                    {
                        _logger.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid transaction ({txs[i].Hash})");
                    }
                    return(false);
                }
            }

            if (releaseSpec.MaximumUncleCount < block.Ommers.Length)
            {
                _logger?.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - uncle count is {block.Ommers.Length} (MAX: {releaseSpec.MaximumUncleCount})");
                return(false);
            }

            if (block.Header.OmmersHash != block.CalculateOmmersHash())
            {
                _logger?.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid uncles hash");
                return(false);
            }

            if (!_ommersValidator.Validate(block.Header, block.Ommers))
            {
                _logger?.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid uncles");
                return(false);
            }

            bool blockHeaderValid = _headerValidator.Validate(block.Header);

            if (!blockHeaderValid)
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid header");
                }
                return(false);
            }

            Keccak txRoot = block.CalculateTxRoot();

            if (txRoot != block.Header.TxRoot)
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) tx root {txRoot} != stated tx root {block.Header.TxRoot}");
                }
                return(false);
            }

            return(true);
        }
        public object Load(string key)
        {
            _logger?.Debug($"DxaCacheAgent::Load({key})");
            object result;
            string cacheRegion = DetermineCacheRegion(key);

            TryGet(key, cacheRegion, out result);
            return(result);
        }
Exemple #21
0
    /// <summary>Process new files in land into stage. Note on the different modes: - LandAndStage: Immutable operation, load
    ///   data downstream from the stage directory - Default: Mutates the files in the same directory. Downstream operations:
    ///   don't run while processing, and fully reload after this is complete</summary>
    /// <returns>stats about the optimisation, and all new files (optimised or not) based on the timestamp</returns>
    public static async Task <IReadOnlyCollection <OptimiseBatch> > OptimisePlan(this ISimpleFileStore store, OptimiseCfg cfg, SPath rootPath,
                                                                                 string ts = null, ILogger log = null)
    {
        log?.Debug("Optimise {Path} - reading current files", rootPath);
        var(byDir, duration) = await ToOptimiseByDir(store, rootPath, ts).WithDuration();

        log?.Debug("Optimise {Path} - read {Files} files across {Partitions} partitions in {Duration}",
                   rootPath, byDir.Sum(p => p.Count()), byDir.Length, duration.HumanizeShort());
        return(byDir.SelectMany(p => OptimisePlan(p, p.Key, cfg)).ToArray());
    }
        protected override async Task OnConnected(IRequest request, string connectionId)
        {
            var onPremiseClaims = GetOnPremiseClaims(request);

            _logger?.Debug("On-premise connected. connection-id={ConnectionId}, link-id={LinkId}, user-name={UserName}, role={Role}", connectionId, onPremiseClaims.OnPremiseId, onPremiseClaims.UserName, onPremiseClaims.Role);

            await RegisterOnPremiseAsync(request, connectionId, onPremiseClaims).ConfigureAwait(false);

            await base.OnConnected(request, connectionId).ConfigureAwait(false);
        }
Exemple #23
0
 public DefaultRetry(ILogger logger) : base(_numAttempts)
 {
     this
         .Chain(r => r.Started += (s, e) => logger.Debug("{Action}...", e.ActionName))
         .Chain(r => r.Success += (s, e) => logger.Debug("{Action} completed successfully in {Elapsed}.", e.ActionName, e.ElapsedTime))
         .Chain(r => r.TransientFailure += (s, e) => logger.Warn(e.Exception, "A transient failure occurred in action {Action}.", e.ActionName))
         .Chain(r => r.PermanentFailure += (s, e) => logger.Error(e.Exception, "A permanent failure occurred in action {Action}.", e.ActionName))
         .WithBackoff<DefaultRetry>(Backoff)
         ;
 }
Exemple #24
0
        /// <inheritdoc />
        public AuthorizationResult Authorize()
        {
            _logger?.Debug(message: "Валидация данных.");
            ValidateAuthorizationParameters();

            _logger?.Debug(message: "Шаг 1. Открытие диалога авторизации");
            var authorizeUrlResult = OpenAuthDialog();

            return(null);
        }
Exemple #25
0
        public void TestInitialize()
        {
            container = new WindsorContainer();
            RegisterServices(container);
            logger = container.Resolve<ILoggerFactory>().Create(this.GetType());

            logger.Debug("Begin BeforeEachTest()");
            BeforeEachTest();
            logger.Debug("Begin [TestMethod]");
        }
Exemple #26
0
        internal void ProcessingData()
        {
            try
            {
                if (_lock)
                {
                    return;
                }

                _lock = true;

                var method = UtilHelper.GetMethodName(MethodBase.GetCurrentMethod());
                _logger?.Info($"{method} => start");
                var watch = System.Diagnostics.Stopwatch.StartNew();

                var data = DataReaderHelper.GetData(
                    _dataReaders, _filtersValidator, _filtersValidatorRepository, _aggregatorsValidator, _aggregatorsValidatorRepository);
                if (!data.Any())
                {
                    _logger?.Debug("No data found...");
                    return;
                }

                var sendedMessages = new Dictionary <SendedMessages, int>();
                foreach (var message in data)
                {
                    if (!_clientsManager.Send(message))
                    {
                        _logger?.Debug("No clients defined to send...");
                        return;
                    }
                    var sendedMessage = new SendedMessages {
                        Name = message.LogicalStorage, Id = message.ReaderId
                    };
                    sendedMessages.AddOrIncrement(sendedMessage, 1);
                }

                foreach (var message in sendedMessages)
                {
                    _logger?.Debug($"Sended: {message.Value} messages from {message.Key}");
                }

                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                _logger?.Info($"{method} => end, Time taken: {elapsedMs}ms");
            }
            catch (Exception ex)
            {
                _logger?.Error(ex.Message);
            }
            finally
            {
                _lock = false;
            }
        }
Exemple #27
0
        public async Task <IBoltProtocol> ConnectAsync(IDictionary <string, string> routingContext)
        {
            await _tcpSocketClient.ConnectAsync(_uri).ConfigureAwait(false);

            SetOpened();
            _logger?.Debug($"~~ [CONNECT] {_uri}");

            var version = await DoHandshakeAsync().ConfigureAwait(false);

            return(SelectBoltProtocol(version, routingContext));
        }
Exemple #28
0
 /// <summary>
 /// <see cref="ISmtpService.SendAdminEmailAsync"/>
 /// </summary>
 public async Task SendAdminEmailAsync(
     string subject,
     string body,
     bool isBodyHtml = true,
     IEnumerable <string> attachmentPaths = null
     )
 {
     _logger?.Debug($"SendAdminMailAsync: admin {_settingsMonitor.CurrentValue.Admin}");
     await SendEmailAsync(
         _settingsMonitor.CurrentValue.Admin, "", "", subject, body, isBodyHtml, attachmentPaths
         ).ConfigureAwait(false);
 }
Exemple #29
0
        public Versioner(ISession session, ILogger<Version> logger)
        {
            _logger = logger;

            _logger.Debug("Define global mappings");
            MappingConfiguration.Global.Define<PocoMapper>();

            _logger.Debug("Create mapper and table instances");
            _mapper = new Mapper(session);
            var table = new Table<DatabaseVersion>(session);
            table.CreateIfNotExists();
        }
Exemple #30
0
        private async void Process()
        {
            try {
                while (Client.Connected)
                {
                    // TODO : Configuration.
                    var limitedStream = new NotFlushingStream(new LimitedStream(_stream, 1024 * 1024, 1024 * 1024));
                    var streamReader  = new StreamReader(limitedStream);

                    var request = await _requestProvider.Provide(streamReader).ConfigureAwait(false);

                    if (request != null)
                    {
                        UpdateLastOperationTime();

                        var context = new HttpContext(request, Client.RemoteEndPoint);

                        _logger?.Debug($"{Client.RemoteEndPoint} : Got request {request.Uri}");

                        await _requestHandler(context).ConfigureAwait(false);

                        if (context.Response != null)
                        {
                            var streamWriter = new StreamWriter(limitedStream)
                            {
                                AutoFlush = false
                            };

                            await WriteResponse(context, streamWriter).ConfigureAwait(false);

                            await limitedStream.ExplicitFlushAsync().ConfigureAwait(false);

                            if (!request.Headers.KeepAliveConnection() || context.Response.CloseConnection)
                            {
                                Client.Close();
                            }
                        }

                        UpdateLastOperationTime();
                    }
                    else
                    {
                        Client.Close();
                    }
                }
            } catch (Exception e) {
                // Hate people who make bad calls.
                _logger?.Warn($"Error while serving : {_remoteEndPoint}", e);
                Client.Close();
            }

            _logger?.Debug($"Lost Client {_remoteEndPoint}");
        }
        public void DispatchRequest(Guid linkId, IOnPremiseConnectorRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            CheckDisposed();
            _logger?.Debug("Dispatching request. link-id={LinkId}, request-id={RequestId}, method={HttpMethod}, url={RequestUrl}", linkId, request.RequestId, request.HttpMethod, request.Url);

            TryGetRequestSubject(linkId)?.OnNext(request);
        }
        public Crawler(ILogger logger, IEnumerable<CrawlJob> crawlJobs)
        {
            Logger = logger;
            CrawlJobs = crawlJobs;

            logger.Info("Web Spider instantiated...");
            if (logger.IsDebugEnabled) {
                logger.Debug("List of URLs to index:");
                foreach (CrawlJob u in crawlJobs)
                    logger.Debug(string.Format("  > {0}", u.Url.ToString()));
            }
        }
        protected IObservable <TMessage> CreateObservable <TMessageType>(bool autoAck = true, Action <TMessageType, ulong> callback = null)
            where TMessageType : class, TMessage
        {
            return(Observable.Create <TMessage>(observer =>
            {
                Logger?.Debug("Creating consumer. exchange-name={ExchangeName}, queue-name={QueueName}, channel-id={ChannelId}", Exchange, QueueName, ChannelId);

                lock (_model)
                {
                    DeclareAndBind();
                    var consumer = new EventingBasicConsumer(_model);
                    var consumerTag = _model.BasicConsume(QueueName, autoAck, consumer);

                    void OnReceived(object sender, BasicDeliverEventArgs args)
                    {
                        Logger?.Verbose("Received data. exchange-name={ExchangeName}, queue-name={QueueName}, channel-id={ChannelId}, data-length={DataLength}", Exchange, QueueName, ChannelId, args.Body.Length);
                        try
                        {
                            var json = Encoding.GetString(args.Body);
                            var message = JsonConvert.DeserializeObject <TMessageType>(json);

                            callback?.Invoke(message, args.DeliveryTag);
                            observer.OnNext(message);
                        }
                        catch (Exception ex)
                        {
                            Logger?.Error(ex, "Error during receiving a message via RabbitMQ. exchange-name={ExchangeName}, queue-name={QueueName}, channel-id={ChannelId}", Exchange, QueueName, ChannelId);

                            if (!autoAck)
                            {
                                Acknowledge(args.DeliveryTag);
                            }
                        }
                    }

                    consumer.Received += OnReceived;

                    return new DelegatingDisposable(Logger, () =>
                    {
                        Logger?.Debug("Disposing consumer. exchange-name={ExchangeName}, queue-name={QueueName}, channel-id={ChannelId}", Exchange, QueueName, ChannelId);

                        consumer.Received -= OnReceived;

                        lock (_model)
                        {
                            _model.BasicCancel(consumerTag);
                            _model.BasicRecover(true);
                            Unbind();
                        }
                    });
                }
            }));
        }
 public void Terminate()
 {
     log?.Debug("[Terminate] Starting Terminate sequence");
     envSetupKit?.RemoveFirewallPortRule();
     log?.Debug("[Terminate] Removed Firewall port rule");
     httpServerKit?.Stop();
     log?.Debug("[Terminate] Stopped HTTP Server");
     notifyIconKit?.Hide();
     log?.Debug("[Terminate] Hide NotifyIcon");
     Thread.Sleep(1000);
     log?.Debug("[Terminate] Env Exit");
     Environment.Exit(Environment.ExitCode);
 }
Exemple #35
0
        /// <summary>
        /// Suggested block validation runs basic checks that can be executed before going through the expensive EVM processing.
        /// </summary>
        /// <param name="block">A block to validate</param>
        /// <returns><value>True</value> if the <paramref name="block"/> is valid, otherwise <value>False</value></returns>
        public bool ValidateSuggestedBlock(Block block)
        {
            Transaction[] txs = block.Transactions;
            for (int i = 0; i < txs.Length; i++)
            {
                if (!_txValidator.IsWellFormed(txs[i], _specProvider.GetSpec(block.Number)))
                {
                    if (_logger.IsDebug)
                    {
                        _logger.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid transaction ({txs[i].Hash})");
                    }
                    return(false);
                }
            }

            if (!_ommersValidator.Validate(block.Header, block.Ommers))
            {
                _logger?.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid ommers");
                return(false);
            }

            bool blockHeaderValid = _headerValidator.Validate(block.Header);

            if (!blockHeaderValid)
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid header");
                }
                return(false);
            }

            if (block.Header.OmmersHash != Keccak.Compute(Rlp.Encode(block.Ommers)))
            {
                _logger?.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid ommers hash");
                return(false);
            }

            Keccak txRoot = block.CalculateTxRoot();

            if (txRoot != block.Header.TransactionsRoot)
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) tx root {txRoot} != stated tx root {block.Header.TransactionsRoot}");
                }
                return(false);
            }

            return(true);
        }
        private string BaseAuth()
        {
            _logger?.Debug("1. Авторизация с помощью логина и пароля.");

            return(Invoke("https://oauth.vk.com/token",
                          new VkParameters
            {
                { "grant_type", "password" },
                { "client_id", "2274003" },
                { "client_secret", "hHbZxrka2uZ6jB1inYsH" },
                { "username", $"{_apiAuthParams.Login}" },
                { "password", $"{_apiAuthParams.Password}" }
            }));
        }
        public WebServerNotAvailable(ILogger logger, int port = 80)
        {
            _logger = logger;
            _port = port;

            _logger.Debug("Starting NOT AVAILABLE web server");

            _listeningSocket = SetupListeningSocket();

            _requestThread = new Thread(WaitForNetworkRequest);
            _requestThread.Start();

            _logger.Debug("NOT AVAILABLE web server is running");
        }
Exemple #38
0
        public void Sign(PrivateKey privateKey, Transaction transaction, UInt256 blockNumber)
        {
            _logger?.Debug($"Signing transaction: {transaction.Value} to {transaction.To} with data {transaction.Data}");
            bool   isEip155Enabled = _specProvider.GetSpec(blockNumber).IsEip155Enabled;
            Keccak hash            = Keccak.Compute(Rlp.Encode(transaction, true, isEip155Enabled, _chainIdValue));

            transaction.Signature = Sign(privateKey, hash);
            if (isEip155Enabled)
            {
                transaction.Signature.V = transaction.Signature.V + 8 + 2 * _chainIdValue;
            }

            _logger?.Debug("Transaction signed");
        }
        /// <summary>
        /// <see cref="ITableauProjectService.GetProjectsAsync"/>
        /// </summary>
        public async Task <IEnumerable <TableauProject> > GetProjectsAsync()
        {
            _logger?.Debug("Getting projects");

            var pageSize       = 1000;
            var pageNumber     = 1;
            var totalRetrieved = 0;
            var totalAvailable = 0;
            var projects       = new List <TableauProject>();

            do
            {
                var url = _tableauApiService.SiteUrl.AppendUri(
                    $"projects?pageSize={pageSize}&pageNumber={pageNumber}"
                    );
                var responseString = await _tableauApiService.SendGetAsync(url).ConfigureAwait(false);

                var responseJson = JToken.Parse(responseString);
                if (!responseJson.Value <JObject>("projects").ContainsKey("project"))
                {
                    break;
                }

                var pagination = JsonConvert.DeserializeObject <TableauPagination>(
                    responseJson.Value <JObject>("pagination").ToString()
                    );

                var pageProjects = JsonConvert.DeserializeObject <List <TableauProject> >(
                    responseJson.Value <JObject>("projects").Value <JArray>("project").ToString()
                    );
                projects.AddRange(pageProjects);

                pageNumber++;
                totalAvailable  = pagination.TotalAvailable;
                totalRetrieved += pagination.PageSize;
            }while (totalRetrieved < totalAvailable);

            projects.ForEach(
                p =>
            {
                p.SiteId     = _tableauApiService.SiteId;
                p.ApiVersion = _tableauApiService.ApiVersion;
            }
                );

            _logger?.Debug($"{projects.Count} projects returned");

            return(projects);
        }
Exemple #40
0
        private async Task ResolveAsync()
        {
            var AffinityPointer = (0b00000001 << Affinity++);

            var ProcessThread = Process.GetCurrentProcess().Threads[Thread.CurrentThread.ManagedThreadId];

            ProcessThread.ProcessorAffinity = (IntPtr)AffinityPointer;

            ProcessThread.PriorityLevel = ThreadPriorityLevel.Highest;

            Logger?.Debug("UDP Server Started Thread {@Thread} with Affinity {@Affinity} & Priority {@Priority}.", Thread.CurrentThread.ManagedThreadId, AffinityPointer, ThreadPriorityLevel.Highest);

            var ProxyResponsibilityChain = new ProxyResponsibilityChain(ProxyResponsibilityChainOptions, MiddlewareResolver);

            while (!CancellationToken.IsCancellationRequested)
            {
                UdpReceiveResult Client = default;

                try
                {
                    Client = await Server.ReceiveAsync().WithCancellation(CancellationToken);

                    var Query = DnSerializer.Deserialize(Client.Buffer);

                    var Answer = await ProxyResponsibilityChain.Execute(Query);

                    var RawAnswer = DnSerializer.Serialize(Answer);

                    await Server.SendAsync(RawAnswer, RawAnswer.Length, Client.RemoteEndPoint);

                    Logger?.Information("Resolved Query {@QueryID} To {@RemoteEndPoint} with {@ResponseCode} For {@Domain}.",
                                        Query.ID, Client.RemoteEndPoint.ToString(), Answer?.ResponseCode, Answer?.Questions.FirstOrDefault()?.Domain.Name);

                    Logger?.Debug("Resolved {@Answer} For {@RemoteEndPoint}", Answer, Client.RemoteEndPoint);
                }
                catch (OperationCanceledException)
                {
                    break;
                }
                catch (Exception Error)
                {
                    Logger?.Debug(Error, $"{@Error} Occurred While Processing.", Error);
                }
                finally
                {
                    var Message = new Message()
                    {
                        ID           = BinaryPrimitives.ReadUInt16BigEndian(Client.Buffer[..2]),
        public static EsDriveInfo FromDirectory(string path, ILogger log)
        {
            try
            {
                string driveName;
                if (OS.IsUnix)
                {
                    driveName = GetDirectoryRootInUnix(path, log);
                    if (driveName == null)
                        return null;
                }
                else
                {
                    driveName = Directory.GetDirectoryRoot(path);
                }

                var drive = new DriveInfo(driveName);
                var esDrive = new EsDriveInfo(drive.Name, drive.TotalSize, drive.AvailableFreeSpace);
                return esDrive;
            }
            catch (Exception ex)
            {
                log.Debug("Error while reading drive info for path {0}. Message: {1}.", path, ex.Message);
                return null;
            }
        }
 public DummyApiCommand(IOctopusAsyncRepositoryFactory repositoryFactory, ILogger log, IOctopusFileSystem fileSystem, IOctopusClientFactory clientFactory)
     : base(clientFactory, repositoryFactory, log, fileSystem)
 {
     var options = Options.For("Dummy");
     options.Add("pill=", "Red or Blue. Blue, the story ends. Red, stay in Wonderland and see how deep the rabbit hole goes.", v => pill = v);
     log.Debug("Pill: " + pill);
 }
Exemple #43
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LogEntryService"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        
        public LogEntryService(ILogger logger)
        {
            _logger = logger;

            var scheduler = new EventLoopScheduler();

            //expire old items
            var timeExpirer = _source.AutoRemove(le =>
                                        {
                                            return TimeSpan.FromSeconds(le.Level == LogLevel.Debug ? 5 : 60);
                                        },TimeSpan.FromSeconds(5),  TaskPoolScheduler.Default)
                                        .Subscribe(removed =>
                                        {
                                            logger.Debug("{0} log items have been automatically removed",removed.Count());
                                        });

          //  var expirer = _source.ExpireFromSource(50).Subscribe();

            //populate the source cache from the logger observable
           var loader = RxAppender.LogEntryObservable
               .ObserveOn(scheduler)
                .Subscribe(item => _source.AddOrUpdate(item));


            _disposer = Disposable.Create(() =>
                                              {
                                                  timeExpirer.Dispose();
                                                   // expirer.Dispose();
                                                    scheduler.Dispose();
                                                    loader.Dispose();
                                                    _source.Dispose();
                                              });

            _logger.Info("Log cache has been constructed");
        }
        public override async Task WriteQueryToStream(Stream stream, ILogger logger, Spec.Query query, CancellationToken cancellationToken)
        {
            using (var memoryBuffer = new MemoryStream(1024))
            using (var streamWriter = new StreamWriter(memoryBuffer, utf8Encoding))
            {
                WriteQuery(new JsonWriter(streamWriter), query);
                streamWriter.Flush();

                var data = memoryBuffer.ToArray();
                memoryBuffer.Seek(0, SeekOrigin.Begin);

                if (logger.InformationEnabled())
                {
                    string dataStr = Encoding.UTF8.GetString(data);
                    logger.Information("JSON query: {0}", dataStr);
                }

                var tokenHeader = BitConverter.GetBytes(query.token);
                if (!BitConverter.IsLittleEndian)
                    Array.Reverse(tokenHeader, 0, tokenHeader.Length);
                memoryBuffer.Write(tokenHeader, 0, tokenHeader.Length);

                var lengthHeader = BitConverter.GetBytes(data.Length);
                if (!BitConverter.IsLittleEndian)
                    Array.Reverse(lengthHeader, 0, lengthHeader.Length);
                memoryBuffer.Write(lengthHeader, 0, lengthHeader.Length);

                memoryBuffer.Write(data, 0, data.Length);

                logger.Debug("Writing packet, {0} bytes", data.Length);
                data = memoryBuffer.ToArray();
                await stream.WriteAsync(data, 0, data.Length, cancellationToken);
            }
        }
Exemple #45
0
        public virtual void Execute(JobExecutionContext context)
        {
            Logger = new ServiceLogger(context.JobDetail.Name);

            if (Monitor.TryEnter(SYNC_LOCK, 3000) == false)
            {
                Logger.Debug("上一次调度未完成,本次调度放弃运行");
                return;
            }

            try
            {
                Logger.Info("调度开始执行");

                InnerExecute(context);

                Logger.Info("调度正常结束");
            }
            catch (Exception e)
            {
                Logger.Error("调度执行时发生异常: " + e);
            }
            finally
            {
                Monitor.Exit(SYNC_LOCK);
            }
        }
        public IEnumerable<ChannelInfo> GetChannels(Stream stream, IJsonSerializer json,ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);

            if (root.channelsJSONObject.rtn != null && root.channelsJSONObject.rtn.Error)
            {
                logger.Error(root.channelsJSONObject.rtn.Message ?? "Failed to download channel information.");
                throw new ApplicationException(root.channelsJSONObject.rtn.Message ?? "Failed to download channel information.");
            }

            if (root.channelsJSONObject != null && root.channelsJSONObject.Channels != null)
            {
                logger.Debug("[NextPvr] ChannelResponse: {0}", json.SerializeToString(root));
                return root.channelsJSONObject.Channels.Select(i => new ChannelInfo
                {
                    Name = i.channel.channelName,
                    Number = i.channel.channelNum.ToString(_usCulture),
                    Id = i.channel.channelOID.ToString(_usCulture),
                    ImageUrl = string.IsNullOrEmpty(i.channel.channelIcon) ? null : (_baseUrl + "/" + i.channel.channelIcon),
                    HasImage = !string.IsNullOrEmpty(i.channel.channelIcon)
                });
            }

            return new List<ChannelInfo>();
        }
        private void UploadToDocuments(AttachmentStream file, string contentType, MailBox mailbox, ILogger log)
        {
            try
            {
                var uploadedFileId = ApiHelper.UploadToDocuments(file.FileStream, file.FileName, contentType, mailbox.EMailInFolder, true);

                log.Debug("ApiHelper.UploadToDocuments() -> uploadedFileId = {0}", uploadedFileId);
            }
            catch (ApiHelperException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound || ex.StatusCode == HttpStatusCode.Forbidden)
                {
                    log.Info("ApiHelper.UploadToDocuments() EMailIN folder '{0}' is unreachable. Try to unlink EMailIN...", mailbox.EMailInFolder);

                    SetMailboxEmailInFolder(mailbox.TenantId, mailbox.UserId, mailbox.MailBoxId, null);

                    mailbox.EMailInFolder = null;

                    CreateUploadToDocumentsFailureAlert(mailbox.TenantId, mailbox.UserId,
                                                        mailbox.MailBoxId,
                                                        (ex.StatusCode == HttpStatusCode.NotFound)
                                                            ? UploadToDocumentsErrorType
                                                                  .FolderNotFound
                                                            : UploadToDocumentsErrorType
                                                                  .AccessDenied);

                    throw;
                }

                log.Error("SaveEmailInData->ApiHelper.UploadToDocuments(fileName: '{0}', folderId: {1}) Exception:\r\n{2}\r\n",
                                      file.FileName, mailbox.EMailInFolder, ex.ToString());

            }
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="PassThroughFileSystem"/> class.
 /// </summary>
 /// <remarks>
 /// The <paramref name="logger"/> is optional.
 /// </remarks>
 public PassThroughFileSystem(ILogger?logger)
 {
     if (GetSequentialScanOnOpenStreamThresholdEnvVariable(out _sequentialScanOnOpenThreshold))
     {
         logger?.Debug($"{nameof(PassThroughFileSystem)}.{SequentialScanOnOpenStreamThreshold}={_sequentialScanOnOpenThreshold}");
     }
 }
        public WebServer(ILogger logger, IGarbage garbage, int port = 80)
        {
            _logger = logger;
            _garbage = garbage;
            _port = port;

            _logger.Debug("Starting web server");

            _responses = new ArrayList();
            _listeningSocket = SetupListeningSocket();

            _requestThread = new Thread(WaitForNetworkRequest);
            _requestThread.Start();

            _logger.Debug("Web server is running");
        }
        private static void SetCurrentUow(IUnitOfWork value, ILogger logger)
        {
            if (value == null)
            {
                ExitFromCurrentUowScope(logger);
                return;
            }

            var unitOfWorkKey = CallContext.LogicalGetData(ContextKey) as string;
            if (unitOfWorkKey != null)
            {
                IUnitOfWork outer;
                if (UnitOfWorkDictionary.TryGetValue(unitOfWorkKey, out outer))
                {
                    if (outer == value)
                    {
                        logger.Warn("Setting the same UOW to the CallContext, no need to set again!");
                        return;
                    }

                    value.Outer = outer;
                }
            }

            unitOfWorkKey = value.Id;
            if (!UnitOfWorkDictionary.TryAdd(unitOfWorkKey, value))
            {
                throw new AbpException("Can not set unit of work! UnitOfWorkDictionary.TryAdd returns false!");
            }

            logger.Debug("Entering a new UOW scope: " + unitOfWorkKey);
            CallContext.LogicalSetData(ContextKey, unitOfWorkKey);
        }
Exemple #51
0
		public static bool ExecuteTool(ILogger logger, string toolName, string arguments, string workingDirectory, Action<ILogger, string> processToolOutput = null)
		{
			try {
				if (processToolOutput == null)
					processToolOutput = (l, s) => l.Info(s);
				Process p = new Process();
				p.StartInfo.UseShellExecute = false;
				p.StartInfo.RedirectStandardError = true;
				p.StartInfo.RedirectStandardOutput = true;
				p.StartInfo.FileName = toolName.FindInPathEnvironmentVariable();
				p.StartInfo.Arguments = arguments;
				p.StartInfo.WorkingDirectory = workingDirectory;
				p.StartInfo.CreateNoWindow = true;
				if (logger != null) {
					p.OutputDataReceived += (object sender, DataReceivedEventArgs e) => processToolOutput(logger, e.Data);
					p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => logger.Error(e.Data);
				}
				var debugLine = "Executing: " + p.StartInfo.FileName + " " + arguments;
				logger.Debug(debugLine);
				p.Start();
				p.BeginOutputReadLine();
				p.BeginErrorReadLine();
				p.WaitForExit();
				return p.ExitCode == 0;
			} catch (Exception e) {
				logger.Error(e);
			}
			return false;
		}
Exemple #52
0
        public async Task ConnectionHandshake(Stream stream, ILogger logger, string authorizationKey, CancellationToken cancellationToken)
        {
            await stream.WriteAsync(connectHeader, 0, connectHeader.Length, cancellationToken);
            logger.Debug("Sent ReQL header");

            if (String.IsNullOrEmpty(authorizationKey))
            {
                await stream.WriteAsync(new byte[] { 0, 0, 0, 0 }, 0, 4, cancellationToken);
            }
            else
            {
                var keyInBytes = Encoding.UTF8.GetBytes(authorizationKey);
                var authKeyLength = BitConverter.GetBytes(keyInBytes.Length);
                if (!BitConverter.IsLittleEndian)
                    Array.Reverse(authKeyLength, 0, authKeyLength.Length);
                await stream.WriteAsync(authKeyLength, 0, authKeyLength.Length);
                await stream.WriteAsync(keyInBytes, 0, keyInBytes.Length);
            }

            await stream.WriteAsync(ProtocolHeader, 0, ProtocolHeader.Length, cancellationToken);

            byte[] authReponseBuffer = new byte[1024];
            var authResponseLength = await stream.ReadUntilNullTerminator(logger, authReponseBuffer, cancellationToken);
            var authResponse = Encoding.ASCII.GetString(authReponseBuffer, 0, authResponseLength);
            if (authResponse != "SUCCESS")
                throw new RethinkDbRuntimeException("Unexpected authentication response; expected SUCCESS but got: " + authResponse);
        }
 public void DebugBinaryDump(ILogger logger, byte[] buffer, string format, params object[] args)
 {
     StringBuilder builder = new StringBuilder();
     StringBuilder hexBuilder = new StringBuilder();
     StringBuilder asciiBuilder = new StringBuilder();
     builder.AppendFormat(format, args);
     builder.AppendLine();
     for (int index = 0; index < buffer.Length; index++)
     {
         if (index > 0 && index % 16 == 0)
         {
             builder.Append(hexBuilder.ToString());
             builder.Append(asciiBuilder.ToString());
             builder.AppendLine();
             hexBuilder.Clear();
             asciiBuilder.Clear();
         }
         hexBuilder.AppendFormat("{0:X2} ", buffer[index]);
         asciiBuilder.Append(Encoding.ASCII.GetString(buffer, index, 1));
     }
     if (hexBuilder.Length > 0)
     {
         builder.Append(hexBuilder.ToString());
         builder.Append(asciiBuilder.ToString());
         builder.AppendLine();
     }
     logger.Debug(builder.ToString());
 }
Exemple #54
0
        /// <summary>
        /// Automatically resolve Ignite home directory.
        /// </summary>
        /// <param name="log">The log.</param>
        /// <returns>
        /// Ignite home directory.
        /// </returns>
        private static string Resolve(ILogger log)
        {
            var probeDirs = new[]
            {
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                Directory.GetCurrentDirectory()
            };

            if (log != null)
                log.Debug("Attempting to resolve IgniteHome in the assembly directory " +
                          "'{0}' and current directory '{1}'...", probeDirs[0], probeDirs[1]);


            foreach (var probeDir in probeDirs.Where(x => !string.IsNullOrEmpty(x)))
            {
                if (log != null)
                    log.Debug("Probing IgniteHome in '{0}'...", probeDir);

                var dir = new DirectoryInfo(probeDir);

                while (dir != null)
                {
                    if (IsIgniteHome(dir))
                        return dir.FullName;

                    dir = dir.Parent;
                }
            }

            return null;
        }
        public void SaveEmailInData(MailBox mailbox, MailMessageItem message, ILogger log)
        {
            if (string.IsNullOrEmpty(mailbox.EMailInFolder))
                return;

            try
            {
                foreach (var attachment in message.Attachments)
                {
                    using (var file = AttachmentManager.GetAttachmentStream(attachment))
                    {
                        log.Debug("SaveEmailInData->ApiHelper.UploadToDocuments(fileName: '{0}', folderId: {1})",
                                  file.FileName, mailbox.EMailInFolder);

                        UploadToDocuments(file, attachment.contentType, mailbox, log);
                    }

                }

            }
            catch (Exception e)
            {
                _log.Error("SaveEmailInData(tenant={0}, userId='{1}', messageId={2}) Exception:\r\n{3}\r\n",
                           mailbox.TenantId, mailbox.UserId, message.Id, e.ToString());
            }
        }
Exemple #56
0
        private UnityContainer RegisterUnityTypes(ILogger logger)
        {
            var container = new UnityContainer();
            container.RegisterType<IRemoteFileFetcherGateway, RemoteFileFetcherGateway>();
            container.RegisterType<IIsraelHikingRepository, IsraelHikingRepository>();
            container.RegisterType<IElevationDataStorage, ElevationDataStorage>(new ContainerControlledLifetimeManager());
            container.RegisterType<IGpsBabelGateway, GpsBabelGateway>();
            container.RegisterType<IRoutingGateway, RoutingGateway>();
            container.RegisterType<ICoordinatesConverter, CoordinatesConverter>();
            container.RegisterType<ILogger, Logger>();

            logger.Debug("Initializing Elevation data.");
            container.Resolve<IElevationDataStorage>().Initialize().ContinueWith((task) => logger.Debug("Finished loading elevation data from files."));

            return container;
        }
 public DefaultTypeConvertibleService(IEnumerable<ITypeConvertibleProvider> providers, ILogger<DefaultTypeConvertibleService> logger)
 {
     _logger = logger;
     providers = providers.ToArray();
     if (_logger.IsEnabled(LogLevel.Debug))
         _logger.Debug($"发现了以下类型转换提供程序:{string.Join(",", providers.Select(p => p.ToString()))}。");
     _converters = providers.SelectMany(p => p.GetConverters()).ToArray();
 }
 public static Task Close(this ISocketListener socketListener, IResponse response, ILogger logger)
 {
     return socketListener.Send(response.ToBytes(), () =>
     {
         logger.Debug("Disconnected client from {0}:{1}", socketListener.RemoteIpAddress, socketListener.RemotePort);
         socketListener.Dispose();
     }, ex => logger.Error("Error sending response: {0}", ex));
 }
Exemple #59
0
        public Versioner(IDbConnectionProvider connectionProvider, ILogger<Version> logger)
        {
            _conn = connectionProvider;
            _logger = logger;

            _logger.Debug("Create mapper and table instances");
            _conn.Perform(conn => conn.CreateTableIfNotExists<DatabaseVersion>());
        }
        public EfMigrator(string assemblyPath, string qualifiedDbConfigName, string appConfigPath, string connectionString, string connectionProvider,
                          ILogger logger)
        {
            _logger = logger;

            appConfigPath = Path.GetFullPath(appConfigPath);
            if (!File.Exists(appConfigPath))
            {
                throw new EfMigrationException($"The {nameof(appConfigPath)} '{appConfigPath}' must exist.");
            }

            var domainSetup = AppDomain.CurrentDomain.SetupInformation;
            domainSetup.ConfigurationFile = appConfigPath;
            _logger.Debug($"Prepared AppDomain setup using {appConfigPath} as the appconfig.");

            var domainName = $"EfMigrator:{Guid.NewGuid()}";
            _domain = AppDomain.CreateDomain(domainName, null, domainSetup);
            _logger.Debug($"Created new AppDomain named {domainName}.");

            var type = typeof(EfMigratorBackend);

            var fullPath = Assembly.GetAssembly(typeof(EfMigratorBackend)).Location;
            //var domain = AppDomain.CurrentDomain.GetAssemblies()
            //                      .Where(x => !x.IsDynamic)
            //                      .Where(x => !x.GlobalAssemblyCache)
            //                      .Select(x => Path.GetDirectoryName(x.Location))
            //                      .Distinct();

            //var domains = string.Join(", ", domain);
            //logger.Debug($"Loading assemblies into appDomain: {domains}.");

            Debug.Assert(fullPath != null, "fullPath != null");

            var migrator = (EfMigratorBackend) _domain.CreateInstanceFromAndUnwrap(fullPath, type.FullName);
            _logger.Debug("Created new instance.");
            migrator.Initialize(assemblyPath, qualifiedDbConfigName, connectionString, connectionProvider);

            _logger.Debug($"Initialized new {nameof(EfMigratorBackend)} within {domainName}.");

            CurrentMigration = migrator.GetCurrentMigration() ?? InitialDatabase;
            var currentMigrationStr = CurrentMigration == InitialDatabase ? "$InitialDatabase" : CurrentMigration;
            _logger.Information($"Current Migration is {currentMigrationStr}.");

            _migratorBackend = migrator;
        }