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 #2
0
        static ProductsController()
        {
            Logger = Log.ForContext<ProductsController>();
            Products = new Fixture().CreateMany<Product>(500).OrderBy(p => p.Id).ToList();

            Logger.Information("created the products {ProductCount}", Products.Count());
        }
        internal static string FixAreaPathInTargetQuery(string sourceWIQLQueryBit, string sourceProject, string targetProject, string[] nodeBasePaths, ILogger?contextLog)
        {
            string targetWIQLQueryBit = sourceWIQLQueryBit;

            if (nodeBasePaths != null && nodeBasePaths.Any() && targetWIQLQueryBit.Contains("[System.AreaPath]"))
            {
                if (sourceProject != targetProject)
                {
                    //Switch out source Area Path with destination
                    foreach (var nodeBasePath in nodeBasePaths)
                    {
                        if (sourceWIQLQueryBit.Contains(nodeBasePath))
                        {
                            contextLog?.Information("[NodeBasePaths] has been set and QueryBit contains [System.AreaPath].  Since {nodeBasePath} was found in the query, updating the projectName from {source} to {target}", nodeBasePath, sourceProject, targetProject);
                            StringBuilder myStringBuilder    = new StringBuilder(sourceWIQLQueryBit);
                            int           locationOfAreaPath = sourceWIQLQueryBit.IndexOf("[System.AreaPath]");
                            int           querySegmentSize   = (sourceWIQLQueryBit.IndexOf(nodeBasePath) + nodeBasePath.Length) - locationOfAreaPath;
                            myStringBuilder.Replace(sourceProject, targetProject, locationOfAreaPath, querySegmentSize);
                            targetWIQLQueryBit = myStringBuilder.ToString();
                        }
                    }
                }
            }

            return(targetWIQLQueryBit);
        }
Exemple #4
0
        /// <summary> Dispose logger if it is not null </summary>
        public static void TryDispose(this ILogger?logger)
        {
            logger?.Information("Finish");
            var dsp = logger as IDisposable;

            dsp?.Dispose();
        }
        private static void PatchGame(ILogger log)
        {
            log.Information("Creating {0}", Paths.PatchedAssemblyFolder);
            Directory.CreateDirectory(Paths.PatchedAssemblyFolder);

            log.Information("Loading original assembly {0}", Paths.OriginalAssembly);
            var patcher = new AssemblyPatcher(Paths.OriginalAssembly, log);
            patcher.EmbedHistory = false;
            patcher.UseBackup = false;

            log.Information("Patching");
            patcher.PatchAssembly(typeof(W2PWMod.ModType).Assembly.Location);

            log.Information("Saving patched file");
            patcher.WriteTo(Paths.PatchedAssembly);
        }
 internal LoggingScope(ILogger logger, string messageTemplate, params object[] propertyValues)
 {
     _Logger = logger;
     _MessageTemplate = messageTemplate;
     _PropertyValues = propertyValues;
     _StopWatch = new Stopwatch();
     _StopWatch.Start();
     _Logger.Information($">> Started: \"{_MessageTemplate}\"", _PropertyValues);
 }
Exemple #7
0
        public void Setup()
        {
            _exception = new Exception("An Error");
            _log = new LoggerConfiguration()
                .WriteTo.Sink(new NullSink())
                .CreateLogger();

            // Ensure template is cached
            _log.Information(_exception, "Hello, {Name}!", "World");
        }
        public NamedPipePoshGitServer(IRepositoryCache repoCache, ILifetimeScope lifetimeScope, ILogger log)
        {
            _log = log;
            _cancellationTokenSource = new CancellationTokenSource();
            _repoCache = repoCache;
            _serializer = JsonSerializer.Create();
            _lifetimeScope = lifetimeScope;

            log.Information("Server started");
        }
        public static void Before()
        {
            logger = new LoggerConfiguration()
                    .ReadFrom.AppSettings()
                    .Enrich.WithMachineName()
                    .Enrich.FromLogContext()
                    .CreateLogger();

            Log.Logger = logger;
            logger.Information("Logger has been initialized!");
        }
Exemple #10
0
        /// <inheritdoc />
        public string Execute()
        {
            var outputRedirect   = new StringBuilder();
            var lastOutputString = string.Empty;

            _console.RedirectOutput(outputRedirect);
            foreach (var scriptLine in _scriptLines)
            {
                if (!scriptLine.IsScript)
                {
                    _logger?.Information($"Line {scriptLine.LineNumber} [{scriptLine.RawLine}] : Line skipped");
                    continue;
                }

                _registry.RootCommand.Invoke(scriptLine.CommandArguments.ToArray());
                lastOutputString = outputRedirect.ToString().Trim();
                outputRedirect.Clear();
                _logger?.Information($"Line {scriptLine.LineNumber} [{scriptLine.RawLine}] : {lastOutputString}");
            }

            return(lastOutputString);
        }
        public NinjectCore(IKernel kernel, ILogger logger, ICoreSettings settings)
        {
            _kernel = kernel;
            _logger = logger;
            _settings = settings;

            _logger.Information("Initializing Core.");

            InitializeKernel();
            InitializeExtensions();

            _logger.Verbose("Core initilized.");
        }
        public WindowMessageHook(
            IEnumerable<IWindowMessageInterceptor> windowMessageInterceptors,
            ILogger logger,
            IConsumerThreadLoop consumerLoop)
        {
            this.windowMessageInterceptors = windowMessageInterceptors;
            this.logger = logger;
            this.consumerLoop = consumerLoop;

            pendingMessages = new Queue<WindowMessageReceivedArgument>();
            cancellationTokenSource = new CancellationTokenSource();

            logger.Information($"Window message hook was constructed using {windowMessageInterceptors.Count()} interceptors.");
        }
 public OneTimePhoneEmulatorDialogMonitor(ILogger logger)
 {
     _logger = logger;
     _windowsPhoneEmulatorDialogMonitor = new WindowsPhoneEmulatorDialogMonitor(logger);
     _timer = new Timer(1000);
     _timer.Elapsed += (sender, e) => _windowsPhoneEmulatorDialogMonitor.ExecuteDialogSlapDown(msg =>
     {
         _logger.Information(msg);
         _timer.Stop();
         _timer = null;
         _windowsPhoneEmulatorDialogMonitor = null;
     });
     _timer.Start();
 }
        public WindowMessageHook(
            IReadOnlyCollection<IWindowMessageInterceptor> windowMessageInterceptors,
            ILogger logger,
            IConsumerThreadLoop consumerLoop,
            IMainWindowHandleContainer mainWindowHandleContainer)
        {
            this.windowMessageInterceptors = windowMessageInterceptors;
            this.logger = logger;
            this.consumerLoop = consumerLoop;
            this.mainWindowHandleContainer = mainWindowHandleContainer;

            pendingMessages = new Queue<WindowMessageReceivedArgument>();
            cancellationTokenSource = new CancellationTokenSource();

            logger.Information(
                $"Window message hook was constructed using {windowMessageInterceptors.Count} interceptors.");
        }
        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;
        }
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            _container = new UnityContainer();
            AccidentalFish.ApplicationSupport.Core.Bootstrapper.RegisterDependencies(_container);
            AccidentalFish.ApplicationSupport.Azure.Bootstrapper.RegisterDependencies(_container);
            Domain.Bootstrapper.RegisterDependencies(_container);
            Domain.Bootstrapper.RegisterInfrastructure(_container);
            AccidentalFish.ApplicationSupport.Processes.Bootstrapper.RegisterDependencies(_container);

            ILoggerFactory loggerFactory = _container.Resolve<ILoggerFactory>();
            _logger = loggerFactory.CreateLongLivedLogger(new LoggerSource("com.accidentalfish.azurelinkboard.background.worker-role"));
            _logger.Information("Starting background worker role instance");

            return base.OnStart();
        }
        public MessagePathConfigurator(IPathTemplatesProvider pathTemplateProvider, ILogger logger)
        {
            if (pathTemplateProvider == null) throw new ArgumentNullException("pathTemplateProvider");
            if (logger == null) throw new ArgumentNullException("logger");

            _logger = logger;
            _pathTemplateProvider = pathTemplateProvider;
            _pathTemplateProvider.PathTemplates.CollectionChanged += PathTemplatesCollectionChanged;

            DefaultSavePath = AppDomain.CurrentDomain.BaseDirectory;
            RenderLoadPaths();

            if (LoadPaths.Any()) DefaultSavePath = LoadPaths.First();

            _logger.Information(
                "Default Message Save Path is Set to {DefaultSavePath}",
                DefaultSavePath);
        }
        internal static string FixAreaPathAndIterationPathForTargetQuery(string sourceWIQLQueryBit, string sourceProject, string targetProject, ILogger?contextLog)
        {
            string targetWIQLQueryBit = sourceWIQLQueryBit;

            if (string.IsNullOrWhiteSpace(targetWIQLQueryBit) ||
                string.IsNullOrWhiteSpace(sourceProject) ||
                string.IsNullOrWhiteSpace(targetProject) ||
                sourceProject == targetProject)
            {
                return(targetWIQLQueryBit);
            }

            var matches = Regex.Matches(targetWIQLQueryBit, RegexPatterForAreaAndIterationPathsFix);

            foreach (Match match in matches)
            {
                if (!match.Success)
                {
                    continue;
                }

                var value = match.Groups["value"].Value;
                if (string.IsNullOrWhiteSpace(value) || !value.StartsWith(sourceProject))
                {
                    continue;
                }

                var slashIndex = value.IndexOf('\\');
                if (slashIndex > 0)
                {
                    var subValue = value.Substring(0, slashIndex);
                    if (subValue == sourceProject)
                    {
                        var targetValue      = targetProject + value.Substring(slashIndex);
                        var targetMatchValue = match.Value.Replace(value, targetValue);
                        targetWIQLQueryBit = targetWIQLQueryBit.Replace(match.Value, targetMatchValue);
                    }
                }
            }

            contextLog?.Information("[FilterWorkItemsThatAlreadyExistInTarget] is enabled. Source project {sourceProject} is replaced with target project {targetProject} on the WIQLQueryBit which resulted into this target WIQLQueryBit \"{targetWIQLQueryBit}\" .", sourceProject, targetProject, targetWIQLQueryBit);

            return(targetWIQLQueryBit);
        }
        public static T DeserializeObject <T>(ILogger?logger, string value)
        {
            try
            {
                JsonSerializerSettings settings = new JsonSerializerSettings
                {
                    MissingMemberHandling = MissingMemberHandling.Error,
                };
#pragma warning disable CS8603 // Possible null reference return.
                return(JsonConvert.DeserializeObject <T>(value, settings));

#pragma warning restore CS8603 // Possible null reference return.
            }
            catch (JsonSerializationException e)
            {
                if (logger == null)
                {
                    Debug.WriteLine(e.ToString());
                }
                logger?.Information("## MODEL UPDATE NEEDED ## Fields found we don't know yet in class '{ClassName}'\r\nError message: {ErrorMessage}; value is \r\n{@Value}", typeof(T), e.Message, value);
                return(JsonConvert.DeserializeObject <T>(value));
            }
        }
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            var builder = new ContainerBuilder();

            builder.RegisterType<FixItQueueManager>().As<IFixItQueueManager>();
            builder.RegisterType<FixItTaskRepository>().As<IFixItTaskRepository>().SingleInstance();
            builder.RegisterType<Logger>().As<ILogger>().SingleInstance();

            container = builder.Build();

            logger = container.Resolve<ILogger>();

            bool result = base.OnStart();

            logger.Information("MyFixItWorkerRole has been started");

            return result;
        }
Exemple #21
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer message, List <object> output)
        {
            var continueToDecode = true;
            var temp             = new List <IPacket>();
            var encryptedString  = "";
            var mapper           = SessionFactory.Instance.Sessions[context.Channel.Id.AsLongText()];

            _region    = mapper.RegionType;
            _sessionId = mapper.SessionId;
            var str = ((Span <byte>)message.Array).Slice(message.ArrayOffset, message.ReadableBytes).ToArray();

            if (_sessionId == 0)
            {
                var pack =
                    _deserializer.Deserialize(DecryptCustomParameter(str, out var endofPacket)) as UnresolvedPacket;

                if (!int.TryParse(pack.Header, out _sessionId))
                {
                    _logger.Error(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.ERROR_SESSIONID));
                    return;
                }

                SessionFactory.Instance.Sessions[context.Channel.Id.AsLongText()].SessionId = _sessionId;
                _logger.Information(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.CLIENT_CONNECTED),
                                    mapper.SessionId);
                temp.Add(pack);
                if (endofPacket.Length == 0)
                {
                    continueToDecode = false;
                }

                str = endofPacket;
            }

            if (continueToDecode)
            {
                var sessionKey    = _sessionId & 0xFF;
                var sessionNumber = unchecked ((byte)(_sessionId >> 6));
                sessionNumber &= 0xFF;
                sessionNumber &= unchecked ((byte)0x80000003);

                switch (sessionNumber)
                {
                case 0:
                    encryptedString =
                        (from character in str
                         let firstbyte = unchecked ((byte)(sessionKey + 0x40))
                                         select unchecked ((byte)(character - firstbyte))).Aggregate(encryptedString,
                                                                                                     (current, highbyte) => current + (char)highbyte);
                    break;

                case 1:
                    encryptedString =
                        (from character in str
                         let firstbyte = unchecked ((byte)(sessionKey + 0x40))
                                         select unchecked ((byte)(character + firstbyte))).Aggregate(encryptedString,
                                                                                                     (current, highbyte) => current + (char)highbyte);
                    break;

                case 2:
                    encryptedString =
                        (from character in str
                         let firstbyte = unchecked ((byte)(sessionKey + 0x40))
                                         select unchecked ((byte)((character - firstbyte) ^ 0xC3))).Aggregate(encryptedString,
                                                                                                              (current, highbyte) => current + (char)highbyte);
                    break;

                case 3:
                    encryptedString =
                        (from character in str
                         let firstbyte = unchecked ((byte)(sessionKey + 0x40))
                                         select unchecked ((byte)((character + firstbyte) ^ 0xC3))).Aggregate(encryptedString,
                                                                                                              (current, highbyte) => current + (char)highbyte);
                    break;

                default:
                    encryptedString += (char)0xF;
                    break;
                }

                temp.AddRange(encryptedString.Split((char)0xFF, StringSplitOptions.RemoveEmptyEntries).Select(p =>
                {
                    try
                    {
                        var packet = _deserializer.Deserialize(DecryptPrivate(p));
                        if (!packet.IsValid)
                        {
                            _logger.Error(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.CORRUPT_PACKET),
                                          packet);
                        }

                        return(packet);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.ERROR_DECODING),
                                      ex.Data["Packet"]);
                        return(new UnresolvedPacket
                        {
                            KeepAliveId = ushort.Parse(ex.Data["Packet"].ToString().Split(" ")[0]), Header = "0"
                        });
                    }
                }));
            }

            if (temp.Count > 0)
            {
                output.Add(temp);
            }
        }
Exemple #22
0
        /// <summary>
        /// Starts the primary thread where all the work is done.
        /// Outputs all of the hosts info so that if we're starting it up, the user can see if anything is wrong, allowing them time to make changes.
        /// </summary>
        public void Start()
        {
            Logger.Debug("Start()");
            RunThread = new Thread(new ThreadStart(StartLogging))
            {
                Name = $"{Host.HostName}-MainThread"
            };
            Logger.Information("Starting ping logging for host {0} ({1})", Host.HostName, Host.IP);
            Logger.Information("Using the following options:");
            Logger.Information("Threshold: {0}ms", Host.Threshold);
            Logger.Information("Timeout: {0}ms", Host.Timeout);
            Logger.Information("Interval: {0}ms", Host.Interval);
            Logger.Information("Packet Size: {0} bytes", Host.PacketSize);

            Logger.Debug("RunThread.Start()");
            RunThread.Start();
        }
 public async Task ProcessAsync(string[] arguments)
 {
     logger.Information("Running installation procedure.");
     await InstallAsync();
 }
        public async Task <HttpResponseMessage> Relay(string fullPathToOnPremiseEndpoint)
        {
            _logger?.Debug("Relaying request. method={RequestMethod}, path={RequestPath}", ControllerContext.Request.Method, fullPathToOnPremiseEndpoint);

            if (fullPathToOnPremiseEndpoint == null)
            {
                _logger?.Information("Path to on premise endpoint is not set");
                return(NotFound());
            }

            var pathInformation = _pathSplitter.Split(fullPathToOnPremiseEndpoint);
            var link            = _linkRepository.GetLink(pathInformation.UserName);

            if (!CanRequestBeHandled(fullPathToOnPremiseEndpoint, pathInformation, link))
            {
                _logger?.Information("Request cannot be handled");
                return(NotFound());
            }

            var request = await _onPremiseRequestBuilder.BuildFromHttpRequest(Request, _backendCommunication.OriginId, pathInformation.PathWithoutUserName).ConfigureAwait(false);

            var statusCode = HttpStatusCode.GatewayTimeout;
            IOnPremiseConnectorResponse response = null;

            try
            {
                request = _interceptorManager.HandleRequest(request, Request, User, out var message);
                if (message != null)
                {
                    _logger?.Verbose("Interceptor caused direct answering of request. request-id={RequestId}, status-code={ResponseStatusCode}", request.RequestId, message.StatusCode);

                    statusCode = message.StatusCode;

                    if (request.AlwaysSendToOnPremiseConnector)
                    {
                        _logger?.Verbose("Interceptor caused always sending of request. request-id={RequestId}", request.RequestId);
                        SendOnPremiseConnectorRequest(link.Id, request);
                    }

                    return(message);
                }

                var task = _backendCommunication.GetResponseAsync(request.RequestId);
                SendOnPremiseConnectorRequest(link.Id, request);

                _logger?.Verbose("Waiting for response. request-id={RequestId}, link-id={LinkId}", request.RequestId, link.Id);
                response = await task.ConfigureAwait(false);

                if (response != null)
                {
                    _logger?.Verbose("Response received. request-id={RequestId}, link-id={LinkId}", request.RequestId, link.Id);
                    statusCode = response.StatusCode;
                }
                else
                {
                    _logger?.Verbose("No response received because of on-premise timeout. request-id={RequestId}, link-id={LinkId}", request.RequestId, link.Id);
                }

                return(_interceptorManager.HandleResponse(request, Request, User, response) ?? _httpResponseMessageBuilder.BuildFromConnectorResponse(response, link, request.RequestId));
            }
            finally
            {
                FinishRequest(request, response, link.Id, fullPathToOnPremiseEndpoint, statusCode);
            }
        }
Exemple #25
0
        public async Task <ImportResult> ImportSystem(DataFileSystem data, PKSystem system, ulong accountId)
        {
            // TODO: make atomic, somehow - we'd need to obtain one IDbConnection and reuse it
            // which probably means refactoring SystemStore.Save and friends etc
            var result = new ImportResult {
                AddedNames    = new List <string>(),
                ModifiedNames = new List <string>(),
                Success       = true // Assume success unless indicated otherwise
            };
            var dataFileToMemberMapping = new Dictionary <string, PKMember>();
            var unmappedMembers         = new List <DataFileMember>();

            // If we don't already have a system to save to, create one
            if (system == null)
            {
                system = await _data.CreateSystem(data.Name);
            }
            result.System = system;

            // Apply system info
            system.Name = data.Name;
            if (data.Description != null)
            {
                system.Description = data.Description;
            }
            if (data.Tag != null)
            {
                system.Tag = data.Tag;
            }
            if (data.AvatarUrl != null)
            {
                system.AvatarUrl = data.AvatarUrl;
            }
            if (data.TimeZone != null)
            {
                system.UiTz = data.TimeZone ?? "UTC";
            }
            await _data.SaveSystem(system);

            // Make sure to link the sender account, too
            await _data.AddAccount(system, accountId);

            // Determine which members already exist and which ones need to be created
            var membersByHid  = new Dictionary <string, PKMember>();
            var membersByName = new Dictionary <string, PKMember>();

            await foreach (var member in _data.GetSystemMembers(system))
            {
                membersByHid[member.Hid]   = member;
                membersByName[member.Name] = member;
            }

            foreach (var d in data.Members)
            {
                PKMember match = null;
                if (membersByHid.TryGetValue(d.Id, out var matchByHid))
                {
                    match = matchByHid;                                                     // Try to look up the member with the given ID
                }
                else if (membersByName.TryGetValue(d.Name, out var matchByName))
                {
                    match = matchByName;                                                              // Try with the name instead
                }
                if (match != null)
                {
                    dataFileToMemberMapping.Add(d.Id, match); // Relate the data file ID to the PKMember for importing switches
                    result.ModifiedNames.Add(d.Name);
                }
                else
                {
                    unmappedMembers.Add(d); // Track members that weren't found so we can create them all
                    result.AddedNames.Add(d.Name);
                }
            }

            // If creating the unmatched members would put us over the member limit, abort before creating any members
            // new total: # in the system + (# in the file - # in the file that already exist)
            if (data.Members.Count - dataFileToMemberMapping.Count + membersByHid.Count > Limits.MaxMemberCount)
            {
                result.Success = false;
                result.Message = $"Import would exceed the maximum number of members ({Limits.MaxMemberCount}).";
                result.AddedNames.Clear();
                result.ModifiedNames.Clear();
                return(result);
            }

            // Create all unmapped members in one transaction
            // These consist of members from another PluralKit system or another framework (e.g. Tupperbox)
            var membersToCreate = new Dictionary <string, string>();

            unmappedMembers.ForEach(x => membersToCreate.Add(x.Id, x.Name));
            var newMembers = await _data.CreateMembersBulk(system, membersToCreate);

            foreach (var member in newMembers)
            {
                dataFileToMemberMapping.Add(member.Key, member.Value);
            }

            // Update members with data file properties
            // TODO: parallelize?
            foreach (var dataMember in data.Members)
            {
                dataFileToMemberMapping.TryGetValue(dataMember.Id, out PKMember member);
                if (member == null)
                {
                    continue;
                }

                // Apply member info
                member.Name = dataMember.Name;
                if (dataMember.DisplayName != null)
                {
                    member.DisplayName = dataMember.DisplayName;
                }
                if (dataMember.Description != null)
                {
                    member.Description = dataMember.Description;
                }
                if (dataMember.Color != null)
                {
                    member.Color = dataMember.Color.ToLower();
                }
                if (dataMember.AvatarUrl != null)
                {
                    member.AvatarUrl = dataMember.AvatarUrl;
                }
                if (dataMember.Prefix != null || dataMember.Suffix != null)
                {
                    member.ProxyTags = new List <ProxyTag> {
                        new ProxyTag(dataMember.Prefix, dataMember.Suffix)
                    };
                }
                else
                {
                    // Ignore proxy tags where both prefix and suffix are set to null (would be invalid anyway)
                    member.ProxyTags = (dataMember.ProxyTags ?? new ProxyTag[] { }).Where(tag => !tag.IsEmpty).ToList();
                }

                member.KeepProxy = dataMember.KeepProxy;

                if (dataMember.Birthday != null)
                {
                    var birthdayParse = DateTimeFormats.DateExportFormat.Parse(dataMember.Birthday);
                    member.Birthday = birthdayParse.Success ? (LocalDate?)birthdayParse.Value : null;
                }

                await _data.SaveMember(member);
            }

            // Re-map the switch members in the likely case IDs have changed
            var mappedSwitches = new List <ImportedSwitch>();

            foreach (var sw in data.Switches)
            {
                var timestamp = InstantPattern.ExtendedIso.Parse(sw.Timestamp).Value;
                var swMembers = new List <PKMember>();
                swMembers.AddRange(sw.Members.Select(x =>
                                                     dataFileToMemberMapping.FirstOrDefault(y => y.Key.Equals(x)).Value));
                mappedSwitches.Add(new ImportedSwitch
                {
                    Timestamp = timestamp,
                    Members   = swMembers
                });
            }
            // Import switches
            if (mappedSwitches.Any())
            {
                await _data.AddSwitchesBulk(system, mappedSwitches);
            }

            _logger.Information("Imported system {System}", system.Hid);
            return(result);
        }
Exemple #26
0
 public Startup(IConfiguration configuration)
 {
     logger.Information($"{nameof(Startup)}");
     Configuration = configuration;
 }
Exemple #27
0
        private void FactorioOutputHandler(object sender, DataReceivedEventArgs e)
        {
            _logger.Information(e.Data);

            if (e.Data.Contains("Starting RCON interface"))
            {
                _logger.Debug("Factorio says RCON interface is ready!");
                OnRconReady?.Invoke(this, e);
            }

            OnOutputData?.Invoke(this, e);
        }
        private static void Main(string[] args)
        {
            if (args.Length < 1 || args[0] != "--startProxy")
            {
                Console.WriteLine("Please don't start the voting proxy process manually as it's only supposed to be launched by the mod itself."
                                  + "\nPass --startProxy as an argument if you want to start the proxy yourself for debugging purposes.");

                Console.ReadKey();

                return;
            }

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.File("./chaosmod/chaosProxy.log", outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext:l}] {Message:lj}{NewLine}{Exception}")
                         .CreateLogger();
            logger = Log.Logger.ForContext <TwitchChatVotingProxy>();

            logger.Information("===============================");
            logger.Information("Starting chaos mod twitch proxy");
            logger.Information("===============================");


            // Read big config file WIP
            var config = new Config.Config("./chaosmod/twitch.ini");


            // Validate voting mode
            EVotingMode votingMode;

            if (config.VotingMode == null)
            {
                votingMode = EVotingMode.MAJORITY;
                logger.Warning($"voting mode is null, using default \"{VotingMode.Lookup(votingMode)}\"");
            }
            else
            {
                votingMode = (EVotingMode)config.VotingMode;
            }

            /*
             * // Create twitch config
             * TwitchVotingReceiverConfig twitchVotingReceiverConfig;
             * try
             * {
             *   twitchVotingReceiverConfig = new TwitchVotingReceiverConfig(config.TwitchChannelName, config.TwitchOAuth, config.TwitchUserName);
             * } catch (Exception e)
             * {
             *  logger.Fatal(e, "failed to create twitch voting receiver config");
             *  return;
             * }
             *
             */

            // Check if OBS overlay should be shown
            OverlayServer.OverlayServer overlayServer = null;
            if (config.OverlayMode == EOverlayMode.OVERLAY_OBS)
            {
                // Create overlay server config
                OverlayServerConfig overlayServerConfig = new OverlayServerConfig(votingMode, config.RetainInitalVotes, config.OverlayServerPort);

                // Create component
                overlayServer = new OverlayServer.OverlayServer(overlayServerConfig);
            }

            // Create components
            //var votingReceiver = new TwitchVotingReceiver(twitchVotingReceiverConfig);
            TwitchChatVotingProxy.votingReceiver = new WSVotingReceiver(null);
            var chaosPipe = new ChaosPipeClient();

            // Start the chaos mod controller
            new ChaosModController(chaosPipe, overlayServer, votingReceiver, config);

            while (true)
            {
            }

            logger.Information("Pipe disconnected, ending program");
        }
 public static void Information(string template, params object[] args)
 {
     _logger.Information(template, args);
 }
Exemple #30
0
        public async Task Invoke(HttpContext context)
        {
            var displayUrl = context.Request.GetDisplayUrl();

            _log.Information(FormatEntryLogMessage(context.Request.Method, displayUrl));

            var stopWatch = new Stopwatch();

            stopWatch.Start();

            try
            {
                await _next.Invoke(context);

                stopWatch.Stop();

                var message = FormatExitLogMessage(MakeRequestName(context), displayUrl, stopWatch.ElapsedMilliseconds, context.Response.StatusCode);

                if (context.Response.StatusCode >= 200 && context.Response.StatusCode <= 399)
                {
                    _log.Information(message);
                }
                else
                {
                    _log.Error(message);
                }
            }
            catch (BadRequestException e)
            {
                stopWatch.Stop();

                if (context.Response.StatusCode != e.Error.Status)
                {
                    context.Response.StatusCode = e.Error.Status;
                }

                if (string.IsNullOrWhiteSpace(e.Error.TraceId))
                {
                    e.Error.TraceId = context.TraceIdentifier;
                }

                var details = JsonConvert.SerializeObject(e.Error, SerializerSettings);

                _log.Error(e,
                           FormatExceptionLogMessage(MakeRequestName(context), displayUrl, stopWatch.ElapsedMilliseconds, context.Response.StatusCode, details));

                await WriteJsonDetails(context, details);
            }
            catch (Exception e)
            {
                stopWatch.Stop();

                if (context.Response.StatusCode < 500)
                {
                    context.Response.StatusCode = 500;
                }

                _log.Error(e, FormatExceptionLogMessage(MakeRequestName(context), displayUrl, stopWatch.ElapsedMilliseconds, context.Response.StatusCode));

                await WriteExceptionResponse(context, e);
            }
        }
 protected void LogInfo(string text)
 {
     _logger.Information($"[{Tag}] {text}");
 }
Exemple #32
0
        /// <summary>
        /// This class is where all of the actual pinging work is done.
        /// I creates a thread that loops until canceled.
        /// The thread fires an event to do the actual pinging.
        /// </summary>
        /// <param name="host">The host that will be pinged.</param>
        public Pinger(Host host)
        {
            Host = host;
            if (!Directory.Exists("./Logs"))
            {
                Directory.CreateDirectory("./Logs");
            }
            if (!Directory.Exists($"./Logs/{Host.HostName}/"))
            {
                Directory.CreateDirectory($"./Logs/{Host.HostName}/");
            }
            var outputTemp      = "[{Timestamp:HH:mm:ss} {Level:u4}] {Message:lj}{NewLine}{Exception}";
            var errorOutputTemp = "[{Timestamp:HH:mm:ss} {Level:u5}] {Message:lj}{NewLine}{Exception}";

            var filePath      = "./Logs/" + Host.HostName + "/" + Host.HostName + "-{Date}.log";
            var errorPathName = "./Logs/" + Host.HostName + "/" + Host.HostName + "-Errors-{Date}.log";
            var warnPathName  = "./Logs/" + Host.HostName + "/" + Host.HostName + "-Warnings-{Date}.log";

#if DEBUG
            var debugOutputTemp = "[{Timestamp:HH:mm:ss.fff} {Level}] ({ThreadId}) {Message:lj}{NewLine}{Exception}";
            var debugPathName   = "./Logs/" + Host.HostName + "/" + Host.HostName + "-Debug-{Date}.log";
#endif
            Logger = new LoggerConfiguration()
#if DEBUG
                     .Enrich.With(new ThreadIdEnricher())
                     .MinimumLevel.Verbose()
#endif
                     .WriteTo.Logger(
                l => l.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Error)
                .WriteTo.RollingFile(
                    errorPathName,
                    restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error,
                    retainedFileCountLimit: Config.DaysToKeepLogs,
                    shared: true,
                    outputTemplate: errorOutputTemp,
                    flushToDiskInterval: TimeSpan.FromSeconds(2)                             //Added this because I noticed that it wasn't consistently flushing to disk at a good interval.
                    )
                )
                     .WriteTo.Logger(
                l => l.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Warning)
                .WriteTo.RollingFile(
                    warnPathName,
                    shared: true,
                    retainedFileCountLimit: Config.DaysToKeepLogs,
                    outputTemplate: outputTemp,
                    flushToDiskInterval: TimeSpan.FromSeconds(2)
                    )
                )
#if DEBUG
                     .WriteTo.Logger(
                l => l.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Debug)
                .WriteTo.RollingFile(
                    debugPathName,
                    shared: true,
                    retainedFileCountLimit: Config.DaysToKeepLogs,
                    restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug,
                    outputTemplate: debugOutputTemp,
                    flushToDiskInterval: TimeSpan.FromSeconds(2)
                    )
                )
#endif
                     .WriteTo.RollingFile(
                filePath,
                shared: true,
                outputTemplate: outputTemp,
                retainedFileCountLimit: Config.DaysToKeepLogs,
                restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information,
                flushToDiskInterval: TimeSpan.FromSeconds(2)
                )
                     .CreateLogger();

            //Check to make sure the packet size isn't too large. Don't want to abuse this.
            if (Host.PacketSize > 65500)
            {
                Logger.Error("Packet size too large. Resetting to 65500 bytes");
                Host.PacketSize = 65500;
            }
            //Make sure that the interval isn't too short. If you set it to be too frequent, it might get flagged as DDoS attack.
            if (Host.Interval < 500)
            {
                Logger.Error("Interval too short. Setting to 500ms");
                Host.Interval = 500;
            }
            //Verify that the IP stored in the settings file matches what it currently resolves to.
            //Mostly in cases of local network and DHCP
            Logger.Information("Verifying IP address of hostname is current.");
            foreach (var ip in Dns.GetHostAddresses(Host.HostName))
            {
                Logger.Debug($"IP: {ip}");
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    if (ip.ToString() == Host.IP)
                    {
                        Logger.Information("IP matches. Continuing");
                    }
                    else
                    {
                        Logger.Warning("IP address does not match last stored. Saving new IP address");
                        Host.IP = ip.ToString();
                    }
                    break;
                }
            }
        }
 public ActionResult <IEnumerable <string> > Get()
 {
     _logger.Information(messageTemplate: "Log informaton from {0} - OK", propertyValue: nameof(ValuesController));
     _logger.Error("Move to ElasticSearch logstash");
     return(new string[] { "value1", "value2" });
 }
Exemple #34
0
        }                                              // ...for the "Warnings-dict" (the old WF-stuff)

        public string  ProcessShipments(OrderGroup orderGroup)
        {
            Logger = LogManager.GetLogger(GetType());

            ShippingMethodDto methods = ShippingManager.GetShippingMethods
                                            (/*Thread.CurrentThread.CurrentUICulture.Name*/ String.Empty);

            OrderGroup order           = orderGroup;
            var        billingCurrency = order.BillingCurrency;

            // request rates, make sure we request rates not bound to selected delivery method
            foreach (OrderForm form in order.OrderForms)
            {
                foreach (Shipment shipment in form.Shipments)
                {
                    bool processThisShipment = true;

                    // is this in use?
                    string discountName = "@ShipmentSkipRateCalc"; // ...this is the "old" promos

                    // If you find the shipment discount which represents ... OLD?
                    if (shipment.Discounts.Cast <ShipmentDiscount>().Any(
                            x => x.ShipmentId == shipment.ShipmentId && x.DiscountName.Equals(discountName)))
                    {
                        processThisShipment = false;
                    }

                    if (!processThisShipment)
                    {
                        continue;
                    }

                    ShippingMethodDto.ShippingMethodRow row =
                        methods.ShippingMethod.FindByShippingMethodId(shipment.ShippingMethodId);

                    // If shipping method is not found, set it to 0 and continue
                    if (row == null)
                    {
                        Logger.Information(String.Format("Total shipment is 0 so skip shipment calculations."));
                        shipment.ShippingSubTotal = 0;
                        continue;
                    }

                    // Check if package contains shippable items, if it does not use the default shipping method instead of the one specified
                    Logger.Debug(String.Format("Getting the type \"{0}\".", row.ShippingOptionRow.ClassName));
                    Type type = Type.GetType(row.ShippingOptionRow.ClassName); // ...the gateway
                    if (type == null)
                    {
                        throw new TypeInitializationException(row.ShippingOptionRow.ClassName, null);
                    }

                    Logger.Debug(String.Format("Creating instance of \"{0}\".", type.Name));

                    // where it starts happening things
                    IShippingGateway provider = null;
                    var orderMarket           = ServiceLocator.Current.GetInstance <IMarketService>()
                                                .GetMarket(order.MarketId);

                    if (orderMarket != null)
                    {
                        provider = (IShippingGateway)Activator.CreateInstance(type, orderMarket);
                    }
                    else
                    {
                        provider = (IShippingGateway)Activator.CreateInstance(type);
                    }

                    Logger.Debug(String.Format("Calculating the rates."));
                    string       message = String.Empty;
                    ShippingRate rate    = provider.GetRate(row.ShippingMethodId, shipment, ref message);

                    if (rate != null)
                    {
                        Logger.Debug(String.Format("Rates calculated."));
                        // check if shipment currency is convertable to Billing currency, and then convert it
                        // Added the namespace below
                        if (!Mediachase.Commerce.Shared.CurrencyFormatter.CanBeConverted
                                (rate.Money, billingCurrency))

                        {
                            Logger.Debug(String.Format("Cannot convert selected shipping's currency({0}) to current currency({1}).", rate.Money.Currency.CurrencyCode, billingCurrency));
                            throw new Exception(String.Format("Cannot convert selected shipping's currency({0}) to current currency({1}).", rate.Money.Currency.CurrencyCode, billingCurrency));
                        }
                        else
                        {
                            Money convertedRate = Mediachase.Commerce.Shared.CurrencyFormatter.ConvertCurrency(rate.Money, billingCurrency);
                            shipment.ShippingSubTotal = convertedRate.Amount;
                        }
                        //return "In Rate";
                    }
                    else
                    {
                        Warnings[String.Concat("NoShipmentRateFound-", shipment.ShippingMethodName)] =
                            String.Concat("No rates have been found for ", shipment.ShippingMethodName);
                        Logger.Debug(String.Format("No rates have been found."));

                        //return "else";
                    }
                }

                //return "Near end";
            }

            return("Hello");
        } // end method
        // A production app would also include an OnStop override to provide for
        // graceful shut-downs of worker-role VMs.  See
        // http://azure.microsoft.com/en-us/documentation/articles/cloud-services-dotnet-multi-tier-app-storage-3-web-role/#restarts
        public override bool OnStart()
        {
            // creare logger
            logger = new Logger();

            // Set the maximum number of concurrent connections.
            ServicePointManager.DefaultConnectionLimit = 12;

            // Read database connection string and open database.
            var dbConnString = CloudConfigurationManager.GetSetting("moviesassignment03DbConnectionString");
            db = new MovieContext(dbConnString);

            // Open storage account using credentials from .cscfg file.
            var storageAccount = CloudStorageAccount.Parse
                (RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
            logger.Information("Creating images blob container named images");
            //Trace.TraceInformation("Creating images blob container named images");
            var blobClient = storageAccount.CreateCloudBlobClient();
            imagesBlobContainer = blobClient.GetContainerReference("images");
            if (imagesBlobContainer.CreateIfNotExists())
            {
                // Enable public access on the newly created "images" container.
                imagesBlobContainer.SetPermissions(
                    new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    });
            }

            logger.Information("Creating images queue");
            //Trace.TraceInformation("Creating images queue");
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            imagesQueue = queueClient.GetQueueReference("images");
            imagesQueue.CreateIfNotExists();

            logger.Information("Storage initialized");
            //Trace.TraceInformation("Storage initialized");
            return base.OnStart();
        }
Exemple #36
0
        public async Task ProcessPayment(string userId, string paymentIntentId, string pricePlanId, CancellationToken cancellationToken)
        {
            Guard.Argument(userId, nameof(userId)).NotNull().NotEmpty().NotWhiteSpace();
            Guard.Argument(paymentIntentId, nameof(paymentIntentId)).NotNull().NotEmpty().NotWhiteSpace();
            Guard.Argument(pricePlanId, nameof(pricePlanId)).NotNull().NotEmpty().NotWhiteSpace();

            var user = await _userRepository.GetUserById(userId, cancellationToken);

            if (user == null)
            {
                throw new UserException("Please create the user first.");
            }

            if (string.IsNullOrWhiteSpace(user.PaymentCustomerId))
            {
                throw new UserException("PaymentCustomerId is missing. Please create the user first.");
            }

            var pricePlan = await _pricePlanRepository.GetPricePlanById(pricePlanId, cancellationToken);

            if (pricePlan == null)
            {
                throw new SubscriptionException($"Unable to find the price plan with '{user.CurrentPricePlanId}' identifier.");
            }

            var paymentIntent = await _paymentService.GetPaymentIntent(paymentIntentId, cancellationToken);

            if (pricePlan.Price != paymentIntent.Amount)
            {
                _logger.Error($"Payment amount is not matching with price plan '{pricePlan.Id}'. Expected '{pricePlan.Price}' and actual '{paymentIntent.Amount}'");
            }

            _logger.Information($"Collected payment of '{paymentIntent.Amount}' in minimum unit for user '{user.Id}'.");

            var nextInvoiceNumberDao = await _invoiceNumberRepository.GetNextInvoiceNumber(cancellationToken);

            var invoiceNumber = _invoiceHelper.CalculateInvoiceNumber(nextInvoiceNumberDao.Number);

            try
            {
                await _invoiceHelper.SendInvoiceAsEmailAttachment(user, paymentIntent, pricePlan.Title, _systemDateTime.GetUtcDateTime(), paymentIntent.Amount, invoiceNumber, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.Error($"Unable to send and invoice for an user {user.Id}. Exception: {ex.Message}");
            }

            var paymentDao = new ProcessedPaymentDao
            {
                UserId           = user.Id,
                PaymentServiceId = paymentIntent.Id,
                Amount           = paymentIntent.Amount,
                PricePlanId      = pricePlan.Id,
                NoOfStamps       = pricePlan.NoOfStamps,
                Created          = paymentIntent.Created,
                InvoiceNumber    = invoiceNumber
            };

            await _paymentRepository.CreatePaymentReceived(paymentDao, cancellationToken);

            _logger.Information($"Previous remaining stamp for the user '{user.Id}' is '{user.RemainingTimeStamps}'.");

            user.CurrentPricePlanId   = pricePlan.Id;
            user.PendingPricePlanId   = null;
            user.RemainingTimeStamps  = pricePlan.NoOfStamps;
            user.PaymentIntentId      = paymentIntentId;
            user.MembershipRenewDate  = _systemDateTime.GetUtcDateTime().AddMonths(1);
            user.MembershipRenewEpoch = user.MembershipRenewDate.Date.ToEpoch();

            await _userRepository.UpdateUser(user, cancellationToken);
        }
        public static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration().MinimumLevel.Debug()
                         .MinimumLevel.Override(nameof(Microsoft), LogEventLevel.Information)
                         .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .WriteTo.Graylog(new GraylogSinkOptions()
            {
                Facility          = "project-ivy-imdb-ratings",
                HostnameOrAddress = Environment.GetEnvironmentVariable("GRAYLOG_HOST"),
                Port          = Convert.ToInt32(Environment.GetEnvironmentVariable("GRAYLOG_PORT")),
                TransportType = TransportType.Udp
            })
                         .CreateLogger();
            _logger = Log.Logger;

            _logger.Information("Application started");

            try
            {
                string connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING");

                var users = (await DbHandler.GetImdbUsers(connectionString)).ToList();
                _logger.Information("Found {UserCount} users with an Imdb account", users.Count);

                foreach (var user in users)
                {
                    _logger.Information("Processing movies for userId: {UserId}", user.userId);

                    var existingIds = await DbHandler.GetMovieIds(connectionString, user.userId);

                    var imdbCookies = await DbHandler.GetImdbUserSecrets(connectionString, user.userId);

                    if (imdbCookies.Count() == 0)
                    {
                        _logger.Information("User {UserId} does not have imdb cookies", user.userId);
                        continue;
                    }

                    var imdbRatings = await ImdbHandler.GetRatings(ImdbRatingsUrl, imdbCookies, user.imdbUsername);

                    var csvOptions   = new CsvParserOptions(true, ',');
                    var movieMapping = new MovieMapping();
                    var csvParser    = new CsvParser <Movie>(csvOptions, movieMapping);

                    var csvReaderOptions = new CsvReaderOptions(new[] { "\n" });
                    var movies           = csvParser.ReadFromString(csvReaderOptions, imdbRatings).Where(x => x.IsValid).Select(x => x.Result).ToList();

                    var newMovies = movies.Where(x => !existingIds.Contains(x.ImdbId));

                    foreach (var newMovie in newMovies)
                    {
                        newMovie.UserId = user.userId;
                        await DbHandler.InsertMovie(connectionString, newMovie);

                        _logger.Information("Movie {Title} added for userId: {UserId}", newMovie.Title, newMovie.UserId);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
            }

            _logger.Information("Application ended");
        }
        private Response ReadJsonResponse(JsonReader json, long token, ILogger logger)
        {
            Spec.Response retval = new Spec.Response();
            retval.token = token;

            if (!json.Read() || json.CurrentToken != JsonToken.ObjectStart)
                throw new RethinkDbInternalErrorException("Expected a readable JSON object in response");

            while (true)
            {
                if (!json.Read())
                    throw new RethinkDbInternalErrorException("Unexpected end-of-frame reading JSON response");
                if (json.CurrentToken == JsonToken.ObjectEnd)
                    break;
                if (json.CurrentToken != JsonToken.MemberName)
                    throw new RethinkDbInternalErrorException("Unexpected JSON state");

                string property = (string)json.CurrentTokenValue;
                if (property == "t")
                    retval.type = ReadResponseType(json);
                else if (property == "r")
                    retval.response.AddRange(ReadDatumArray(json));
                else if (property == "b")
                    retval.backtrace = ReadBacktrace(json);
                else if (property == "p")
                    logger.Warning("Profiling is not currently supported by rethinkdb-net; profiling data will be discarded");
                else
                    logger.Information("Unexpected property {0} in JSON response; ignoring", property);
            }

            return retval;
        }
Exemple #39
0
        public async Task Study(string name)
        {
            try
            {
                var list = new List <CustomRequest>
                {
                    new CustomRequest {
                        a = 1
                    },
                    new CustomRequest {
                        a = 2
                    },
                    new CustomRequest {
                        a = 3
                    },
                };
                ////单播
                //Console.WriteLine("_mediator.Send");
                _mediator.Send(list.FirstOrDefault());
                Console.WriteLine("zasdasd");
                //Console.WriteLine("_mediator.SendAllAsync");
                ////异步广播
                //try
                //{
                //    await _mediator.SendAllAsync(list);
                //}
                //catch (AggregateException ex)
                //{
                //    var exM = string.Join(",", ex.InnerExceptions.Select(s => s.Message));
                //    Console.WriteLine(exM);
                //}

                //Console.WriteLine("_mediator.SendAll");
                ////同步广播
                //await _mediator.SendAll(list);

                ////异步发布订阅
                //Console.WriteLine("_asyncPublisher.Publish");
                //try
                //{
                //    await _asyncPublisher.Publish(new CustomNotification { MsgId = "1" }, PublishStrategy.ParallelNoWait);
                //}
                //catch (AggregateException ex)
                //{
                //    Console.WriteLine(ex.Message);
                //}
                //catch (Exception ex)
                //{
                //    Console.WriteLine(ex.Message);
                //}
                throw new Exception("aaa");
                //同步发布订阅
                //Console.WriteLine("_mediator.PublishOne");
                //await _mediator.Publish(new CustomNotification { MsgId = "1" });
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "异常", 1, 1);
                _logger.Information(ex, "异常", 1, 1);
                _logger.Warning(ex, "异常", 1, 1);
                _logger.Fatal(ex, "异常", 1, 1);
                _logger.Debug(ex, "异常", 1, 1);
                _logger.Verbose(ex, "异常", 1, 1);
            }
        }
Exemple #40
0
        static void Main(string[] args)
        {
            #if !DEBUG  // Catch any unhandled exceptions if we are in release mode.
                AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
            #endif

            // use invariant culture - we have to set it explicitly for every thread we create to
            // prevent any file-reading problems (mostly because of number formats).
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            // start the ioc kernel.
            var kernel = TinyIoCContainer.Current;
            var bootstrapper = new Bootstrapper(kernel);
            var objectFactory = kernel.Resolve<IObjectFactory>();
            var configFactory = kernel.Resolve<IConfigFactory>();

            // print intro texts.
            ConsoleWindow.PrintBanner();
            ConsoleWindow.PrintLicense();

            // check if we have a valid config file.
            var configManager = configFactory.GetConfigManager();
            if (!configManager.ConfigExists)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Couldn't read config/config.json! Make sure you rename config/config-sample.json as config/config.json.");
                Console.ResetColor();
                return;
            }

            // initialize log-manager.
            var logManager = objectFactory.GetLogManager();
            logManager.Initialize();

            // print a version banner.
            _logger = Log.ForContext<Program>();
            _logger.Information("CoiniumServ {0} {1:l} warming-up..", VersionInfo.CodeName, Assembly.GetAssembly(typeof(Program)).GetName().Version);
            PlatformManager.PrintPlatformBanner();

            // initialize config manager.
            configManager.Initialize();

            // start pool manager.
            var poolManager = objectFactory.GetPoolManager();
            poolManager.Run();

            // start web server.
            var webServer = objectFactory.GetWebServer();

            while (true) // idle loop & command parser
            {
                var line = Console.ReadLine();
                CommandManager.Parse(line);
            }
        }
        //private async Task<ServiceDto> CallConsul(HttpContext context, ILogger log, string serviceName)
        //{
        //    try
        //    {
        //        var data = new ServiceDto();
        //        log.Verbose("Searching service in Consul...");

        //        using (var client = new ConsulClient())
        //        {
        //            var consulCatalog = await client.Catalog.Service(serviceName);

        //            if (consulCatalog.Response.Length > 0)
        //            {
        //                var service = consulCatalog.Response[0];
        //                data.Address = IPAddress.Parse(service.Address);
        //                data.Port = service.ServicePort;

        //                log.Information("Sending request to {Host}:{port}...", service.Address, data.Port);
        //            }
        //            else
        //            {
        //                log.Warning("Service not found!");
        //                context.Response.Send(404);
        //            }
        //        }

        //        return data;
        //    }
        //    catch (Exception e)
        //    {
        //        log.Error(e, "Cannot call Consul");
        //        context.Response.Send(500);
        //        return null;
        //    }
        //}

        private static async Task CallService(HttpContext context, HttpRequest request, ILogger log, ServiceInfo serviceInfo)
        {
            IPAddress serviceAdress = IPAddress.Parse(serviceInfo.Address);
            int servicePort = serviceInfo.Port;

            using (context)
            {
                try
                {
                    using (var client = new TcpClient())
                    {
                        client.Connect(serviceAdress, servicePort);

                        using (var realService = client.GetStream())
                        {
                            log.Verbose("Sending request...");

                            await request.RedirectToAsync(realService);

                            log.Verbose("Waiting response...");

                            await context.Response.RedirectFromAsync(realService);

                            log.Information("Finished!");
                        }
                    }
                }
                catch (Exception e)
                {
                    log.Error(e, "Cannot call service");
                    context.Response.Send(500);
                }
            }
        }
 private void LogAll(ILogger logger)
 {
     logger.Error("Error Logged");
     logger.Warning("Warning Logged");
     logger.Information("Information Logged");
     logger.Debug("Debug Logged");
 }
 static void RunLoggingStuff(ILogger logger)
 {
     var timer = Stopwatch.StartNew();
     foreach (var s in _stuffToLog) logger.Information(s);
     logger.Information(timer.ElapsedMilliseconds.ToString());
 }
Exemple #44
0
 public void Info(string msg, params object[] args)
 {
     _logger.Information(msg, args);
 }
Exemple #45
0
        public async Task <OrphanageDataModel.Persons.Father> GetFather(int Fid)
        {
            _logger.Information($"trying to get father with Id ({Fid})");
            using (var dbContext = new OrphanageDbCNoBinary())
            {
                var father = await dbContext.Fathers.AsNoTracking()
                             .Include(f => f.Families)
                             .Include(f => f.Name)
                             .FirstOrDefaultAsync(f => f.Id == Fid);

                if (father == null)
                {
                    _logger.Warning($"Father with id{Fid} cannot be found null is returned");
                    return(null);
                }
                _selfLoopBlocking.BlockFatherSelfLoop(ref father);
                setFatherEntities(ref father, dbContext);
                _uriGenerator.SetFatherUris(ref father);
                father.OrphansCount = await GetOrphansCount(Fid, dbContext);

                father.WifeName = await(GetWifeName(father));
                _logger.Information($"returned Father with id {Fid}");
                return(father);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PoolConfig"/> class.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <param name="coinConfig"></param>
        public PoolConfig(dynamic config, ICoinConfig coinConfig)
        {
            try
            {
                _logger = Log.ForContext<PoolConfig>().ForContext("Component", coinConfig.Name);

                Enabled = config.enabled ? config.enabled : false;

                if (Enabled == false) // if the configuration is not enabled
                    return; // just skip reading rest of the parameters.

                // load the sections.
                Coin = coinConfig; // assign the coin config.
                Daemon = new DaemonConfig(config.daemon);
                Meta = new MetaConfig(config.meta);
                Wallet = new WalletConfig(config.wallet);
                Rewards = new RewardsConfig(config.rewards);
                Payments = new PaymentConfig(config.payments);
                Miner = new MinerConfig(config.miner);
                Job = new JobConfig(config.job);
                Stratum = new StratumServerConfig(config.stratum);
                Banning = new BanConfig(config.banning);
                Storage = new StorageConfig(config.storage);
                Getwork = new GetworkServerConfig(config.getwork);

                // process extra checks
                if (Storage.Layer is MposStorageConfig)
                {
                    if (Payments.Enabled)
                    {
                        Payments.Disable();
                        _logger.Information("Disabled payment processor as it can not be enabled when MPOS mode is on");
                    }
                }

                Valid = true;
            }
            catch (Exception e)
            {
                Valid = false;
                _logger.Error(e, "Error loading pool configuration");
            }
        }
Exemple #47
0
        public async Task StartAsync()
        {
            try
            {
                Log.Logger = new LoggerConfiguration()
                             .WriteTo.Sentry(o =>
                {
                    o.Dsn                    = new Dsn(Config.Bot.SentryDsn);
                    o.Environment            = Config.Bot.Environment;
                    o.MinimumBreadcrumbLevel = LogEventLevel.Verbose;
                    o.MinimumEventLevel      = LogEventLevel.Error;
                    o.SendDefaultPii         = true;
                    o.AttachStacktrace       = true;
                })
                             .MinimumLevel.Verbose()
                             .WriteTo.File("logs/rabbot.log", rollingInterval: RollingInterval.Day)
                             .WriteTo.Console()
                             .CreateLogger();

                var config = new DiscordSocketConfig
                {
                    TotalShards         = 1,
                    LogLevel            = LogSeverity.Verbose,
                    MessageCacheSize    = 1000,
                    ExclusiveBulkDelete = true
                };

                var services = new ServiceCollection()
                               .AddSingleton(_client         = new DiscordShardedClient(config))
                               .AddSingleton(_commandService = new CommandService(new CommandServiceConfig
                {
                    DefaultRunMode        = RunMode.Async,
                    LogLevel              = LogSeverity.Verbose,
                    CaseSensitiveCommands = false,
                    ThrowOnError          = false
                }))
                               .AddSingleton <TwitchService>()
                               .AddSingleton <YouTubeVideoService>()
                               .AddSingleton <CommandHandler>()
                               .AddSingleton <StartupService>()
                               .AddSingleton <AudioService>()
                               .AddSingleton <LoggingService>()
                               .AddSingleton <Logging>()
                               .AddSingleton <StreakService>()
                               .AddSingleton <AttackService>()
                               .AddSingleton <LevelService>()
                               .AddSingleton <MuteService>()
                               .AddSingleton <WarnService>()
                               .AddSingleton <EventService>()
                               .AddSingleton <ApiService>()
                               .AddSingleton <DiscordApiService>()
                               .AddSingleton <InteractiveService>()
                               .AddSingleton <EasterEventService>()
                               .AddSingleton <ImageService>()
                               .AddSingleton <CacheService>()
                               .AddSingleton <RuleAcceptService>()
                               .AddSingleton <Helper>();



                //Add logging
                ConfigureServices(services);

                //Build services
                var serviceProvider = services.BuildServiceProvider();

                //Instantiate logger/tie-in logging
                serviceProvider.GetRequiredService <LoggingService>();

                // Run Migrations
                var db = DatabaseService.Instance.Open();
                _logger.Information($"Checking database={db.GetType().Name}...");

                using (db)
                {
                    if (db.Database.GetPendingMigrations().Any())
                    {
                        _logger.Information($"Applying database={db.GetType().Name} migrations...");
                        db.Database.Migrate();
                    }
                    else
                    {
                        _logger.Information($"{db.GetType().Name} is up2date!");
                    }
                }

                //Start the bot
                await serviceProvider.GetRequiredService <StartupService>().StartAsync();

                //Load up services
                serviceProvider.GetRequiredService <CommandHandler>();
                serviceProvider.GetRequiredService <TwitchService>();
                serviceProvider.GetRequiredService <YouTubeVideoService>();
                serviceProvider.GetRequiredService <StreakService>();
                serviceProvider.GetRequiredService <AttackService>();
                serviceProvider.GetRequiredService <LevelService>();
                serviceProvider.GetRequiredService <Logging>();
                serviceProvider.GetRequiredService <MuteService>();
                serviceProvider.GetRequiredService <WarnService>();
                serviceProvider.GetRequiredService <EventService>();
                serviceProvider.GetRequiredService <ApiService>();
                serviceProvider.GetRequiredService <EasterEventService>();
                serviceProvider.GetRequiredService <ImageService>();
                serviceProvider.GetRequiredService <CacheService>();
                serviceProvider.GetRequiredService <RuleAcceptService>();
                serviceProvider.GetRequiredService <Helper>();

                new Task(() => RunConsoleCommand(), TaskCreationOptions.LongRunning).Start();

                //Block this program until it is closed.
                await Task.Delay(-1);
            }
            catch (Exception e)
            {
                _logger.Error(e, $"Error in {nameof(StartAsync)}");
                Console.WriteLine($"Startup failed. Please check the config file.");
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(0);
            }
        }
        void RenderToVSTS(ActivityElement element, ILogger log, string indent)
        {
            if (!IsPrintable(element))
                return;

            log.Information("{Indent:l}         {Status:l}: {Name:l}", indent, element.Status, element.Name);

            foreach (var logEntry in element.LogElements)
            {
                log.Information("{Category,-8:l}{Indent:l}   {Message:l}", logEntry.Category, logEntry.MessageText);
            }

            foreach (var child in element.Children)
            {
                RenderToVSTS(child, log, indent + "  ");
            }
        }
 private void OnApplicationExit(object sender, EventArgs e)
 {
     FiddlerOptions.SaveProfile();
     Map.SaveMapOverlays();
     _logger.Information("UOFiddler - Application exit.");
 }
Exemple #50
0
        public async Task <byte[]> ConvertToXlsx(IDictionary <string, IList <string> > data, CancellationToken cancellationToken)
        {
            return(await Task.Factory.StartNew(() =>
            {
                _logger.Information("trying to convert lists of data to xlsx file");
                _logger.Information("trying to open Excel Work Book.");
                ClosedXML.Excel.XLWorkbook wbook = new ClosedXML.Excel.XLWorkbook(ClosedXML.Excel.XLEventTracking.Disabled);
                _logger.Information("trying to add Excel Work Sheet.");
                var sheet = wbook.Worksheets.Add("sheet1");
                int row = 1;
                int col = 1;
                int rowsCount = data[data.Keys.First()].Count;
                int columnsCount = data.Keys.Count;
                var keys = data.Keys.ToArray();
                _logger.Information($"start printing data to excel file, ColumnsCount={columnsCount} . RowsCount={rowsCount}");
                for (row = 1; row <= rowsCount + 1; row++)
                {
                    for (col = 1; col <= columnsCount; col++)
                    {
                        string key = keys[col - 1];
                        var values = data[key];

                        if (row == 1)
                        {
                            //write the column header
                            sheet.Cell(1, col).Value = key;
                        }
                        else
                        {
                            sheet.Cell(row, col).Value = values[row - 2];
                        }
                    }
                    if (cancellationToken != null && cancellationToken.IsCancellationRequested)
                    {
                        _logger.Information($"the operation has broken, a cancellation request has been sent.");
                        break;
                    }
                }
                _logger.Information($"all data has been printed successfully to the excel file.");
                sheet.ExpandColumns();
                setHeaderStyle(sheet, 1, 1, 1, columnsCount);
                setBorder(sheet, 2, 1, rowsCount + 1, columnsCount);
                wbook.Author = "Orphanage Service V" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    wbook.SaveAs(memoryStream);
                    _logger.Information($"the excel file has been saved successfully, an array of bytes will be returned.");
                    return memoryStream.ToArray();
                }
            }));
        }
Exemple #51
0
        /// <summary>
        /// Create redirects table and SP for version number
        /// </summary>
        private static void Create()
        {
            bool create = true;

            var dba = DataAccessBaseEx.GetWorker();

            _log.Information("Create 404 handler redirects table START");
            string createTableScript = @"CREATE TABLE [dbo].[BVN.NotFoundRequests](
	                                    [ID] [int] IDENTITY(1,1) NOT NULL,
	                                    [OldUrl] [nvarchar](2000) NOT NULL,
	                                    [Requested] [datetime] NULL,
	                                    [Referer] [nvarchar](2000) NULL
                                        ) ON [PRIMARY]";

            create = dba.ExecuteNonQuery(createTableScript);

            _log.Information("Create 404 handler redirects table END");


            if (create)
            {
                _log.Information("Create 404 handler version SP START");
                string versionSP = @"CREATE PROCEDURE [dbo].[bvn_notfoundversion] AS RETURN " + Configuration.Configuration.CURRENT_VERSION;

                if (!dba.ExecuteNonQuery(versionSP))
                {
                    create = false;
                    _log.Error("An error occured during the creation of the 404 handler version stored procedure. Canceling.");
                }

                _log.Information("Create 404 handler version SP END");
            }

            if (create)
            {
                _log.Information("Create Clustered index START");
                string clusteredIndex =
                    "CREATE CLUSTERED INDEX NotFoundRequests_ID ON [dbo].[BVN.NotFoundRequests] (ID)";

                if (!dba.ExecuteNonQuery(clusteredIndex))
                {
                    create = false;
                    _log.Error("An error occurred during the creation of the 404 handler redirects clustered index. Canceling.");
                }

                _log.Information("Create Clustered index END");
            }

            Valid = create;

            // copy dds items, if there are any.
            try
            {
                // the old redirect class is obsolete, and should only be used for this upgrade
#pragma warning disable CS0618
                var oldCustomrRedirectStore = DataStoreFactory.GetStore(typeof(FileNotFound.CustomRedirects.CustomRedirect));
                var oldCustomRedirects      = oldCustomrRedirectStore.Items <FileNotFound.CustomRedirects.CustomRedirect>().ToList();
#pragma warning restore CS0618
                if (oldCustomRedirects.Count > 0)
                {
                    var newCustomrRedirectStore = DataStoreFactory.GetStore(typeof(CustomRedirect));
                    DataStoreHandler dsHandler  = new DataStoreHandler();
                    foreach (var oldCustomRedirect in oldCustomRedirects)
                    {
                        var newRedirect = new CustomRedirect(oldCustomRedirect.OldUrl, oldCustomRedirect.NewUrl, oldCustomRedirect.WildCardSkipAppend);
                        dsHandler.SaveCustomRedirect(newRedirect);
                    }
                    // oldCustomrRedirectStore.DeleteAll();
                }
            }
            catch (Exception ex)
            {
                _log.Error("Error during DDS upgrade: " + ex);
            }
        }
Exemple #52
0
 public void LogInformation(ILogger log, string title, string content)
 {
     log.Information("userId: " + this.userId + ", sessionId:" + this.sessionId + "\n" + title + " " + content);
 }
Exemple #53
0
 public Task Handle(MyEvent @event, EventContext eventContext)
 {
     _logger.Information("Processing event : '{Event}'", @event);
     return(Task.CompletedTask);
 }