Example #1
0
        public static IConfiguration ConfigureNLog(this IConfiguration configuration, ILogger logger = null)
        {
            try
            {
                logger?.LogInformation("Configuration has been reloaded - applying LoggingConfiguration");

                var nLogSection = configuration.GetSection("LoggingConfiguration")?.GetSection("NLog");

                if (nLogSection is null)
                {
                    logger?.LogInformation("Section JsonLoggingConfiguration:NLog not found; skipping reconfiguration");
                    return(configuration);
                }

                LogManager.Configuration = new NLogLoggingConfiguration(nLogSection);

                logger?.LogInformation("new LoggingConfiguration has been applied");
            }
            catch (Exception e)
            {
                logger?.LogWarning($"new LoggingConfiguration could not be applied: {e}");
            }

            return(configuration);
        }
 public StorageLoader(CloudStorageAccount storageAccount, string containerName, FrameworkLogger logger)
 {
     logger.LogInformation("StorageLoader container: {ContainerName}", containerName);
     _storageAccount = storageAccount;
     _containerName = containerName;
     _logger = logger;
 }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            // add NLog for logging
            loggerFactory.AddNLog(new LogFactory(new NLog.Config.XmlLoggingConfiguration(logConfigurationFile)));
            _log = loggerFactory.CreateLogger<Startup>();

            // generate some log output
            _log.LogInformation("Happy table logging!");
            _log.LogInformation(string.Format("Log configuration: {0}", logConfigurationFile));

            app.UseIISPlatformHandler();

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
Example #4
0
        public async Task RunAsync(CancellationToken token)
        {
            try
            {
                await StartAsync();

                var waitForStop = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);
                token.Register(_ => waitForStop.TrySetResult(null), null);

                await waitForStop.Task;
            }
            finally
            {
                await StopAsync();

                _logger?.LogInformation("Goodbye. 👋");
            }
        }
        /// <summary>
        /// Starts the hosted service and initializes the consumer or producer by either setting up the consumption of
        /// messages or by starting the producer's message queueing functionality.
        ///
        /// For details on the default implementations of consumers and producers, see <see cref="RabbitMqConsumer{T}"/>
        /// and <see cref="RabbitMqProducer{T}"/>.
        /// </summary>
        /// <param name="cancellationToken"/>
        /// <returns/>
        public virtual Task StartAsync(CancellationToken cancellationToken)
        {
            Debug.Assert(
                _isProperlyInitialized,
                $"This {nameof(RabbitMqService<T>)} instance should have been created through a call to " +
                $"{nameof(RabbitMqService<T>)}.{nameof(Create)}.");

            _logger?.LogInformation($"RabbitMqService {_rmqConfig.Id} is starting.");

            if (Bus.IsConnected)
            {
                _logger?.LogDebug($"Connected to RabbitMQ with configuration {_rmqConfig.Id}.");
            }

            Bus.Connected += (sender, args) =>
                             _logger?.LogDebug($"Connected to RabbitMQ with configuration {_rmqConfig.Id}.");

            Bus.Disconnected += (sender, args) =>
                                _logger?.LogDebug($"Disconnected from RabbitMQ with configuration {_rmqConfig.Id}.");

            // run the setup callbacks on connection

            if (Bus.IsConnected)
            {
                _onConnected.ForEach(callback =>
                                     HandleCallbackError(callback)(Bus, _rmqConfig, cancellationToken, _logger));
            }

            _onConnected.ForEach(callback => Bus.Connected += (sender, args) =>
                                                              HandleCallbackError(callback)(Bus, _rmqConfig, cancellationToken, _logger));

            if (_isConsumer)
            {
                InitializeConsumer(cancellationToken);
            }
            else
            {
                InitializeProducer(cancellationToken);
            }

            return(Task.CompletedTask);
        }
Example #6
0
        public static async Task Main(string[] args)
        {
            ILogger logger = null;

            try
            {
                var host = BuildHost(args);
                logger = host.Services.GetRequiredService <ILogger <Program> >();
                logger?.LogInformation("Worker starting...");
                await host.RunAsync();

                logger?.LogInformation("Worker ended.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                logger?.LogCritical(ex, "Worker terminated unexpectedly.");
            }
            finally
            {
                await Task.Delay(10000);
            }
        }
Example #7
0
        public async Task RunAsync()
        {
            try
            {
                await StartAsync();

                var waitForStop = new TaskCompletionSource <object?>(TaskCreationOptions.RunContinuationsAsynchronously);
                _lifetime?.ApplicationStopping.Register(obj =>
                {
                    _logger?.LogInformation("Tye Host is stopping...");
                    waitForStop.TrySetResult(null);
                }, null);
                await waitForStop.Task;
            }
            finally
            {
                await StopAsync();
            }
        }
        public static IReadOnlyDictionary<string, int> Load(string name, ILoader loader, FrameworkLogger logger)
        {
            try
            {
                using (JsonReader jsonReader = loader.GetReader(name))
                {
                    return CreateDictionary(jsonReader);
                }
            }
            catch (Exception e)
            {
                if (IndexingUtils.IsFatal(e))
                {
                    throw;
                }

                logger.LogInformation("Unable to load {0}. Exception Message : {1}", name, e.Message);

                return new Dictionary<string, int>();
            }
        }
Example #9
0
 public void WriteInfo(string message)
 {
     log.LogInformation(message);
 }
Example #10
0
 public void LogInformation(string message)
 {
     _logger.LogInformation(message);
 }
Example #11
0
        static void Main(string[] args)
        {
            Console.WriteLine("SIPSorcery SIP to WebRTC example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource exitCts = new CancellationTokenSource(); // Cancellation token to stop the SIP transport and RTP stream.

            AddConsoleLogger();

            // Start web socket.
            Console.WriteLine("Starting web socket server...");
            _webSocketServer = new WebSocketServer(IPAddress.Any, WEBSOCKET_PORT, true);
            _webSocketServer.SslConfiguration.ServerCertificate          = new X509Certificate2(WEBSOCKET_CERTIFICATE_PATH);
            _webSocketServer.SslConfiguration.CheckCertificateRevocation = false;
            //_webSocketServer.Log.Level = WebSocketSharp.LogLevel.Debug;
            _webSocketServer.AddWebSocketService <SDPExchange>("/", (sdpExchanger) =>
            {
                sdpExchanger.WebSocketOpened   += SendSDPOffer;
                sdpExchanger.SDPAnswerReceived += SDPAnswerReceived;
            });
            _webSocketServer.Start();

            Console.WriteLine($"Waiting for browser web socket connection to {_webSocketServer.Address}:{_webSocketServer.Port}...");

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

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

            //EnableTraceLogs(sipTransport);

            RTPMediaSession RtpMediaSession = null;

            // Create a SIP user agent to receive a call from a remote SIP client.
            // Wire up event handlers for the different stages of the call.
            var userAgent = new SIPUserAgent(sipTransport, null);

            // We're only answering SIP calls, not placing them.
            userAgent.OnCallHungup += () =>
            {
                Log.LogInformation($"Call hungup by remote party.");
                exitCts.Cancel();
            };
            userAgent.ServerCallCancelled += (uas) => Log.LogInformation("Incoming call cancelled by caller.");

            sipTransport.SIPTransportRequestReceived += async(localEndPoint, remoteEndPoint, sipRequest) =>
            {
                if (sipRequest.Header.From != null &&
                    sipRequest.Header.From.FromTag != null &&
                    sipRequest.Header.To != null &&
                    sipRequest.Header.To.ToTag != null)
                {
                    // This is an in-dialog request that will be handled directly by a user agent instance.
                }
                else if (sipRequest.Method == SIPMethodsEnum.INVITE)
                {
                    if (userAgent?.IsCallActive == true)
                    {
                        Log.LogWarning($"Busy response returned for incoming call request from {remoteEndPoint}: {sipRequest.StatusLine}.");
                        // If we are already on a call return a busy response.
                        UASInviteTransaction uasTransaction = new UASInviteTransaction(sipTransport, sipRequest, null);
                        SIPResponse          busyResponse   = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.BusyHere, null);
                        uasTransaction.SendFinalResponse(busyResponse);
                    }
                    else
                    {
                        Log.LogInformation($"Incoming call request from {remoteEndPoint}: {sipRequest.StatusLine}.");
                        var incomingCall = userAgent.AcceptCall(sipRequest);

                        RtpMediaSession = new RTPMediaSession(SDPMediaTypesEnum.audio, (int)SDPMediaFormatsEnum.PCMU, AddressFamily.InterNetwork);
                        await userAgent.Answer(incomingCall, RtpMediaSession);

                        RtpMediaSession.OnRtpPacketReceived += (rtpPacket) => OnMediaSampleReady?.Invoke(SDPMediaTypesEnum.audio, rtpPacket.Header.Timestamp, rtpPacket.Payload);

                        Log.LogInformation($"Answered incoming call from {sipRequest.Header.From.FriendlyDescription()} at {remoteEndPoint}.");
                    }
                }
                else
                {
                    Log.LogDebug($"SIP {sipRequest.Method} request received but no processing has been set up for it, rejecting.");
                    SIPResponse notAllowedResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.MethodNotAllowed, null);
                    await sipTransport.SendResponseAsync(notAllowedResponse);
                }
            };

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

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

            #region Cleanup.

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

            RtpMediaSession?.Close();

            if (userAgent != null)
            {
                if (userAgent.IsCallActive)
                {
                    Log.LogInformation($"Hanging up call to {userAgent?.CallDescriptor?.To}.");
                    userAgent.Hangup();
                }

                // 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();
            }

            #endregion
        }
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            var jobOptions = new JobRunnerOptions(args);

            Console.Title = jobOptions.JobName != null ? $"Exceptionless {jobOptions.JobName} Job" : "Exceptionless Jobs";

            string environment = Environment.GetEnvironmentVariable("EX_AppMode");

            if (String.IsNullOrWhiteSpace(environment))
            {
                environment = "Production";
            }

            string currentDirectory = Directory.GetCurrentDirectory();
            var    config           = new ConfigurationBuilder()
                                      .SetBasePath(currentDirectory)
                                      .AddYamlFile("appsettings.yml", optional: true, reloadOnChange: true)
                                      .AddYamlFile($"appsettings.{environment}.yml", optional: true, reloadOnChange: true)
                                      .AddEnvironmentVariables("EX_")
                                      .AddCommandLine(args)
                                      .Build();

            var options = AppOptions.ReadFromConfiguration(config);

            var loggerConfig = new LoggerConfiguration().ReadFrom.Configuration(config);

            if (!String.IsNullOrEmpty(options.ExceptionlessApiKey))
            {
                loggerConfig.WriteTo.Sink(new ExceptionlessSink(), LogEventLevel.Verbose);
            }

            var serilogLogger = loggerConfig.CreateLogger();

            _logger = new SerilogLoggerFactory(serilogLogger).CreateLogger <Program>();

            var configDictionary = config.ToDictionary("Serilog");

            _logger.LogInformation("Bootstrapping Exceptionless {JobName} job(s) in {AppMode} mode ({InformationalVersion}) on {MachineName} with settings {@Settings}", jobOptions.JobName ?? "All", environment, options.InformationalVersion, Environment.MachineName, configDictionary);

            bool useApplicationInsights = !String.IsNullOrEmpty(options.ApplicationInsightsKey);

            var builder = WebHost.CreateDefaultBuilder(args)
                          .UseEnvironment(environment)
                          .UseConfiguration(config)
                          .UseDefaultServiceProvider((ctx, o) => {
                o.ValidateScopes = ctx.HostingEnvironment.IsDevelopment();
            })
                          .ConfigureKestrel(c => {
                c.AddServerHeader = false;
                //c.AllowSynchronousIO = false; // TODO: Investigate issue with JSON Serialization.
            })
                          .UseSerilog(serilogLogger, true)
                          .ConfigureServices((ctx, services) => {
                services.AddHttpContextAccessor();

                AddJobs(services, jobOptions);

                if (useApplicationInsights)
                {
                    services.AddApplicationInsightsTelemetry();
                }

                Bootstrapper.RegisterServices(services);
                var serviceProvider = services.BuildServiceProvider();
                Insulation.Bootstrapper.RegisterServices(serviceProvider, services, options, true);

                services.PostConfigure <HostFilteringOptions>(o => {
                    if (o.AllowedHosts == null || o.AllowedHosts.Count == 0)
                    {
                        // "AllowedHosts": "localhost;127.0.0.1;[::1]"
                        var hosts = ctx.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        // Fall back to "*" to disable.
                        o.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
                    }
                });

                services.AddSingleton <IOptionsChangeTokenSource <HostFilteringOptions> >(new ConfigurationChangeTokenSource <HostFilteringOptions>(ctx.Configuration));
                services.AddTransient <IStartupFilter, HostFilteringStartupFilter>();
            })
                          .Configure(app => {
                Bootstrapper.LogConfiguration(app.ApplicationServices, options, _logger);

                if (!String.IsNullOrEmpty(options.ExceptionlessApiKey) && !String.IsNullOrEmpty(options.ExceptionlessServerUrl))
                {
                    app.UseExceptionless(ExceptionlessClient.Default);
                }

                app.UseHealthChecks("/health", new HealthCheckOptions {
                    Predicate = hcr => !String.IsNullOrEmpty(jobOptions.JobName) ? hcr.Tags.Contains(jobOptions.JobName) : hcr.Tags.Contains("AllJobs")
                });

                app.UseHealthChecks("/ready", new HealthCheckOptions {
                    Predicate = hcr => hcr.Tags.Contains("Critical")
                });

                app.UseWaitForStartupActionsBeforeServingRequests();
                app.Use((context, func) => context.Response.WriteAsync($"Running Job: {jobOptions.JobName}"));
            });

            if (String.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
            {
                builder.UseContentRoot(Directory.GetCurrentDirectory());
            }

            if (useApplicationInsights)
            {
                builder.UseApplicationInsights(options.ApplicationInsightsKey);
            }

            var metricOptions = MetricOptions.ReadFromConfiguration(config);

            if (!String.IsNullOrEmpty(metricOptions.Provider))
            {
                ConfigureMetricsReporting(builder, metricOptions);
            }

            return(builder);
        }
Example #13
0
        /// <summary>
        /// Main background task.
        /// </summary>
        /// <param name="taskInstance"></param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral              = taskInstance.GetDeferral();
            taskInstance.Canceled += TaskInstanceCanceled;

            try
            {
                // Copy the appsetting.json file if necessary.
                if (CopyAppSettings().Result)
                {
                    // Set the default culture.
                    CultureInfo.CurrentCulture = new CultureInfo("en-US");

                    // Read the application settings file containing the Serilog configuration.
                    var configuration = new ConfigurationBuilder()
                                        .SetBasePath(ApplicationData.Current.LocalFolder.Path)
                                        .AddJsonFile("appsettings.json", false, false)
                                        .AddEnvironmentVariables()
                                        .Build();

                    configuration.GetSection("AppSettings")?.Bind(_settings);

                    // Setting up the static Serilog logger.
                    //Log.Logger = new LoggerConfiguration()
                    //    .ReadFrom.Configuration(configuration)
                    //    .Enrich.FromLogContext()
                    //    .CreateLogger();

                    StorageFolder folder   = ApplicationData.Current.LocalFolder;
                    string        fullPath = folder.Path + "\\Logs\\{Date}.log";

                    Log.Logger = new LoggerConfiguration()
                                 .MinimumLevel.Debug()
                                 .Enrich.FromLogContext()
                                 .WriteTo.RollingFile(fullPath)
                                 .CreateLogger();

                    // Setting up the application logger.
                    var services = new ServiceCollection()
                                   .AddLogging(builder =>
                    {
                        builder.AddSerilog();
                    });

                    // Add services.
                    services.AddSingleton <ILoggerFactory>(logger => new SerilogLoggerFactory(null, true));
                    services.Configure <SettingsData>(configuration.GetSection("AppSettings"));
                    services.Configure <AppSettings>(configuration.GetSection("AppSettings"));
                    services.AddSingleton <ISettingsData, SettingsData>();

                    // Setting up the Zipato HTTP client.
                    services.AddHttpClient <IZipatoClient, ZipatoClient>(client =>
                    {
                        client.BaseAddress = new Uri(_settings.Servers.Zipato);
                        client.Timeout     = TimeSpan.FromSeconds(_settings.Timeout);
                    })
                    .ConfigureHttpMessageHandlerBuilder(config => new HttpClientHandler
                    {
                        ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); }
                    })
                    .AddPolicyHandler(HttpPolicyExtensions
                                      .HandleTransientHttpError()
                                      .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
                                      .WaitAndRetryAsync(_settings.Retries,
                                                         attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt))));

                    // Setup the data values.
                    services.AddSingleton <NetatmoValues>();
                    services.AddSingleton <ETAPU11Values>();
                    services.AddSingleton <EM300LRValues>();
                    services.AddSingleton <FroniusValues>();
                    services.AddSingleton <KWLEC200Values>();
                    services.AddSingleton <HomeDataValues>();
                    services.AddSingleton <WallboxValues>();

                    // Build the service provider and add the logger.
                    var serviceProvider = services.BuildServiceProvider();
                    _logger = serviceProvider.GetService <ILogger <StartupTask> >();

                    // Get the data values instances.
                    _netatmoValues  = ActivatorUtilities.CreateInstance <NetatmoValues>(serviceProvider);
                    _etapu11Values  = ActivatorUtilities.CreateInstance <ETAPU11Values>(serviceProvider);
                    _em300lrValues  = ActivatorUtilities.CreateInstance <EM300LRValues>(serviceProvider);
                    _froniusValues  = ActivatorUtilities.CreateInstance <FroniusValues>(serviceProvider);
                    _kwlec200Values = ActivatorUtilities.CreateInstance <KWLEC200Values>(serviceProvider);
                    _homeDataValues = ActivatorUtilities.CreateInstance <HomeDataValues>(serviceProvider);
                    _wallboxValues  = ActivatorUtilities.CreateInstance <WallboxValues>(serviceProvider);

                    // Update immediately.
                    ThreadPoolTimer.CreateTimer(async(timer) => await SendValuesAsync(), TimeSpan.Zero);

                    // Setup periodic timer (updating every 60 seconds).
                    _timer = ThreadPoolTimer.CreatePeriodicTimer(async(timer) => await SendValuesAsync(), TimeSpan.FromMinutes(1));
                }
                else
                {
                    throw new ApplicationException("StartupTask application settings not found.");
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, $"Exception StartupTask.");
                _deferral.Complete();
            }

            _logger?.LogInformation($"StartupTask done.");
        }
Example #14
0
        public void ProcessEvents(string applicationName,
                                  string serviceName,
                                  int processId,
                                  string replicaName,
                                  ReplicaStatus replica,
                                  CancellationToken cancellationToken)
        {
            var hasEventPipe = false;

            for (int i = 0; i < 10; ++i)
            {
                if (DiagnosticsClient.GetPublishedProcesses().Contains(processId))
                {
                    hasEventPipe = true;
                    break;
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                Thread.Sleep(500);
            }

            if (!hasEventPipe)
            {
                _logger.LogInformation("Process id {PID}, does not support event pipe", processId);
                return;
            }

            _logger.LogInformation("Listening for event pipe events for {ServiceName} on process id {PID}", replicaName, processId);

            // Create the logger factory for this replica
            using var loggerFactory = LoggerFactory.Create(builder => ConfigureLogging(serviceName, replicaName, builder));

            // Create the tracer for this replica
            Tracer tracer = null;

            using var tracerFactory = TracerFactory.Create(builder =>
            {
                builder.AddCollector(t =>
                {
                    tracer = t;
                    return(t);
                });

                ConfigureTracing(serviceName, replicaName, builder);
            });

            var providers = new List <EventPipeProvider>()
            {
                // Runtime Metrics
                new EventPipeProvider(
                    SystemRuntimeEventSourceName,
                    EventLevel.Informational,
                    (long)ClrTraceEventParser.Keywords.None,
                    new Dictionary <string, string>()
                {
                    { "EventCounterIntervalSec", "1" }
                }
                    ),
                new EventPipeProvider(
                    MicrosoftAspNetCoreHostingEventSourceName,
                    EventLevel.Informational,
                    (long)ClrTraceEventParser.Keywords.None,
                    new Dictionary <string, string>()
                {
                    { "EventCounterIntervalSec", "1" }
                }
                    ),
                new EventPipeProvider(
                    GrpcAspNetCoreServer,
                    EventLevel.Informational,
                    (long)ClrTraceEventParser.Keywords.None,
                    new Dictionary <string, string>()
                {
                    { "EventCounterIntervalSec", "1" }
                }
                    ),

                // Application Metrics
                new EventPipeProvider(
                    applicationName,
                    EventLevel.Informational,
                    (long)ClrTraceEventParser.Keywords.None,
                    new Dictionary <string, string>()
                {
                    { "EventCounterIntervalSec", "1" }
                }
                    ),

                // Logging
                new EventPipeProvider(
                    MicrosoftExtensionsLoggingProviderName,
                    EventLevel.LogAlways,
                    (long)(LoggingEventSource.Keywords.JsonMessage | LoggingEventSource.Keywords.FormattedMessage)
                    ),

                // Distributed Tracing

                // Activity correlation
                new EventPipeProvider(TplEventSource,
                                      keywords: 0x80,
                                      eventLevel: EventLevel.LogAlways),

                // Diagnostic source events
                new EventPipeProvider(DiagnosticSourceEventSource,
                                      keywords: 0x1 | 0x2,
                                      eventLevel: EventLevel.Verbose,
                                      arguments: new Dictionary <string, string>
                {
                    { "FilterAndPayloadSpecs", DiagnosticFilterString }
                })
            };

            while (!cancellationToken.IsCancellationRequested)
            {
                EventPipeSession session = null;
                var client = new DiagnosticsClient(processId);

                try
                {
                    session = client.StartEventPipeSession(providers);
                }
                catch (EndOfStreamException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    if (!cancellationToken.IsCancellationRequested)
                    {
                        _logger.LogDebug(0, ex, "Failed to start the event pipe session");
                    }

                    // We can't even start the session, wait until the process boots up again to start another metrics thread
                    break;
                }

                void StopSession()
                {
                    try
                    {
                        session.Stop();
                    }
                    catch (EndOfStreamException)
                    {
                        // If the app we're monitoring exits abruptly, this may throw in which case we just swallow the exception and exit gracefully.
                    }
                    // We may time out if the process ended before we sent StopTracing command. We can just exit in that case.
                    catch (TimeoutException)
                    {
                    }
                    // On Unix platforms, we may actually get a PNSE since the pipe is gone with the process, and Runtime Client Library
                    // does not know how to distinguish a situation where there is no pipe to begin with, or where the process has exited
                    // before dotnet-counters and got rid of a pipe that once existed.
                    // Since we are catching this in StopMonitor() we know that the pipe once existed (otherwise the exception would've
                    // been thrown in StartMonitor directly)
                    catch (PlatformNotSupportedException)
                    {
                    }
                }

                using var _ = cancellationToken.Register(() => StopSession());

                try
                {
                    var source     = new EventPipeEventSource(session.EventStream);
                    var activities = new Dictionary <string, ActivityItem>();

                    source.Dynamic.All += traceEvent =>
                    {
                        try
                        {
                            // Uncomment to debug the diagnostics source event source
                            //if (traceEvent.EventName == "Message")
                            //{
                            //    _logger.LogTrace("[" + replicaName + "]:" + traceEvent.PayloadValue(0));
                            //}
                            //// Distributed tracing
                            // else
                            if (traceEvent.EventName == "Activity1Start/Start")
                            {
                                var listenerEventName = (string)traceEvent.PayloadByName("EventName");

                                if (traceEvent.PayloadByName("Arguments") is IDictionary <string, object>[] arguments)
                                {
                                    string           activityId    = null;
                                    string           parentId      = null;
                                    string           operationName = null;
                                    string           httpMethod    = null;
                                    string           path          = null;
                                    DateTime         startTime     = default;
                                    ActivityIdFormat idFormat      = default;

                                    foreach (var arg in arguments)
                                    {
                                        var key   = (string)arg["Key"];
                                        var value = (string)arg["Value"];

                                        if (key == "ActivityId")
                                        {
                                            activityId = value;
                                        }
                                        else if (key == "ActivityParentId")
                                        {
                                            parentId = value;
                                        }
                                        else if (key == "ActivityOperationName")
                                        {
                                            operationName = value;
                                        }
                                        else if (key == "Method")
                                        {
                                            httpMethod = value;
                                        }
                                        else if (key == "Path")
                                        {
                                            path = value;
                                        }
                                        else if (key == "ActivityStartTime")
                                        {
                                            startTime = new DateTime(long.Parse(value), DateTimeKind.Utc);
                                        }
                                        else if (key == "ActivityIdFormat")
                                        {
                                            idFormat = Enum.Parse <ActivityIdFormat>(value);
                                        }
                                    }

                                    if (string.IsNullOrEmpty(activityId))
                                    {
                                        // Not a 3.1 application (we can detect this earlier)
                                        return;
                                    }

                                    // REVIEW: We need to create the Span with the specific trace and span id that came from remote process
                                    // but OpenTelemetry doesn't currently have an easy way to do that so this only works for a single
                                    // process as we're making new ids instead of using the ones in the application.
                                    //if (idFormat == ActivityIdFormat.Hierarchical)
                                    //{
                                    //    // We need W3C to make it work
                                    //    return;
                                    //}

                                    // This is what open telemetry currently does
                                    // https://github.com/open-telemetry/opentelemetry-dotnet/blob/4ba732af062ddc2759c02aebbc91335aaa3f7173/src/OpenTelemetry.Collector.AspNetCore/Implementation/HttpInListener.cs#L65-L92

                                    ISpan parentSpan = null;

                                    if (!string.IsNullOrEmpty(parentId) &&
                                        activities.TryGetValue(parentId, out var parentItem))
                                    {
                                        parentSpan = parentItem.Span;
                                    }

                                    var span = tracer.StartSpan(path, parentSpan, SpanKind.Server, new SpanCreationOptions {
                                        StartTimestamp = startTime
                                    });

                                    // REVIEW: Things we're unable to do
                                    // - We can't get a headers
                                    // - We can't get at features in the feature collection of the HttpContext
                                    span.PutHttpPathAttribute(path);
                                    span.PutHttpMethodAttribute(httpMethod);
                                    span.SetAttribute("service.instance", replicaName);

                                    activities[activityId] = new ActivityItem
                                    {
                                        Span      = span,
                                        StartTime = startTime
                                    };
                                }
                            }
                            else if (traceEvent.EventName == "Activity1Stop/Stop")
                            {
                                var listenerEventName = (string)traceEvent.PayloadByName("EventName");

                                if (traceEvent.PayloadByName("Arguments") is IDictionary <string, object>[] arguments)
                                {
                                    string   activityId = null;
                                    TimeSpan duration   = default;
                                    int      statusCode = 0;

                                    foreach (var arg in arguments)
                                    {
                                        var key   = (string)arg["Key"];
                                        var value = (string)arg["Value"];

                                        if (key == "ActivityId")
                                        {
                                            activityId = value;
                                        }
                                        else if (key == "StatusCode")
                                        {
                                            statusCode = int.Parse(value);
                                        }
                                        else if (key == "ActivityDuration")
                                        {
                                            duration = new TimeSpan(long.Parse(value));
                                        }
                                    }

                                    if (string.IsNullOrEmpty(activityId))
                                    {
                                        // Not a 3.1 application (we can detect this earlier)
                                        return;
                                    }

                                    if (activities.TryGetValue(activityId, out var activityItem))
                                    {
                                        var span = activityItem.Span;

                                        span.PutHttpStatusCode(statusCode, null);

                                        span.End(activityItem.StartTime + duration);

                                        activities.Remove(activityId);
                                    }
                                }
                            }
                            else if (traceEvent.EventName == "Activity2Start/Start")
                            {
                                var listenerEventName = (string)traceEvent.PayloadByName("EventName");

                                _logger.LogDebug("[" + replicaName + "]: " + listenerEventName + " fired");
                            }
                            else if (traceEvent.EventName == "Activity2Stop/Stop")
                            {
                                var listenerEventName = (string)traceEvent.PayloadByName("EventName");

                                _logger.LogDebug("[" + replicaName + "]: " + listenerEventName + " fired");
                            }

                            // Metrics
                            else if (traceEvent.EventName.Equals("EventCounters"))
                            {
                                var payloadVal   = (IDictionary <string, object>)traceEvent.PayloadValue(0);
                                var eventPayload = (IDictionary <string, object>)payloadVal["Payload"];

                                ICounterPayload payload = CounterPayload.FromPayload(eventPayload);

                                replica.Metrics[traceEvent.ProviderName + "/" + payload.Name] = payload.Value;
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "Error processing counter for {ProviderName}:{EventName}", traceEvent.ProviderName, traceEvent.EventName);
                        }
                    };

                    // Logging
                    string lastFormattedMessage = "";

                    var logActivities = new Dictionary <Guid, LogActivityItem>();
                    var stack         = new Stack <Guid>();

                    source.Dynamic.AddCallbackForProviderEvent(MicrosoftExtensionsLoggingProviderName, "ActivityJsonStart/Start", (traceEvent) =>
                    {
                        var factoryId    = (int)traceEvent.PayloadByName("FactoryID");
                        var categoryName = (string)traceEvent.PayloadByName("LoggerName");
                        var argsJson     = (string)traceEvent.PayloadByName("ArgumentsJson");

                        // TODO: Store this information by logger factory id
                        var item = new LogActivityItem
                        {
                            ActivityID   = traceEvent.ActivityID,
                            ScopedObject = new LogObject(JsonDocument.Parse(argsJson).RootElement),
                        };

                        if (stack.TryPeek(out var parentId) && logActivities.TryGetValue(parentId, out var parentItem))
                        {
                            item.Parent = parentItem;
                        }

                        stack.Push(traceEvent.ActivityID);
                        logActivities[traceEvent.ActivityID] = item;
                    });

                    source.Dynamic.AddCallbackForProviderEvent(MicrosoftExtensionsLoggingProviderName, "ActivityJsonStop/Stop", (traceEvent) =>
                    {
                        var factoryId    = (int)traceEvent.PayloadByName("FactoryID");
                        var categoryName = (string)traceEvent.PayloadByName("LoggerName");

                        stack.Pop();
                        logActivities.Remove(traceEvent.ActivityID);
                    });

                    source.Dynamic.AddCallbackForProviderEvent(MicrosoftExtensionsLoggingProviderName, "MessageJson", (traceEvent) =>
                    {
                        // Level, FactoryID, LoggerName, EventID, EventName, ExceptionJson, ArgumentsJson
                        var logLevel      = (LogLevel)traceEvent.PayloadByName("Level");
                        var factoryId     = (int)traceEvent.PayloadByName("FactoryID");
                        var categoryName  = (string)traceEvent.PayloadByName("LoggerName");
                        var eventId       = (int)traceEvent.PayloadByName("EventId");
                        var eventName     = (string)traceEvent.PayloadByName("EventName");
                        var exceptionJson = (string)traceEvent.PayloadByName("ExceptionJson");
                        var argsJson      = (string)traceEvent.PayloadByName("ArgumentsJson");

                        // There's a bug that causes some of the columns to get mixed up
                        if (eventName.StartsWith("{"))
                        {
                            argsJson      = exceptionJson;
                            exceptionJson = eventName;
                            eventName     = null;
                        }

                        if (string.IsNullOrEmpty(argsJson))
                        {
                            return;
                        }

                        Exception exception = null;

                        var logger = loggerFactory.CreateLogger(categoryName);

                        var scopes = new List <IDisposable>();

                        if (logActivities.TryGetValue(traceEvent.ActivityID, out var logActivityItem))
                        {
                            // REVIEW: Does order matter here? We're combining everything anyways.
                            while (logActivityItem != null)
                            {
                                scopes.Add(logger.BeginScope(logActivityItem.ScopedObject));

                                logActivityItem = logActivityItem.Parent;
                            }
                        }

                        try
                        {
                            if (exceptionJson != "{}")
                            {
                                var exceptionMessage = JsonSerializer.Deserialize <JsonElement>(exceptionJson);
                                exception            = new LoggerException(exceptionMessage);
                            }

                            var message = JsonSerializer.Deserialize <JsonElement>(argsJson);
                            if (message.TryGetProperty("{OriginalFormat}", out var formatElement))
                            {
                                var formatString = formatElement.GetString();
                                var formatter    = new LogValuesFormatter(formatString);
                                object[] args    = new object[formatter.ValueNames.Count];
                                for (int i = 0; i < args.Length; i++)
                                {
                                    args[i] = message.GetProperty(formatter.ValueNames[i]).GetString();
                                }

                                logger.Log(logLevel, new EventId(eventId, eventName), exception, formatString, args);
                            }
                            else
                            {
                                var obj = new LogObject(message, lastFormattedMessage);
                                logger.Log(logLevel, new EventId(eventId, eventName), obj, exception, LogObject.Callback);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogDebug(ex, "Error processing log entry for {ServiceName}", replicaName);
                        }
                        finally
                        {
                            scopes.ForEach(d => d.Dispose());
                        }
                    });

                    source.Dynamic.AddCallbackForProviderEvent(MicrosoftExtensionsLoggingProviderName, "FormattedMessage", (traceEvent) =>
                    {
                        // Level, FactoryID, LoggerName, EventID, EventName, FormattedMessage
                        var logLevel         = (LogLevel)traceEvent.PayloadByName("Level");
                        var factoryId        = (int)traceEvent.PayloadByName("FactoryID");
                        var categoryName     = (string)traceEvent.PayloadByName("LoggerName");
                        var eventId          = (int)traceEvent.PayloadByName("EventId");
                        var eventName        = (string)traceEvent.PayloadByName("EventName");
                        var formattedMessage = (string)traceEvent.PayloadByName("FormattedMessage");

                        if (string.IsNullOrEmpty(formattedMessage))
                        {
                            formattedMessage = eventName;
                            eventName        = "";
                        }

                        lastFormattedMessage = formattedMessage;
                    });

                    source.Process();
                }
        public EventStoreConnectionStatusMonitor(IEventStoreConnection connection, ILoggerFactory?loggerFactory = null)
        {
            _eventStoreConnection = connection;

            _logger = loggerFactory?.CreateLogger(nameof(EventStoreConnectionStatusMonitor));

            _isConnected = new BehaviorSubject <bool>(false);

            var connected = Observable.FromEventPattern <ClientConnectionEventArgs>(h => connection.Connected += h, h => connection.Connected -= h).Select(_ =>
            {
                return(ConnectionStatus.Connected);
            });

            var disconnected = Observable.FromEventPattern <ClientConnectionEventArgs>(h => connection.Disconnected += h, h => connection.Disconnected -= h).Select(arg =>
            {
                _logger?.LogInformation($"{nameof(EventStoreConnectionStatusMonitor)} => Connection lost - [{arg.EventArgs.RemoteEndPoint}]");

                return(ConnectionStatus.Disconnected);
            });

            var reconnecting = Observable.FromEventPattern <ClientReconnectingEventArgs>(h => connection.Reconnecting += h, h => connection.Reconnecting -= h).Select(_ =>
            {
                return(ConnectionStatus.Connecting);
            });

            var closed = Observable.FromEventPattern <ClientClosedEventArgs>(h => connection.Closed += h, h => connection.Closed -= h).Select(arg =>
            {
                _logger?.LogInformation($"{nameof(EventStoreConnectionStatusMonitor)} => Connection closed - [{arg.EventArgs.Reason}]");

                return(ConnectionStatus.Closed);
            });

            var errorOccurred = Observable.FromEventPattern <ClientErrorEventArgs>(h => connection.ErrorOccurred += h, h => connection.ErrorOccurred -= h).Select(arg =>
            {
                _logger?.LogError(arg.EventArgs.Exception, $"{nameof(EventStoreConnectionStatusMonitor)} => An error occured while connected to EventStore");

                return(ConnectionStatus.ErrorOccurred);
            });

            var authenticationFailed = Observable.FromEventPattern <ClientAuthenticationFailedEventArgs>(h => connection.AuthenticationFailed += h, h => connection.AuthenticationFailed -= h).Select(arg =>
            {
                _logger?.LogError($"{nameof(EventStoreConnectionStatusMonitor)} => Authentication failed while connecting to EventStore - [{arg.EventArgs.Reason}]");

                return(ConnectionStatus.AuthenticationFailed);
            });

            _connectionInfoChanged = Observable.Merge(connected, disconnected, reconnecting, closed, errorOccurred, authenticationFailed)
                                     .Scan(ConnectionInfo.InitialDisconnected, UpdateConnectionInfo)
                                     .StartWith(ConnectionInfo.InitialDisconnected)
                                     .Do(connectionInfo =>
            {
                ConnectionInfo = connectionInfo;
                _logger?.LogInformation($"{nameof(EventStoreConnectionStatusMonitor)} => ConnectionInfo - {connectionInfo}");
                _isConnected.OnNext(connectionInfo.Status == ConnectionStatus.Connected);
            })
                                     .Replay(1);

            _cleanUp = _connectionInfoChanged.Connect();

            _eventStoreConnection.ConnectAsync().Wait();
        }
Example #16
0
        async static Task Main()
        {
            Console.WriteLine("SIPSorcery SIP to WebRTC example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource exitCts = new CancellationTokenSource(); // Cancellation token to stop the SIP transport and RTP stream.

            Log = AddConsoleLogger();

            // Start web socket.
            Console.WriteLine("Starting web socket server...");
            var webSocketServer = new WebSocketServer(IPAddress.Any, WEBSOCKET_PORT);

            webSocketServer.AddWebSocketService <WebRTCWebSocketPeer>("/", (peer) => peer.CreatePeerConnection = CreatePeerConnection);
            webSocketServer.Start();

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

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

            //EnableTraceLogs(sipTransport);

            // Create a SIP user agent to receive a call from a remote SIP client.
            // Wire up event handlers for the different stages of the call.
            var userAgent = new SIPUserAgent(sipTransport, null, true);

            // We're only answering SIP calls, not placing them.
            userAgent.OnCallHungup += (dialog) =>
            {
                Log.LogInformation($"Call hungup by remote party.");
                exitCts.Cancel();
            };
            userAgent.ServerCallCancelled += (uas) => Log.LogInformation("Incoming call cancelled by caller.");
            userAgent.OnIncomingCall      += async(ua, req) =>
            {
                Log.LogInformation($"Incoming call request from {req.RemoteSIPEndPoint}: {req.StatusLine}.");
                var incomingCall = userAgent.AcceptCall(req);

                var rtpSession = new RTPSession(false, false, false);
                rtpSession.AcceptRtpFromAny = true;
                MediaStreamTrack audioTrack = new MediaStreamTrack(new List <AudioFormat> {
                    new AudioFormat(SDPWellKnownMediaFormatsEnum.PCMU)
                });
                rtpSession.addTrack(audioTrack);
                MediaStreamTrack videoTrack = new MediaStreamTrack(new VideoFormat(VideoCodecsEnum.VP8, 100));
                rtpSession.addTrack(videoTrack);

                await userAgent.Answer(incomingCall, rtpSession);

                rtpSession.OnRtpPacketReceived  += ForwardAudioToPeerConnection;
                rtpSession.OnVideoFrameReceived += ForwardVideoFrameToPeerConnection; // ForwardVideoFrameToSIP;

                Log.LogInformation($"Answered incoming call from {req.Header.From.FriendlyDescription()} at {req.RemoteSIPEndPoint}.");

                _rtpSession = rtpSession;
                RequestPeerConnectionKeyFrame(_peerConnection);
            };

            Console.WriteLine($"Waiting for browser web socket connection to {webSocketServer.Address}:{webSocketServer.Port}...");
            var contactURI = new SIPURI(SIPSchemesEnum.sip, sipTransport.GetSIPChannels().First().ListeningSIPEndPoint);

            Console.WriteLine($"Waiting for incoming SIP call to {contactURI}.");
            Console.WriteLine("NOTE: Once SIP and WebRTC parties are connected and if the video does not start press 'k' to request a key frame.");

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

            // Wait for a signal saying the call failed, was cancelled with ctrl-c or completed.
            await Task.Run(() => OnKeyPress(exitCts.Token));

            #region Cleanup.

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

            _rtpSession?.Close("app exit");

            if (userAgent != null)
            {
                if (userAgent.IsCallActive)
                {
                    Log.LogInformation($"Hanging up call to {userAgent?.CallDescriptor?.To}.");
                    userAgent.Hangup();
                }

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

            if (sipTransport != null)
            {
                Log.LogInformation("Shutting down SIP transport...");
                sipTransport.Shutdown();
            }

            #endregion
        }
Example #17
0
        public async Task Execute(IJobExecutionContext job)
        {
            try
            {
                var settings = await _lidarrSettings.GetSettingsAsync();

                if (settings.Enabled)
                {
                    await _notification.Clients.Clients(NotificationHub.AdminConnectionIds)
                    .SendAsync(NotificationHub.NotificationEvent, "Lidarr Artist Sync Started");

                    try
                    {
                        var artists = await _lidarrApi.GetArtists(settings.ApiKey, settings.FullUri);

                        if (artists != null && artists.Any())
                        {
                            var strat = _ctx.Database.CreateExecutionStrategy();
                            await strat.ExecuteAsync(async() =>
                            {
                                // Let's remove the old cached data
                                using (var tran = await _ctx.Database.BeginTransactionAsync())
                                {
                                    await _ctx.Database.ExecuteSqlRawAsync("DELETE FROM LidarrArtistCache");
                                    tran.Commit();
                                }
                            });

                            var artistCache = new List <LidarrArtistCache>();
                            foreach (var a in artists)
                            {
                                if (a.id > 0)
                                {
                                    artistCache.Add(new LidarrArtistCache
                                    {
                                        ArtistId        = a.id,
                                        ArtistName      = a.artistName,
                                        ForeignArtistId = a.foreignArtistId,
                                        Monitored       = a.monitored
                                    });
                                }
                            }
                            strat = _ctx.Database.CreateExecutionStrategy();
                            await strat.ExecuteAsync(async() =>
                            {
                                using (var tran = await _ctx.Database.BeginTransactionAsync())
                                {
                                    await _ctx.LidarrArtistCache.AddRangeAsync(artistCache);

                                    await _ctx.SaveChangesAsync();
                                    tran.Commit();
                                }
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        await _notification.Clients.Clients(NotificationHub.AdminConnectionIds)
                        .SendAsync(NotificationHub.NotificationEvent, "Lidarr Artist Sync Failed");

                        _logger.LogError(LoggingEvents.Cacher, ex, "Failed caching queued items from Lidarr");
                    }

                    await _notification.Clients.Clients(NotificationHub.AdminConnectionIds)
                    .SendAsync(NotificationHub.NotificationEvent, "Lidarr Artist Sync Finished");

                    await OmbiQuartz.TriggerJob(nameof(ILidarrAlbumSync), "DVR");
                }
            }
            catch (Exception)
            {
                _logger.LogInformation(LoggingEvents.LidarrArtistCache, "Lidarr is not setup, cannot cache Artist");
            }
        }
Example #18
0
        private static async Task StartApp(StartupOptions options)
        {
            ServerApplicationPaths appPaths = CreateApplicationPaths(options);

            // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
            Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);

            IConfiguration appConfig = await CreateConfiguration(appPaths).ConfigureAwait(false);

            CreateLogger(appConfig, appPaths);

            _logger = _loggerFactory.CreateLogger("Main");

            AppDomain.CurrentDomain.UnhandledException += (sender, e)
                                                          => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");

            // Intercept Ctrl+C and Ctrl+Break
            Console.CancelKeyPress += (sender, e) =>
            {
                if (_tokenSource.IsCancellationRequested)
                {
                    return; // Already shutting down
                }

                e.Cancel = true;
                _logger.LogInformation("Ctrl+C, shutting down");
                Environment.ExitCode = 128 + 2;
                Shutdown();
            };

            // Register a SIGTERM handler
            AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
            {
                if (_tokenSource.IsCancellationRequested)
                {
                    return; // Already shutting down
                }

                _logger.LogInformation("Received a SIGTERM signal, shutting down");
                Environment.ExitCode = 128 + 15;
                Shutdown();
            };

            _logger.LogInformation("Jellyfin version: {Version}", Assembly.GetEntryAssembly().GetName().Version);

            ApplicationHost.LogEnvironmentInfo(_logger, appPaths);

            // Increase the max http request limit
            // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.
            ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);

            // Disable the "Expect: 100-Continue" header by default
            // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
            ServicePointManager.Expect100Continue = false;

// CA5359: Do Not Disable Certificate Validation
#pragma warning disable CA5359

            // Allow all https requests
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); });
#pragma warning restore CA5359

            Batteries_V2.Init();
            if (raw.sqlite3_enable_shared_cache(1) != raw.SQLITE_OK)
            {
                Console.WriteLine("WARN: Failed to enable shared cache for SQLite");
            }

            using (var appHost = new CoreAppHost(
                       appPaths,
                       _loggerFactory,
                       options,
                       new ManagedFileSystem(_loggerFactory.CreateLogger <ManagedFileSystem>(), appPaths),
                       new NullImageEncoder(),
                       new NetworkManager(_loggerFactory.CreateLogger <NetworkManager>()),
                       appConfig))
            {
                await appHost.InitAsync(new ServiceCollection()).ConfigureAwait(false);

                appHost.ImageProcessor.ImageEncoder = GetImageEncoder(appPaths, appHost.LocalizationManager);

                await appHost.RunStartupTasksAsync().ConfigureAwait(false);

                try
                {
                    // Block main thread until shutdown
                    await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
                }
                catch (TaskCanceledException)
                {
                    // Don't throw on cancellation
                }
            }

            if (_restartOnShutdown)
            {
                StartNewInstance(options);
            }
        }
Example #19
0
        /// <summary>
        /// Runs a single task as part of the overall job.
        /// </summary>
        /// <param name="options">The options that dictate the type of task to run.</param>
        /// <param name="taskNumber">The number assigned to this task.</param>
        /// <returns>A boolean indicating whether this single task succeeded or not.</returns>
        private static async Task <bool> RunTask(Options options, int taskNumber)
        {
            SIPTransport sipTransport = new SIPTransport();

            sipTransport.PreferIPv6NameResolution = options.PreferIPv6;

            if (options.Verbose)
            {
                sipTransport.EnableTraceLogs();
            }

            try
            {
                DateTime startTime = DateTime.Now;

                var dstUri = ParseDestination(options.Destination);

                logger.LogDebug($"Destination SIP URI {dstUri}");

                if (options.SourcePort != 0)
                {
                    var sipChannel = sipTransport.CreateChannel(dstUri.Protocol,
                                                                options.PreferIPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork,
                                                                options.SourcePort);
                    sipTransport.AddSIPChannel(sipChannel);
                }

                Task <bool> task = null;

                switch (options.Scenario)
                {
                case Scenarios.reg:
                    task = InitiateRegisterTaskAsync(sipTransport, dstUri);
                    break;

                case Scenarios.uac:
                case Scenarios.uacw:
                    task = InitiateCallTaskAsync(sipTransport, dstUri, options.Scenario, options.Timeout);
                    break;

                case Scenarios.opt:
                default:
                    task = SendOptionsTaskAsync(sipTransport, dstUri);
                    break;
                }

                var result = await Task.WhenAny(task, Task.Delay(options.Timeout * 1000 + TIMEOUT_CLEANUP_MILLISECONDS));

                TimeSpan duration = DateTime.Now.Subtract(startTime);
                bool     failed   = false;

                if (!task.IsCompleted)
                {
                    logger.LogWarning($"=> Request to {dstUri} did not get a response on task {taskNumber} after {duration.TotalMilliseconds.ToString("0")}ms.");
                    failed = true;
                }
                else if (!task.Result)
                {
                    logger.LogWarning($"=> Request to {dstUri} did not get the expected response on task {taskNumber} after {duration.TotalMilliseconds.ToString("0")}ms.");
                    failed = true;
                }
                else
                {
                    logger.LogInformation($"=> Got correct response on send {taskNumber} in {duration.TotalMilliseconds.ToString("0")}ms.");
                }

                return(!failed);
            }
            finally
            {
                logger.LogDebug("Shutting down the SIP transport...");
                sipTransport.Shutdown();
            }
        }
Example #20
0
        /// <summary>
        /// Executes the command set by the program's command line arguments.
        /// </summary>
        /// <param name="options">The options that dictate the SIP command to execute.</param>
        static async Task RunCommand(Options options)
        {
            try
            {
                var seriLogger = new LoggerConfiguration()
                                 .Enrich.FromLogContext()
                                 .MinimumLevel.Is(options.Verbose ?
                                                  Serilog.Events.LogEventLevel.Verbose :
                                                  Serilog.Events.LogEventLevel.Debug)
                                 .WriteTo.Console(theme: AnsiConsoleTheme.Code)
                                 .CreateLogger();
                var factory = new SerilogLoggerFactory(seriLogger);
                SIPSorcery.LogFactory.Set(factory);
                logger = factory.CreateLogger <Program>();

                logger.LogDebug($"RunCommand scenario {options.Scenario}, destination {options.Destination}");

                Stopwatch sw = new Stopwatch();
                sw.Start();

                CancellationTokenSource cts = new CancellationTokenSource();
                int taskCount    = 0;
                int successCount = 0;

                List <Task> tasks = new List <Task>();

                for (int i = 0; i < options.Concurrent; i++)
                {
                    var task = Task.Run(async() =>
                    {
                        while (taskCount < options.Count && !cts.IsCancellationRequested)
                        {
                            int taskNum  = Interlocked.Increment(ref taskCount);
                            bool success = await RunTask(options, taskNum);

                            if (success)
                            {
                                Interlocked.Increment(ref successCount);
                            }
                            else if (options.BreakOnFail)
                            {
                                cts.Cancel();
                                break;
                            }

                            if (success && options.Period > 0)
                            {
                                await Task.Delay(options.Period * 1000);
                            }
                        }
                    }, cts.Token);

                    tasks.Add(task);

                    // Spread the concurrent tasks out a tiny bit.
                    await Task.Delay(Crypto.GetRandomInt(500, 2000));
                }

                // Wait for all the concurrent tasks to complete.
                await Task.WhenAll(tasks.ToArray());

                sw.Stop();

                // Give the transport half a second to shutdown (puts the log messages in a better sequence).
                await Task.Delay(500);

                logger.LogInformation($"=> Command completed task count {taskCount} success count {successCount} duration {sw.Elapsed.TotalSeconds:0.##}s.");
            }
            catch (Exception excp)
            {
                logger.LogError($"Exception RunCommand. {excp.Message}");
            }
        }
Example #21
0
 public void LogReceived(bool IsCallBackMessage, string refranceNumber)
 {
     _logger.LogInformation("{CreationDate} {Status} {ReferenceNumber}",
                            DateTime.Now, IsCallBackMessage ? MessageLifeCycle.ReceiveCallBackFromQueue : MessageLifeCycle.ReceiveFromQueue,
                            refranceNumber);
 }
Example #22
0
        static void Main(string[] args)
        {
            ConfigureServices(serviceCollection);

            serviceProvider = serviceCollection.BuildServiceProvider();

            logger = serviceProvider.GetService <ILogger <Program> >();

            logger.LogInformation($"Shortel Token {appConfig.ShoreTelToken}");
            logger.LogInformation($"Shoretel Host {appConfig.Host}");
            logger.LogInformation($"Shortel Domain {appConfig.Domain}");
            logger.LogInformation($"Shortel Username {appConfig.UserName}");
            logger.LogInformation($"Smtp Host {appConfig.SmtpHost}");
            logger.LogInformation($"Smtp port {appConfig.SmtpPort}");
            logger.LogInformation($"Smtp port {appConfig.SendEmailDelay}");
            foreach (string user in appConfig.UsersToRespondTo)
            {
                logger.LogInformation($"Users to respond to {user}");
            }

            msgHub = new TinyMessengerHub(new ErrorHandler(logger));

            msgHub.Subscribe <ActiveMessage>(m =>
            {
                logger.LogDebug("Enter ActiveMessage");
                try
                {
                    var email = emailCollection.GetOrAdd(m.message.Thread, e => new Email(m.message.From.Bare, m.message.Thread));
                    Monitor.Enter(email);
                    try
                    {
                        if (email.mailBody.Length < 1)
                        {
                            if (appConfig.UsersToRespondTo.FindIndex(x => x.Equals(email.EmailFrom, StringComparison.OrdinalIgnoreCase)) >= 0)
                            {
                                var txtMsg = "I am unable to respond to ShoreTel IMs right now.  Leave a message, exit the conversation and I will get back with you,";
                                var sndMsg = new Matrix.Xmpp.Client.Message(m.message.From, MessageType.Chat, txtMsg, "");
                                xmppClient.SendAsync(sndMsg).GetAwaiter().GetResult();
                            }
                        }
                        email.AddString(m.message.Body);
                    }
                    finally
                    {
                        Monitor.Exit(email);
                    }
                }
                catch (Exception e)
                {
                    logger.LogError($"Active message error {e.Message}");
                }
                logger.LogDebug("Exit ActiveMessage");
            });

            msgHub.Subscribe <GoneMessage>(m =>
            {
                logger.LogDebug("Enter GoneMessage");
                try
                {
                    Email email;
                    if (emailCollection.TryRemove(m.Thread, out email))
                    {
                        Monitor.Enter(email);
                        try
                        {
                            using (var client = new SmtpClient(new MailKit.ProtocolLogger("smtp.log", false)))
                            {
                                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                                client.CheckCertificateRevocation          = false;

                                client.ConnectAsync(appConfig.SmtpHost, appConfig.SmtpPort, SecureSocketOptions.StartTlsWhenAvailable).GetAwaiter().GetResult();

                                var mailMsg = new MimeMessage();

                                mailMsg.From.Add(new MailboxAddress(email.EmailFrom));
                                mailMsg.To.Add(new MailboxAddress(appConfig.UserName));

                                mailMsg.Subject = $"ShoreTel message from {email.EmailFrom}";

                                var builder = new BodyBuilder
                                {
                                    TextBody = email.mailBody.ToString()
                                };

                                mailMsg.Body = builder.ToMessageBody();

                                client.SendAsync(mailMsg).GetAwaiter().GetResult();

                                client.DisconnectAsync(true).GetAwaiter().GetResult();
                            }
                        }
                        finally
                        {
                            Monitor.Exit(email);
                        }
                    }
                }
                catch (Exception e)
                {
                    logger.LogError($"Gone message error {e.Message}");
                }
                logger.LogDebug("Exit GoneMessage");
            });


            var pipelineInitializerAction = new Action <IChannelPipeline, ISession>((pipeline, session) =>
            {
                pipeline.AddFirst(new MyLoggingHandler(logger));
            });

            xmppClient = new XmppClient()
            {
                Username    = appConfig.UserName,
                XmppDomain  = appConfig.Domain,
                SaslHandler = new ShoretelSSOProcessor(appConfig.ShoreTelToken),
                // use a local server for dev purposes running
                // on a non standard XMPP port 5333
                HostnameResolver = new StaticNameResolver(IPAddress.Parse(appConfig.Host), appConfig.Port)
            };

            xmppClient.XmppSessionStateObserver.Subscribe(v =>
            {
                Console.WriteLine($"State changed: {v}");
                logger.LogInformation(v.ToString());
            });

            xmppClient
            .XmppXElementStreamObserver
            .Where(el => el is Presence)
            .Subscribe(el =>
            {
                logger.LogDebug("Enter Presence observer");
                //Console.WriteLine(el.ToString());
                //logger.LogInformation(el.ToString());
                logger.LogDebug("Exit Presence observer");
            });

            xmppClient
            .XmppXElementStreamObserver
            .Where(el => el is Message)
            .Subscribe(el =>
            {
                logger.LogDebug("Enter Message observer");
                var msg = el as Message;

                switch (msg.Chatstate)
                {
                case Matrix.Xmpp.Chatstates.Chatstate.Active:
                    msgHub.PublishAsync(new ActiveMessage(msg), x => { });
                    break;

                case Matrix.Xmpp.Chatstates.Chatstate.Composing:
                    break;

                case Matrix.Xmpp.Chatstates.Chatstate.Gone:
                    msgHub.PublishAsync(new GoneMessage(msg.Thread), x => { });
                    break;
                }

                logger.LogDebug("Exit Message observer");
            });

            xmppClient
            .XmppXElementStreamObserver
            .Where(el => el is Iq)
            .Subscribe(el =>
            {
                Console.WriteLine(el.ToString());
                logger.LogInformation(el.ToString());
            });

            xmppClient.ConnectAsync().GetAwaiter().GetResult();

            // Send our presence to the server
            xmppClient.SendPresenceAsync(Show.Chat, "free for chat").GetAwaiter().GetResult();

            using (Timer t = new Timer(TimerCallback, null, 0, 1000))
            {
                Console.ReadLine();
            }

            // Disconnect the XMPP connection
            xmppClient.DisconnectAsync().GetAwaiter().GetResult();
        }
Example #23
0
        public static async Task OnCreateLeagueCommandHandlerOrchestrator
            ([OrchestrationTrigger] DurableOrchestrationContext context,
            Microsoft.Extensions.Logging.ILogger log)
        {
            CommandRequest <Create_New_League_Definition> cmdRequest = context.GetInput <CommandRequest <Create_New_League_Definition> >();

            if (null != cmdRequest)
            {
                ActivityResponse resp = await context.CallActivityWithRetryAsync <ActivityResponse>("CreateLeagueCommandLogParametersActivity",
                                                                                                    DomainSettings.CommandRetryOptions(),
                                                                                                    cmdRequest);

                Create_New_League_Definition parameters = cmdRequest.GetParameters();
                IEnumerable <CommandNotificationImpactedEntity> impactedEntities = null;
                if (null != parameters)
                {
                    Tuple <string, string>[] entitiesImpacted = new Tuple <string, string>[] { new Tuple <string, string>(@"League", parameters.LeagueName) };
                    impactedEntities = CommandNotificationImpactedEntity.CreateImpactedEntityList(entitiesImpacted);
                }

                #region Logging
                if (null != log)
                {
                    if (null != resp)
                    {
                        log.LogInformation($"{resp.FunctionName} complete: {resp.Message } ");
                    }
                }
                #endregion
                if (null != resp)
                {
                    context.SetCustomStatus(resp);
                }

                if (!resp.FatalError)
                {
                    // validate the command
                    bool valid = await context.CallActivityWithRetryAsync <bool>("CreateLeagueCommandValidationActivity",
                                                                                 DomainSettings.CommandRetryOptions(),
                                                                                 cmdRequest);

                    if (!valid)
                    {
                        resp.Message    = $"Validation failed for command {cmdRequest.CommandName} id: {cmdRequest.CommandUniqueIdentifier }";
                        resp.FatalError = true;
                    }
                }

                if (!resp.FatalError)
                {
                    CommandStepResponse stepResponse = new CommandStepResponse()
                    {
                        CommandName             = cmdRequest.CommandName,
                        CommandUniqueIdentifier = cmdRequest.CommandUniqueIdentifier,
                        StepName         = resp.FunctionName,
                        Message          = resp.Message,
                        ImpactedEntities = impactedEntities
                    };
                    resp = await context.CallActivityAsync <ActivityResponse>("CommandStepCompleteActivity", stepResponse);
                }

                if (!resp.FatalError)
                {
                    // execute the command
                    resp = await context.CallActivityWithRetryAsync <ActivityResponse>("CreateLeagueCommandHandlerAction",
                                                                                       DomainSettings.CommandRetryOptions(),
                                                                                       cmdRequest);

                    #region Logging
                    if (null != log)
                    {
                        if (null != resp)
                        {
                            log.LogInformation($"{resp.FunctionName} complete: {resp.Message } ");
                        }
                    }
                    #endregion
                    if (null != resp)
                    {
                        context.SetCustomStatus(resp);
                    }
                }

                if (!resp.FatalError)
                {
                    // 3) Mark the step as complete
                    CommandStepResponse stepResponse = new CommandStepResponse()
                    {
                        CommandName             = cmdRequest.CommandName,
                        CommandUniqueIdentifier = cmdRequest.CommandUniqueIdentifier,
                        StepName         = resp.FunctionName,
                        Message          = resp.Message,
                        ImpactedEntities = impactedEntities
                    };
                    resp = await context.CallActivityAsync <ActivityResponse>("CommandStepCompleteActivity", stepResponse);
                }

                if (!resp.FatalError)
                {
                    resp = await context.CallActivityAsync <ActivityResponse>("CommandCompleteActivity", cmdRequest);
                }

                #region Logging
                if (null != log)
                {
                    if (null != resp)
                    {
                        log.LogInformation($"{resp.FunctionName} complete: {resp.Message } ");
                    }
                }
                #endregion
                if (null != resp)
                {
                    context.SetCustomStatus(resp);
                }
            }
            else
            {
                #region Logging
                if (null != log)
                {
                    // Unable to get the request details from the orchestration
                    log.LogError("OnCreateLeagueCommandHandlerOrchestrator : Unable to get the command request from the context");

                    string contextAsString = context.GetInput <string>();
                    if (!string.IsNullOrWhiteSpace(contextAsString))
                    {
                        log.LogError($"Context was {contextAsString} ");
                    }
                    else
                    {
                        log.LogError($"Context was blank ");
                    }
                }
                #endregion
                return;
            }
        }
Example #24
0
        public async Task <IActionResult> Post([FromBody] NewQRReq reqForm)
        {
            _logger.LogInformation("start request new QR service");
            DBModels dbModel = new DBModels();
            //validate TransId

            string transIdResult = await dbModel.checkTransId(reqForm.UserID, reqForm.TransId);

            if (transIdResult != "")
            {
                return(Ok(new NewQR_Fail()
                {
                    Msg = transIdResult
                }));
            }

            //TODO: Check promotion code
            List <ProductDetail> prodDetail = await dbModel.GetProductDetailFromProductList(reqForm.Company, reqForm.Product);

            if (prodDetail.Count == 0)
            {
                return(Ok(new NewQR_Fail()
                {
                    Msg = "Invalid Company or/and Product"
                }));
            }

            if (reqForm.NewQty <= 0)
            {
                return(Ok(new NewQR_Fail()
                {
                    Msg = "Invalid new quantity"
                }));
            }

            Double discount = 0;

            if (reqForm.PromotionCode.ToUpper() == "50% OFF")
            {
                discount = 0.5;
            }

            double   ttlAmt    = System.Math.Round(prodDetail[0].UnitPrice * reqForm.NewQty * (1 - discount), 2);//String.Format("{0:0.00}", 123.4567);  -->123.45
            DateTime transTime = DateTime.Now;

            //getToken
            var s = await authService.getToken();

            var    data1 = JsonConvert.DeserializeObject <Dictionary <string, string> >(await authService.getToken());
            string token = (data1["access_token"] ?? "").ToString();

            if (token == "")
            {
                return(Unauthorized());
            }

            //check balance
            if (!(await eWalletAPI.checkEWalletBalanceAsync(token, reqForm.UserID, ttlAmt)))
            {
                return(Ok(new NewQR_Fail()
                {
                    Msg = "Not enough balance"
                }));
            }

            string newQR = "";

            if (reqForm.ReqType == "Submit")
            {
                //deduct balance
                if (!(await eWalletAPI.deductEWalletBalanceAsync(token, reqForm.UserID, ttlAmt, reqForm.TransId, reqForm.Product, reqForm.Company, reqForm.Remark)))
                {
                    return(Ok(new NewQR_Fail()
                    {
                        Msg = "Deduct amount fail"
                    }));
                }

                await dbModel.InitNewQRCode(reqForm.UserID, reqForm.TransId, transTime, reqForm.NewQty, ttlAmt, reqForm.PromotionCode);

                //get new QR
                string reqResult = await iJoozAPI.reqQR("New", reqForm.TransId, reqForm.TransTime, "member", reqForm.UserID, "-", prodDetail[0].Currency, prodDetail[0].UnitPrice, reqForm.NewQty, DateTime.Now.AddMonths(24));

                if (reqResult == "")
                {
                    return(Ok(new NewQR_Fail()
                    {
                        Msg = "Get QR Code from iJooz Fail"
                    }));
                }
                else
                {
                    var data = JsonConvert.DeserializeObject <Dictionary <string, string> >(reqResult);
                    if (data["result"] == "Success")
                    {
                        newQR = data["qrCode"];
                    }
                    else
                    {
                        return(Ok(new NewQR_Fail()
                        {
                            Msg = "Get QR Code from iJooz Fail2"
                        }));
                    }
                }

                await dbModel.SaveNewQRCode(reqForm.UserID, reqForm.TransId, newQR, reqForm.Company, reqForm.NewQty, reqForm.Product, prodDetail[0].Currency, prodDetail[0].UnitPrice, DateTime.Now.AddYears(10));
            }
            else if (reqForm.ReqType != "Preview")
            {
                return(Ok(new NewQR_Fail()
                {
                    Msg = "Invalid Request Type"
                }));
            }

            List <NewQRDetail> detailList = new List <NewQRDetail> {
                new NewQRDetail()
                {
                    TransId     = reqForm.TransId,
                    ReqType     = reqForm.ReqType,
                    Company     = reqForm.Company,
                    Product     = reqForm.Product,
                    QRCode      = newQR,
                    TtlQty      = reqForm.NewQty,
                    Currency    = prodDetail[0].Currency,
                    Amt         = ttlAmt,
                    ExpiredDate = DateTime.Now.AddYears(10)
                }
            };

            return(Ok(new NewQR_OK()
            {
                QrDetail = detailList
            }));
        }
Example #25
0
        public static void Main(string[] args)
        {
            CryptographyCommandhandler cryptographyCmdHandler = new CryptographyCommandhandler(new KeyGenerator());

            cryptographyCmdHandler.HandleGenerateKeysCommand(out string walletPubKey, out string walletPrivKey);
            PushKeyPair(walletPubKey, walletPrivKey);

            Console.WriteLine("Your new public key: " + walletPubKey);
            Console.WriteLine("Your new private key: " + walletPrivKey);
            Console.WriteLine("Loading blockchain..");

            var       networkIdentifier = "testnet";
            var       services          = SetupDI(networkIdentifier, walletPubKey, walletPrivKey);
            ushort    listeningPort     = NetworkConstants.DefaultListeningPort;
            IPAddress publicIP          = IPAddress.Parse("127.0.0.1"); // Our public IP so other nodes can find us, todo

            if (args.Length > 1 && args[0] == "-port")
            {
                listeningPort = ushort.Parse(args[1]);
            }

            GetServices(
                services,
                out IBlockchainRepository blockchainRepo,
                out ITransactionRepository transactionRepo,
                out ITransactionCreator transactionCreator,
                out ITimestamper timestamper,
                out ISkuRepository skuRepository,
                out INetworkManager networkManager,
                out ILoggerFactory loggerFactory,
                out ISkuRepository skuRepo,
                out Miner miner
                );
            _logger = loggerFactory.CreateLogger <Program>();
            Blockchain blockchain = blockchainRepo.GetChainByNetId(networkIdentifier);

            // Command handlers, only large commands are handles by these separate handlers.
            AccountsCommandHandler             accountsCmdHandler       = new AccountsCommandHandler(transactionRepo, networkIdentifier);
            SkusCommandHandler                 skusCmdHandler           = new SkusCommandHandler(blockchainRepo, timestamper, skuRepository, networkIdentifier);
            TransactionsCommandHandler         transactionsCmdHandler   = new TransactionsCommandHandler(transactionRepo, networkIdentifier);
            TransactionPoolCommandHandler      txpoolCmdHandler         = new TransactionPoolCommandHandler();
            TransferTokensCommandHandler       transferTokensCmdHandler = new TransferTokensCommandHandler(transactionRepo, transactionCreator);
            CreateSkuCommandHandler            createSkuCmdHandler      = new CreateSkuCommandHandler(transactionRepo, transactionCreator);
            TransferSupplyCommandHandler       transferSupplyCmdHandler = new TransferSupplyCommandHandler(skuRepository, transactionRepo, transactionCreator, networkIdentifier);
            NetworkingCommandHandler           networkingCmdHandler     = new NetworkingCommandHandler();
            TransactionGeneratorCommandHandler txGeneratorCmdHandler    = new TransactionGeneratorCommandHandler(miner, transactionCreator, skuRepo, blockchainRepo);
            CreateSupplyCommandHandler         createSupplyCmdHandler   = new CreateSupplyCommandHandler(skuRepository, transactionRepo, transactionCreator, networkIdentifier);
            DestroySupplyCommandHandler        destroySupplyCmdHandler  = new DestroySupplyCommandHandler(skuRepository, transactionRepo, transactionCreator, networkIdentifier);

            _logger.LogInformation("Loaded blockchain. Current height: {Height}", blockchain.CurrentHeight == -1 ? "GENESIS" : blockchain.CurrentHeight.ToString());
            networkManager.AcceptConnections(publicIP, listeningPort, new CancellationTokenSource());

            networkManager.ConnectToPeer(new NetworkNode(ConnectionType.Outbound, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345)));

            PrintConsoleCommands();

            var skuTransactions = 0;
            var txpool          = ConcurrentTransactionPool.GetInstance();

            EventPublisher.GetInstance().OnValidTransactionReceived += (object sender, TransactionReceivedEventArgs txargs) =>
            {
                if (txargs.Transaction.Action == TransactionAction.CreateSku.ToString())
                {
                    skuTransactions++;
                }

                if (skuTransactions > 200000 && txpool.Count() < 1)
                {
                    miner.StopMining(true);
                    txGeneratorCmdHandler.HandleStopCommand();
                }
            };

            var input = "";

            while (input != "exit")
            {
                input = Console.ReadLine().ToLower();
                switch (input)
                {
                case "help":
                    PrintConsoleCommands();
                    break;

                case "transactiongenerator startandmine":
                    txGeneratorCmdHandler.HandleStartCommand(true);
                    break;

                case "transactiongenerator start":
                    txGeneratorCmdHandler.HandleStartCommand(false);
                    break;

                case "transactiongenerator stop":
                    txGeneratorCmdHandler.HandleStopCommand();
                    break;

                case "generatekeys":
                    cryptographyCmdHandler.HandleGenerateKeysCommand(out walletPubKey, out walletPrivKey);
                    PushKeyPair(walletPubKey, walletPrivKey);
                    Console.WriteLine("Your new public key: " + walletPubKey);
                    Console.WriteLine("Your new private key: " + walletPrivKey);
                    Console.Write("> ");
                    break;

                case "accounts":
                case "users":
                case "balances":
                    accountsCmdHandler.HandleCommand();
                    break;

                case "skus":
                    skusCmdHandler.HandleCommand();
                    break;

                case "txpool":
                case "transactionpool":
                case "pendingtransactions":
                    txpoolCmdHandler.HandleCommand(miner.TransactionPool);
                    break;

                case "transactions":
                    transactionsCmdHandler.HandleCommand();
                    break;

                case "startmining":
                    miner.StartMining();
                    Console.Write("> ");
                    break;

                case "stopmining":
                    miner.StopMining(true);
                    PrintConsoleCommands();
                    break;

                case "resetblockchain":
                    miner.StopMining(false);
                    blockchainRepo.Delete(networkIdentifier);
                    Console.WriteLine("Blockchain deleted.");
                    blockchain = blockchainRepo.GetChainByNetId(networkIdentifier);
                    networkManager.Dispose();
                    _logger.LogWarning("All network connections shut down.");
                    // Initialize all variables again because the heap references changed.
                    services = SetupDI(networkIdentifier, walletPubKey, walletPrivKey);
                    GetServices(
                        services,
                        out blockchainRepo,
                        out transactionRepo,
                        out transactionCreator,
                        out timestamper,
                        out skuRepository,
                        out networkManager,
                        out var ingored,
                        out skuRepo,
                        out miner
                        );
                    networkManager.AcceptConnections(publicIP, listeningPort, new CancellationTokenSource());
                    accountsCmdHandler       = new AccountsCommandHandler(transactionRepo, networkIdentifier);
                    skusCmdHandler           = new SkusCommandHandler(blockchainRepo, timestamper, skuRepository, networkIdentifier);
                    transactionsCmdHandler   = new TransactionsCommandHandler(transactionRepo, networkIdentifier);
                    txpoolCmdHandler         = new TransactionPoolCommandHandler();
                    transferTokensCmdHandler = new TransferTokensCommandHandler(transactionRepo, transactionCreator);
                    createSkuCmdHandler      = new CreateSkuCommandHandler(transactionRepo, transactionCreator);
                    txGeneratorCmdHandler    = new TransactionGeneratorCommandHandler(miner, transactionCreator, skuRepo, blockchainRepo);
                    _logger.LogInformation("Loaded blockchain. Current height: {Height}", blockchain.CurrentHeight == -1 ? "GENESIS" : blockchain.CurrentHeight.ToString());
                    Console.Write("> ");
                    break;

                case "transfertokens":
                    transferTokensCmdHandler.HandleCommand(networkIdentifier);
                    break;

                case "createsku":
                    createSkuCmdHandler.HandleCommand(networkIdentifier);
                    break;

                case "transfersupply":
                    transferSupplyCmdHandler.HandleCommand();
                    break;

                case "createsupply":
                    createSupplyCmdHandler.HandleCommand();
                    break;

                case "destroysupply":
                    destroySupplyCmdHandler.HandleCommand();
                    break;

                case "networking setport":
                    listeningPort = networkingCmdHandler.HandleSetPortCommand(listeningPort);
                    break;

                case "networking setaddress":
                    publicIP = networkingCmdHandler.HandleSetAddressCommand(publicIP);
                    break;

                case "networking connect":
                    networkingCmdHandler.HandleConnectCommand(networkManager);
                    break;

                case "networking disconnect":
                    networkingCmdHandler.HandleDisconnectCommand(networkManager);
                    break;

                case "networking pool":
                    networkingCmdHandler.HandleListPoolCommand(NetworkNodesPool.GetInstance(loggerFactory));
                    break;

                case "networking stop":
                    networkManager.Dispose();
                    break;

                case "networking start":
                    if (networkManager.IsDisposed)
                    {
                        networkManager = GetService <INetworkManager>(services);
                    }
                    networkManager.AcceptConnections(publicIP, listeningPort, new CancellationTokenSource());
                    break;

                case "networking restart":
                    networkManager.Dispose();
                    Thread.Sleep(1000);
                    networkManager = GetService <INetworkManager>(services);
                    networkManager.AcceptConnections(publicIP, listeningPort, new CancellationTokenSource());
                    break;

                default:
                    Console.WriteLine("I don't recognize that command.");
                    Console.Write("> ");
                    break;
                }
            }
        }
Example #26
0
        public async Task CacheContent()
        {
            try
            {
                var settings = await _lidarrSettings.GetSettingsAsync();

                if (settings.Enabled)
                {
                    try
                    {
                        var albums = await _lidarrApi.GetAllAlbums(settings.ApiKey, settings.FullUri);

                        if (albums != null && albums.Any())
                        {
                            // Let's remove the old cached data
                            using (var tran = await _ctx.Database.BeginTransactionAsync())
                            {
                                await _ctx.Database.ExecuteSqlCommandAsync("DELETE FROM LidarrAlbumCache");

                                tran.Commit();
                            }

                            var albumCache = new List <LidarrAlbumCache>();
                            foreach (var a in albums)
                            {
                                if (a.id > 0)
                                {
                                    albumCache.Add(new LidarrAlbumCache
                                    {
                                        ArtistId        = a.artistId,
                                        ForeignAlbumId  = a.foreignAlbumId,
                                        ReleaseDate     = a.releaseDate,
                                        TrackCount      = a.currentRelease?.trackCount ?? 0,
                                        Monitored       = a.monitored,
                                        Title           = a.title,
                                        PercentOfTracks = a.statistics?.percentOfEpisodes ?? 0m,
                                        AddedAt         = DateTime.Now,
                                    });
                                }
                            }

                            using (var tran = await _ctx.Database.BeginTransactionAsync())
                            {
                                await _ctx.LidarrAlbumCache.AddRangeAsync(albumCache);

                                await _ctx.SaveChangesAsync();

                                tran.Commit();
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _logger.LogError(LoggingEvents.Cacher, ex, "Failed caching queued items from Lidarr Album");
                    }

                    _job.Enqueue(() => _availability.Start());
                }
            }
            catch (Exception)
            {
                _logger.LogInformation(LoggingEvents.LidarrArtistCache, "Lidarr is not setup, cannot cache Album");
            }
        }
Example #27
0
 private void OnStarted()
 {
     _logger.LogInformation("Application started...");
 }
Example #28
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        // Configure is called after ConfigureServices is called.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //loggerFactory.MinimumLevel = LogLevel.Information;
            // root min level: you have to set this the most detailed, because if not ASPlog will not pass it to the NLogExtension
            loggerFactory.MinimumLevel = Microsoft.Extensions.Logging.LogLevel.Debug;

            // A. ASP.NET5 LogLevels can come from appsettings.json or set here programmatically. But Configuration.GetSection("") returns text from the file,
            // and not the file itself, so ConsoleLogger is not able to reload config when appsettings.json file is changed.
            // For that you need a FileSystem watcher manually, which is not OK on Linux systems I guess or not on DNXCore
            // Therefore logging level cannot be changed by modifying that file (at least, not without extra FileSystemWatcher programming)
            // B. On the other hand Nlog is based on DNX, not DNXCore, and implements FileSystemWatcher properly, and I tested it and
            // when the app.nlog file is changed by Notepad nLog under Asp.NET notices the LogLevelChange.
            loggerFactory.AddConsole(Configuration.GetSection("LoggingToConsole"));
            //loggerFactory.AddConsole(LogLevel.Debug);     // write to the Console  (if available) window as Colorful multiline (in Kestrel??) . MinLevel can be specified. by default it is LogLevel.Information
            loggerFactory.AddDebug(Microsoft.Extensions.Logging.LogLevel.Debug);       // write to the Debug output window (in VS). MinLevel can be specified. by default it is LogLevel.Information
            #if !DNXCORE50
            #if NlogInternalLoggingNeeded
            // nLog searches these config files in GetCandidateFileNames() (version nLog 3.1), later renamed to GetCandidateConfigFileNames()
            // NLog.config from application directory, "C:\\Users\\gyantal\\.dnx\\runtimes\\dnx-clr-win-x86.1.0.0-rc1-update1\\bin\\NLog.config"
            string standardCandidate = Path.Combine(NLog.LogFactory.CurrentAppDomain.BaseDirectory, "NLog.config");   // myExeFolder/Nlog.config
            // current config file with (EXE) .config renamed to .nlog, "g:\\work\\Archi-data\\GitHubRepos\\SQHealthMonitor\\src\\SQHealthMonitor\\app.nlog"
            string appDotNlog = Path.ChangeExtension(NLog.LogFactory.CurrentAppDomain.ConfigurationFile, ".nlog"); //myExeFolder/MyExe
            // get path to NLog.dll.nlog only if the assembly is not in the GAC, "C:\\Users\\gyantal\\.dnx\\packages\\NLog\\4.2.2\\lib\\net45\\NLog.dll.nlog"
            string dllDotNlog = typeof(NLog.LogFactory).Assembly.Location + ".nlog";

            NLog.Common.InternalLogger.LogLevel = NLog.LogLevel.Trace;  // this sets up from the default highLevel Info to detailed Trace; in order for Internal NLog logging to be Verbose
            NLog.Common.InternalLogger.LogToConsole = true;
            NLog.Common.InternalLogger.LogFile = @"g:\temp\nlogKestrel_InternalLogger.log";
            #endif
            //NLog.ILogger tempNlogLogger = LogManager.GetCurrentClassLogger();   //https://github.com/nlog/NLog/wiki/Configuration-file
            //SetNLogTableStorageConnectionString();
            //// when nlog.config is rewritten while the exe is running, AzureTableStorageConnectionString is lost
            //LogManager.ConfigurationReloaded += (sender, args) => { SetNLogTableStorageConnectionString(); };
            //tempNlogLogger.Info("This Logger created by LogManager() works properly under ASP.NET5. Writes proper AzuteStorageTable");

            //During Webserver runtime(Debugging in VS), file modification of app.nlog should not be done in VS2015, because
            //VS has a trick that it doesn't change file's Time under Debug, and so NLog.dll will not notice that this config file has been changed.
            //So, change this config file in NotePad.exe or TotalCommander, etc.
            NLog.LogFactory nlogLogFactory = new global::NLog.LogFactory();
            SetNLogTableStorageConnectionStringAndEmailSmtp(nlogLogFactory);
            // when nlog.config is rewritten while the exe is running, AzureTableStorageConnectionString is lost
            nlogLogFactory.ConfigurationReloaded += (sender, args) => { SetNLogTableStorageConnectionStringAndEmailSmtp(nlogLogFactory); };

            loggerFactory.AddProvider(new NLogLoggerProvider(nlogLogFactory));

            //nlogLogFactory.ConfigurationReloaded += (sender, args) => { SetNLogTableStorageConnectionString(); };
            //loggerFactory.AddNLog(nlogLogFactory);

            //loggerFactory.AddEventLog();  // probably Windows Eventlogs, implemented in Microsoft.Extensions.Logging.EventLog

            System.AppDomain.CurrentDomain.DomainUnload += (sender, args) => {
                Thread.Sleep(1);
                nlogLogFactory.Flush();
                LogManager.Flush();
            };
            System.AppDomain.CurrentDomain.ProcessExit += (sender, args) => {
                //Checked: when I shutdown the Webserver, by typing Ctrl-C, saying Initiate Webserver shutdown, this is called second after calling Dispose() of all IDispose objects
                Thread.Sleep(1);
                nlogLogFactory.Flush();
                LogManager.Flush();
            };
            System.AppDomain.CurrentDomain.UnhandledException += (sender, args) => {
                Thread.Sleep(1);
                nlogLogFactory.Flush();
                LogManager.Flush();
            };
            #endif

            mStartupLogger = loggerFactory.CreateLogger(typeof(Program).FullName);
            mStartupLogger.LogInformation("****START: Loggers are initialized in Startup.Configure()"); // high Level UserInfo
            #if !DNXCORE50

            ////Logger = LogManager.GetCurrentClassLogger();   //https://github.com/nlog/NLog/wiki/Configuration-file
            //SetNLogTableStorageConnectionString();
            //// when nlog.config is rewritten while the exe is running, AzureTableStorageConnectionString is lost
            //LogManager.ConfigurationReloaded += (sender, args) => { SetNLogTableStorageConnectionString(); };

            //var mStartupLogger2 = loggerFactory.CreateLogger(typeof(Program).FullName + "2");
            //mStartupLogger2.LogInformation("****creating mStartupLogger2 after setting ConnString."); // high Level UserInfo
            #endif

            //gStartupLogger.LogDebug("This is LogDebug() log info");  // most detailed, Trace in nLog
            //gStartupLogger.LogVerbose("This is LogVerbose() log info");  // normal-detailed, Debug in nLog
            //gStartupLogger.LogInformation("This is LogInformation() log info"); // high Level UserInfo

            // Add the platform handler to the request pipeline.
            app.UseIISPlatformHandler();    // : it is needed to resolve the Windows identity corresponding to the token flowed by IIS.

            if (env.IsDevelopment())
            {
                //app.UseDeveloperExceptionPage();
            }

            //Utils.InitSt();
            // Agy: I think this ASP5 solution is token based too. Just stores token in Cookies, which is perfect for a Browser based app like AngularJS
            //A. Conclusion: Storage user-token(not proper bearer token, but token) in cookies is good (in an AngularJS webApp, cookie storage is ideal.)
            //https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/
            //Conclusion: "Stormpath recommends that you store your JWT in cookies for web applications, because of the additional security they provide, and the simplicity of protecting against CSRF with modern web frameworks. HTML5 Web Storage (from here to Authentication Header) is vulnerable to XS"
            //> Basically, the caller of webServiceApi has to provide the userInfo.So, it has to store somewhere.
            //This article says: always use JWT Tokens. (ASP5 uses that, because it always send the full user info in the Cookies)
            //0.Browser based: Storing in Browser RAM in Javascript variable (from here to the "HTML Authentication header") is not good.Restart Browser Tab/Refresh will result => use has to log-in again.
            //1.Browser based: HTML5 WebStorage and from here to the "HTML Authentication header"
            //2.Browser based: cookie storage persistent too. Better.
            //3.Native App based: store in App memory, or in a file, etc. however you want.And use "HTML Authentication header" with the tokens.
            //B. ASP5 don't support yet the proper bearer tokens, but it doesn't matter.
            //https://en.wikipedia.org/wiki/Basic_access_authentication
            //https://developers.google.com/gmail/markup/actions/verifying-bearer-tokens
            //Bearer Tokens are part of the OAuth V2 standard and widely adopted by Google APIs.
            //// Agy: They will support it later. For now, I should forget it.
            //https://github.com/aspnet/Identity/search?q=Bearer&type=Issues&utf8=%E2%9C%93
            //https://github.com/aspnet/Identity/issues/495
            //In case anyone needs bearer tokens earlier.Basic example of Identity with Bearer tokens.
            //https://github.com/bigfont/AspNet.Security.OpenIdConnect.Server/tree/bigfont/samples/ResourceOwnerPasswordFlow
            //Probably later, this is a style how you should do it (for API calls, user-data should come from HTML header, from Browser user data should come from Cookie:
            //app.UseWhen(context => context.Request.Path.StartsWithSegments(new PathString("/api")), branch =>
            //{ branch.UseOAuthBearerAuthentication(options =>

            //string cId = Configuration["A:G:CId"], cSe = Configuration["A:G:CSe"];
            //string cId = Configuration["AppSettings:A_G_CId"], cSe = Configuration["AppSettings:A_G_CSe"];
            string cId = Configuration["A_G_CId"], cSe = Configuration["A_G_CSe"];
            if (!String.IsNullOrEmpty(cId) && !String.IsNullOrEmpty(cSe))
            {
                mStartupLogger.LogInformation("A_G_CId and A_G_CSe from Config has been found. Initializing GoogelAuthentication.");
                app.UseCookieAuthentication(options =>
                {
                    //options.LoginPath = "/account/login";
                    options.AuthenticationScheme = "Cookies";
                    options.AutomaticAuthenticate = true;
                    //options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
                    options.ExpireTimeSpan = TimeSpan.FromDays(10);
                    options.SlidingExpiration = false;
                });

                //// from official sample; name suggest it is token based, albeit it is not named Bearer; feeling: app.UseCookieAuthentication() is exactly this
                //app.UseOAuthAuthentication("Google-AccessToken", options =>
                //{
                //    options.AuthenticationScheme = "Google-AccessToken";
                //    //options.DisplayName = "Google-AccessToken",
                //    options.ClientId = Utils.g_YmVsYUJlbG92aXRz[0];
                //    options.ClientSecret = Utils.g_YmVsYUJlbG92aXRz[1];
                //    options.CallbackPath = new PathString("/signin-google-token");
                //    options.AuthorizationEndpoint = GoogleAuthenticationDefaults.AuthorizationEndpoint;
                //    options.TokenEndpoint = GoogleAuthenticationDefaults.TokenEndpoint;
                //    options.Scope.Add("https://www.googleapis.com/auth/plus.profile.emails.read");
                //});

                // this is from the official GitHub sample https://github.com/aspnet/Identity/blob/b9be30c6cdf055394eb5ca9cd95d02419fcdf4b4/samples/IdentitySample.Mvc/Startup.cs
                app.UseGoogleAuthentication(options =>
                {
                    options.ClientId = Encoding.UTF8.GetString(Convert.FromBase64String(cId));
                    options.ClientSecret = Encoding.UTF8.GetString(Convert.FromBase64String(cSe));

                    //options.SignInScheme = null; // by default, which doesn't work itself. It needs UseCookieAuthentication()
                    //options.SignInScheme = "Google-AccessToken"; // 2015-10-02: "System.NotSupportedException"; I guess later they will support it
                    options.SignInScheme = "Cookies";
                    options.AutomaticAuthenticate = true;  // this is false by default; if it is true, all [Authorize] Actions try to log-in to Google

                    // don't touch CallbackPath then: The CallbackPath is the google middleware callback, not the application callback. You set the application callback path on the RedirectUri property on the AuthenticationProperties that you pass when you call Challenge on the IAuthenticationManager
                    //options.CallbackPath = new PathString("/TestAuth/oauthcallback");   //new PathString("/signin-google"); is the default

                    // Scopes: Official Google page is here: https://developers.google.com/+/web/api/rest/oauth
                    // Robert uses this: { "scope", "https://www.googleapis.com/auth/plus.profile.emails.read" },  // as per stackoverflow.com/a/23764783 . Despite the docs (e.g. developers.google.com/+/api/oauth#login-scopes) suggest "email", that resulted in "this app would like to have offline access" after a couple of days
                    // http://stackoverflow.com/questions/24410179/is-there-a-way-to-only-get-a-users-email-address-with-googles-oauth2-impleme
                    // Conclusion: the First item: "Know who you are on Google" is always there. Cannot make it disappear. It is Google's policy.
                    options.Scope.Add("https://www.googleapis.com/auth/plus.profile.emails.read"); // George: Robert thinks it is better then "email", but it asked ""this app would like to have offline access"" too

                    //options.AuthenticationScheme = "Google"; // this is by default
                    //options.AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/auth"; // suggest token based, not cookie based
                });
            }
            else
            {
                mStartupLogger.LogWarning("A_G_CId and A_G_CSe from Config has NOT been found. Cannot initialize GoogelAuthentication.");
            }

            // Configure the HTTP request pipeline.
            app.UseStaticFiles();   // without it, the Server will not return static HTML files
            //app.UseDefaultFiles();
            //app.UseDefaultFiles(new Microsoft.AspNet.StaticFiles.DefaultFilesOptions() { DefaultFileNames = new[] { "Index.html" } });

            // Add MVC to the request pipeline.
            //app.UseMvc();
            //app.UseMvcWithDefaultRoute();  // following template: '{controller=Home}/{action=Index}/{id?}'.
            app.UseMvc(routes =>
             {
                 //routes.IgnoreRoute("");    //ignore empty routes //Re: Is there a workaround for routes.IgnoreRoute() in ASP.NET 5? (Method not implemented [yet])

                 // http://stackoverflow.com/questions/28017193/how-to-ignore-routes-in-mvc6
                 //routes.MapRoute(
                 //   name: "RootHomepage",
                 //   template: "",   // empty Route Should go to Index.html
                 //   defaults: new { controller = "RootHomepageRedirect", action = "Index" });

                 routes.MapRoute(
                    name: "route1",
                    template: "DeveloperDashboardForLocalDevelopment",
                    defaults: new { controller = "RootHomepageRedirect", action = "DeveloperDashboardForLocalDevelopment" }
                );
                routes.MapRoute(
                    name: "route2",
                    template: "UserDashboardForLocalDevelopment",
                    defaults: new { controller = "RootHomepageRedirect", action = "UserDashboardForLocalDevelopment" }
                );

                 routes.MapRoute(
                    name: "route3",
                    template: "DeveloperDashboard",
                    defaults: new { controller = "RootHomepageRedirect", action = "DeveloperDashboard" }
                );
                 routes.MapRoute(
                     name: "default",
                     template: "{controller}/{action}/{id?}",   // this is needed for Controller methods as Actions to be subPath items in URL
                     defaults: new { controller = "RootHomepageRedirect", action = "Index" });
             });

            // Add the following route for porting Web API 2 controllers.
            // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
        }
Example #29
0
        static void Main()
        {
            Console.WriteLine("SIPSorcery Call Hold and Blind Transfer example.");
            Console.WriteLine("Press 'c' to initiate a call to the default destination.");
            Console.WriteLine("Press 'h' to place an established call on and off hold.");
            Console.WriteLine("Press 'H' to hangup an established call.");
            Console.WriteLine("Press 't' to request a blind transfer on an established call.");
            Console.WriteLine("Press 'q' or ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource exitCts = new CancellationTokenSource(); // Cancellation token to stop the SIP transport and RTP stream.

            AddConsoleLogger();

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

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

            Console.WriteLine($"Listening for incoming calls on: {sipTransport.GetSIPChannels().First().ListeningEndPoint}.");

            //EnableTraceLogs(sipTransport);

            _currentDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            RtpAVSession rtpAVSession = null;

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

            userAgent.RemotePutOnHold   += () => Log.LogInformation("Remote call party has placed us on hold.");
            userAgent.RemoteTookOffHold += () => Log.LogInformation("Remote call party took us off hold.");

            sipTransport.SIPTransportRequestReceived += async(localEndPoint, remoteEndPoint, sipRequest) =>
            {
                if (sipRequest.Header.From != null &&
                    sipRequest.Header.From.FromTag != null &&
                    sipRequest.Header.To != null &&
                    sipRequest.Header.To.ToTag != null)
                {
                    // This is an in-dialog request that will be handled directly by a user agent instance.
                }
                else if (sipRequest.Method == SIPMethodsEnum.INVITE)
                {
                    if (userAgent?.IsCallActive == true)
                    {
                        Log.LogWarning($"Busy response returned for incoming call request from {remoteEndPoint}: {sipRequest.StatusLine}.");
                        // If we are already on a call return a busy response.
                        UASInviteTransaction uasTransaction = new UASInviteTransaction(sipTransport, sipRequest, null);
                        SIPResponse          busyResponse   = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.BusyHere, null);
                        uasTransaction.SendFinalResponse(busyResponse);
                    }
                    else
                    {
                        Log.LogInformation($"Incoming call request from {remoteEndPoint}: {sipRequest.StatusLine}.");
                        var incomingCall = userAgent.AcceptCall(sipRequest);

                        rtpAVSession = new RtpAVSession(new AudioOptions {
                            AudioSource = AudioSourcesEnum.Microphone
                        }, null);
                        await userAgent.Answer(incomingCall, rtpAVSession);

                        Log.LogInformation($"Answered incoming call from {sipRequest.Header.From.FriendlyDescription()} at {remoteEndPoint}.");
                    }
                }
                else
                {
                    Log.LogDebug($"SIP {sipRequest.Method} request received but no processing has been set up for it, rejecting.");
                    SIPResponse notAllowedResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.MethodNotAllowed, null);
                    await sipTransport.SendResponseAsync(notAllowedResponse);
                }
            };

            // At this point the call has been initiated and everything will be handled in an event handler.
            Task.Run(async() =>
            {
                try
                {
                    while (!exitCts.Token.WaitHandle.WaitOne(0))
                    {
                        var keyProps = Console.ReadKey();

                        if (keyProps.KeyChar == 'c')
                        {
                            if (!userAgent.IsCallActive)
                            {
                                rtpAVSession = new RtpAVSession(new AudioOptions {
                                    AudioSource = AudioSourcesEnum.Microphone
                                }, null);
                                bool callResult = await userAgent.Call(DEFAULT_DESTINATION_SIP_URI, SIP_USERNAME, SIP_PASSWORD, rtpAVSession);

                                Log.LogInformation($"Call attempt {((callResult) ? "successfull" : "failed")}.");
                            }
                            else
                            {
                                Log.LogWarning("There is already an active call.");
                            }
                        }
                        else if (keyProps.KeyChar == 'h')
                        {
                            // Place call on/off hold.
                            if (userAgent.IsCallActive)
                            {
                                if (userAgent.IsOnLocalHold)
                                {
                                    Log.LogInformation("Taking the remote call party off hold.");
                                    userAgent.TakeOffHold();
                                    await(userAgent.MediaSession as RtpAVSession).SetSources(new AudioOptions {
                                        AudioSource = AudioSourcesEnum.Microphone
                                    }, null);
                                }
                                else
                                {
                                    Log.LogInformation("Placing the remote call party on hold.");
                                    userAgent.PutOnHold();
                                    await(userAgent.MediaSession as RtpAVSession).SetSources(new AudioOptions
                                    {
                                        AudioSource = AudioSourcesEnum.Music,
                                        SourceFiles = new Dictionary <SDPMediaFormatsEnum, string>
                                        {
                                            { SDPMediaFormatsEnum.PCMU, _currentDir + "/" + AUDIO_FILE_PCMU }
                                        }
                                    }, null);
                                }
                            }
                            else
                            {
                                Log.LogWarning("There is no active call to put on hold.");
                            }
                        }
                        else if (keyProps.KeyChar == 'H')
                        {
                            if (userAgent.IsCallActive)
                            {
                                Log.LogInformation("Hanging up call.");
                                userAgent.Hangup();
                            }
                        }
                        else if (keyProps.KeyChar == 't')
                        {
                            // Initiate a blind transfer to the remote call party.
                            if (userAgent.IsCallActive)
                            {
                                var transferURI = SIPURI.ParseSIPURI(TRANSFER_DESTINATION_SIP_URI);
                                bool result     = await userAgent.BlindTransfer(transferURI, TimeSpan.FromSeconds(TRANSFER_TIMEOUT_SECONDS), exitCts.Token);
                                if (result)
                                {
                                    // If the transfer was accepted the original call will already have been hungup.
                                    // Wait a second for the transfer NOTIFY request to arrive.
                                    await Task.Delay(1000);
                                    exitCts.Cancel();
                                }
                                else
                                {
                                    Log.LogWarning($"Transfer to {TRANSFER_DESTINATION_SIP_URI} failed.");
                                }
                            }
                            else
                            {
                                Log.LogWarning("There is no active call to transfer.");
                            }
                        }
                        else if (keyProps.KeyChar == 'q')
                        {
                            // Quit application.
                            exitCts.Cancel();
                        }
                    }
                }
                catch (Exception excp)
                {
                    SIPSorcery.Sys.Log.Logger.LogError($"Exception Key Press listener. {excp.Message}.");
                }
            });

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

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

            #region Cleanup.

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

            rtpAVSession?.Close("app exit");

            if (userAgent != null)
            {
                if (userAgent.IsCallActive)
                {
                    Log.LogInformation($"Hanging up call to {userAgent?.CallDescriptor?.To}.");
                    userAgent.Hangup();
                }

                // 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();
            }

            #endregion
        }
        public RabbitMqConnectionStatusMonitor(IRabbitMqConnection connection, ILoggerFactory?loggerFactory = null)
        {
            _rabbitMqConnection = connection;

            _logger = loggerFactory?.CreateLogger(nameof(RabbitMqConnectionStatusMonitor));

            _isConnected = new BehaviorSubject <bool>(false);

            _rabbitMqConnection.Connect();

            var blocked = Observable.FromEventPattern <ConnectionBlockedEventArgs>(h => connection.AutoRecoveringConnection.ConnectionBlocked += h, h => connection.AutoRecoveringConnection.ConnectionBlocked -= h).Select(e =>
            {
                _logger?.LogInformation($"AMQP connection blocked - {nameof(ShutdownEventArgs)} => {e.EventArgs?.ToJson()}");

                return(ConnectionStatus.Disconnected);
            });

            var unblocked = Observable.FromEventPattern <EventArgs>(h => connection.AutoRecoveringConnection.ConnectionUnblocked += h, h => connection.AutoRecoveringConnection.ConnectionUnblocked -= h).Select(e =>
            {
                _logger?.LogInformation($"AMQP connection unblocked - {nameof(EventArgs)} => {e.EventArgs?.ToJson()}");

                return(ConnectionStatus.Connected);
            });

            var shutdowned = Observable.FromEventPattern <ShutdownEventArgs>(h => connection.AutoRecoveringConnection.ConnectionShutdown += h, h => connection.AutoRecoveringConnection.ConnectionShutdown -= h).Select(e =>
            {
                _logger?.LogInformation($"AMQP connection shutdown - {nameof(ShutdownEventArgs)} => {e.EventArgs?.ToJson()}");

                return(ConnectionStatus.Disconnected);
            });

            var closed = Observable.FromEventPattern <CallbackExceptionEventArgs>(h => connection.AutoRecoveringConnection.CallbackException += h, h => connection.AutoRecoveringConnection.CallbackException -= h).Select(e =>
            {
                _logger?.LogError(e.EventArgs.Exception, $"An exception occured in a callback process - {nameof(CallbackExceptionEventArgs)} => {e.EventArgs?.ToJson()}");

                return(ConnectionStatus.ErrorOccurred);
            });

            var errorOccurred = Observable.FromEventPattern <EventArgs>(h => connection.AutoRecoveringConnection.RecoverySucceeded += h, h => connection.AutoRecoveringConnection.RecoverySucceeded -= h).Select(e =>
            {
                _logger?.LogInformation($"AMQP connection recovery success - {nameof(EventArgs)} => {e.EventArgs?.ToJson()}");

                return(ConnectionStatus.Connected);
            });

            var connectionRecoveryError = Observable.FromEventPattern <ConnectionRecoveryErrorEventArgs>(h => connection.AutoRecoveringConnection.ConnectionRecoveryError += h, h => connection.AutoRecoveringConnection.ConnectionRecoveryError -= h).Select(e =>
            {
                _logger?.LogError(e.EventArgs.Exception, $"AMQP connection recovery error - {nameof(ConnectionRecoveryErrorEventArgs)} => {e.EventArgs?.ToJson()}");

                return(ConnectionStatus.Disconnected);
            });

            _connectionInfoChanged = Observable.Merge(blocked, unblocked, shutdowned, closed, errorOccurred, connectionRecoveryError)
                                     .Scan(ConnectionInfo.InitialConnected, UpdateConnectionInfo)
                                     .StartWith(ConnectionInfo.InitialConnected)
                                     .Do(connectionInfo =>
            {
                ConnectionInfo = connectionInfo;
                _logger?.LogInformation($"{nameof(RabbitMqConnectionStatusMonitor)} => ConnectionInfo - {connectionInfo}");
                _isConnected.OnNext(connectionInfo.Status == ConnectionStatus.Connected);
            })
                                     .Replay(1);

            _cleanUp = _connectionInfoChanged.Connect();
        }
        public void Load(string name, ILoader loader, FrameworkLogger logger)
        {
            // The data in downloads.v1.json will be an array of Package records - which has Id, Array of Versions and download count.
            // Sample.json : [["AutofacContrib.NSubstitute",["2.4.3.700",406],["2.5.0",137]],["Assman.Core",["2.0.7",138]]....
            using (var jsonReader = loader.GetReader(name))
            {
                try
                {
                    jsonReader.Read();

                    while (jsonReader.Read())
                    {
                        try
                        {
                            if (jsonReader.TokenType == JsonToken.StartArray)
                            {
                                JToken record = JToken.ReadFrom(jsonReader);
                                string id = String.Intern(record[0].ToString().ToLowerInvariant());

                                // The second entry in each record should be an array of versions, if not move on to next entry.
                                // This is a check to safe guard against invalid entries.
                                if (record.Count() == 2 && record[1].Type != JTokenType.Array)
                                {
                                    continue;
                                }

                                if (!_downloads.ContainsKey(id))
                                {
                                    _downloads.Add(id, new DownloadsByVersion());
                                }
                                var versions = _downloads[id];

                                foreach (JToken token in record)
                                {
                                    if (token != null && token.Count() == 2)
                                    {
                                        string version = String.Intern(token[0].ToString().ToLowerInvariant());
                                        versions[version] = token[1].ToObject<int>();
                                    }
                                }
                            }
                        }
                        catch (JsonReaderException ex)
                        {
                            logger.LogInformation("Invalid entry found in downloads.v1.json. Exception Message : {0}", ex.Message);
                        }
                    }
                }
                catch (JsonReaderException ex)
                {
                    logger.LogError("Data present in downloads.v1.json is invalid. Couldn't get download data.", ex);
                }
            }
        }
Example #32
0
        private static async Task StartApp(StartupOptions options)
        {
            ServerApplicationPaths appPaths = CreateApplicationPaths(options);

            // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
            Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
            await CreateLogger(appPaths);

            _logger = _loggerFactory.CreateLogger("Main");

            AppDomain.CurrentDomain.UnhandledException += (sender, e)
                                                          => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");

            // Intercept Ctrl+C and Ctrl+Break
            Console.CancelKeyPress += (sender, e) =>
            {
                if (_tokenSource.IsCancellationRequested)
                {
                    return; // Already shutting down
                }
                e.Cancel = true;
                _logger.LogInformation("Ctrl+C, shutting down");
                Environment.ExitCode = 128 + 2;
                Shutdown();
            };

            // Register a SIGTERM handler
            AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
            {
                if (_tokenSource.IsCancellationRequested)
                {
                    return; // Already shutting down
                }
                _logger.LogInformation("Received a SIGTERM signal, shutting down");
                Environment.ExitCode = 128 + 15;
                Shutdown();
            };

            _logger.LogInformation("Jellyfin version: {Version}", Assembly.GetEntryAssembly().GetName().Version);

            EnvironmentInfo environmentInfo = new EnvironmentInfo(GetOperatingSystem());

            ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo);

            SQLitePCL.Batteries_V2.Init();

            // Allow all https requests
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); });

            var fileSystem = new ManagedFileSystem(_loggerFactory, environmentInfo, null, appPaths.TempDirectory, true);

            using (var appHost = new CoreAppHost(
                       appPaths,
                       _loggerFactory,
                       options,
                       fileSystem,
                       environmentInfo,
                       new NullImageEncoder(),
                       new NetworkManager(_loggerFactory, environmentInfo)))
            {
                await appHost.Init(new ServiceCollection());

                appHost.ImageProcessor.ImageEncoder = GetImageEncoder(fileSystem, appPaths, appHost.LocalizationManager);

                await appHost.RunStartupTasks();

                // TODO: read input for a stop command

                try
                {
                    // Block main thread until shutdown
                    await Task.Delay(-1, _tokenSource.Token);
                }
                catch (TaskCanceledException)
                {
                    // Don't throw on cancellation
                }
            }

            if (_restartOnShutdown)
            {
                StartNewInstance(options);
            }
        }
Example #33
0
        static void Main()
        {
            Console.WriteLine("SIPSorcery call hold example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource exitCts = new CancellationTokenSource(); // Cancellation token to stop the SIP transport and RTP stream.

            AddConsoleLogger();

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

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

            EnableTraceLogs(sipTransport);

            // Create two user agents. Each gets configured to answer an incoming call.
            var userAgent1 = new SIPUserAgent(sipTransport, null);
            var userAgent2 = new SIPUserAgent(sipTransport, null);

            // Only one of the user agents can use the microphone and speaker. The one designated
            // as the active agent gets the devices.
            SIPUserAgent    activeUserAgent  = null;
            RTPMediaSession activeRtpSession = null;

            // Get the default speaker.
            var(audioOutEvent, audioOutProvider) = GetAudioOutputDevice();
            m_audioOutProvider = audioOutProvider;
            WaveInEvent waveInEvent = GetAudioInputDevice();

            userAgent1.OnCallHungup        += () => Log.LogInformation($"UA1: Call hungup by remote party.");
            userAgent1.ServerCallCancelled += (uas) => Log.LogInformation("UA1: Incoming call cancelled by caller.");

            userAgent2.OnCallHungup        += () => Log.LogInformation($"UA2: Call hungup by remote party.");
            userAgent2.ServerCallCancelled += (uas) => Log.LogInformation("UA2: Incoming call cancelled by caller.");

            userAgent2.OnTransferNotify += (sipFrag) =>
            {
                if (!string.IsNullOrEmpty(sipFrag))
                {
                    Log.LogInformation($"UA2: Transfer status update: {sipFrag.Trim()}.");
                    if (sipFrag?.Contains("SIP/2.0 200") == true)
                    {
                        // The transfer attempt got a succesful answer. Can hangup the call.
                        userAgent2.Hangup();
                        exitCts.Cancel();
                    }
                }
            };

            sipTransport.SIPTransportRequestReceived += (locelEndPoint, remoteEndPoint, sipRequest) =>
            {
                if (sipRequest.Header.From != null &&
                    sipRequest.Header.From.FromTag != null &&
                    sipRequest.Header.To != null &&
                    sipRequest.Header.To.ToTag != null)
                {
                    // This is an in-dialog request that will be handled directly by a user agent instance.
                }
                else if (sipRequest.Method == SIPMethodsEnum.INVITE)
                {
                    if (!userAgent1.IsCallActive)
                    {
                        Log.LogInformation($"UA1: Incoming call request from {remoteEndPoint}: {sipRequest.StatusLine}.");
                        var incomingCall = userAgent1.AcceptCall(sipRequest);

                        var rtpMediaSession = new RTPMediaSession(SDPMediaTypesEnum.audio, (int)SDPMediaFormatsEnum.PCMU, AddressFamily.InterNetwork);
                        rtpMediaSession.RemotePutOnHold   += () => Log.LogInformation("UA1: Remote call party has placed us on hold.");
                        rtpMediaSession.RemoteTookOffHold += () => Log.LogInformation("UA1: Remote call party took us off hold.");

                        userAgent1.Answer(incomingCall, rtpMediaSession)
                        .ContinueWith(task =>
                        {
                            activeUserAgent  = userAgent1;
                            activeRtpSession = rtpMediaSession;
                            activeRtpSession.OnRtpPacketReceived += PlaySample;
                            waveInEvent.StartRecording();

                            Log.LogInformation($"UA1: Answered incoming call from {sipRequest.Header.From.FriendlyDescription()} at {remoteEndPoint}.");
                        }, exitCts.Token);
                    }
                    else if (!userAgent2.IsCallActive)
                    {
                        Log.LogInformation($"UA2: Incoming call request from {remoteEndPoint}: {sipRequest.StatusLine}.");

                        var incomingCall    = userAgent2.AcceptCall(sipRequest);
                        var rtpMediaSession = new RTPMediaSession(SDPMediaTypesEnum.audio, (int)SDPMediaFormatsEnum.PCMU, AddressFamily.InterNetwork);
                        rtpMediaSession.RemotePutOnHold   += () => Log.LogInformation("UA2: Remote call party has placed us on hold.");
                        rtpMediaSession.RemoteTookOffHold += () => Log.LogInformation("UA2: Remote call party took us off hold.");

                        userAgent2.Answer(incomingCall, rtpMediaSession)
                        .ContinueWith(task =>
                        {
                            activeRtpSession.OnRtpPacketReceived -= PlaySample;

                            activeUserAgent  = userAgent2;
                            activeRtpSession = rtpMediaSession;
                            activeRtpSession.PutOnHold();
                            activeRtpSession.OnRtpPacketReceived += PlaySample;

                            Log.LogInformation($"UA2: Answered incoming call from {sipRequest.Header.From.FriendlyDescription()} at {remoteEndPoint}.");
                        }, exitCts.Token);
                    }
                    else
                    {
                        // If both user agents are already on a call return a busy response.
                        Log.LogWarning($"Busy response returned for incoming call request from {remoteEndPoint}: {sipRequest.StatusLine}.");
                        UASInviteTransaction uasTransaction = new UASInviteTransaction(sipTransport, sipRequest, null);
                        SIPResponse          busyResponse   = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.BusyHere, null);
                        uasTransaction.SendFinalResponse(busyResponse);
                    }
                }
                else
                {
                    Log.LogDebug($"SIP {sipRequest.Method} request received but no processing has been set up for it, rejecting.");
                    SIPResponse notAllowedResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.MethodNotAllowed, null);
                    return(sipTransport.SendResponseAsync(notAllowedResponse));
                }

                return(Task.FromResult(0));
            };

            // Wire up the RTP send session to the audio input device.
            uint rtpSendTimestamp = 0;

            waveInEvent.DataAvailable += (object sender, WaveInEventArgs args) =>
            {
                byte[] sample      = new byte[args.Buffer.Length / 2];
                int    sampleIndex = 0;

                for (int index = 0; index < args.BytesRecorded; index += 2)
                {
                    var ulawByte = NAudio.Codecs.MuLawEncoder.LinearToMuLawSample(BitConverter.ToInt16(args.Buffer, index));
                    sample[sampleIndex++] = ulawByte;
                }

                if (activeRtpSession != null)
                {
                    activeRtpSession.SendAudioFrame(rtpSendTimestamp, sample);
                    rtpSendTimestamp += (uint)sample.Length;
                }
            };

            // At this point the call has been initiated and everything will be handled in an event handler.
            Task.Run(async() =>
            {
                try
                {
                    while (!exitCts.Token.WaitHandle.WaitOne(0))
                    {
                        var keyProps = Console.ReadKey();

                        if (keyProps.KeyChar == 't')
                        {
                            if (userAgent1.IsCallActive && userAgent2.IsCallActive)
                            {
                                bool result = await userAgent2.AttendedTransfer(userAgent1.Dialogue, TimeSpan.FromSeconds(TRANSFER_TIMEOUT_SECONDS), exitCts.Token);
                                if (!result)
                                {
                                    Log.LogWarning($"Attended transfer failed.");
                                }
                            }
                            else
                            {
                                Log.LogWarning("There need to be two active calls before the attended transfer can occur.");
                            }
                        }
                        else if (keyProps.KeyChar == 'q')
                        {
                            // Quit application.
                            exitCts.Cancel();
                        }
                    }
                }
                catch (Exception excp)
                {
                    SIPSorcery.Sys.Log.Logger.LogError($"Exception Key Press listener. {excp.Message}.");
                }
            });

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

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

            #region Cleanup.

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

            userAgent1?.Hangup();
            userAgent2?.Hangup();
            waveInEvent?.StopRecording();
            audioOutEvent?.Stop();

            // Give any BYE or CANCEL requests time to be transmitted.
            Log.LogInformation("Waiting 1s for calls to be cleaned up...");
            Task.Delay(1000).Wait();

            SIPSorcery.Net.DNSManager.Stop();

            if (sipTransport != null)
            {
                Log.LogInformation("Shutting down SIP transport...");
                sipTransport.Shutdown();
            }

            #endregion
        }
Example #34
0
        public async Task <IActionResult> Post([FromBody] ShareQRReq reqForm)
        {
            _logger.LogInformation("start share QR balance");

            DBModels dbModel = new DBModels();

            //validate TransId
            string transIdResult = await dbModel.checkTransId(reqForm.UserID, reqForm.TransId);

            if (transIdResult != "")
            {
                return(Ok(new ShareQR_Fail()
                {
                    Msg = transIdResult
                }));
            }

            //get product info based on QR
            List <QrBalance> prodDetail = await dbModel.GetProductDetailFromQR_Status(reqForm.UserID, reqForm.QRCode);

            if (prodDetail.Count == 0)
            {
                return(Ok(new ShareQR_Fail()
                {
                    Msg = "Invalid QR Code"
                }));
            }

            if (reqForm.SharedQty <= 0)
            {
                return(Ok(new ShareQR_Fail()
                {
                    Msg = "Invalid shared quantity"
                }));
            }
            else if (reqForm.SharedQty > prodDetail[0].Qty)
            {
                return(Ok(new ShareQR_Fail()
                {
                    Msg = "Shared quantity can't be higher than available quantity"
                }));
            }

            DateTime transTime        = DateTime.Now;
            int      ttlQtyAfterShare = prodDetail[0].Qty - reqForm.SharedQty;
            DateTime ExpiryDate       = prodDetail[0].ExpiryDate;

            await dbModel.InitShareQRCode(reqForm.UserID, reqForm.QRCode, reqForm.TransId, transTime, reqForm.SharedQty);

            //Share QR (need to get new ttl qty & new expirydate)
            string SharedQRCode = "";
            string reqResult    = await iJoozAPI.reqQR("Share", reqForm.TransId, reqForm.TransTime, "member", reqForm.UserID, reqForm.QRCode, prodDetail[0].Currency, prodDetail[0].UnitPrice, reqForm.SharedQty, DateTime.Now.AddMonths(24));

            if (reqResult == "")
            {
                return(Ok(new ShareQR_Fail()
                {
                    Msg = "Get QR Code from iJooz Fail"
                }));
            }
            else
            {
                var data = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(reqResult);
                if (data["result"] == "Success")
                {
                    SharedQRCode     = data["qrCode"];
                    ttlQtyAfterShare = Convert.ToInt16(data["balanceQty"]);
                }
                else
                {
                    return(Ok(new ShareQR_Fail()
                    {
                        Msg = "Get QR Code from iJooz Fail2"
                    }));
                }
            }

            await dbModel.SaveShareQRCode(reqForm.UserID, reqForm.TransId, reqForm.QRCode, ttlQtyAfterShare, SharedQRCode, reqForm.SharedQty, reqForm.Remark);

            List <QrDetail> detailList = new List <QrDetail> {
                new QrDetail()
                {
                    TransId      = reqForm.TransId,
                    QRCode       = prodDetail[0].QRCode,
                    RemainQty    = ttlQtyAfterShare,
                    SharedQRCode = SharedQRCode,
                    SharedQty    = reqForm.SharedQty,
                    ExpiryDate   = prodDetail[0].ExpiryDate,
                    Remark       = reqForm.Remark
                }
            };

            return(Ok(new ShareQR_OK()
            {
                QrDetail = detailList
            }));
        }
        public void ProcessEvents(
            string applicationName,
            string serviceName,
            int processId,
            string replicaName,
            IDictionary <string, string> metrics,
            CancellationToken cancellationToken)
        {
            var hasEventPipe = false;

            for (var i = 0; i < 10; ++i)
            {
                if (DiagnosticsClient.GetPublishedProcesses().Contains(processId))
                {
                    hasEventPipe = true;
                    break;
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                Thread.Sleep(500);
            }

            if (!hasEventPipe)
            {
                _logger.LogInformation("Process id {PID}, does not support event pipe", processId);
                return;
            }

            _logger.LogInformation("Listening for event pipe events for {ServiceName} on process id {PID}", replicaName, processId);

            // Create the logger factory for this replica
            using var loggerFactory = LoggerFactory.Create(builder => ConfigureLogging(serviceName, replicaName, builder));

            var processor = new SimpleSpanProcessor(CreateSpanExporter(serviceName, replicaName));

            var providers = new List <EventPipeProvider>()
            {
                // Runtime Metrics
                new EventPipeProvider(
                    SystemRuntimeEventSourceName,
                    EventLevel.Informational,
                    (long)ClrTraceEventParser.Keywords.None,
                    new Dictionary <string, string>()
                {
                    { "EventCounterIntervalSec", "1" }
                }
                    ),
                new EventPipeProvider(
                    MicrosoftAspNetCoreHostingEventSourceName,
                    EventLevel.Informational,
                    (long)ClrTraceEventParser.Keywords.None,
                    new Dictionary <string, string>()
                {
                    { "EventCounterIntervalSec", "1" }
                }
                    ),
                new EventPipeProvider(
                    GrpcAspNetCoreServer,
                    EventLevel.Informational,
                    (long)ClrTraceEventParser.Keywords.None,
                    new Dictionary <string, string>()
                {
                    { "EventCounterIntervalSec", "1" }
                }
                    ),

                // Application Metrics
                new EventPipeProvider(
                    applicationName,
                    EventLevel.Informational,
                    (long)ClrTraceEventParser.Keywords.None,
                    new Dictionary <string, string>()
                {
                    { "EventCounterIntervalSec", "1" }
                }
                    ),

                // Logging
                new EventPipeProvider(
                    MicrosoftExtensionsLoggingProviderName,
                    EventLevel.LogAlways,
                    (long)(LoggingEventSource.Keywords.JsonMessage | LoggingEventSource.Keywords.FormattedMessage)
                    ),

                // Distributed Tracing

                // Activity correlation
                new EventPipeProvider(TplEventSource,
                                      keywords: 0x80,
                                      eventLevel: EventLevel.LogAlways),

                // Diagnostic source events
                new EventPipeProvider(DiagnosticSourceEventSource,
                                      keywords: 0x1 | 0x2,
                                      eventLevel: EventLevel.Verbose,
                                      arguments: new Dictionary <string, string>
                {
                    { "FilterAndPayloadSpecs", DiagnosticFilterString }
                })
            };

            while (!cancellationToken.IsCancellationRequested)
            {
                EventPipeSession session = null;
                var client = new DiagnosticsClient(processId);

                try
                {
                    session = client.StartEventPipeSession(providers);
                }
                catch (EndOfStreamException)
                {
                    break;
                }
                // If the process has already exited, a ServerNotAvailableException will be thrown.
                catch (ServerNotAvailableException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    if (!cancellationToken.IsCancellationRequested)
                    {
                        _logger.LogDebug(0, ex, "Failed to start the event pipe session");
                    }

                    // We can't even start the session, wait until the process boots up again to start another metrics thread
                    break;
                }

                void StopSession()
                {
                    try
                    {
                        session.Stop();
                    }
                    catch (EndOfStreamException)
                    {
                        // If the app we're monitoring exits abruptly, this may throw in which case we just swallow the exception and exit gracefully.
                    }
                    // We may time out if the process ended before we sent StopTracing command. We can just exit in that case.
                    catch (TimeoutException)
                    {
                    }
                    // On Unix platforms, we may actually get a PNSE since the pipe is gone with the process, and Runtime Client Library
                    // does not know how to distinguish a situation where there is no pipe to begin with, or where the process has exited
                    // before dotnet-counters and got rid of a pipe that once existed.
                    // Since we are catching this in StopMonitor() we know that the pipe once existed (otherwise the exception would've
                    // been thrown in StartMonitor directly)
                    catch (PlatformNotSupportedException)
                    {
                    }
                    // If the process has already exited, a ServerNotAvailableException will be thrown.
                    // This can always race with tye shutting down and a process being restarted on exiting.
                    catch (ServerNotAvailableException)
                    {
                    }
                }

                using var _ = cancellationToken.Register(() => StopSession());

                try
                {
                    var source = new EventPipeEventSource(session.EventStream);

                    // Distribued Tracing
                    HandleDistributedTracingEvents(source, processor);

                    // Metrics
                    HandleEventCounters(source, metrics);

                    // Logging
                    HandleLoggingEvents(source, loggerFactory, replicaName);

                    source.Process();
                }
                catch (DiagnosticsClientException ex)
                {
                    _logger.LogDebug(0, ex, "Failed to start the event pipe session");
                }
                catch (Exception)
                {
                    // This fails if stop is called or if the process dies
                }
                finally
                {
                    session?.Dispose();
                }
            }

            _logger.LogInformation("Event pipe collection completed for {ServiceName} on process id {PID}", replicaName, processId);
        }