Esempio n. 1
0
        public async Task <MimeMessage> RunAsync(MimeMessage message, ISessionContext context, IMessageTransaction transaction, CancellationToken cancellationToken)
        {
            _logger?.Log(LogLevel.Information, "Injecting headers into message");

            try
            {
                //Add headers to the top of the message
                var bodyTextParts = message.BodyParts.OfType <TextPart>().ToList();
                var htmlBody      = bodyTextParts.LastOrDefault(btp => btp.IsHtml);
                var textBody      = bodyTextParts.LastOrDefault(btp => !btp.IsHtml);

                if (htmlBody != null)
                {
                    var bodyTagLocation = htmlBody.Text.IndexOf("<body>", StringComparison.OrdinalIgnoreCase);
                    var insertLocation  = bodyTagLocation == -1 ? 0 : bodyTagLocation + 6;
                    htmlBody.Text = htmlBody.Text.Insert(insertLocation, $"\n{HeaderFormatter.GetHtmlHeaders(message)}");
                }

                if (textBody != null)
                {
                    textBody.Text = $"{HeaderFormatter.GetPlainTextHeaders(message)}\n{textBody.Text}";
                }
            }
            catch (Exception exception)
            {
                _logger?.Log(LogLevel.Error, exception, "Error injecting headers into message");
                //Don't throw, continue routing message
            }

            return(await Task.FromResult(message).ConfigureAwait(false));
        }
Esempio n. 2
0
        public async Task <MimeMessage> RunAsync(MimeMessage message, ISessionContext context, IMessageTransaction transaction, CancellationToken cancellationToken)
        {
            _logger?.Log(LogLevel.Information, "Sending message");

            try
            {
                using (var smtpClient = await _create(cancellationToken))
                {
                    await _connect(smtpClient, cancellationToken);

                    if (_authenticate != null)
                    {
                        await _authenticate(smtpClient, cancellationToken);
                    }

                    await smtpClient.SendAsync(message, cancellationToken).ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                _logger?.Log(LogLevel.Error, exception, "Unable to send message");
                throw;
            }

            return(message);
        }
Esempio n. 3
0
        public async Task <MimeMessage> RunAsync(MimeMessage message, ISessionContext context, IMessageTransaction transaction, CancellationToken cancellationToken)
        {
            _logger?.Log(LogLevel.Information, "Rerouting message");

            try
            {
                var toKeep  = message.To.Mailboxes.Where(m => _keepAddressPredicates != null && _keepAddressPredicates.Any(p => p(m.ToString()))).ToList();
                var ccKeep  = message.Cc.Mailboxes.Where(m => _keepAddressPredicates != null && _keepAddressPredicates.Any(p => p(m.ToString()))).ToList();
                var bccKeep = message.Bcc.Mailboxes.Where(m => _keepAddressPredicates != null && _keepAddressPredicates.Any(p => p(m.ToString()))).ToList();

                message.To.Clear();
                message.Cc.Clear();
                message.Bcc.Clear();

                message.To.AddRange(toKeep);
                message.Cc.AddRange(ccKeep);
                message.Bcc.AddRange(bccKeep);

                message.To.AddRange(_rerouteToInternetAddresses.Select(a => new MailboxAddress(a)));
            }
            catch (Exception exception)
            {
                _logger?.Log(LogLevel.Error, exception, "Unable to reroute message");
                throw; //If error, abort so external customers don't get messages
            }

            return(await Task.FromResult(message).ConfigureAwait(false));
        }
Esempio n. 4
0
        public async Task <MimeMessage> RunAsync(MimeMessage message, ISessionContext context, IMessageTransaction transaction, CancellationToken cancellationToken)
        {
            _logger?.Log(LogLevel.Information, $"Adding BCC to {string.Join(", ", _bccEmails)}");

            try
            {
                message.Bcc.AddRange(_bccEmails.Select(bcc => new MailboxAddress(bcc)));
            }
            catch (Exception exception)
            {
                _logger?.Log(LogLevel.Error, exception, $"Error adding BCC to {string.Join(", ", _bccEmails)}");
                //Don't throw, continue routing message
            }

            return(await Task.FromResult(message).ConfigureAwait(false));
        }
        public async Task <MimeMessage> RunAsync(MimeMessage message, ISessionContext context, IMessageTransaction transaction, CancellationToken cancellationToken)
        {
            _logger?.Log(LogLevel.Information, "Adding headers as an attachment");

            try
            {
                var stream       = new MemoryStream();
                var streamWriter = new StreamWriter(stream);
                streamWriter.Write(HeaderFormatter.GetPlainTextHeaders(message));
                streamWriter.Flush();
                stream.Position = 0;

                var attachment = new MimePart("text", "plain")
                {
                    Content                 = new MimeContent(stream),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName                = "OriginalHeaders.txt"
                };

                //Add the attachment to the existing parent-level multipart if it exists.
                //Otherwise create a parent multipart and put the message body and attachment in it.
                if (message.Body is Multipart multipart)
                {
                    multipart.Add(attachment);
                }
                else
                {
                    message.Body = new Multipart("mixed")
                    {
                        message.Body, attachment
                    };
                }
            }
            catch (Exception exception)
            {
                _logger?.Log(LogLevel.Error, exception, "Error adding headers as an attachment");
                //Don't throw, continue routing message
            }

            return(await Task.FromResult(message).ConfigureAwait(false));
        }
 /// <summary>
 /// This method is called when the <see cref="T:Microsoft.Extensions.Hosting.IHostedService" /> starts. The implementation should return a task that represents
 /// the lifetime of the long running operation(s) being performed.
 /// </summary>
 /// <param name="stoppingToken">Triggered when <see cref="M:Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken)" /> is called.</param>
 /// <returns>
 /// A <see cref="T:System.Threading.Tasks.Task" /> that represents the long running operations.
 /// </returns>
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     // create subscriptions to the channels
     await Task.Run(() =>
     {
         _subscriptions.ForEach(s =>
         {
             s.Subscribe(_natsUrl);
             s.Start().GetAwaiter().GetResult();
         });
         _logger?.Log(LogLevel.Information, "All subscriptions started.");
     });
 }
        /// <summary>
        /// Initializes a new base instance of the <see cref="NatsSubscriptionBackgroundService" /> class.
        /// </summary>
        /// <param name="natsUrl">The nats URL.</param>
        /// <param name="group">The queue group.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="registerMethods">The registrarion action.</param>
        protected JsonRpcSubscriptionBackgroundService(string natsUrl, string group,
                                                       ILoggerProvider logger, Action <JsonRpcServiceProxyWrapper> registerMethods)
        {
            _logger  = logger.CreateLogger(MethodBase.GetCurrentMethod().DeclaringType.FullName);
            _natsUrl = natsUrl;

            _wrapper = new JsonRpcServiceProxyWrapper();
            registerMethods(_wrapper);

            foreach (string channel in _wrapper.Methods)
            {
                _logger?.Log(LogLevel.Information, $"Create subscription {channel}");
                _subscriptions.Add(new JsonRpcSubscription(channel, group, _wrapper, _logger));
            }
        }
Esempio n. 8
0
 public void Log(NuGet.Common.LogLevel level, string data)
 {
     logger.Log(ConvertLevel(level), $"NuGet [{fileName}]: {data}");
 }
Esempio n. 9
0
 public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception?exception,
                          Func <TState, Exception?, string>?formatter)
 {
     Logged?.Invoke(logLevel, eventId, state, exception, formatter != null ? (o, e) => formatter((TState)o, e) : null);
     _baseLogger.Log(logLevel, eventId, state, exception, formatter);
 }
Esempio n. 10
0
 public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
 {
     adaptee.Log(logLevel, eventId, state, exception, formatter);
 }
 public void Log <TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception exception,
                          Func <TState, Exception, string> formatter)
 {
     _logger.Log(logLevel, eventId, new MyLogEvent <TState>(state, formatter).AddProp("ActivityId", 42), exception, MyLogEvent <TState> .Formatter);
 }
Esempio n. 12
0
 void Microsoft.Extensions.Logging.ILogger.Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) =>
 logger.Log <TState>(logLevel, eventId, state, exception, formatter);
Esempio n. 13
0
 public void Log(string details) => microsoftLogger.Log(LogLevel.Information, details);
Esempio n. 14
0
 public bool WriteCore(TraceEventType eventType, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
 {
     _logger.Log(MapToLogLevel(eventType), eventId, state, exception, formatter);
     return(true);
 }
Esempio n. 15
0
 public void Log(DnsClient.Internal.LogLevel logLevel, int eventId, Exception exception, string message, params object[] args)
 {
     _logger.Log((Microsoft.Extensions.Logging.LogLevel)logLevel, eventId, exception, message, args);
 }
 /// <inheritdoc/>
 public void Write(LogLevel logLevel, string message, params object[] args)
 => _logger.Log(TranslateLogLevel(logLevel), message, args);
Esempio n. 17
0
 public void Log(LogMessageReceivedEventArgs logEvent)
 {
     _baseLogger.Log(TranslateLogLevel(logEvent.MessageType), logEvent.Message);
 }
 public void Log(NHibernateLogLevel logLevel, NHibernateLogValues state, Exception exception)
 {
     _msLogger.Log(MapLevels[logLevel], 0, new FormattedLogValues(state.Format, state.Args), exception, MessageFormatter);
 }
Esempio n. 19
0
 public void WriteLine(string line)
 {
     _extLogger.Log(LogLevel.Trace, $"[HEXDUMP] {line}");
 }
Esempio n. 20
0
        protected override void WriteInternal(Acb.Core.Logging.LogLevel level, object message, Exception exception)
        {
            var msg = message.GetType().IsSimpleType() ? message.ToString() : JsonConvert.SerializeObject(message);

            _logger.Log(Convert(level), new EventId(0), exception, msg);
        }
 public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) =>
 _logger.Log <TState>(logLevel, eventId, state, exception, formatter);
Esempio n. 22
0
 public void Write(EventType eventType, Func <string> logMessage)
 {
     _logger.Log(MapEventTypeToLogLevel(eventType), 0, logMessage, null, (state, exception) => state());
 }
Esempio n. 23
0
        public async Task <MimeMessage> RunAsync(MimeMessage message, ISessionContext context, IMessageTransaction transaction,
                                                 CancellationToken cancellationToken)
        {
            _logger?.Log(LogLevel.Information, "Rerouting message");

            try
            {
                var routes = _rerouteRules.Where(r => r.Rule(message, context, transaction)).ToArray();

                _logger?.Log(LogLevel.Information, $"Found {routes.Length} matching routes: {string.Join(", ", routes.Select(r => r.Name))}");

                ICollection <string> toEmails = routes.SelectMany(r => r.ToEmails)
                                                .Distinct(new EmailEqualityComparer())
                                                .ToArray();

                _logger?.Log(LogLevel.Information, $"Rerouting email to {string.Join(", ", toEmails)}");

                if (!toEmails.Any())
                {
                    if (_defaultReroute == null)
                    {
                        throw new Exception("No route found and no default route specified");
                    }

                    _logger?.Log(LogLevel.Information, "No route found. Using default route.");
                    toEmails = _defaultReroute;
                }

                var toKeep = message.To.Mailboxes.Where(m => _keepAddressPredicates != null && _keepAddressPredicates.Any(p => p(m.ToString()))).ToList();

                if (toKeep.Any())
                {
                    _logger?.Log(LogLevel.Information, $"Keeping To addresses {string.Join(", ", toKeep)}");
                }

                var ccKeep = message.Cc.Mailboxes.Where(m => _keepAddressPredicates != null && _keepAddressPredicates.Any(p => p(m.ToString()))).ToList();

                if (ccKeep.Any())
                {
                    _logger?.Log(LogLevel.Information, $"Keeping CC addresses {string.Join(", ", ccKeep)}");
                }

                var bccKeep = message.Bcc.Mailboxes.Where(m => _keepAddressPredicates != null && _keepAddressPredicates.Any(p => p(m.ToString()))).ToList();

                if (ccKeep.Any())
                {
                    _logger?.Log(LogLevel.Information, $"Keeping BCC addresses {string.Join(", ", bccKeep)}");
                }

                message.To.Clear();
                message.Cc.Clear();
                message.Bcc.Clear();

                message.To.AddRange(toKeep);
                message.Cc.AddRange(ccKeep);
                message.Bcc.AddRange(bccKeep);

                message.To.AddRange(toEmails.Select(r => new MailboxAddress(r)));
            }
            catch (Exception exception)
            {
                _logger?.Log(LogLevel.Error, exception, "Unable to reroute message");
                throw; //If error, abort so external customers don't get messages
            }

            return(await Task.FromResult(message).ConfigureAwait(false));
        }
Esempio n. 24
0
        static async Task Main(string[] args)
        {
            var serilogger = new LoggerConfiguration()
                             .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
                             .CreateLogger();
            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder
                // .AddFilter("Microsoft", LogLevel.Warning)
                // .AddFilter("System", LogLevel.Warning)
                // .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
                .AddSerilog(serilogger)
                .AddConsole();
            });

            _logger = loggerFactory.CreateLogger <Program>();

            // Register extensions to Json.NET Serialization
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Converters = new List <JsonConverter>
                {
                    new MathJsonConverter(),
                    Converter.DateTimeConverter,
                    Converter.BinaryConverter,
                    Converter.GroupingConverter,
                    Converter.PocoExprConverter
                }
            };
            Converter.Serializer.Converters.Add(new MathJsonConverter());

            // Register extensions to MessagePack Serialization
            var resolver = CompositeResolver.Create(
                MathResolver.Instance,
                NativeGuidResolver.Instance,
                StandardResolver.Instance
                );
            var options = MessagePackSerializerOptions.Standard.WithResolver(resolver);

            MessagePackSerializer.DefaultOptions = options;

            var connection = R.Connection().Hostname("asgard.gamecult.games")
                             .Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();

            var cache = new DatabaseCache();

            // When entries are changed locally, push the changes to RethinkDB
            cache.OnDataUpdateLocal += async entry =>
            {
                var table  = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var result = await R.Db("Aetheria").Table(table).Update(entry).RunAsync(connection);

                _logger.Log(LogLevel.Information, $"Uploaded entry to RethinkDB: {entry.ID} result: {result}");
            };

            cache.OnDataInsertLocal += async entry =>
            {
                var table    = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var inserted = false;
                for (int i = 0; i < 5 && !inserted; i++)
                {
                    try
                    {
                        var result = await R.Db("Aetheria").Table(table).Insert(entry).RunAsync(connection);

                        _logger.Log(LogLevel.Information, $"Inserted entry to RethinkDB: {entry.ID} result: {result}");
                        inserted = true;
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e, e.Message);
                    }
                }
                if (!inserted)
                {
                    _logger.LogError("Failed to insert after 5 attempts!");
                }
            };

            cache.OnDataDeleteLocal += async entry =>
            {
                var table  = entry.GetType().GetCustomAttribute <RethinkTableAttribute>()?.TableName ?? "Other";
                var result = await R.Db("Aetheria").Table(table).Get(entry.ID).Delete().RunAsync(connection);

                _logger.Log(LogLevel.Information, $"Deleted entry from RethinkDB: {entry.ID} result: {result}");
            };

            // Get data from RethinkDB
            await GetTable("Items", connection, cache);
            await GetTable("Galaxy", connection, cache);
            await GetTable("Users", connection, cache);

            // Subscribe to changes from RethinkDB
            SubscribeTable("Items", connection, cache);
            SubscribeTable("Galaxy", connection, cache);
            SubscribeTable("Users", connection, cache);

            var server = new MasterServer(cache)
            {
                Logger = _logger
            };

            server.Start();

            var context = new GameContext(cache, s => _logger.Log(LogLevel.Information, s));

            context.MapLayers = cache.GetAll <GalaxyMapLayerData>().ToDictionary(m => m.Name);

            server.AddMessageListener <GalaxyRequestMessage>(galaxyRequest => galaxyRequest.Peer.Send(
                                                                 new GalaxyResponseMessage
            {
                Zones = cache.GetAll <ZoneData>().Select(zd =>
                                                         new GalaxyResponseZone
                {
                    Name     = zd.Name,
                    Position = zd.Position,
                    ZoneID   = zd.ID,
                    Links    = zd.Wormholes?.ToArray() ?? Array.Empty <Guid>()
                }).ToArray(),
                GlobalData  = context.GlobalData,
                StarDensity = context.MapLayers["StarDensity"]
            }));

            server.AddMessageListener <BlueprintsRequestMessage>(blueprintRequest => blueprintRequest.Peer.Send(
                                                                     new BlueprintsResponseMessage
            {
                Blueprints = cache.GetAll <BlueprintData>().ToArray()
            }));

            server.AddMessageListener <ZoneRequestMessage>(zoneRequest =>
            {
                var zone = cache.Get <ZoneData>(zoneRequest.ZoneID);

                // Zone has not been populated, generate the contents now!
                if (!zone.Visited)
                {
                    zone.Visited = true;
                    OrbitData[] orbits;
                    PlanetData[] planets;
                    ZoneGenerator.GenerateZone(
                        global: context.GlobalData,
                        zone: zone,
                        mapLayers: context.MapLayers.Values,
                        resources: cache.GetAll <SimpleCommodityData>().Where(i => i.ResourceDensity.Any()),
                        orbitData: out orbits,
                        planetsData: out planets);
                    cache.AddAll(orbits);
                    cache.AddAll(planets);
                    cache.Add(zone);
                }
                zoneRequest.Peer.Send(
                    new ZoneResponseMessage
                {
                    Zone     = zone,
                    Contents = zone.Orbits.Select(id => cache.Get(id))
                               .Concat(zone.Planets.Select(id => cache.Get(id)))
                               .Concat(zone.Stations.Select(id => cache.Get(id))).ToArray()
                });
            });

            Observable.Timer(DateTimeOffset.Now, TimeSpan.FromSeconds(60)).SubscribeOn(NewThreadScheduler.Default).Subscribe(_ =>
            {
                _logger.Log(LogLevel.Information, R.Now().Run <DateTime>(connection).ToString() as string);
            });

            while (true)
            {
                Thread.Sleep(100);
            }
        }