Esempio n. 1
0
 public void NLog_WithIf()
 {
     if (_nLogger.IsInfoEnabled)
     {
         _nLogger.Info(Message, 2022);
     }
 }
Esempio n. 2
0
        public static bool PopulateListBoxWithFileNames(string folder, string extensions, ListBox listBox)
        {
            bool result = false;

            try
            {
                DirectoryInfo di = new DirectoryInfo(folder);

                string   rawList = extensions;
                string[] splits  = rawList.Split(',');

                listBox.Items.Clear();

                foreach (string split in splits)
                {
                    foreach (FileInfo fileInfo in di.GetFiles(split, SearchOption.TopDirectoryOnly))
                    {
                        listBox.Items.Add(fileInfo.Name);
                        logger.Info("File " + fileInfo.Name.ToString() + " found");
                    }
                }

                result = true;
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                result = false;
            }
            return(result);
        }
Esempio n. 3
0
 public void Info(string message)
 {
     if (log.IsInfoEnabled)
     {
         log.Info(message);
     }
 }
        private static async Task Init()
        {
            //setup our DI
            var serviceCollection = new ServiceCollection()
                                    .AddLogging()
                                    .AddSingleton <IConfigurationReader, EnvironmentConfigurationReader>()
                                    //.AddSingleton<ITrafficSegmentConfigurator, BlobSegmentConfigurator>()
                                    .AddSingleton <ITrafficSegmentConfigurator, TwinSegmentConfigurator>()
                                    .AddSingleton <ITimeSimulationSettings, TimeSimulationSettings>()
                                    .AddSingleton <IEventGenerator, EventGenerator>();

            if (IsEdgeEnvironment)
            {
                _logger.Info($"This container is running in edge environment, creating iot edge module transmitter");
                serviceCollection.AddSingleton <ICameraTransmitterConfigurator, IoTEdgeModuleTransmitterConfiguration>();
            }
            else
            {
                _logger.Info($"This container is *not* running in edge environment, creating iot hub transmitter");
                serviceCollection.AddSingleton <ICameraTransmitterConfigurator, IoTHubTransmitterConfigurator>();
            }

            var serviceProvider = serviceCollection.BuildServiceProvider();

            _generator = serviceProvider.GetService <IEventGenerator>();
        }
Esempio n. 5
0
        static async Task <int> Main(string[] args)
        {
            try
            {
                Log.Info("Running application with parameters {@arguments}", args);
                var runner = new AppRunner <ConsoleApplication>();
                ConfigureApplication(runner);
                var exitCode = await runner.RunAsync(args);

                Log.Info("Application exited with error code {exitCode}.", exitCode);
                return(exitCode);
            }
            catch (Exception e)
            {
                Log.Error(e, "Application terminated in an unexpected way.");
                return(-1);
            }
            finally
            {
                LogManager.Flush(TimeSpan.FromSeconds(2));
#if DEBUG
                Console.ReadKey();
#endif
            }
        }
Esempio n. 6
0
        public void IntegrateAsset(string ClientID, string UserID, string Token)
        {
            logger.Info("Scheduled Fleet complete asset job triggered");
            var client = new RestClient(_integrationAppSettings.AssetURL);

            client.Timeout = -1;
            var request = new RestRequest(Method.GET);

            request.AddHeader("ClientID", ClientID);
            request.AddHeader("UserID", UserID);
            request.AddHeader("Token", Token);
            IRestResponse response = client.Execute(request);
            AssetResp     ASResp   = new AssetResp();

            ASResp = JsonConvert.DeserializeObject <AssetResp>(response.Content);
            List <Vehicle> vehicles = new List <Vehicle>();

            if (ASResp.Errors == null)
            {
                foreach (var vsRes in ASResp.Data)
                {
                    try
                    {
                        Vehicle vh = new Vehicle();
                        vh.AssetId      = vsRes.ID;
                        vh.Registration = vsRes.LicensePlate;
                        vh.Make         = vsRes.Make;
                        vh.Model        = vsRes.Model;
                        string GuidID  = vsRes.ID;
                        var    CatType = AssetType(GuidID, ClientID, UserID, Token);
                        if (CatType != 0)
                        {
                            vh.Category = CatType;
                        }
                        if (vsRes.AssetType != null)
                        {
                            vh.Type = (vsRes.AssetType.ToString().Contains("Fleet")) ? 1 : 2;
                        }
                        else
                        {
                            vh.Type = 1;
                        }
                        vh.Active       = true;
                        vh.Availability = true;
                        vh.CreatedDate  = DateTime.Now;
                        vh.ModifiedDate = DateTime.Now;
                        if (vsRes.IsDeleted != null && vsRes.IsDeleted != true)
                        {
                            vehicles.Add(vh);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Info(ex.ToString() + ", Ids :" + vsRes.ID.ToString() + ", vsRes.LicensePlate:" + vsRes.LicensePlate.ToString());
                    }
                }
                DBAction dba = new DBAction(_integrationAppSettings);
                dba.IntegrateAssetsintoDB(vehicles);
            }
        }
Esempio n. 7
0
 private static void Main(string[] args)
 {
     LogManager.LoadConfiguration("nlog.config");
     LogManager.ReconfigExistingLoggers();
     SubscribeToUnhandledException();
     logger.Info("Start application");
     Parser.Default.ParseArguments <Options>(args).WithParsed(Run);
 }
Esempio n. 8
0
        public IActionResult Ekle()
        {
            var list = service.Brans.GetAll(x => !x.SilindiMi).Data;

            //SelectList slct = new SelectList(list, "Id", "Ad");
            //ViewBag.BransList = slct;
            ViewBag.THBransList = list;
            nlogger.Info("Branş ekle sayfası açıldı.");
            return(View());
        }
Esempio n. 9
0
        public void Intercept(IInvocation invocation)
        {
            _logger.Info("Calling method {0} with parameters {1}... ",
                         invocation.Method.Name,
                         string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()));

            invocation.Proceed();

            _logger.Info("Done: result was {0}.", invocation.ReturnValue);
        }
        public static IEventStoreConnection ConfigureStore()
        {
            Logger.Info("Setting up Eventstore");
            var connectionString = ConfigurationManager.ConnectionStrings["EventStore"];
            var data             = connectionString.ConnectionString.Split(';');

            var hosts = data.Where(x => x.StartsWith("Host", StringComparison.CurrentCultureIgnoreCase));

            if (!hosts.Any())
            {
                throw new ArgumentException("No Host parameter in eventstore connection string");
            }

            var endpoints = hosts.Select(x =>
            {
                var addr = x.Substring(5).Split(':');
                if (addr[0] == "localhost")
                {
                    return(new IPEndPoint(IPAddress.Loopback, int.Parse(addr[1])));
                }
                return(new IPEndPoint(IPAddress.Parse(addr[0]), int.Parse(addr[1])));
            }).ToArray();

            var cred     = new UserCredentials("admin", "changeit");
            var settings = EventStore.ClientAPI.ConnectionSettings.Create()
                           .UseCustomLogger(new EventStoreLogger())
                           .KeepReconnecting()
                           .KeepRetrying()
                           .SetClusterGossipPort(endpoints.First().Port - 1)
                           .SetHeartbeatInterval(TimeSpan.FromSeconds(30))
                           .SetGossipTimeout(TimeSpan.FromMinutes(5))
                           .SetHeartbeatTimeout(TimeSpan.FromMinutes(5))
                           .SetTimeoutCheckPeriodTo(TimeSpan.FromMinutes(1))
                           .SetDefaultUserCredentials(cred);

            IEventStoreConnection client;

            if (hosts.Count() != 1)
            {
                settings = settings
                           .SetGossipSeedEndPoints(endpoints);

                var clusterSettings = EventStore.ClientAPI.ClusterSettings.Create()
                                      .DiscoverClusterViaGossipSeeds()
                                      .SetGossipSeedEndPoints(endpoints.Select(x => new IPEndPoint(x.Address, x.Port - 1)).ToArray())
                                      .SetGossipTimeout(TimeSpan.FromMinutes(5))
                                      .Build();

                client = EventStoreConnection.Create(settings, clusterSettings, "Riak");
            }
            else
            {
                client = EventStoreConnection.Create(settings, endpoints.First(), "Riak");
            }

            client.ConnectAsync().Wait();

            return(client);
        }
Esempio n. 11
0
        private static void RunAsService(string[] args)
        {
            logger.Info("Running as service");
            var testService = new AppWin32Service(args.Where(a => a != RunAsServiceFlag).ToArray());

            testService.OnStart += Start;
            testService.OnStop  += Stop;
            var serviceHost = new Win32ServiceHost(testService);

            serviceHost.Run();
        }
Esempio n. 12
0
        public void ConvertTest()
        {
            var p = new paypal {
                landingPage  = "a",
                addrOverride = "b"
            };

            var xmlDoc = XmlDocumentFactory.Create(p);
            var xDoc   = XDocumentFactory.CreateDocFromXmlSerializer(p);

            log.Info(xmlDoc.ToXDocument().ToString());
            log.Info(xDoc.ToXmlDocument().OuterXml);
        }
Esempio n. 13
0
        // GET: Planner
        public ActionResult Index()
        {
            _logger.Info("Plan Index invoked");
            var plans = _plannerService.GetPlans();

            return(View(plans));
        }
Esempio n. 14
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var(cluster, session) = await BootStrapCassandra(_configuration.For <Configuration.Cassandra>(), _logger).ConfigureAwait(false);

            _session = session;
            _cluster = cluster;
            var rabbitMqConfiguration = _configuration.For <Configuration.RabbitMQ>();

            _connection = BootStrapBroker(rabbitMqConfiguration);

            _consumer = await BootstrapConsumer(session, _connection, rabbitMqConfiguration).ConfigureAwait(false);

            _logger.Info("ServiceStarted");
        }
Esempio n. 15
0
        //function to get user info
        static Customer RegisterUser() //this needs to input the new user in the DB
        {
/*            //have user enter all info.
 *          Console.WriteLine("Please enter your Street and home number.");
 *          string street = Console.ReadLine();
 *          Console.WriteLine("Please enter your City.");
 *          string city = Console.ReadLine();
 *          Console.WriteLine("Please enter your Zip Code.");
 *          int zip = Convert.ToInt32(Console.ReadLine());*/

            //Customer customer1 = new Customer(fName, lName);
            Customer customer1 = new Customer();
            bool     success   = false;

            while (success == false)
            {
                try
                {
                    Console.WriteLine("\nPlease enter your First Name.");
                    string fName = Console.ReadLine();
                    customer1.CustomerFirstName = fName;
                    success = true;
                }
                catch (ArgumentException ex)
                {
                    Console.WriteLine(ex.Message);
                    s_logger.Info(ex);
                }
            }

            success = false;
            while (success == false)
            {
                try
                {
                    Console.WriteLine("\nPlease enter your Last Name.");
                    string lName = Console.ReadLine();
                    customer1.CustomerLastName = lName;
                    success = true;
                }
                catch (ArgumentException ex)
                {
                    Console.WriteLine(ex.Message);
                    s_logger.Info(ex);
                }
            }

            return(customer1);
        }//END OF Register User()
Esempio n. 16
0
        private static void OnCancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            logger?.Info(() => "SIGINT received. Exiting.");
            Console.WriteLine("SIGINT received. Exiting.");

            try
            {
                cts?.Cancel();
            }
            catch
            {
            }

            e.Cancel = true;
        }
Esempio n. 17
0
        public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddNLog();
            HostingEnvironment.ConfigureNLog($"nlog.{HostingEnvironment.EnvironmentName}.config");

            if (HostingEnvironment.IsDevelopment() || HostingEnvironment.IsStaging())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(s => s.SwaggerEndpoint("/swagger/v1/swagger.json", "Streetwood API"));
            }
            else
            {
                app.UseHsts();
                app.UseHttpsRedirection();
            }

            app.UseCors(s =>
            {
                s.AllowAnyOrigin();
                s.AllowAnyHeader();
                s.AllowAnyMethod();
            });

            app.UseAuthentication();
            app.UseStaticFiles();
            app.UseMiddleware <ExceptionHandlerMiddleware>();
            app.UseMvc();

            applicationLifetime.ApplicationStopped.Register(() => Container.Dispose());
            logger.Info("Application successfully configured.");
        }
Esempio n. 18
0
        public void Info(string msg, params object[] args)
        {
            var msg2 = string.Format("{0} - {1}", _callerClass, msg); // duh .. NLog ${callsite} does not work due to the wrapping

            try
            {
                //do not check the msg pars on each call for performace reasons
                _logger.Info(msg2, args);
            }
            catch (Exception ex)
            {
                bool msgParameterOk = !args.Any() || MessageParametersOK(msg2, args);

                if (msgParameterOk)
                {
                    // must be a logging problem
                    LogFallback(ex);
                    LogFallback(msg2);
                }
                else
                {
                    // parameter problem, probably nullpointer
                    // The logging can still have a problem, so rety without msg parameters
                    Info("Message parameter problem! " + msg);
                }
            }
        }
Esempio n. 19
0
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", false, true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
                          .AddEnvironmentVariables();

            ConfigurationExtensions.Environment = env.EnvironmentName;
            ConfigurationExtensions.Current     = builder.Build();
            //if (ConfigurationExtensions.IsDevelopment())
            //    builder.AddUserSecrets<Startup>();

            FlurlHttp.Configure(settings =>
            {
                settings.BeforeCall =
                    call => Logger.Info(new LogData("Calling api",
                                                    $"{{ \"method\": \"{call.Request?.Method}\", \"url\": \"{call.Request?.RequestUri}\", \"headers\": \"{call.Request?.Headers?.ToString()} {call.Request?.Content?.Headers?.ToString()}\", , \"content\": \"{call.Request?.Content?.ReadAsStringAsync().Result}\" }}")
                                        .ToJson());
                settings.OnError = call => Logger.Error(call.Exception,
                                                        new LogData("Error on api call",
                                                                    (call.Exception as FlurlHttpException)?.GetResponseJsonAsync().Result)
                                                        .ToJson());
            });
        }
Esempio n. 20
0
        public void Log(LogEntry entry)
        {
            _logger = GetLogger(INFO);
            switch (entry.Severity)
            {
            case LoggingEventType.Debug:
                _logger.Debug(entry.Exception, entry.Message);
                break;

            case LoggingEventType.Information:
                _logger.Info(entry.Exception, entry.Message);
                break;

            case LoggingEventType.Warning:
                _logger.Warn(entry.Exception, entry.Message);
                break;

            case LoggingEventType.Error:
                _logger.Error(entry.Exception);
                break;

            case LoggingEventType.Fatal:
                _logger.Fatal(entry.Exception, entry.Message);
                break;

            default:
                break;
            }
        }
Esempio n. 21
0
        public IActionResult SaveSection([Required] OcelotConfigSection configSection)
        {
            ConfigValidationResult result = _validator.Validate(configSection).Result;

            if (result.IsError)
            {
                _logger.Warn("Ocelot配置片段错误: " + JsonConvert.SerializeObject(result.Errors));
                return(BadRequest(result.Errors));
            }
            else
            {
                _sectionRepo.SaveOrUpdate(configSection);
                _logger.Info("保存Ocelot配置片段: " + JsonConvert.SerializeObject(configSection));
                return(Ok(configSection));
            }
        }
 public void Info(string messageFormat, params object[] parameters)
 {
     if (!Log.IsInfoEnabled)
     {
         return;
     }
     Log.Info(messageFormat, parameters);
 }
Esempio n. 23
0
        public void Init()
        {
            _logger.Info(
                "\r\n^*********************************^" +
                "\r\n!                                 !" +
                "\r\n!    VideoGate started            !" +
                "\r\n!                                 !" +
                "\r\n^*********************************^ ");

            if (DirectoryPathService.isDEBUG())
            {
                _logger.Info("DEBUG mode ON");
            }

            IDirectoryPathService directoryPathService = new DirectoryPathService();
            IConfiguration        configuration        = new ConfigurationBuilder()
                                                         .AddJsonFile(Path.Combine(directoryPathService.RootPath, "appsettings.json"))
                                                         .Build();
            IAppConfigurationFacade appConfigurationFacade = new AppConfigurationFacade(configuration);


            _logger.Info($"WebServer starting at http://+:" + appConfigurationFacade.HttpPort);


            _webHost = WebHost.CreateDefaultBuilder()
                       .UseConfiguration(configuration)
                       .ConfigureServices(provider =>
            {
                provider.TryAddSingleton <IAppConfigurationFacade>(appConfigurationFacade);
                provider.TryAddSingleton <IDirectoryPathService>(directoryPathService);
            }
                                          )
                       .UseUrls("http://+:" + appConfigurationFacade.HttpPort)
                       .UseStartup <Startup>()
                       .UseContentRoot(directoryPathService.WebContentRootPath)
                       .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Warning);
            })
                       .UseNLog()
                       .Build();


            _webHost.Start();
        }
Esempio n. 24
0
        public async Task <Responses.MinerSettings> SetMinerSettingsAsync(string poolId, string address,
                                                                          [FromBody] Requests.UpdateMinerSettingsRequest request)
        {
            var pool = GetPool(poolId);

            if (string.IsNullOrEmpty(address))
            {
                throw new ApiException("Invalid or missing miner address", HttpStatusCode.NotFound);
            }

            if (request?.Settings == null)
            {
                throw new ApiException("Invalid or missing settings", HttpStatusCode.BadRequest);
            }

            if (!IPAddress.TryParse(request.IpAddress, out var requestIp))
            {
                throw new ApiException("Invalid IP address", HttpStatusCode.BadRequest);
            }

            // fetch recent IPs
            var ips = await cf.Run(con => shareRepo.GetRecentyUsedIpAddresses(con, null, poolId, address));

            // any known ips?
            if (ips == null || ips.Length == 0)
            {
                throw new ApiException("Address not recently used for mining", HttpStatusCode.NotFound);
            }

            // match?
            if (!ips.Any(x => IPAddress.TryParse(x, out var ipAddress) && ipAddress.IsEqual(requestIp)))
            {
                throw new ApiException("None of the recently used IP addresses matches the request", HttpStatusCode.Forbidden);
            }

            // map settings
            var mapped = mapper.Map <Persistence.Model.MinerSettings>(request.Settings);

            // clamp limit
            if (pool.PaymentProcessing != null)
            {
                mapped.PaymentThreshold = Math.Max(mapped.PaymentThreshold, pool.PaymentProcessing.MinimumPayment);
            }

            mapped.PoolId  = pool.Id;
            mapped.Address = address;

            // finally update the settings
            return(await cf.RunTx(async (con, tx) =>
            {
                await minerRepo.UpdateSettings(con, tx, mapped);

                logger.Info(() => $"Updated settings for pool {pool.Id}, miner {address}");

                var result = await minerRepo.GetSettings(con, tx, mapped.PoolId, mapped.Address);
                return mapper.Map <Responses.MinerSettings>(result);
            }));
        }
Esempio n. 25
0
        static Customer LogIn(IProject0Repository projectRepository)
        {
            var customer     = new Customer();
            var customerList = projectRepository.GetCustomers();

            while (customer.FirstName == null)
            {
                _io.Output("Enter your firstName: ");
                string firstName = _io.Input();
                _io.Output("Enter your lastName: ");
                string lastName = _io.Input();
                try
                {
                    var test = customerList.First(c => c.FirstName.ToLower() == firstName && c.LastName.ToLower() == lastName);
                    customer = test;
                }
                catch (ArgumentException ex)
                {
                    _io.Output("Your name does not match our database.");
                    s_logger.Info(ex);
                    Console.WriteLine(ex.Message);
                }
            }
            return(customer);
        }
Esempio n. 26
0
 public void Info(object message)
 {
     if (IsInfoEnabled)
     {
         loger.Info(message);
     }
 }
Esempio n. 27
0
 public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager,
                         IAuthenticationManager authenticationManager, ILogger logger)
 {
     _userManager           = userManager;
     _signInManager         = signInManager;
     _authenticationManager = authenticationManager;
     _logger = logger;
     _logger.Info("");
 }
        public async Task Run()
        {
            log.Info($"SERVER START");

            try
            {
                using (var input = Console.OpenStandardInput())
                    using (var output = Console.OpenStandardOutput())
                    {
                        await RunAndWaitExit(input, output);
                    }
            }
            catch (Exception e)
            {
                log.Error($"Exception running language server: {e}");
            }

            log.Info($"SERVER END");
        }
Esempio n. 29
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  DBConnectionString : {_appSettings}");
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                //optionsBuilder.UseSqlServer("Data Source=10.200.2.116;Initial Catalog=GLP_LOPA;Persist Security Info=True;User ID=Sa;Password=Sw0rd@2020");
                optionsBuilder.UseSqlServer(_appSettings);
            }
        }
Esempio n. 30
0
        public void CreateTest()
        {
            var p = new paypal {
                landingPage  = "a",
                addrOverride = "b"
            };

            var xml = XmlDocumentFactory.Create(p);

            log.Info(xml.OuterXml);
        }
        public DataBaseContext(ILogger logger) : base ("name = TournamentDBConnection")
        {
            
            _logger = logger;
            _logger.Debug("InstanceId: " + _instanceId);


            //Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataBaseContext,MigrationConfiguration>());
            Database.SetInitializer(new DatabaseInitializer());

#if DEBUG
            Database.Log = s => Trace.Write(s);
#endif
            this.Database.Log = s => _logger.Info((s.Contains("SELECT") || s.Contains("UPDATE") || s.Contains("DELETE") || s.Contains("INSERT")) ? "\n" + s.Trim() : s.Trim());
        }