public MigrationsOperations(
            [NotNull] ILoggerProvider loggerProvider,
            [NotNull] string assemblyName,
            [NotNull] string startupAssemblyName,
            [CanBeNull] string environment,
            [NotNull] string projectDir,
            [NotNull] string rootNamespace)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));
            Check.NotEmpty(assemblyName, nameof(assemblyName));
            Check.NotEmpty(startupAssemblyName, nameof(startupAssemblyName));
            Check.NotNull(projectDir, nameof(projectDir));
            Check.NotNull(rootNamespace, nameof(rootNamespace));

            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(loggerProvider);

            _loggerProvider = loggerProvider;
            _logger = new LazyRef<ILogger>(() => loggerFactory.CreateCommandsLogger());
            _projectDir = projectDir;
            _rootNamespace = rootNamespace;
            _contextOperations = new DbContextOperations(
                loggerProvider,
                assemblyName,
                startupAssemblyName,
                environment);

            var startup = new StartupInvoker(startupAssemblyName, environment);
            _servicesBuilder = new DesignTimeServicesBuilder(startup);
        }
Beispiel #2
0
        public static void Main(string[] args)
        {
            // serilog provider configuration
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.ColoredConsole()
                .CreateLogger();

            // logger factory for program.cs - startup case
            var log = new LoggerFactory().AddSerilog().CreateLogger(typeof(Program).FullName);
            log.LogInformation("Starting from console launcher... press enter to stop.");

            // load config
            var config = new ConfigurationBuilder()
                            .AddJsonFile("analyserconf.json")
                            .Build();

            // use microsofts built in simple DI container.
            var services = new ServiceCollection();
            configureServices(services, config);
            var sp = services.BuildServiceProvider();

            IDictionary<uint, AircraftBeaconSpeedAndTrack> beaconDisplayBuffer = null;
            var events = new Dictionary<string, List<AircraftTrackEvent>>();

            // disposable pattern to stop on read-line.
            using (var analyser = sp.GetService<Core.OGNAnalyser>())
            {
                attachConsoleDisplay(beaconDisplayBuffer, events, analyser);
                Console.ReadLine();
            }
        }
 public FixUsingsFacts()
 {
     _loggerFactory = new LoggerFactory();
     _loggerFactory.AddConsole();
     _logger = _loggerFactory.CreateLogger<FixUsingsFacts>();
     _loader = new TestOmnisharpAssemblyLoader(_logger);
 }
Beispiel #4
0
        public static async Task RunSiteTest(string siteName, ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, string applicationBaseUrl,
            Func<HttpClient, ILogger, CancellationToken, Task> validator)
        {
            var logger = new LoggerFactory()
                            .AddConsole()
                            .CreateLogger(string.Format("{0}:{1}:{2}:{3}", siteName, serverType, runtimeFlavor, architecture));

            using (logger.BeginScope("RunSiteTest"))
            {
                var deploymentParameters = new DeploymentParameters(GetPathToApplication(siteName), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint = applicationBaseUrl,
                    SiteName = "HttpTestSite",
                };

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult = deployer.Deploy();
                    var httpClientHandler = new HttpClientHandler();
                    var httpClient = new HttpClient(httpClientHandler)
                    {
                        BaseAddress = new Uri(deploymentResult.ApplicationBaseUri),
                        Timeout = TimeSpan.FromSeconds(10)
                    };

                    await validator(httpClient, logger, deploymentResult.HostShutdownToken);
                }
            }
        }
Beispiel #5
0
        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            var sqlLoggerFactory = new LoggerFactory();
            sqlLoggerFactory.AddConsole(Configuration.GetSection("SqlLogging"));

            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddMvc();

            var entityFramework = services;
            entityFramework= entityFramework
                .AddEntityFrameworkSqlServer()
                .AddDbContext<DDDContext>(options =>
                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"],
                x => x.MigrationsAssembly("DDDCore.Application"))
                .UseLoggerFactory(sqlLoggerFactory));

            //Domain
            services.AddScoped<IClienteService, ClienteService>();

            //infra
            services.AddScoped<IClienteRepository, ClienteRepository>();
            services.AddScoped<DDDContext>();
        }
Beispiel #6
0
 public Program(IRuntimeEnvironment runtimeEnv)
 {
     var loggerFactory = new LoggerFactory();
     CommandOutputProvider = new CommandOutputProvider(runtimeEnv);
     loggerFactory.AddProvider(CommandOutputProvider);
     Logger = loggerFactory.CreateLogger<Program>();
 }
        public void ClassesWithOwnInterfacesAreRegisteredOnlyInterfaceTypes()
        {
            var logerFactory = new LoggerFactory();
            var services = new ServiceCollection();
            var registrationConvention = new DefaultRegistrationConvention(logerFactory);

            var types = new HashSet<Type>
            {
                typeof(TransientInterfacedClass),
                typeof(ScopedInterfacedClass),
                typeof(SingletoneInterfacedClass),
            };

            registrationConvention.RegisterServices(types, services);

            Assert.Equal(3, services.Count);

            Assert.Equal(ServiceLifetime.Transient, services[0].Lifetime);
            Assert.Equal(typeof(ITransientInterface), services[0].ServiceType);

            Assert.Equal(ServiceLifetime.Scoped, services[1].Lifetime);
            Assert.Equal(typeof(IScopedInterface), services[1].ServiceType);

            Assert.Equal(ServiceLifetime.Singleton, services[2].Lifetime);
            Assert.Equal(typeof(ISingletoneInterface), services[2].ServiceType);
        }
Beispiel #8
0
 static void Main(string[] args)
 {
     var appName = "Sample";
     var factory = new LoggerFactory();
     factory.AddFile();
     var logger = factory.CreateLogger(appName);
     logger.LogInformation("Application Start!");
     logger.LogInformation("Hello Boy!");
     try
     {
         try
         {
             int.Parse("a");
         }
         catch (Exception ex)
         {
             throw new Exception("解析数字时发生错误", ex);
         }
     }
     catch (Exception ex2)
     {
         logger.LogError("这里是写入错误测试消息", ex2);
     }
     logger.LogInformation("Application End!");
     Thread.Sleep(1000);
 }
        public CodingActionsV2Facts()
        {
            _loggerFactory = new LoggerFactory();
            _loggerFactory.AddConsole();
            _logger = _loggerFactory.CreateLogger<CodingActionsV2Facts>();

            _loader = new TestOmnisharpAssemblyLoader(_logger);
        }
 public static ConfigurationBuilderCachePart WithMicrosoftLogging(this ConfigurationBuilderCachePart part, Action<ILoggerFactory> factory)
 {
     NotNull(part, nameof(part));
     NotNull(factory, nameof(factory));
     var externalFactory = new LoggerFactory();
     factory(externalFactory);
     return part.WithLogging(typeof(MicrosoftLoggerFactoryAdapter), externalFactory);
 }
        public async Task NtlmAuthenticationTest(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, string applicationBaseUrl)
        {
            var logger = new LoggerFactory()
                            .AddConsole(LogLevel.Warning)
                            .CreateLogger(string.Format("Ntlm:{0}:{1}:{2}", serverType, runtimeFlavor, architecture));

            using (logger.BeginScope("NtlmAuthenticationTest"))
            {
                var musicStoreDbName = Guid.NewGuid().ToString().Replace("-", string.Empty);
                var connectionString = string.Format(DbUtils.CONNECTION_STRING_FORMAT, musicStoreDbName);

                var deploymentParameters = new DeploymentParameters(Helpers.GetApplicationPath(), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint = applicationBaseUrl,
                    EnvironmentName = "NtlmAuthentication", //Will pick the Start class named 'StartupNtlmAuthentication'
                    ApplicationHostConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("NtlmAuthentation.config") : null,
                    SiteName = "MusicStoreNtlmAuthentication", //This is configured in the NtlmAuthentication.config
                    UserAdditionalCleanup = parameters =>
                    {
                        if (!Helpers.RunningOnMono)
                        {
                            // Mono uses InMemoryStore
                            DbUtils.DropDatabase(musicStoreDbName, logger);
                        }
                    }
                };

                // Override the connection strings using environment based configuration
                deploymentParameters.EnvironmentVariables
                    .Add(new KeyValuePair<string, string>(
                        "SQLAZURECONNSTR_DefaultConnection",
                        string.Format(DbUtils.CONNECTION_STRING_FORMAT, musicStoreDbName)));

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult = deployer.Deploy();
                    var httpClientHandler = new HttpClientHandler() { UseDefaultCredentials = true };
                    var httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(deploymentResult.ApplicationBaseUri) };

                    // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                    var response = await RetryHelper.RetryRequest(async () =>
                    {
                        return await httpClient.GetAsync(string.Empty);
                    }, logger: logger, cancellationToken: deploymentResult.HostShutdownToken);

                    Assert.False(response == null, "Response object is null because the client could not " +
                        "connect to the server after multiple retries");

                    var validator = new Validator(httpClient, httpClientHandler, logger, deploymentResult);
                    await validator.VerifyNtlmHomePage(response);

                    //Should be able to access the store as the Startup adds necessary permissions for the current user
                    await validator.AccessStoreWithPermissions();

                    logger.LogInformation("Variation completed successfully.");
                }
            }
        }
        public static IServiceCollection AddLogging(IServiceCollection services)
        {
            var loggerFactory = new LoggerFactory();
            loggerFactory.AddNLog();

            services.AddSingleton<ILoggerFactory>(loggerFactory);

            return services;
        }
        private async Task OpenIdConnectTestSuite(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, string applicationBaseUrl)
        {
            var logger = new LoggerFactory()
                            .AddConsole(LogLevel.Warning)
                            .CreateLogger(string.Format("OpenId:{0}:{1}:{2}", serverType, runtimeFlavor, architecture));

            using (logger.BeginScope("OpenIdConnectTestSuite"))
            {
                var musicStoreDbName = Guid.NewGuid().ToString().Replace("-", string.Empty);
                var connectionString = string.Format(DbUtils.CONNECTION_STRING_FORMAT, musicStoreDbName);

                var deploymentParameters = new DeploymentParameters(Helpers.GetApplicationPath(), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint = applicationBaseUrl,
                    EnvironmentName = "OpenIdConnectTesting",
                    UserAdditionalCleanup = parameters =>
                    {
                        if (!Helpers.RunningOnMono
                            && TestPlatformHelper.IsWindows)
                        {
                            // Mono uses InMemoryStore
                            DbUtils.DropDatabase(musicStoreDbName, logger);
                        }
                    }
                };

                // Override the connection strings using environment based configuration
                deploymentParameters.EnvironmentVariables
                    .Add(new KeyValuePair<string, string>(
                        "SQLAZURECONNSTR_DefaultConnection",
                        string.Format(DbUtils.CONNECTION_STRING_FORMAT, musicStoreDbName)));

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult = deployer.Deploy();
                    var httpClientHandler = new HttpClientHandler() { AllowAutoRedirect = false };
                    var httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(deploymentResult.ApplicationBaseUri) };

                    // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                    var response = await RetryHelper.RetryRequest(async () =>
                    {
                        return await httpClient.GetAsync(string.Empty);
                    }, logger: logger, cancellationToken: deploymentResult.HostShutdownToken);

                    Assert.False(response == null, "Response object is null because the client could not " +
                        "connect to the server after multiple retries");

                    var validator = new Validator(httpClient, httpClientHandler, logger, deploymentResult);
                    await validator.VerifyHomePage(response);

                    // OpenIdConnect login.
                    await validator.LoginWithOpenIdConnect();

                    logger.LogInformation("Variation completed successfully.");
                }
            }
        }
Beispiel #14
0
        public async Task HelloWorld(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, string applicationBaseUrl, ServerType delegateServer, ApplicationType applicationType)
        {
            var logger = new LoggerFactory()
                            .AddConsole()
                            .AddDebug()
                            .CreateLogger($"HelloWorld:{serverType}:{runtimeFlavor}:{architecture}:{delegateServer}");

            using (logger.BeginScope("HelloWorldTest"))
            {
                var deploymentParameters = new DeploymentParameters(Helpers.GetTestSitesPath(applicationType), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint = applicationBaseUrl,
                    EnvironmentName = "HelloWorld", // Will pick the Start class named 'StartupHelloWorld',
                    ServerConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("Http.config") : null,
                    SiteName = "HttpTestSite", // This is configured in the Http.config
                    TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
                    ApplicationType = applicationType
                };

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult = deployer.Deploy();
                    var httpClientHandler = new HttpClientHandler();
                    var httpClient = new HttpClient(httpClientHandler)
                    {
                        BaseAddress = new Uri(deploymentResult.ApplicationBaseUri),
                        Timeout = TimeSpan.FromSeconds(5),
                    };

                    // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                    var response = await RetryHelper.RetryRequest(() =>
                    {
                        return httpClient.GetAsync(string.Empty);
                    }, logger, deploymentResult.HostShutdownToken, retryCount: 30);

                    var responseText = await response.Content.ReadAsStringAsync();
                    try
                    {
                        Assert.Equal("Hello World", responseText);

                        response = await httpClient.GetAsync("/Path%3F%3F?query");
                        responseText = await response.Content.ReadAsStringAsync();
                        Assert.Equal("/Path??", responseText);

                        response = await httpClient.GetAsync("/Query%3FPath?query?");
                        responseText = await response.Content.ReadAsStringAsync();
                        Assert.Equal("?query?", responseText);
                    }
                    catch (XunitException)
                    {
                        logger.LogWarning(response.ToString());
                        logger.LogWarning(responseText);
                        throw;
                    }
                }
            }
        }
        public void SettingsConstructor__WithLoggerFactorySucceeds()
        {
            // Arrange
            LoggerFactory logFactory = new LoggerFactory();
            ConfigServerClientSettings settings = new ConfigServerClientSettings();

            // Act and Assert
            var provider = new ConfigServerConfigurationProvider(settings, logFactory);
            Assert.NotNull(provider.Logger);
        }
Beispiel #16
0
        /// <summary>
        ///  Adds a console logger. Can be omitted if internal SIPSorcery debug and warning messages are not required.
        /// </summary>
        private static void AddConsoleLogger()
        {
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug)
                                .WriteTo.Console()
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);
            SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;
        }
Beispiel #17
0
        public Logger(LoggerFactory loggerFactory, string name)
        {
            _loggerFactory = loggerFactory;
            _name = name;

            var providers = loggerFactory.GetProviders();
            _loggers = new ILogger[providers.Length];
            for (var index = 0; index != providers.Length; index++)
            {
                _loggers[index] = providers[index].CreateLogger(name);
            }
        }
        public void ClassesWithSomeInterfacesAreNotRegistered()
        {
            var logerFactory = new LoggerFactory();
            var services = new ServiceCollection();
            var registrationConvention = new DefaultRegistrationConvention(logerFactory);

            var types = new HashSet<Type> { typeof(ClassWithSomeInterface) };

            registrationConvention.RegisterServices(types, services);

            Assert.Equal(0, services.Count);
        }
        public TaskRunnerTests()
        {
            var lf = new LoggerFactory();
            lf.AddConsole();

            var serviceProvider = new ServiceCollection()
                .AddTransient(_ => new SampleTask(settings))
                .BuildServiceProvider();

            sampleTask = new TaskRunner<SampleTask>(lf, serviceProvider.GetService<IServiceScopeFactory>());
            sampleTask.Interval = TimeSpan.FromSeconds(5);
        }
Beispiel #20
0
        /// <summary>
        /// Wires up the dotnet logging infrastructure to STDOUT.
        /// </summary>
        private static void EnableConsoleLogger()
        {
            // Logging configuration. Can be omitted if internal SIPSorcery debug and warning messages are not required.
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug)
                                .WriteTo.Console()
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);
            SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;
        }
Beispiel #21
0
        private static void InitializeDatabaseFactory()
        {
            LoggingConfiguration factoryConfiguration = new LoggingConfiguration();

            // All messages from Trace to Warn levels write to the general file
            FileTarget fileTarget_DatabaseGeneral = new FileTarget()
            {
                Name             = $"{Constants.ApplicationNameFormatted}Database",
                FileName         = Path.Combine(Constants.LogDirectory, "Database.General.log"),
                Layout           = "${longdate} [${pad:padCharacter= :padding=5:fixedLength=true:alignmentOnTruncation=Right:${uppercase:${level}}}] [${callsite:includeNamespace=false:cleanNamesOfAnonymousDelegates=true:cleanNamesOfAsyncContinuations=true}] ${message}",
                ArchiveFileName  = Path.Combine(Constants.LogDirectory, "Database.General{#}.Archive.log"),
                ArchiveEvery     = FileArchivePeriod.Day,
                ArchiveNumbering = ArchiveNumberingMode.Rolling,
                MaxArchiveFiles  = 7,
                ConcurrentWrites = false
            };
            // Limit how often the file will get written to disk.
            // Default: BufferSize = 50 (log events), FlushTimeout = 5000 (milliseconds)
            BufferingTargetWrapper fileAsyncTargetWrapper_DatabaseGeneral = new BufferingTargetWrapper {
                Name           = $"{Constants.ApplicationNameFormatted}Database",
                WrappedTarget  = fileTarget_DatabaseGeneral,
                BufferSize     = 75,
                FlushTimeout   = 5000,
                SlidingTimeout = false
            };

            factoryConfiguration.AddTarget(fileAsyncTargetWrapper_DatabaseGeneral);
            factoryConfiguration.AddRule(LogLevel.Info, LogLevel.Warn, $"{Constants.ApplicationNameFormatted}Database");

            // All messages from Warn to Fatal levels write to the error file with advanced trace information
            FileTarget fileTarget_DatabaseError = new FileTarget()
            {
                Name             = $"{Constants.ApplicationNameFormatted}Database",
                FileName         = Path.Combine(Constants.LogDirectory, "Database.Error.log"),
                Layout           = "${longdate} [${pad:padCharacter= :padding=5:fixedLength=true:alignmentOnTruncation=Right:${uppercase:${level}}}] [${callsite:includeSourcePath=true:cleanNamesOfAnonymousDelegates=true:cleanNamesOfAsyncContinuations=true}:${callsite-linenumber}; ${stacktrace}] ${message}${exception:format=ToString,StackTrace}",
                ArchiveFileName  = Path.Combine(Constants.LogDirectory, "Database.Error{#}.Archive.log"),
                ArchiveEvery     = FileArchivePeriod.Day,
                ArchiveNumbering = ArchiveNumberingMode.Rolling,
                MaxArchiveFiles  = 7,
                ConcurrentWrites = false
            };

            factoryConfiguration.AddTarget(fileTarget_DatabaseError);
            factoryConfiguration.AddRule(LogLevel.Error, LogLevel.Fatal, $"{Constants.ApplicationNameFormatted}Database");

            _DatabaseFactoryNLog = new LogFactory(factoryConfiguration);
            NLogLoggerProvider loggerProvider = new NLogLoggerProvider(new NLogProviderOptions(), _DatabaseFactoryNLog);

            DatabaseFactory = new MSLogging.LoggerFactory(new[] { loggerProvider });
        }
Beispiel #22
0
        public static void Main(string[] args)
        {
            ILoggerFactory loggerFactory = new LoggerFactory();
            _eventPublisher = new MessageBus(loggerFactory);
            RegisterHandlers(_eventPublisher);
            
            var connection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 1113));
            connection.ConnectAsync().Wait();

            // var subscription = connection.SubscribeToAllAsync(true, Appeared, Dropped, new UserCredentials("admin", "changeit")).Result;
            var subscription = connection.SubscribeToAllFrom(Position.Start, true, Appeared, null, Dropped, new UserCredentials("admin", "changeit"));

            Console.Read();
        }
Beispiel #23
0
    /// <summary>
    /// Creates a LoggerFactory from the given log filename
    /// </summary>
    /// <param name="logFileName"></param>
    /// <returns></returns>
    private static LoggerFactory CreateLoggerFactory(string logFileName)
    {
        Log.Logger = new LoggerConfiguration()
                     .WriteTo.File(logFileName, rollingInterval: RollingInterval.Month,
                                   outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}{NewLine}",
                                   restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Warning)
                     .WriteTo.Console(outputTemplate: "{Message:lj}{NewLine}")
                     .CreateLogger();

        var factory = new LoggerFactory();

        factory.AddSerilog(Log.Logger);
        return(factory);
    }
Beispiel #24
0
        //private static Microsoft.Extensions.Logging.ILogger logger = SIPSorcery.Sys.Log.Logger;

        public static void InitTestLogger(ITestOutputHelper output)
        {
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .MinimumLevel.Verbose()
                                .WriteTo.TestOutput(output, Serilog.Events.LogEventLevel.Verbose)
                                .WriteTo.Console(Serilog.Events.LogEventLevel.Verbose)
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);

            SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;
            //logger = SIPSorcery.Sys.Log.Logger;
        }
        public DefaultLoggerFactory(IConfigAccessor configAccessor)
        {
            _loggingConfig = configAccessor.Get <LoggingConfig>();
            _loggerFactory = new MSLoggerFactory();
            var instrumentationConfig = configAccessor.Get <InstrumentationConfig>();

            var level = EventLevel(_loggingConfig.Level);

            _loggerFactory.AddSerilog(new LoggerConfiguration().MinimumLevel.Verbose().Enrich
                                      .WithProperty("SourceContext", null).Enrich
                                      .WithProperty(nameof(instrumentationConfig.ServiceName),
                                                    instrumentationConfig.ServiceName ?? instrumentationConfig.ApplicationCode).Enrich
                                      .FromLogContext().WriteTo.RollingFile(_loggingConfig.FilePath, level, outputTemplate, null, 1073741824,
                                                                            31, null, false, false, TimeSpan.FromMilliseconds(500)).CreateLogger());
        }
        public void AspNetCoreLogging_MinLogLevel_Warn()
        {
            var external = new LoggerFactory();
            external.AddConsole(LogLevel.Warning);
            var loggerFactory = new MicrosoftLoggerFactoryAdapter(external);
            var logger = loggerFactory.CreateLogger("cat");

            logger.Should().NotBeNull();
            logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse();
            logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeFalse();
            logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeFalse();
            logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeTrue();
            logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue();
            logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue();
        }
Beispiel #27
0
        private static async void RunProgram()
        {
            try
            {
                var serilogPlcMqtt = new Microsoft.Extensions.Logging.LoggerFactory().AddSerilog(Log.Logger).CreateLogger <PlcMqttConnection>();
                _mqttmaganer = new PlcMqttConnection(_settings, serilogPlcMqtt);;
                _mqttmaganer.OnSetCommandReceived     += Mqttmaganer_OnSetCommandReceived;
                _mqttmaganer.OnMqttClientConnected    += Mqttmaganer_OnMqttClientConnected;
                _mqttmaganer.OnMqttClientDisconnected += Mqttmaganer_OnMqttClientDisconnected;
                Log.Information("Connecting to Mqtt using {ip}:{port}", _settings.MqttBroker_IPAddress, _settings.MqttBroker_Port);
                await _mqttmaganer.ConnectAsync();


                var serilogPlcConnector    = new Microsoft.Extensions.Logging.LoggerFactory().AddSerilog(Log.Logger).CreateLogger <PLCMitsubishiConnector>();
                PLCMitsubishiConnector plc = new PLCMitsubishiConnector(_settings, serilogPlcConnector);

                var serilogPlcManager = new Microsoft.Extensions.Logging.LoggerFactory().AddSerilog(Log.Logger).CreateLogger <PLCMitsubishiManager>();
                _plcMonitoring = new PLCMitsubishiManager(plc, serilogPlcManager);
                _plcMonitoring.OnMemoryChangeValue         += PlcMonitoring_OnMemoryChangeValue;
                _plcMonitoring.OnConnectedToPlcDevice      += PlcMonitoring_OnConnectedToPlcDevice;
                _plcMonitoring.OnDisconnectedFromPlcDevice += PlcMonitoring_OnDisconnectedFromPlcDevice;
                _plcMonitoring.AddMemoriesFromSettings(_settings);

                while (true)
                {
                    var key = Console.ReadKey(true);
                    if (key.Key == ConsoleKey.S)
                    {
                        lock (_consoleLock)
                        {
                            PrintStatus();
                            continue;
                        }
                    }
                    if (key.Key == ConsoleKey.C)
                    {
                        lock (_consoleLock)
                        {
                            Console.Clear();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Logger.Fatal(ex, "Failure during program running");
            }
        }
        public async Task HelloWorld(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, string applicationBaseUrl, ServerType delegateServer)
        {
            var logger = new LoggerFactory()
                            .AddConsole()
                            .CreateLogger($"HelloWorld:{serverType}:{runtimeFlavor}:{architecture}:{delegateServer}");

            using (logger.BeginScope("HelloWorldTest"))
            {
                var deploymentParameters = new DeploymentParameters(Helpers.GetTestSitesPath(), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint = applicationBaseUrl,
                    Command = delegateServer == ServerType.WebListener ? "weblistener" : "web",
                    PublishWithNoSource = true, // Always publish with no source, otherwise it can't build and sign IISPlatformHandler
                    EnvironmentName = "HelloWorld", // Will pick the Start class named 'StartupHelloWorld',
                    ApplicationHostConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("Http.config") : null,
                    SiteName = "HttpTestSite", // This is configured in the Http.config
                };

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult = deployer.Deploy();
                    var httpClientHandler = new HttpClientHandler();
                    var httpClient = new HttpClient(httpClientHandler)
                    {
                        BaseAddress = new Uri(deploymentResult.ApplicationBaseUri),
                        Timeout = TimeSpan.FromSeconds(5),
                    };

                    // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                    var response = await RetryHelper.RetryRequest(() =>
                    {
                        return httpClient.GetAsync(string.Empty);
                    }, logger, deploymentResult.HostShutdownToken, retryCount: 30);

                    var responseText = await response.Content.ReadAsStringAsync();
                    try
                    {
                        Assert.Equal("Hello World", responseText);
                    }
                    catch (XunitException)
                    {
                        logger.LogWarning(response.ToString());
                        logger.LogWarning(responseText);
                        throw;
                    }
                }
            }
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                //.Enrich.FromLogContext()
                                .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug)
                                .WriteTo.Console(theme: AnsiConsoleTheme.Code)
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);
            SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;
            logger = SIPSorcery.Sys.Log.Logger;

            var result = Parser.Default.ParseArguments <Options>(args)
                         .WithParsed <Options>(opts => RunCommand(opts).Wait());
        }
Beispiel #30
0
 public static void Main()
 {
   try
   {
     // 
     var loggerFactory = new LoggerFactory().AddConsole();
     CreateLogger(loggerFactory);
     _logger.LogInformation("Start");
     RunAsync().Wait();
   }
   catch (Exception E)
   {
     _logger.LogError(E.Message + ", " + E.InnerException ?? "no InnerException available");
     Console.ReadKey();
   }
 }
Beispiel #31
0
        /// <summary>
        /// Enable detailed SIP log messages.
        /// </summary>
        private static void EnableTraceLogs(SIPTransport sipTransport)
        {
            // Logging configuration. Can be ommitted if internal SIPSorcery debug and warning messages are not required.
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug)
                                .WriteTo.Console()
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);
            SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;

            sipTransport.SIPRequestInTraceEvent += (localEP, remoteEP, req) =>
            {
                Log.LogDebug($"Request received: {localEP}<-{remoteEP}");
                Log.LogDebug(req.ToString());
            };

            sipTransport.SIPRequestOutTraceEvent += (localEP, remoteEP, req) =>
            {
                Log.LogDebug($"Request sent: {localEP}->{remoteEP}");
                Log.LogDebug(req.ToString());
            };

            sipTransport.SIPResponseInTraceEvent += (localEP, remoteEP, resp) =>
            {
                Log.LogDebug($"Response received: {localEP}<-{remoteEP}");
                Log.LogDebug(resp.ToString());
            };

            sipTransport.SIPResponseOutTraceEvent += (localEP, remoteEP, resp) =>
            {
                Log.LogDebug($"Response sent: {localEP}->{remoteEP}");
                Log.LogDebug(resp.ToString());
            };

            sipTransport.SIPRequestRetransmitTraceEvent += (tx, req, count) =>
            {
                Log.LogDebug($"Request retransmit {count} for request {req.StatusLine}, initial transmit {DateTime.Now.Subtract(tx.InitialTransmit).TotalSeconds.ToString("0.###")}s ago.");
            };

            sipTransport.SIPResponseRetransmitTraceEvent += (tx, resp, count) =>
            {
                Log.LogDebug($"Response retransmit {count} for response {resp.ShortDescription}, initial transmit {DateTime.Now.Subtract(tx.InitialTransmit).TotalSeconds.ToString("0.###")}s ago.");
            };
        }
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.LiterateConsole()
                .CreateLogger();

            var logger = new LoggerFactory()
                .AddSerilog()
                .CreateLogger(typeof(Program).FullName);

            logger.LogInformation("Starting");

            var startTime = DateTimeOffset.UtcNow;
            logger.LogInformation(1, "Started at {StartTime} and 0x{Hello:X} is hex of 42", startTime, 42);

            try
            {
                throw new Exception("Boom");
            }
            catch (Exception ex)
            {
                logger.LogCritical("Unexpected critical error starting application", ex);
                logger.Log(LogLevel.Critical, 0, "Unexpected critical error", ex, null);
                // This write should not log anything
                logger.Log(LogLevel.Critical, 0, null, null, null);
                logger.LogError("Unexpected error", ex);
                logger.LogWarning("Unexpected warning", ex);
            }

            using (logger.BeginScope("Main"))
            {
                logger.LogInformation("Waiting for user input");
                var key = Console.Read();
                logger.LogInformation("User pressed {@KeyInfo}", new { Key = key, KeyChar = (char)key });
            }

            var endTime = DateTimeOffset.UtcNow;
            logger.LogInformation(2, "Stopping at {StopTime}", endTime);

            logger.LogInformation("Stopping");

            logger.LogInformation(Environment.NewLine);
            logger.LogInformation("{Result,-10:l}{StartTime,15:l}{EndTime,15:l}{Duration,15:l}", "RESULT", "START TIME", "END TIME", "DURATION(ms)");
            logger.LogInformation("{Result,-10:l}{StartTime,15:l}{EndTime,15:l}{Duration,15:l}", "------", "----- ----", "--- ----", "------------");
            logger.LogInformation("{Result,-10:l}{StartTime,15:mm:s tt}{EndTime,15:mm:s tt}{Duration,15}", "SUCCESS", startTime, endTime, (endTime - startTime).TotalMilliseconds);
        }
Beispiel #33
0
        public static int Main(string[] args)
        {
            var app = new CommandLineApplication();
            app.Name = "dotnet-projectmodel-server";
            app.Description = ".NET Project Model Server";
            app.FullName = ".NET Design Time Server";
            app.Description = ".NET Design Time Server";
            app.HelpOption("-?|-h|--help");

            var verbose = app.Option("--verbose", "Verbose ouput", CommandOptionType.NoValue);
            var hostpid = app.Option("--host-pid", "The process id of the host", CommandOptionType.SingleValue);
            var hostname = app.Option("--host-name", "The name of the host", CommandOptionType.SingleValue);
            var port = app.Option("--port", "The TCP port used for communication", CommandOptionType.SingleValue);

            app.OnExecute(() =>
            {
                var loggerFactory = new LoggerFactory();
                loggerFactory.AddConsole(verbose.HasValue() ? LogLevel.Debug : LogLevel.Information);

                var logger = loggerFactory.CreateLogger<Program>();

                if (!MonitorHostProcess(hostpid, logger))
                {
                    return 1;
                }

                var intPort = CheckPort(port, logger);
                if (intPort == -1)
                {
                    return 1;
                }

                if (!hostname.HasValue())
                {
                    logger.LogError($"Option \"{hostname.LongName}\" is missing.");
                    return 1;
                }

                var program = new Program(intPort, hostname.Value(), loggerFactory);
                program.OpenChannel();

                return 0;
            });

            return app.Execute(args);
        }
Beispiel #34
0
        public async Task RunTestAndVerifyResponse(
            RuntimeFlavor runtimeFlavor,
            RuntimeArchitecture runtimeArchitechture,
            string applicationBaseUrl,
            string environmentName,
            string locale,
            string expectedText)
        {
            var logger = new LoggerFactory()
                            .AddConsole()
                            .CreateLogger(string.Format("Localization Test Site:{0}:{1}:{2}", ServerType.Kestrel, runtimeFlavor, runtimeArchitechture));

            using (logger.BeginScope("LocalizationTest"))
            {
                var deploymentParameters = new DeploymentParameters(GetApplicationPath(), ServerType.Kestrel, runtimeFlavor, runtimeArchitechture)
                {
                    ApplicationBaseUriHint = applicationBaseUrl,
                    Command = "web",
                    EnvironmentName = environmentName
                };

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult = deployer.Deploy();

                    var cookie = new Cookie("ASPNET_CULTURE", "c=" + locale + "|uic=" + locale);
                    var cookieContainer = new CookieContainer();
                    cookieContainer.Add(new Uri(deploymentResult.ApplicationBaseUri), cookie);

                    var httpClientHandler = new HttpClientHandler();
                    httpClientHandler.CookieContainer = cookieContainer;

                    var httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(deploymentResult.ApplicationBaseUri) };

                    // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                    var response = await RetryHelper.RetryRequest(() =>
                    {
                        return httpClient.GetAsync(string.Empty);
                    }, logger, deploymentResult.HostShutdownToken);

                    var responseText = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Response Text " + responseText);
                    Assert.Equal(expectedText, responseText);
                }
            }
        }
Beispiel #35
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            // attempt to make a global exception handler to avoid crashes
            // https://social.msdn.microsoft.com/Forums/vstudio/en-US/c37599d9-21e8-4c32-b00e-926f97c8f639/global-exception-handler-for-vs-2008-excel-addin?forum=vsto
            // https://stackoverflow.com/questions/12115030/catch-c-sharp-wpf-unhandled-exception-in-word-add-in-before-microsoft-displays-e
            // https://exceptionalcode.wordpress.com/2010/02/17/centralizing-vsto-add-in-exception-management-with-postsharp/
            // https://www.add-in-express.com/forum/read.php?FID=5&TID=12667
            RegisterToExceptionEvents();

            var myUserControl1 = new ucApiCredentials();

            apiCredentialsTaskPane = this.CustomTaskPanes.Add(myUserControl1, "API Credentials");
            apiCredentialsTaskPane.VisibleChanged +=
                new EventHandler(myCustomTaskPane_VisibleChanged);

            // instantiate and configure logging. Using serilog here, to log to console and a text-file.
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .MinimumLevel.Debug()
                                .WriteTo.Console()
#pragma warning disable S1075 // URIs should not be hardcoded
                                .WriteTo.File("c:\\temp\\logs\\myapp.txt", rollingInterval: RollingInterval.Day)
#pragma warning restore S1075 // URIs should not be hardcoded
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);

            // create logger and put it to work.
            var logProvider = loggerFactory.CreateLogger <ThisAddIn>();

            logProvider.LogDebug("debiggung");
            Logger = logProvider;

            // Configure PostSharp Logging to use Serilog
            LoggingServices.DefaultBackend = new MicrosoftLoggingBackend(loggerFactory);

            Globals.ThisAddIn.ApiUrl      = Settings.Default?.ApiUrl;
            Globals.ThisAddIn.ApiUsername = Settings.Default?.ApiUsername;
            Globals.ThisAddIn.OWAUrl      = Settings.Default?.OWAUrl;
            Globals.ThisAddIn.OWAUsername = Settings.Default?.OWAUsername;

            this.Application.WorkbookActivate += Application_WorkbookActivate;
            this.Application.WorkbookOpen     += Application_WorkbookOpen;
        }
Beispiel #36
0
        static void Main(string[] args)
        {
            Console.WriteLine("SIPSorcery registration user agent example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Logging configuration. Can be ommitted if internal SIPSorcery debug and warning messages are not required.
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug)
                                .WriteTo.Console()
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);
            SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;

            // If your default DNS server supports SRV records there is no need to set a specific DNS server.
            DNSManager.SetDNSServers(new List <IPEndPoint> {
                IPEndPoint.Parse("8.8.8.8:53")
            });

            // Set up a default SIP transport.
            var sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());
            int port         = FreePort.FindNextAvailableUDPPort(SIPConstants.DEFAULT_SIP_PORT);
            var sipChannel   = new SIPUDPChannel(new IPEndPoint(LocalIPConfig.GetDefaultIPv4Address(), port));

            sipTransport.AddSIPChannel(sipChannel);

            // Create a client user agent to maintain a periodic registration with a SIP server.
            var regUserAgent = new SIPRegistrationUserAgent(
                sipTransport,
                "softphonesample",
                "password",
                "sipsorcery.com");

            // Event handlers for the different stages of the registration.
            regUserAgent.RegistrationFailed           += (uri, err) => SIPSorcery.Sys.Log.Logger.LogError($"{uri.ToString()}: {err}");
            regUserAgent.RegistrationTemporaryFailure += (uri, msg) => SIPSorcery.Sys.Log.Logger.LogWarning($"{uri.ToString()}: {msg}");
            regUserAgent.RegistrationRemoved          += (uri) => SIPSorcery.Sys.Log.Logger.LogError($"{uri.ToString()} registration failed.");
            regUserAgent.RegistrationSuccessful       += (uri) => SIPSorcery.Sys.Log.Logger.LogInformation($"{uri.ToString()} registration succeeded.");

            // Start the thread to perform the initial registration and then periodically resend it.
            regUserAgent.Start();
        }
Beispiel #37
0
        public static IServiceCollection ConfigureLogging(this IServiceCollection services)
        {
            // instantiate and configure logging. Using serilog here, to log to console and a text-file.
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .WriteTo.Console()
                                //.WriteTo.File("logs\\myapp.txt", rollingInterval: RollingInterval.Day)
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);

            // create logger and put it to work.
            var logProvider = loggerFactory.CreateLogger("DotNetCoreWCF.Client");

            services.AddSingleton <ILoggerFactory>(loggerFactory);
            services.AddSingleton <Microsoft.Extensions.Logging.ILogger>(logProvider);

            return(services);
        }
        private static RouteContext CreateRouteContext(string requestPath, ILoggerFactory factory = null)
        {
            if (factory == null)
            {
                factory = new LoggerFactory();
            }

            var request = new Mock<HttpRequest>(MockBehavior.Strict);
            request.SetupGet(r => r.Path).Returns(new PathString(requestPath));

            var context = new Mock<HttpContext>();
            context.SetupGet(c => c.Items)
                   .Returns(new Dictionary<object, object>());
            context.Setup(m => m.RequestServices.GetService(typeof(ILoggerFactory)))
                .Returns(factory);
            context.SetupGet(c => c.Request).Returns(request.Object);

            return new RouteContext(context.Object);
        }
Beispiel #39
0
        public static IUnityContainer ConfigureLogging(this IUnityContainer container)
        {
            // instantiate and configure logging. Using serilog here, to log to console and a text-file.
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .WriteTo.Console()
                                //.WriteTo.File("logs\\myapp.txt", rollingInterval: RollingInterval.Day)
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);

            // create logger and put it to work.
            var logProvider = loggerFactory.CreateLogger("DotNetCoreWCF.Host");

            container.RegisterInstance <ILoggerFactory>(loggerFactory);
            container.RegisterInstance <Microsoft.Extensions.Logging.ILogger>(logProvider);

            return(container);
        }
Beispiel #40
0
        protected void Application_Start()
        {
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();

            Log.Logger = new Serilog.LoggerConfiguration()
                         .Enrich.WithHttpRequestId()
                         .Enrich.WithHttpRequestType()
                         .Enrich.WithHttpRequestRawUrl()
                         .Enrich.WithMachineName()
                         .Enrich.WithProperty("CPU", Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER"))
                         .WriteTo.File(Server.MapPath("~/App_Data/logs.txt"))
                         .WriteTo.Seq("http://localhost:5341")
                         .MinimumLevel.Debug()
                         .CreateLogger();

            loggerFactory.AddSerilog(Log.Logger);

            // create logger and put it to work.
            var logProvider = loggerFactory.CreateLogger <MvcApplication>();

            logProvider.LogInformation("Hi Serilog!");

            var container = new Container
            {
                Options = { DefaultScopedLifestyle = new WebRequestLifestyle() }
            };

            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

            // register logger factory and generic logger
            container.RegisterInstance <ILoggerFactory>(loggerFactory);
            container.RegisterSingleton(typeof(ILogger <>), typeof(Logger <>));

            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Beispiel #41
0
        public void Contact()
        {
            // Arrange
            var config = new ConfigurationRoot(new List<IConfigurationProvider> {new MemoryConfigurationProvider(new MemoryConfigurationSource())});
            config["kEY1"] = "keyValue1";
            config["key2"] = "keyValue2";
            config["USERNAME"] = "******";
            var otherSettings = new OtherSettings { Numbers = new int[] { 234, 567 } };
            var options = new OptionsWrapper<OtherSettings>(otherSettings);
            var loggerFactory = new LoggerFactory();
            var logger = loggerFactory.CreateLogger<HomeController>();
            IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());

            HomeController controller = new HomeController(config, options, logger, cache);

            // Act
            ViewResult result = controller.Contact() as ViewResult;

            // Assert
            Assert.Equal("keyValue1 SNeagu 234, 567", result.ViewBag.Message);
        }
Beispiel #42
0
        public void Log_AggregatesExceptionsFromMultipleLoggers()
        {
            // Arrange
            var store = new List<string>();
            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(new CustomLoggerProvider("provider1", ThrowExceptionAt.Log, store));
            loggerFactory.AddProvider(new CustomLoggerProvider("provider2", ThrowExceptionAt.Log, store));
            var logger = loggerFactory.CreateLogger("Test");

            // Act
            var aggregateException = Assert.Throws<AggregateException>(() => logger.LogInformation("Hello!"));

            // Assert
            Assert.Empty(store);
            Assert.NotNull(aggregateException);
            Assert.Equal("An error occurred while writing to logger(s).", aggregateException.Message);
            var exceptions = aggregateException.InnerExceptions;
            Assert.Equal(2, exceptions.Count);
            Assert.Equal("provider1.Test-Error occurred while logging data.", exceptions[0].Message);
            Assert.Equal("provider2.Test-Error occurred while logging data.", exceptions[1].Message);
        }
Beispiel #43
0
    static int Main(string[] args)
    {
        Console.WriteLine($"{AppName} v{AppVersion} by Klarth");

        LoggerFactory = CreateLoggerFactory(DefaultLogFileName);
        var verbs = LoadVerbs();

        ExitCode code = ExitCode.Unset;

        var parser = new Parser(with => {
            with.CaseSensitive = false;
            with.AutoHelp      = true;
            with.AutoVersion   = true;
        });

        var parserResult = parser.ParseArguments(args, verbs)
                           .WithNotParsed(errors =>
        {
            code = ExitCode.InvalidCommandArguments;
        })
                           .WithParsed(options =>
        {
            var logFileName = GetFullLogFileName(options);
            if (!BootstrapTileShop(logFileName))
            {
                code = ExitCode.EnvironmentError;
            }
            else
            {
                code = ExecuteHandler(options);
            }
        });

        var errorCodeDescription = code switch
        {
            ExitCode.Success => "Operation completed successfully",
            ExitCode.Unset => "Operation exited without setting an exit code",
            ExitCode.Exception => "Operation failed due to an exception",
            ExitCode.EnvironmentError => "Operation failed because the TileShop environment could not be loaded",
            ExitCode.InvalidCommandArguments => $"Operation failed due to invalid command line options",
            ExitCode.ProjectOpenError => "Operation failed because the project could not be opened or validated",
            ExitCode.ImportOperationFailed => "Operation failed due to an import error",
            ExitCode.ExportOperationFailed => "Operation failed due to an export error",
            _ => $"Operation failed with an unknown exit code '{code}'"
        };

        if (code == ExitCode.InvalidCommandArguments)
        {
            DisplayHelp(parserResult);
        }

        if (code != ExitCode.Success)
        {
            Log.Error(errorCodeDescription);
        }
        else
        {
            Log.Information(errorCodeDescription);
        }

        return((int)code);
    }
Beispiel #44
0
        private static readonly int RTP_REPORTING_PERIOD_SECONDS = 5;       // Period at which to write RTP stats.

        static void Main()
        {
            Console.WriteLine("SIPSorcery client user agent example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource cts = new CancellationTokenSource();
            bool isCallHungup           = false;
            bool hasCallFailed          = false;

            // Logging configuration. Can be ommitted if internal SIPSorcery debug and warning messages are not required.
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug)
                                .WriteTo.Console()
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);
            SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;

            // Set up a default SIP transport.
            IPAddress defaultAddr  = LocalIPConfig.GetDefaultIPv4Address();
            var       sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());
            int       port         = FreePort.FindNextAvailableUDPPort(SIPConstants.DEFAULT_SIP_PORT + 2);
            var       sipChannel   = new SIPUDPChannel(new IPEndPoint(defaultAddr, port));

            sipTransport.AddSIPChannel(sipChannel);

            // Initialise an RTP session to receive the RTP packets from the remote SIP server.
            Socket rtpSocket     = null;
            Socket controlSocket = null;

            NetServices.CreateRtpSocket(defaultAddr, 49000, 49100, false, out rtpSocket, out controlSocket);
            var rtpSendSession = new RTPSession((int)RTPPayloadTypesEnum.PCMU, null, null);

            // Create a client user agent to place a call to a remote SIP server along with event handlers for the different stages of the call.
            var uac = new SIPClientUserAgent(sipTransport);

            uac.CallTrying  += (uac, resp) => SIPSorcery.Sys.Log.Logger.LogInformation($"{uac.CallDescriptor.To} Trying: {resp.StatusCode} {resp.ReasonPhrase}.");
            uac.CallRinging += (uac, resp) => SIPSorcery.Sys.Log.Logger.LogInformation($"{uac.CallDescriptor.To} Ringing: {resp.StatusCode} {resp.ReasonPhrase}.");
            uac.CallFailed  += (uac, err) =>
            {
                SIPSorcery.Sys.Log.Logger.LogWarning($"{uac.CallDescriptor.To} Failed: {err}");
                hasCallFailed = true;
            };
            uac.CallAnswered += (uac, resp) =>
            {
                if (resp.Status == SIPResponseStatusCodesEnum.Ok)
                {
                    SIPSorcery.Sys.Log.Logger.LogInformation($"{uac.CallDescriptor.To} Answered: {resp.StatusCode} {resp.ReasonPhrase}.");
                    IPEndPoint remoteRtpEndPoint = SDP.GetSDPRTPEndPoint(resp.Body);

                    SIPSorcery.Sys.Log.Logger.LogDebug($"Sending initial RTP packet to remote RTP socket {remoteRtpEndPoint}.");

                    // Send a dummy packet to open the NAT session on the RTP path.
                    rtpSendSession.SendAudioFrame(rtpSocket, remoteRtpEndPoint, 0, new byte[] { 0x00 });
                }
                else
                {
                    SIPSorcery.Sys.Log.Logger.LogWarning($"{uac.CallDescriptor.To} Answered: {resp.StatusCode} {resp.ReasonPhrase}.");
                }
            };

            // The only incoming request that needs to be explicitly handled for this example is if the remote end hangs up the call.
            sipTransport.SIPTransportRequestReceived += (SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest) =>
            {
                if (sipRequest.Method == SIPMethodsEnum.BYE)
                {
                    SIPNonInviteTransaction byeTransaction = sipTransport.CreateNonInviteTransaction(sipRequest, remoteEndPoint, localSIPEndPoint, null);
                    SIPResponse             byeResponse    = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                    byeTransaction.SendFinalResponse(byeResponse);

                    if (uac.IsUACAnswered)
                    {
                        SIPSorcery.Sys.Log.Logger.LogInformation("Call was hungup by remote server.");
                        isCallHungup = true;
                        cts.Cancel();
                    }
                }
            };

            // It's a good idea to start the RTP receiving socket before the call request is sent.
            // A SIP server will generally start sending RTP as soon as it has processed the incoming call request and
            // being ready to receive will stop any ICMP error response being generated.
            Task.Run(() => SendRecvRtp(rtpSocket, rtpSendSession, cts));

            // Start the thread that places the call.
            SIPCallDescriptor callDescriptor = new SIPCallDescriptor(
                SIPConstants.SIP_DEFAULT_USERNAME,
                null,
                DESTINATION_SIP_URI,
                SIPConstants.SIP_DEFAULT_FROMURI,
                null, null, null, null,
                SIPCallDirection.Out,
                SDP.SDP_MIME_CONTENTTYPE,
                GetSDP(rtpSocket.LocalEndPoint as IPEndPoint).ToString(),
                null);

            uac.Call(callDescriptor);

            // At this point the call has been initiated and everything will be handled in an event handler or on the RTP
            // receive task. The code below is to gracefully exit.
            // Ctrl-c will gracefully exit the call at any point.
            Console.CancelKeyPress += async delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                cts.Cancel();

                SIPSorcery.Sys.Log.Logger.LogInformation("Exiting...");

                rtpSocket?.Close();
                controlSocket?.Close();

                if (!isCallHungup && uac != null)
                {
                    if (uac.IsUACAnswered)
                    {
                        SIPSorcery.Sys.Log.Logger.LogInformation($"Hanging up call to {uac.CallDescriptor.To}.");
                        uac.Hangup();
                    }
                    else if (!hasCallFailed)
                    {
                        SIPSorcery.Sys.Log.Logger.LogInformation($"Cancelling call to {uac.CallDescriptor.To}.");
                        uac.Cancel();
                    }

                    // Give the BYE or CANCEL request time to be transmitted.
                    SIPSorcery.Sys.Log.Logger.LogInformation("Waiting 1s for call to clean up...");
                    await Task.Delay(1000);
                }

                SIPSorcery.Net.DNSManager.Stop();

                if (sipTransport != null)
                {
                    SIPSorcery.Sys.Log.Logger.LogInformation("Shutting down SIP transport...");
                    sipTransport.Shutdown();
                }
            };
        }
Beispiel #45
0
        public void ConfigureServices(IServiceCollection services)
        {
            //++Jeff and Steve added this in an attempt to get CORS enabled
            var _loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var cors           = new DefaultCorsPolicyService(_loggerFactory.CreateLogger <DefaultCorsPolicyService>())
            {
                AllowAll = true
            };

            services.AddSingleton <ICorsPolicyService>(cors);
            //--Jeff and Steve added this in an attempt to get CORS enabled

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlite(Configuration.GetConnectionString("Users")));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            //Configure the ASP.NET Identity service
            services.Configure <IdentityOptions>(options =>
            {
                // DON'T DO THIS IN PRODUCTION ENVIRONMENTS!!!!!
                // Relax the password requirements for the demo environment
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 4;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequiredUniqueChars    = 3;

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings
                options.User.RequireUniqueEmail = true;
            });

            services.AddMvc();

            services.Configure <IISOptions>(iis =>
            {
                iis.AuthenticationDisplayName = "Windows";
                iis.AutomaticAuthentication   = false;
            });

            var connectionString   = Configuration.GetConnectionString("Configuration");
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
                          .AddAspNetIdentity <ApplicationUser>()
                          // this adds the config data from DB (clients, resources, CORS)
                          .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = db =>
                                             db.UseSqlite(connectionString,
                                                          sql => sql.MigrationsAssembly(migrationsAssembly));
            })
                          // this adds the operational data from DB (codes, tokens, consents)
                          .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = db =>
                                             db.UseSqlite(connectionString,
                                                          sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup = true;
                // options.TokenCleanupInterval = 15; // interval in seconds. 15 seconds useful for debugging
            });

            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                throw new Exception("need to configure key material");
            }

            services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.ClientId     = "708996912208-9m4dkjb5hscn7cjrn5u0r4tbgkbj1fko.apps.googleusercontent.com";
                options.ClientSecret = "wdfPY6t8H8cecgjlxud__4Gh";
            });

            services.UseAdminUI();
        }
        private static readonly int RTP_REPORTING_PERIOD_SECONDS = 5;       // Period at which to write RTP stats.

        static void Main()
        {
            Console.WriteLine("SIPSorcery client user agent server example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Logging configuration. Can be ommitted if internal SIPSorcery debug and warning messages are not required.
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug)
                                .WriteTo.Console()
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);
            SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;

            // Set up a default SIP transport.
            IPAddress defaultAddr  = LocalIPConfig.GetDefaultIPv4Address();
            var       sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());
            int       port         = FreePort.FindNextAvailableUDPPort(SIPConstants.DEFAULT_SIP_PORT);
            var       sipChannel   = new SIPUDPChannel(new IPEndPoint(defaultAddr, port));

            sipTransport.AddSIPChannel(sipChannel);

            // To keep things a bit simpler this example only supports a single call at a time and the SIP server user agent
            // acts as a singleton
            SIPServerUserAgent      uas    = null;
            CancellationTokenSource uasCts = null;

            // Because this is a server user agent the SIP transport must start listening for client user agents.
            sipTransport.SIPTransportRequestReceived += (SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest) =>
            {
                if (sipRequest.Method == SIPMethodsEnum.INVITE)
                {
                    SIPSorcery.Sys.Log.Logger.LogInformation("Incoming call request: " + localSIPEndPoint + "<-" + remoteEndPoint + " " + sipRequest.URI.ToString() + ".");

                    // If there's already a call in progress hang it up. Of course this is not ideal for a real softphone or server but it
                    // means this example can be kept a little it simpler.
                    uas?.Hangup();

                    UASInviteTransaction uasTransaction = sipTransport.CreateUASTransaction(sipRequest, remoteEndPoint, localSIPEndPoint, null);
                    uas    = new SIPServerUserAgent(sipTransport, null, null, null, SIPCallDirection.In, null, null, null, uasTransaction);
                    uasCts = new CancellationTokenSource();

                    uas.Progress(SIPResponseStatusCodesEnum.Trying, null, null, null, null);
                    uas.Progress(SIPResponseStatusCodesEnum.Ringing, null, null, null, null);

                    // Initialise an RTP session to receive the RTP packets from the remote SIP server.
                    Socket rtpSocket     = null;
                    Socket controlSocket = null;
                    NetServices.CreateRtpSocket(defaultAddr, 49000, 49100, false, out rtpSocket, out controlSocket);

                    IPEndPoint rtpEndPoint    = rtpSocket.LocalEndPoint as IPEndPoint;
                    IPEndPoint dstRtpEndPoint = SDP.GetSDPRTPEndPoint(sipRequest.Body);
                    var        rtpSession     = new RTPSession((int)RTPPayloadTypesEnum.PCMU, null, null);

                    var rtpTask = Task.Run(() => SendRecvRtp(rtpSocket, rtpSession, dstRtpEndPoint, AUDIO_FILE, uasCts))
                                  .ContinueWith(_ => { if (uas?.IsHungup == false)
                                                       {
                                                           uas?.Hangup();
                                                       }
                                                });

                    uas.Answer(SDP.SDP_MIME_CONTENTTYPE, GetSDP(rtpEndPoint).ToString(), null, SIPDialogueTransferModesEnum.NotAllowed);
                }
                else if (sipRequest.Method == SIPMethodsEnum.BYE)
                {
                    SIPSorcery.Sys.Log.Logger.LogInformation("Call hungup.");
                    SIPNonInviteTransaction byeTransaction = sipTransport.CreateNonInviteTransaction(sipRequest, remoteEndPoint, localSIPEndPoint, null);
                    SIPResponse             byeResponse    = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                    byeTransaction.SendFinalResponse(byeResponse);
                    uas?.Hangup();
                    uasCts?.Cancel();
                }
            };

            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;

                SIPSorcery.Sys.Log.Logger.LogInformation("Exiting...");
                if (uas?.IsHungup == false)
                {
                    uas?.Hangup();
                }
                uasCts?.Cancel();

                if (sipTransport != null)
                {
                    SIPSorcery.Sys.Log.Logger.LogInformation("Shutting down SIP transport...");
                    sipTransport.Shutdown();
                }
            };
        }
Beispiel #47
0
        static void Main(string[] args)
        {
            ILoggerFactory logfactory = new Microsoft.Extensions.Logging.LoggerFactory();
            Random         r          = new Random((int)(DateTime.Now.Ticks + (long)Environment.CurrentManagedThreadId));

            IConfigurationRoot config = new ConfigurationBuilder()
                                        .AddJsonFile("appsettings.json", optional: false)
                                        .Build();
            var cfg = config.Get <MqttConfig>();

            logfactory.AddConsole(true);


            switch (cfg.mode)
            {
            case (1):
            case (2):
            { break; }

            default:
            {
                Console.WriteLine("Mode (1=listen,2=publish)");
                string m = Console.ReadLine();
                cfg.mode = int.Parse(m);
                break;
            }
            }
            ;

            switch (cfg.mode)
            {
            case (2):
            {
                Console.WriteLine("publishing!");
                var t = _publish().Result;
                break;
            }

            case (1):
            {
                Console.WriteLine("subscribing!");
                var xm = new XamMqtt(cfg, logfactory.CreateLogger <XamMqtt>());
                xm.subscribe();
                //_subscribe(cfg);
                break;
            }
            }

            /*
             *   if (mode == 1)
             *     {
             *       client.MessageStream.Subscribe(new Obs());
             *       var t = client.SubscribeAsync("house/serverroom/temp", System.Net.Mqtt.MqttQualityOfService.AtLeastOnce);
             *       t.Wait();
             *     }
             *
             *   Console.WriteLine("Type 'q' to quit");
             *   string text = null;
             *   do {
             *     text = Console.ReadLine();
             *     if (mode == 2 && text != "q")
             *       {
             *         if (!client.IsConnected)
             *           {
             *             client.ConnectAsync(new MqttClientCredentials("blarg")).Wait();
             *           }
             *         var x = _SendMsg(r, client).Result;
             *         Console.WriteLine(x);
             *       }
             *
             *   } while(text != "q");
             *
             *   var t1 = client.DisconnectAsync();
             *   t1.Wait();
             *   client.Dispose();
             */
        }
Beispiel #48
0
        static void Main()
        {
            Console.WriteLine("SIPSorcery client user agent server example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Logging configuration. Can be ommitted if internal SIPSorcery debug and warning messages are not required.
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug)
                                .WriteTo.Console()
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);
            SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;

            // Set up a default SIP transport.
            var sipTransport = new SIPTransport();

            sipTransport.ContactHost = Dns.GetHostName();

            sipTransport.AddSIPChannel(new SIPUDPChannel(new IPEndPoint(IPAddress.Any, SIP_LISTEN_PORT)));
            //sipTransport.AddSIPChannel(new SIPUDPChannel(new IPEndPoint(IPAddress.IPv6Any, SIP_LISTEN_PORT)));
            //sipTransport.AddSIPChannel(new SIPTCPChannel(new IPEndPoint(IPAddress.Any, SIP_LISTEN_PORT)));
            //sipTransport.AddSIPChannel(new SIPTCPChannel(new IPEndPoint(IPAddress.IPv6Any, SIP_LISTEN_PORT)));

            //if (File.Exists("localhost.pfx"))
            //{
            //    var certificate = new X509Certificate2(@"localhost.pfx", "");
            //    sipTransport.AddSIPChannel(new SIPTLSChannel(certificate, new IPEndPoint(IPAddress.Any, SIPS_LISTEN_PORT)));
            //    sipTransport.AddSIPChannel(new SIPTLSChannel(certificate, new IPEndPoint(IPAddress.IPv6Any, SIPS_LISTEN_PORT)));
            //}

            //EnableTraceLogs(sipTransport);

            // To keep things a bit simpler this example only supports a single call at a time and the SIP server user agent
            // acts as a singleton
            SIPServerUserAgent      uas    = null;
            CancellationTokenSource rtpCts = null; // Cancellation token to stop the RTP stream.

            // Because this is a server user agent the SIP transport must start listening for client user agents.
            sipTransport.SIPTransportRequestReceived += async(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest) =>
            {
                if (sipRequest.Method == SIPMethodsEnum.INVITE)
                {
                    SIPSorcery.Sys.Log.Logger.LogInformation("Incoming call request: " + localSIPEndPoint + "<-" + remoteEndPoint + " " + sipRequest.URI.ToString() + ".");
                    //SIPSorcery.Sys.Log.Logger.LogDebug(sipRequest.ToString());

                    // If there's already a call in progress hang it up. Of course this is not ideal for a real softphone or server but it
                    // means this example can be kept simpler.
                    if (uas?.IsHungup == false)
                    {
                        uas?.Hangup(false);
                    }
                    rtpCts?.Cancel();

                    UASInviteTransaction uasTransaction = sipTransport.CreateUASTransaction(sipRequest, remoteEndPoint, localSIPEndPoint, null);
                    uas    = new SIPServerUserAgent(sipTransport, null, null, null, SIPCallDirection.In, null, null, null, uasTransaction);
                    rtpCts = new CancellationTokenSource();

                    // In practice there could be a number of reasons to reject the call. Unsupported extensions, mo matching codecs etc. etc.
                    if (sipRequest.Header.HasUnknownRequireExtension)
                    {
                        // The caller requires an extension that we don't support.
                        SIPSorcery.Sys.Log.Logger.LogWarning($"Rejecting incoming call due to one or more required exensions not being supported, required extensions: {sipRequest.Header.Require}.");
                        uas.Reject(SIPResponseStatusCodesEnum.NotImplemented, "Unsupported Require Extension", null);
                    }
                    else
                    {
                        uas.Progress(SIPResponseStatusCodesEnum.Trying, null, null, null, null);
                        uas.Progress(SIPResponseStatusCodesEnum.Ringing, null, null, null, null);

                        // Simulating answer delay to test provisional response retransmits.
                        await Task.Delay(2000);

                        // Initialise an RTP session to receive the RTP packets from the remote SIP server.
                        Socket rtpSocket     = null;
                        Socket controlSocket = null;
                        NetServices.CreateRtpSocket(localSIPEndPoint.Address, 49000, 49100, false, out rtpSocket, out controlSocket);

                        IPEndPoint rtpEndPoint    = rtpSocket.LocalEndPoint as IPEndPoint;
                        IPEndPoint dstRtpEndPoint = SDP.GetSDPRTPEndPoint(sipRequest.Body);
                        var        rtpSession     = new RTPSession((int)RTPPayloadTypesEnum.PCMU, null, null);

                        var rtpTask = Task.Run(() => SendRecvRtp(rtpSocket, rtpSession, dstRtpEndPoint, AUDIO_FILE, rtpCts))
                                      .ContinueWith(_ => { if (uas?.IsHungup == false)
                                                           {
                                                               uas?.Hangup(false);
                                                           }
                                                    });

                        uas.Answer(SDP.SDP_MIME_CONTENTTYPE, GetSDP(rtpEndPoint).ToString(), null, SIPDialogueTransferModesEnum.NotAllowed);
                    }
                }
                else if (sipRequest.Method == SIPMethodsEnum.BYE)
                {
                    SIPSorcery.Sys.Log.Logger.LogInformation("Call hungup.");
                    SIPNonInviteTransaction byeTransaction = sipTransport.CreateNonInviteTransaction(sipRequest, remoteEndPoint, localSIPEndPoint, null);
                    SIPResponse             byeResponse    = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                    byeTransaction.SendFinalResponse(byeResponse);
                    uas?.Hangup(true);
                    rtpCts?.Cancel();
                }
                else if (sipRequest.Method == SIPMethodsEnum.OPTIONS)
                {
                    try
                    {
                        SIPSorcery.Sys.Log.Logger.LogInformation($"{localSIPEndPoint.ToString()}<-{remoteEndPoint.ToString()}: {sipRequest.StatusLine}");
                        //SIPSorcery.Sys.Log.Logger.LogDebug(sipRequest.ToString());
                        SIPResponse optionsResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                        sipTransport.SendResponse(optionsResponse);
                    }
                    catch (Exception optionsExcp)
                    {
                        SIPSorcery.Sys.Log.Logger.LogWarning($"Failed to send SIP OPTIONS response. {optionsExcp.Message}");
                    }
                }
            };

            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;

                SIPSorcery.Sys.Log.Logger.LogInformation("Exiting...");
                rtpCts?.Cancel();
                if (uas?.IsHungup == false)
                {
                    uas?.Hangup(false);

                    // Give the BYE or CANCEL request time to be transmitted.
                    SIPSorcery.Sys.Log.Logger.LogInformation("Waiting 1s for call to hangup...");
                    Task.Delay(1000).Wait();
                }

                if (sipTransport != null)
                {
                    SIPSorcery.Sys.Log.Logger.LogInformation("Shutting down SIP transport...");
                    sipTransport.Shutdown();
                }
            };
        }
Beispiel #49
0
        /// <summary>
        /// The program's Main is an <see langword="async"/> Task . Entry point to the Program
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>

        public static async Task Main(string[] args)
        {
            #region Startup logger
            // Configure a startup logger, prior to getting the Logger configuration from the ConfigurationRoot
            // Serilog is the logging provider I picked to provide a logging solution for the Console01 application
            // Enable Serilog's internal debug logging. Note that internal logging will not write to any user-defined Sources
            //  https://github.com/serilog/serilog-sinks-file/blob/dev/example/Sample/Program.cs
            Serilog.Debugging.SelfLog.Enable(System.Console.Out);
            // Another example is at https://stackify.com/serilog-tutorial-net-logging/
            //  This brings in the System.Diagnostics.Debug namespace and writes the SelfLog there
            Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
            Serilog.Debugging.SelfLog.WriteLine("in Program.Main(Serilog Self Log)");
            // Another example is at https://github.com/serilog/serilog-extensions-logging/blob/dev/samples/Sample/Program.cs
            // Another is https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/
            // Creating a `LoggerProviderCollection` lets Serilog optionally write events through other dynamically-added MEL ILoggerProviders.
            //var providers = new LoggerProviderCollection();
            // Setup Serilog's static logger with an initial configuration sufficient to log startup errors

            // create a local Serilog logger for use during Program startup
            var serilogLoggerConfiguration = new Serilog.LoggerConfiguration()
                                             .MinimumLevel.Verbose()
                                             .Enrich.FromLogContext()
                                             .Enrich.WithThreadId()
                                             .WriteTo.Console(outputTemplate: "Static startup Serilog {Timestamp:HH:mm:ss zzz} [{Level}] ({Name:l}) {Message}{NewLine}{Exception}")
                                             .WriteTo.Seq(serverUrl: "http://*****:*****@"C:\Dropbox\whertzing\GitHub\ATAP.Utilities\devlog\A01Console.{Date}.log", fileSizeLimitBytes: 1024, outputTemplate: "Static Serilog {Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}", rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true, retainedFileCountLimit: 31)
                                             .WriteTo.Debug();
            //.Enrich.WithHttpRequestId()
            //.Enrich.WithUserName()
            //.WithExceptionDetails()
            //.WriteTo.Providers(providers)

            Serilog.Core.Logger serilogLogger = serilogLoggerConfiguration.CreateLogger();
            // Set the Static logger called Log to use this LoggerConfiguration
            Serilog.Log.Logger = serilogLogger;
            Log.Debug("{Program} {Main}: The program Console01 is starting", "Program", "Main");
            Log.Debug("{Program} {Main}: LoggerFactory and local logger defined with a default startup configuration:", "Program", "Main");

            // Set the MEL LoggerFactory to use this LoggerConfiguration
            Microsoft.Extensions.Logging.ILoggerFactory mELoggerFactory = new Microsoft.Extensions.Logging.LoggerFactory().AddSerilog();
            Microsoft.Extensions.Logging.ILogger        mELlogger       = mELoggerFactory.CreateLogger("Program");
            mELlogger.LogDebug("{0} {1}: The program Console01 is starting", "Program", "Main");
            mELlogger.LogDebug("{0} {1}: LoggerFactory and local logger defined with a default startup configuration:", "Program", "Main");
            #endregion

            #region stringLocalizers and optionally resource managers for InternationalizatioN (AKA I18N)
            // populate the string localizers for Program
            Options = Microsoft.Extensions.Options.Options.Create(new LocalizationOptions());
            StringLocalizerFactory = new ResourceManagerStringLocalizerFactory(Options, NullLoggerFactory.Instance);
            DebugLocalizer         = StringLocalizerFactory.Create(nameof(Resources), "ATAP.Console.Console01");
            ExceptionLocalizer     = StringLocalizerFactory.Create(nameof(Resources), "ATAP.Console.Console01");
            ConfigLCL   = StringLocalizerFactory.Create(nameof(Resources), "ATAP.Console.Console01");
            UILocalizer = StringLocalizerFactory.Create(nameof(Resources), "ATAP.Console.Console01");

            // If localized non-string resources are needed, uncomment the following block
            // Load the ResourceManagers from the installation directory. These provide access to all localized resources including non-string resources
            // Cannot create more-derived types from a ResourceManager. Gets Invalid cast. See also https://stackoverflow.com/questions/2500280/invalidcastexception-for-two-objects-of-the-same-type/30623970, the invalid cast might be because ResourceManagers are not per-assembly?
            // i.e., the following will no compile DebugResourceManager debugResourceManager = (DebugResourceManager)new ResourceManager("ATAP.Console.Console01.Properties.ConsoleDebugResources", typeof(ConsoleDebugResources).Assembly);
            // These will compile if needed
            //var debugResourceManager = new ResourceManager("ATAP.Console.Console01.Properties.ConsoleDebugResources", typeof(ConsoleDebugResources).Assembly);
            //var exceptionResourceManager = new ResourceManager("ATAP.Console.Console01.Properties.ConsoleExceptionResources", typeof(ConsoleExceptionResources).Assembly);
            //var uIResourceManager = new ResourceManager("ATAP.Console.Console01.Properties.ConsoleUIResources", typeof(ConsoleUIResources).Assembly);
            #endregion region

            #region initialStartup and loadedFrom directories
            // When running as a Windows service, the initial working dir is usually %WinDir%\System32, but the program (and configuration files) is probably installed to a different directory
            // When running as a *nix service, the initial working dir could be anything. The program (and machine-wide configuration files) are probably installed in the location where the service starts. //ToDo: verify this
            // When running as a Windows or Linux Console App, the initial working dir could be anything, but the program (and machine-wide configuration files) is probably installed to a different directory.
            // When running as a console app, it is very possible that there may be local (to the initial startup directory) configuration files to load
            // get the initial startup directory
            // get the directory where the executing assembly (usually .exe) and possibly machine-wide configuration files are installed to.
            var initialStartupDirectory = Directory.GetCurrentDirectory();                             //ToDo: Catch exceptions
            mELlogger.LogDebug(DebugLocalizer["{0} {1}: initialStartupDirectory: {2}", "Program", "Main", initialStartupDirectory]);
            var loadedFromDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //ToDo: Catch exceptions
            mELlogger.LogDebug(DebugLocalizer["{0} {1}: loadedFromDirectory: {2}", "Program", "Main", loadedFromDirectory]);
            #endregion region

            #region initial genericHostConfigurationBuilder and genericHostConfigurationRoot
            // Create the initial genericHostConfigurationBuilder for this genericHost's ConfigurationRoot. This creates an ordered chain of configuration providers. The first providers in the chain have the lowest priority, the last providers in the chain have a higher priority.
            // Initial configuration does not take Environment into account.
            var genericHostConfigurationBuilder = ConfigurationExtensions.ATAPStandardConfigurationBuilder(
                GenericHostDefaultConfiguration.Production, true, null, GenericHostStringConstants.genericHostSettingsFileName,
                GenericHostStringConstants.hostSettingsFileNameSuffix, loadedFromDirectory, initialStartupDirectory, hostEnvPrefixes, args, switchMappings);

            // Create this program's initial genericHost's ConfigurationRoot
            var genericHostConfigurationRoot = genericHostConfigurationBuilder.Build();
            #endregion

            #region (optional) Debugging the  Configuration
            // for debugging and education, uncomment this region and inspect the two section Lists (using debugger Locals) to see exactly what is in the configuration
            //    var sections = genericHostConfigurationRoot.GetChildren();
            //    List<IConfigurationSection> sectionsAsListOfIConfigurationSections = new List<IConfigurationSection>();
            //    List<ConfigurationSection> sectionsAsListOfConfigurationSections = new List<ConfigurationSection>();
            //    foreach (var iSection in sections) sectionsAsListOfIConfigurationSections.Add(iSection);
            //    foreach (var iSection in sectionsAsListOfIConfigurationSections) sectionsAsListOfConfigurationSections.Add((ConfigurationSection)iSection);
            #endregion

            #region Environment determination and validation
            // ToDo: Before the genericHost is built, have to use a StringConstant for the string that means "Production", and hope the ConfigurationRoot value for Environment matches the StringConstant
            // Determine the environment (Debug, TestingUnit, TestingX, QA, QA1, QA2, ..., Staging, Production) to use from the initialGenericHostConfigurationRoot
            var envNameFromConfiguration = genericHostConfigurationRoot.GetValue <string>(GenericHostStringConstants.EnvironmentConfigRootKey, GenericHostStringConstants.EnvironmentDefault);
            mELlogger.LogDebug(DebugLocalizer["{0} {1}: Initial environment name: {2}", "Program", "Main", envNameFromConfiguration]);

            // optional: Validate that the environment provided is one this program understands how to use
            // Accepting any string for envNameFromConfiguration might pose a security risk, as it will allow arbitrary files to be loaded into the configuration root
            switch (envNameFromConfiguration)
            {
            case GenericHostStringConstants.EnvironmentDevelopment:
                // ToDo: Programmers can add things here
                break;

            case GenericHostStringConstants.EnvironmentProduction:
                // This is the expected leg for Production environment
                break;

            default:
                // IF you want to accept any environment name as OK, just comment out the following throw
                // Keep the throw in here if you want to explicitly disallow any environment other than ones specified in the switch
                throw new NotImplementedException(ExceptionLocalizer["The Environment {0} is not supported", envNameFromConfiguration]);
            }
            ;
            #endregion

            #region final (Environment-aware) genericHostConfigurationBuilder and appConfigurationBuilder
            // If the initial genericHostConfigurationRoot specifies the Environment is production, then the genericHostConfigurationBuilder is correct  "as-is"
            //   but if not, build a 2nd (final) genericHostConfigurationBuilder, this time including environment-specific configuration providers
            if (envNameFromConfiguration != GenericHostStringConstants.EnvironmentProduction)
            {
                // Recreate the ConfigurationBuilder for this genericHost, this time including environment-specific configuration providers.
                mELlogger.LogDebug(DebugLocalizer["{0} {1}: Recreating genericHostConfigurationBuilder for Environment: {2}"], "Program", "Main", envNameFromConfiguration);
                genericHostConfigurationBuilder = ConfigurationExtensions.ATAPStandardConfigurationBuilder(GenericHostDefaultConfiguration.Production, false, envNameFromConfiguration,
                                                                                                           GenericHostStringConstants.genericHostSettingsFileName, GenericHostStringConstants.hostSettingsFileNameSuffix, loadedFromDirectory, initialStartupDirectory, hostEnvPrefixes, args, switchMappings);
            }

            // Create the appConfigurationBuilder, either as Production or as some other environment specific
            IConfigurationBuilder appConfigurationBuilder;
            mELlogger.LogDebug(DebugLocalizer["{0} {1}: Creating appConfigurationBuilder for Environment: {2}"], "Program", "Main", envNameFromConfiguration);
            appConfigurationBuilder = ConfigurationExtensions.ATAPStandardConfigurationBuilder(Console01DefaultConfiguration.Production, envNameFromConfiguration == GenericHostStringConstants.EnvironmentProduction, envNameFromConfiguration,
                                                                                               Console01StringConstants.SettingsFileName, Console01StringConstants.SettingsFileNameSuffix, loadedFromDirectory, initialStartupDirectory, appEnvPrefixes, args, switchMappings);
            #endregion


            #region Configure the genericHostBuilder, including DI-Container, IHostLifetime, services in the services collection, genericHostConfiguration, and appConfiguration

            // Make a GenericHostBuilder with the Configuration (as above), and chose a specific instance of an IHostLifetime
            var genericHostBuilder = GenericHostExtensions.ATAPStandardGenericHostBuilderForConsoleLifetime(genericHostConfigurationBuilder, appConfigurationBuilder);

            // Add the specific IHostLifetime for this program (or service)
            //ToDo: implement service and serviced, then see if this can be moved to the ATAPStandardGenericHostBuilder static extension method
            genericHostBuilder.ConfigureServices((hostContext, services) => {
                services.AddSingleton <IHostLifetime, ConsoleLifetime>();
                //services.AddOptions<ConsoleLifetime>(Options => Options.SuppressStatusMessages = true);
            });

            // in Production, surpress the startup messages appearing on the Console stdout
            if (envNameFromConfiguration == GenericHostStringConstants.EnvironmentProduction)
            {
                //genericHostBuilder.Configure<ConsoleLifetimeOptions>(Options => Options.SuppressStatusMessages = true); //
            }

            #region Configure the GenericHost logging per the Logging section in ConfigurationRoot
            genericHostBuilder.ConfigureLogging((hostContext, loggingBuilder) => {
                loggingBuilder.AddConfiguration(genericHostConfigurationRoot.GetSection("Logging"));
                //loggingBuilder.UseSerilog
            });
            // Build the GH configuration
            //genericHostConfigurationRoot = genericHostConfigurationBuilder.Build();
            //// Create a LoggerFactory, configure it to use Serilog
            //loggerConfiguration = genericHostConfigurationRoot.GetSection("Logging");
            //// redefine the factory according to the new configuration
            //factory = new LoggerFactory();
            //factory.AddSerilog(loggerConfiguration.CreateLogger());
            //// Set the LogFactory in the ATP.Utilities.Logging class
            //LogProvider.SetLogFactory(factory);
            //// Set the LogFactory in the DI-Services
            //// ToDo: LoggerFactory loggerFactory.SetLogFactory(factory);
            //// redefine the local logger from this factory, configured with the startup logging as defined in the Logging section of the configurationRoot
            //logger = factory.CreateLogger("Console01");
            //serilogLogger.LogDebug(DebugLocalizer["{0} {1}: LoggerFactory and local logger redefined per the Logging section in the configuration settings:"], "Program", "Main");
            //// Copy this tour "standard logger
            //// Create a LoggerFactory, configure it to use Serilog
            //var factory = new LoggerFactory();
            //var x = serilogLoggerConfiguration..CreateLoggerF();
            //factory.AddSerilog(serilogLoggerConfiguration.CreateLogger());
            //LogProvider.SetLogFactory(factory);
            //// Create a local logger from this factory, configured with the startup logging defined above
            //logger = factory.CreateLogger("Console01");
            //// For this program, I've selected Serilog as the underlying serilogLogger.
            //genericHostBuilder.UseSerilog();
            #endregion

            // Add specific services for this application
            genericHostBuilder.ConfigureServices((hostContext, services) => {
                // Localization for the services
                services.AddLocalization(options => options.ResourcesPath = "Resources");
                services.AddSingleton <IConsoleSinkHostedService, ConsoleSinkHostedService>();
                services.AddSingleton <IConsoleSourceHostedService, ConsoleSourceHostedService>();
                //services.AddHostedService<ConsoleMonitorBackgroundService>(); // Only use this service in a GenericHost having a DI-injected IHostLifetime of type ConsoleLifetime.
                services.AddHostedService <Console01BackgroundService>(); // Only use this service in a GenericHost having a DI-injected IHostLifetime of type ConsoleLifetime.
                //services.AddSingleton<IFileSystemWatchersHostedService, FileSystemWatchersHostedService>();
                services.AddSingleton <IObservableResetableTimersHostedService, ObservableResetableTimersHostedService>();
                //services.AddSingleton<IFileSystemWatchersAsObservableFactoryService, FileSystemWatchersAsObservableFactoryService>();
            });
            #endregion

            // Build the Host
            var genericHost = genericHostBuilder.Build();

            // Use the ConfigurationSettings for ConsoleLifetimeOptions.SuppressStatusMessages
            //services.Configure<ConsoleLifetimeOptions>(opts opts.SuppressStatusMessages = Configuration["SuppressStatusMessages"] != null)

            // Start it going
            try {
                mELlogger.LogDebug(DebugLocalizer["{0} {1}: \"using\" the genericHost.", "Program", "Main"]);
                using (genericHost) {
                    mELlogger.LogDebug(DebugLocalizer["{0} {1}: Calling StartAsync on the genericHost.", "Program", "Main"]);

                    // Start the generic host running all its services and setup listeners for stopping
                    // all the rigamarole in https://andrewlock.net/introducing-ihostlifetime-and-untangling-the-generic-host-startup-interactions/

                    // Attribution to https://stackoverflow.com/questions/52915015/how-to-apply-hostoptions-shutdowntimeout-when-configuring-net-core-generic-host for OperationCanceledException notes
                    // ToDo: further investigation to ensure OperationCanceledException should be ignored in all cases (service or console host, kestrel or IntegratedIISInProcessWebHost)
                    try {
                        // The RunAsync method exists on a genericHost instance having a DI container instance that resolves a IHostLifetime. There are three "standard" implementations of IHostLifetime, Console, Service (Windows) and Serviced (*nix)
                        // await genericHost.RunAsync().ConfigureAwait(false);
                        // From MSMQ process sample at https://github.com/dotnet/extensions/blob/master/src/Hosting/samples/SampleMsmqHost/Program.cs
                        // start the genericHost
                        await genericHost.StartAsync().ConfigureAwait(false);

                        //ToDo: Better understanding - should the primary BackgroundService be run here instead of as a Background service?

                        // Nothing to do, the HostedServices and BackgroundServices do it all
                        ////// ToDo:  Deal with application lifetime? can applications stop, and restart, within the lifetime of the genericHost
                        //////// Get the CancellationToken stored in IHostApplicationLifetime ApplicationStopping
                        ////// var applicationLifetime = genericHost.Services.GetRequiredService<IHostApplicationLifetime>();
                        ////// var cT = applicationLifetime.ApplicationStopping;
                        //////// hang out until cancellation is requested
                        //////while (!cT.IsCancellationRequested) {
                        //////  cT.ThrowIfCancellationRequested();
                        //////}
                        // wait for the genericHost to shutdown
                        await genericHost.WaitForShutdownAsync().ConfigureAwait(false);
                    }
                    catch (OperationCanceledException e) {
                        ; // Just ignore OperationCanceledException to suppress it from bubbling upwards if the main program was cancelledOperationCanceledException
                          // The Exception should be shown in the ETW trace
                          //ToDo: Add Error level or category to ATAPUtilitiesETWProvider, and make OperationCanceled one of the catagories
                          // Specifically log the details of the cancellation (where it originated)
                          // ATAPUtilitiesETWProvider.Log.Information($"Exception in Program.Main: {e.Exception.GetType()}: {e.Exception.Message}");
                    } // Other kinds of exceptions bubble up to the catch block for the surrounding try, where the Serilog logger records it
                    finally {
                        // Dispose of any resources held directly by this program. Resources held by services in the DI-Container will be disposed of by the genericHost as it tears down
                        //if (DisposeThis != null) { DisposeThis.Dispose(); }
                    }

                    // Here, the StartAsync has completed, the Main method is over
                    // Log Program finishing to ETW if it happens to resume execution here for some reason(as of 06/2019, ILWeaving this assembly results in a thrown invalid CLI Program Exception
                    // ATAP.Utilities.ETW.ATAPUtilitiesETWProvider.Log(">Program.Main");
                    mELlogger.LogDebug(DebugLocalizer["{0} {1}: the genericHost has exitied "], "Program", "Main");
                }
            }
            catch (Exception ex) {
                MELLogger.LogCritical(ExceptionLocalizer["{0} {1}: genericHost start-up failed. ExceptionMessage: {2}", "Program", "Main", ex.Message]);
                throw ex;
            }
            finally {
                // ToDo: How to do something similar for MEL logger?
                Log.CloseAndFlush();
            }

            #region Playing with CSharpSyntaxTree
            // Just playing with the CSharpSyntaxTree feature here
            //SyntaxTree tree = CSharpSyntaxTree.ParseText(programText);
            //CompilationUnitSyntax root = tree.GetCompilationUnitRoot();
            // Use the debugger and Locals window to see these objects
            #endregion region
            mELlogger.LogDebug(DebugLocalizer["{0} {1}: Program:Main is exiting", "Program", "Main"]);
        }
Beispiel #50
0
        private const int SUCCESS_REGISTRATION_COUNT = 3;   // Number of successful registrations to attempt before exiting process.

        static void Main(string[] args)
        {
            Console.WriteLine("SIPSorcery registration user agent example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Logging configuration. Can be ommitted if internal SIPSorcery debug and warning messages are not required.
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug)
                                .WriteTo.Console()
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);
            SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;

            // Set up a default SIP transport.
            var sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());
            int port         = FreePort.FindNextAvailableUDPPort(SIPConstants.DEFAULT_SIP_PORT);
            var sipChannel   = new SIPUDPChannel(new IPEndPoint(LocalIPConfig.GetDefaultIPv4Address(), port));

            sipTransport.AddSIPChannel(sipChannel);

            // Create a client user agent to maintain a periodic registration with a SIP server.
            var regUserAgent = new SIPRegistrationUserAgent(
                sipTransport,
                "softphonesample",
                "password",
                "sipsorcery.com",
                120);

            int successCounter = 0;
            ManualResetEvent taskCompleteMre = new ManualResetEvent(false);

            // Event handlers for the different stages of the registration.
            regUserAgent.RegistrationFailed           += (uri, err) => SIPSorcery.Sys.Log.Logger.LogError($"{uri.ToString()}: {err}");
            regUserAgent.RegistrationTemporaryFailure += (uri, msg) => SIPSorcery.Sys.Log.Logger.LogWarning($"{uri.ToString()}: {msg}");
            regUserAgent.RegistrationRemoved          += (uri) => SIPSorcery.Sys.Log.Logger.LogError($"{uri.ToString()} registration failed.");
            regUserAgent.RegistrationSuccessful       += (uri) =>
            {
                SIPSorcery.Sys.Log.Logger.LogInformation($"{uri.ToString()} registration succeeded.");
                Interlocked.Increment(ref successCounter);
                SIPSorcery.Sys.Log.Logger.LogInformation($"Successful registrations {successCounter} of {SUCCESS_REGISTRATION_COUNT}.");

                if (successCounter == SUCCESS_REGISTRATION_COUNT)
                {
                    taskCompleteMre.Set();
                }
            };

            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                SIPSorcery.Sys.Log.Logger.LogInformation("Exiting...");
                taskCompleteMre.Set();
            };

            // Start the thread to perform the initial registration and then periodically resend it.
            regUserAgent.Start();

            taskCompleteMre.WaitOne();

            regUserAgent.Stop();
            if (sipTransport != null)
            {
                SIPSorcery.Sys.Log.Logger.LogInformation("Shutting down SIP transport...");
                sipTransport.Shutdown();
            }
            SIPSorcery.Net.DNSManager.Stop();
        }
Beispiel #51
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationIdentityContext>(options =>
                                                               options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("AspNetCore")));
            //add aspnet identity
            services.AddIdentity <Framework.AspNetIdentity.ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores <ApplicationIdentityContext>()
            .AddUserManager <ApplicationUserManager>()
            .AddDefaultTokenProviders();

            var clients = Configuration.GetSection("ClientSettings").Get <Client[]>();

            foreach (var item in clients)
            {
                item.ClientSecrets = new List <Secret> {
                    new Secret("secret".Sha256())
                };
            }

            var apiResources = Configuration.GetSection("ApiResources").Get <ApiResource[]>();

            //add identityserver
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(apiResources)
            //.AddInMemoryClients(Config.GetClients())
            .AddInMemoryClients(clients)
            .AddAspNetIdentity <ApplicationUser>();

            services.AddTransient <IProfileService, IdentityClaimsProfileService>();

            services.AddMvc();
            //  .AddRazorPagesOptions(options =>
            //  {
            //      options.Conventions.AuthorizeFolder("/Account/Manage");
            //      options.Conventions.AuthorizePage("/Account/Logout");
            //  }) ;


            //add serilog
            Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration).CreateLogger();
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory().AddSerilog(Log.Logger);

            services.AddSingleton(loggerFactory).AddLogging();

            // Register no-op EmailSender used by account confirmation and password reset during development
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713


            //add authentication
            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = "http://localhost:57906";
                options.RequireHttpsMetadata = false;

                options.ApiName = "api2";
            });

            services.AddScoped <IJwtTokenManagerService, JwtTokenManager>();
            //end add authentication
        }
Beispiel #52
0
        static void Main(string[] args)
        {
            Console.WriteLine("SIPSorcery client user agent example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource rtpCts = new CancellationTokenSource(); // Cancellation token to stop the RTP stream.
            bool isCallHungup  = false;
            bool hasCallFailed = false;

            // Logging configuration. Can be ommitted if internal SIPSorcery debug and warning messages are not required.
            var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
            var loggerConfig  = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug)
                                .WriteTo.Console()
                                .CreateLogger();

            loggerFactory.AddSerilog(loggerConfig);
            SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;

            SIPURI callUri = SIPURI.ParseSIPURI(DEFAULT_DESTINATION_SIP_URI);

            if (args != null && args.Length > 0)
            {
                if (!SIPURI.TryParse(args[0]))
                {
                    Log.LogWarning($"Command line argument could not be parsed as a SIP URI {args[0]}");
                }
                else
                {
                    callUri = SIPURI.ParseSIPURIRelaxed(args[0]);
                }
            }

            Log.LogInformation($"Call destination {callUri}.");

            // Set up a default SIP transport.
            var       sipTransport = new SIPTransport();
            int       port         = SIPConstants.DEFAULT_SIP_PORT + 1000;
            IPAddress localAddress = sipTransport.GetLocalAddress(IPAddress.Parse("8.8.8.8"));

            sipTransport.AddSIPChannel(new SIPUDPChannel(new IPEndPoint(localAddress, port)));
            //sipTransport.AddSIPChannel(new SIPUDPChannel(new IPEndPoint(IPAddress.Any, port)));
            //sipTransport.AddSIPChannel(new SIPUDPChannel(new IPEndPoint(IPAddress.IPv6Any, port)));

            //EnableTraceLogs(sipTransport);

            // Select the IP address to use for RTP based on the destination SIP URI.
            var endPointForCall = callUri.ToSIPEndPoint() == null?sipTransport.GetDefaultSIPEndPoint(callUri.Protocol) : sipTransport.GetDefaultSIPEndPoint(callUri.ToSIPEndPoint());

            // Initialise an RTP session to receive the RTP packets from the remote SIP server.
            Socket rtpSocket     = null;
            Socket controlSocket = null;
            // TODO (find something better): If the SIP endpoint is using 0.0.0.0 for SIP use loopback for RTP.
            IPAddress rtpAddress = localAddress;

            NetServices.CreateRtpSocket(rtpAddress, 49000, 49100, false, out rtpSocket, out controlSocket);
            var rtpSendSession = new RTPSession((int)RTPPayloadTypesEnum.PCMU, null, null);

            // Create a client user agent to place a call to a remote SIP server along with event handlers for the different stages of the call.
            var uac = new SIPClientUserAgent(sipTransport);

            uac.CallTrying += (uac, resp) =>
            {
                Log.LogInformation($"{uac.CallDescriptor.To} Trying: {resp.StatusCode} {resp.ReasonPhrase}.");
            };
            uac.CallRinging += (uac, resp) => Log.LogInformation($"{uac.CallDescriptor.To} Ringing: {resp.StatusCode} {resp.ReasonPhrase}.");
            uac.CallFailed  += (uac, err) =>
            {
                Log.LogWarning($"{uac.CallDescriptor.To} Failed: {err}");
                hasCallFailed = true;
            };
            uac.CallAnswered += (uac, resp) =>
            {
                if (resp.Status == SIPResponseStatusCodesEnum.Ok)
                {
                    Log.LogInformation($"{uac.CallDescriptor.To} Answered: {resp.StatusCode} {resp.ReasonPhrase}.");

                    IPEndPoint remoteRtpEndPoint = SDP.GetSDPRTPEndPoint(resp.Body);

                    Log.LogDebug($"Sending initial RTP packet to remote RTP socket {remoteRtpEndPoint}.");

                    // Send a dummy packet to open the NAT session on the RTP path.
                    rtpSendSession.SendAudioFrame(rtpSocket, remoteRtpEndPoint, 0, new byte[] { 0x00 });
                }
                else
                {
                    Log.LogWarning($"{uac.CallDescriptor.To} Answered: {resp.StatusCode} {resp.ReasonPhrase}.");
                }
            };

            // The only incoming request that needs to be explicitly handled for this example is if the remote end hangs up the call.
            sipTransport.SIPTransportRequestReceived += (SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest) =>
            {
                if (sipRequest.Method == SIPMethodsEnum.BYE)
                {
                    SIPNonInviteTransaction byeTransaction = sipTransport.CreateNonInviteTransaction(sipRequest, remoteEndPoint, localSIPEndPoint, null);
                    SIPResponse             byeResponse    = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                    byeTransaction.SendFinalResponse(byeResponse);

                    if (uac.IsUACAnswered)
                    {
                        Log.LogInformation("Call was hungup by remote server.");
                        isCallHungup = true;
                        rtpCts.Cancel();
                    }
                }
            };

            // It's a good idea to start the RTP receiving socket before the call request is sent.
            // A SIP server will generally start sending RTP as soon as it has processed the incoming call request and
            // being ready to receive will stop any ICMP error response being generated.
            Task.Run(() => SendRecvRtp(rtpSocket, rtpSendSession, rtpCts));

            // Start the thread that places the call.
            SIPCallDescriptor callDescriptor = new SIPCallDescriptor(
                SIPConstants.SIP_DEFAULT_USERNAME,
                null,
                callUri.ToString(),
                SIPConstants.SIP_DEFAULT_FROMURI,
                null, null, null, null,
                SIPCallDirection.Out,
                SDP.SDP_MIME_CONTENTTYPE,
                GetSDP(rtpSocket.LocalEndPoint as IPEndPoint).ToString(),
                null);

            uac.Call(callDescriptor);

            // Ctrl-c will gracefully exit the call at any point.
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                rtpCts.Cancel();
            };

            // At this point the call has been initiated and everything will be handled in an event handler or on the RTP
            // receive task. The code below is to gracefully exit.

            // Wait for a signal saying the call failed, was cancelled with ctrl-c or completed.
            rtpCts.Token.WaitHandle.WaitOne();

            Log.LogInformation("Exiting...");

            rtpSocket?.Close();
            controlSocket?.Close();

            if (!isCallHungup && uac != null)
            {
                if (uac.IsUACAnswered)
                {
                    Log.LogInformation($"Hanging up call to {uac.CallDescriptor.To}.");
                    uac.Hangup();
                }
                else if (!hasCallFailed)
                {
                    Log.LogInformation($"Cancelling call to {uac.CallDescriptor.To}.");
                    uac.Cancel();
                }

                // Give the BYE or CANCEL request time to be transmitted.
                Log.LogInformation("Waiting 1s for call to clean up...");
                Task.Delay(1000).Wait();
            }

            SIPSorcery.Net.DNSManager.Stop();

            if (sipTransport != null)
            {
                Log.LogInformation("Shutting down SIP transport...");
                sipTransport.Shutdown();
            }
        }
        static async Task Setup()
        {
            appSettings = new ConfigurationBuilder()
                          .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                          .AddJsonFile("appSettings.json")
                          .Build()
                          .Get <AppSettings>();

            var logger = new Microsoft.Extensions.Logging.LoggerFactory().CreateLogger("DigitalTwins");

            httpClient = new HttpClient(new LoggingHttpHandler(logger))
            {
                BaseAddress = new Uri($"{appSettings.BaseUrl}/api/v1.0/"),
            };
            var accessTokenFilename = ".accesstoken";
            var accessToken         = System.IO.File.Exists(accessTokenFilename) ? System.IO.File.ReadAllText(accessTokenFilename) : null;

            if (accessToken != null)
            {
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
            }

            // just a random query to check if authorized
            if (!(await httpClient.GetAsync("ontologies")).IsSuccessStatusCode)
            {
                var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(appSettings.Authority);
                var codeResult  = await authContext.AcquireDeviceCodeAsync(appSettings.Resource, appSettings.ClientId);

                Console.WriteLine(codeResult.Message);
                accessToken = (await authContext.AcquireTokenByDeviceCodeAsync(codeResult)).AccessToken;
                System.IO.File.WriteAllText(accessTokenFilename, accessToken);
                if (httpClient.DefaultRequestHeaders.Contains("Authorization"))
                {
                    httpClient.DefaultRequestHeaders.Remove("Authorization");
                }
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
            }

            clients = new Clients(httpClient);

            spaces  = clients.SpacesClient.Get();
            devices = clients.DevicesClient.Get();

            var ids = await clients.SpacesClient.RetrieveAsync(name : "root");

            if (ids.Any())
            {
                rootId = ids.First().Id;
            }
            else
            {
                rootId = await clients.SpacesClient.CreateAsync(new SpaceCreate
                {
                    Name   = "root",
                    TypeId = 59 // Tenant
                });
            }

            spaceTypes       = clients.TypesClient.Get(ExtendedTypeCreateCategory.SpaceType, rootId);
            deviceTypes      = clients.TypesClient.Get(ExtendedTypeCreateCategory.DeviceType, rootId);
            sensorTypes      = clients.TypesClient.Get(ExtendedTypeCreateCategory.SensorType, rootId);
            sensorDataTypes  = clients.TypesClient.Get(ExtendedTypeCreateCategory.SensorDataType, rootId);
            spaceBlobType    = clients.TypesClient.Get(ExtendedTypeCreateCategory.SpaceBlobType, rootId);
            spaceBlobSubType = clients.TypesClient.Get(ExtendedTypeCreateCategory.SpaceBlobSubtype, rootId);
        }
Beispiel #54
-1
        static void Main(string[] args)
        {
            try
            {
                ILogger logger  = new Microsoft.Extensions.Logging.LoggerFactory().CreateLogger("Shopping.ConsoleUI");
                var     app     = Bootstrapper.Bootstrap(logger);
                var     program = new Program(app);
                program.StartAsync().GetAwaiter().GetResult();;
            }
            catch (Exception e)
            {
                var color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.Message);
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine(e);
                Console.ForegroundColor = color;
            }

            finally
            {
                Console.WriteLine("Hit enter to exit");
                Console.ReadLine();
            }
        }
Beispiel #55
-1
        public TestHelper()
        {
            LoggerFactory = new LoggerFactory();

            var testVerbose = Environment.GetEnvironmentVariable("DOTNET_TEST_VERBOSE");
            if (testVerbose == "2")
            {
                LoggerFactory.AddConsole(LogLevel.Trace);
            }
            else if (testVerbose == "1")
            {
                LoggerFactory.AddConsole(LogLevel.Information);
            }
            else
            {
                LoggerFactory.AddConsole(LogLevel.Warning);
            }

            _tempPath = CreateTempFolder();
            var dthTestProjectsFolder = Path.Combine(FindRoot(), "testapp", "DthTestProjects");
            CopyFiles(dthTestProjectsFolder, _tempPath);

            var logger = LoggerFactory.CreateLogger<TestHelper>();
            logger.LogInformation($"Test projects are copied to {_tempPath}");
        }
        public void AspNetCoreLogging_MinLogLevel_Debug()
        {
            var external = new LoggerFactory();

            // TODO: remove in RC2
            external.MinimumLevel = LogLevel.Debug;
            // TODO: change Debug to Trace in RC2 (yes, in RC1 Verbose is higher than debug, and Verbose got renamed to Trace, later, too!)
            external.AddConsole(LogLevel.Verbose);

            var loggerFactory = new MicrosoftLoggerFactoryAdapter(external);
            var logger = loggerFactory.CreateLogger("cat");

            logger.Should().NotBeNull();
            logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse();
            logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeTrue();
            logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeTrue();
            logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeTrue();
            logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue();
            logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue();
        }