Example #1
0
        private async Task StopAsync()
        {
            try
            {
                if (_processor != null)
                {
                    await _processor.StopAsync(_application);
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "Error while shutting down");
            }
            finally
            {
                if (DashboardWebApplication != null)
                {
                    // Stop the host after everything else has been shutdown
                    try
                    {
                        await DashboardWebApplication.StopAsync();
                    }
                    catch (OperationCanceledException)
                    {
                        // ignore cancellation failures from stop async
                    }
                }
            }

            _processor = null;
        }
        /// <summary>
        /// Starts the subscription
        /// </summary>
        /// <summary>
        /// Starts the subscription
        /// </summary>
        public async Task Start()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException($"{typeof(JsonRpcSubscription).FullName}@{this.GetHashCode()}");
            }
            if (!_client.IsConnected)
            {
                _client.Connect();
            }
            if (_subscription != null)
            {
                await _client.UnsubAsync(_subscription);

                _subscription = null;
            }
            _subscription = await _client.SubAsync(_sInfo, stream => stream.Subscribe(msg =>
            {
                try
                {
                    byte[] resp = OnMessage(msg.Payload);
                    _client.Pub(msg.ReplyTo, resp);
                }
                catch (Exception ex)
                {
                    _logger?.LogError(ex, "Error publishing NATS message");
                }
            }, error => {
                _logger?.LogError(error, "Fatal error in NATS subscription handler");
            }));
        }
        public static QueryBoostingContext Load(string fileName, ILoader loader, FrameworkLogger logger)
        {
            try
            {
                using (var reader = loader.GetReader(fileName))
                {
                    var serializer = new JsonSerializer();

                    var value = serializer.Deserialize<QueryBoostingContext>(reader);

                    return value;
                }
            }
            catch (Exception ex)
            {
                if (IndexingUtils.IsFatal(ex))
                {
                    throw;
                }

                logger.LogError($"Unable to load {fileName}.", ex);
            }

            return Default;
        }
Example #4
0
        public NugetPackage(ILogger logger)
        {
            _logger = logger;
            try
            {
                ISettings settings;

                try
                {
                    settings = Settings.LoadDefaultSettings(
                        root: null,
                        configFileName: null,
                        machineWideSettings: new XPlatMachineWideSetting());
                }
                catch (NuGetConfigurationException ex)
                {
                    // create default settings using a non-existent config file
                    settings = new Settings(nameof(Script.ScriptRunner));
                }

                GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(settings);
                _configFilePaths    = new List <string>(); //SettingsUtility.GetConfigFilePaths(settings);
                _packageSources     = SettingsUtility.GetEnabledSources(settings);

                DefaultCredentialServiceUtility.SetupDefaultCredentialService(NullLogger.Instance,
                                                                              nonInteractive: false);

                var sourceProvider = new PackageSourceProvider(settings);
            }
            catch (Exception e)
            {
                _logger?.LogError(e.Message + e.StackTrace);
                _initializationException = ExceptionDispatchInfo.Capture(e);
            }
        }
        public async Task WriteResponseAsync(IOwinContext context, Exception e, FrameworkLogger logger)
        {
            logger.LogError("Internal server error", e);

            await WriteResponseAsync(context, HttpStatusCode.InternalServerError, JObject.FromObject(new
            {
                error = "Internal server error",
                httpRequestId = context.Get<string>(CorrelationIdMiddleware.CorrelationIdHeaderKey)
            }));
        }
        public static void Load(string name, ILoader loader, FrameworkLogger logger, IDictionary<string, HashSet<string>> targetDictionary)
        {
            try
            {
                using (var jsonReader = loader.GetReader(name))
                {
                    UpdateDictionary(jsonReader, targetDictionary);
                }
            }
            catch (Exception e)
            {
                if (IsFatal(e))
                {
                    throw;
                }

                logger.LogError($"Unable to load {name}.", e);
            }
        }
Example #7
0
        public NugetPackage(ILogger logger, NugetManager manager)
        {
            _manager = manager;
            _logger  = logger;
            try
            {
                ISettings settings;
                try
                {
                    settings = Settings.LoadDefaultSettings(
                        root: null,
                        configFileName: null,
                        machineWideSettings: new XPlatMachineWideSetting());
                }
                catch (NuGetConfigurationException)
                {
                    // create default settings using a non-existent config file
                    settings = new Settings(nameof(NugetPackage));
                }

                GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(settings);
                _configFilePaths    = new List <string>(); //SettingsUtility.GetConfigFilePaths(settings);
                var sources = SettingsUtility.GetEnabledSources(settings);
                _packageSources = _manager.AdditionalSources.Select(p => new PackageSource(p.source, p.name)).Concat(sources).ToList();
                DefaultCredentialServiceUtility.SetupDefaultCredentialService(NullLogger.Instance,
                                                                              nonInteractive: false);

                var sourceProvider = new PackageSourceProvider(settings);
                var providers      = new List <Lazy <INuGetResourceProvider> >();
                providers.AddRange(Repository.Provider.GetCoreV3());
                _sourceRepositories = _packageSources.Select(s => new SourceRepository(s, providers)).ToList();
            }
            catch (Exception e)
            {
                _logger?.LogError(e.Message + e.StackTrace);
                _initializationException = ExceptionDispatchInfo.Capture(e);
            }
        }
        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);
                }

                // Fire the orchestration to do the actual work of sending notifications
                Command_Get_Notifications_Request payload = new Command_Get_Notifications_Request()
                {
                    CommandName             = cmdRequest.CommandName,
                    CommandUniqueIdentifier = cmdRequest.CommandUniqueIdentifier.ToString()
                };

                // call the orchestrator...
                resp = await context.CallSubOrchestratorAsync <ActivityResponse>("CommandNotificationOrchestrator", payload);

                #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;
            }
        }
        public static async Task <ActivityResponse> QueryProjectionProcessorOrchestrator(
            [OrchestrationTrigger] DurableOrchestrationContext context,
            Microsoft.Extensions.Logging.ILogger log)
        {
            ActivityResponse response = new ActivityResponse()
            {
                FunctionName = "QueryProjectionProcessorOrchestrator"
            };

            Query_Projections_Projection_Request request = context.GetInput <Query_Projections_Projection_Request>();

            if (null != request)
            {
                Guid UniqueIdentifierGuid;
                if (!Guid.TryParse(request.UniqueIdentifier, out UniqueIdentifierGuid))
                {
                    if (!Guid.TryParse(request.CallbackOrchestrationIdentifier, out UniqueIdentifierGuid))
                    {
                        if (!Guid.TryParse(context.ParentInstanceId, out UniqueIdentifierGuid))
                        {
                            if (!Guid.TryParse(context.InstanceId, out UniqueIdentifierGuid))
                            {
                                UniqueIdentifierGuid = Guid.NewGuid();
                            }
                        }
                    }
                }



                // get all the projection requests for the query
                List <Query_Projections_Projection_Return> allProjections = await context
                                                                            .CallActivityWithRetryAsync <List <Query_Projections_Projection_Return> >("GetQueryProjectionsStatusProjectionActivity",
                                                                                                                                                      DomainSettings.QueryRetryOptions(),
                                                                                                                                                      request);

                if (null != allProjections)
                {
                    #region Logging
                    if (null != log)
                    {
                        log.LogInformation($"Query {request.QueryName}.{request.UniqueIdentifier} has {allProjections.Count} projections total ");
                    }
                    #endregion

                    // Run them - This should be done by fan-out/fan-in
                    List <Task <ProjectionResultsRecord <object> > > allProjectionTasks = new List <Task <ProjectionResultsRecord <object> > >();

                    // run all the outstanding projections in parallel
                    foreach (Query_Projections_Projection_Return projectionRequest in allProjections)
                    {
                        if (projectionRequest.ProjectionState == Query_Projections_Projection_Return.QueryProjectionState.Queued)
                        {
                            ProjectionRequest projRequest = new ProjectionRequest()
                            {
                                ParentRequestName                 = request.QueryName,
                                CorrelationIdentifier             = UniqueIdentifierGuid,
                                DomainName                        = projectionRequest.Projection.DomainName,
                                AggregateTypeName                 = projectionRequest.Projection.AggregateTypeName,
                                AggregateInstanceUniqueIdentifier = projectionRequest.Projection.InstanceKey,
                                AsOfDate       = request.AsOfDate,
                                ProjectionName = projectionRequest.Projection.ProjectionTypeName
                            };

                            if (null != projRequest)
                            {
                                context.SetCustomStatus(projRequest);
                            }


                            // mark it as in-flight
                            response = await context.CallActivityWithRetryAsync <ActivityResponse>("LogQueryProjectionInFlightActivity",
                                                                                                   DomainSettings.QueryRetryOptions(),
                                                                                                   projRequest);

                            if (null != response)
                            {
                                context.SetCustomStatus(response);
                            }
                        }
                    }

                    // Now start them running using a fan-out/fan in pattern
                    foreach (Query_Projections_Projection_Return projectionRequested in allProjections)
                    {
                        if (projectionRequested.ProjectionState == Query_Projections_Projection_Return.QueryProjectionState.Queued)
                        {
                            ProjectionRequest projectionRequest = new ProjectionRequest()
                            {
                                ParentRequestName                 = request.QueryName,
                                CorrelationIdentifier             = UniqueIdentifierGuid,
                                DomainName                        = projectionRequested.Projection.DomainName,
                                AggregateTypeName                 = projectionRequested.Projection.AggregateTypeName,
                                AggregateInstanceUniqueIdentifier = projectionRequested.Projection.InstanceKey,
                                AsOfDate       = request.AsOfDate,
                                ProjectionName = projectionRequested.Projection.ProjectionTypeName
                            };


                            // and start running it...
                            allProjectionTasks.Add(context.CallActivityWithRetryAsync <ProjectionResultsRecord <object> >("RunProjectionActivity",
                                                                                                                          DomainSettings.QueryRetryOptions(),
                                                                                                                          projectionRequest));
                        }
                    }

                    // Run the projections in parallel...
                    await Task.WhenAll(allProjectionTasks);

                    // and save their results to the query
                    foreach (var returnValue in allProjectionTasks)
                    {
                        ProjectionResultsRecord <object> result = returnValue.Result;

                        if (null != result)
                        {
                            if (!result.Error)
                            {
                                response = await context.CallActivityWithRetryAsync <ActivityResponse>("LogQueryProjectionResultActivity",
                                                                                                       DomainSettings.QueryRetryOptions(),
                                                                                                       result);
                            }
                            else
                            {
                                #region Logging
                                if (null != log)
                                {
                                    log.LogError($"Error running projection {result.ProjectionName} - {result.StatusMessage} ");
                                }
                                #endregion
                                response.Message = $"Error running projection {result.ProjectionName} - {result.StatusMessage} ";
                            }
                            if (null != response)
                            {
                                context.SetCustomStatus(response);
                            }
                        }
                        else
                        {
                            #region Logging
                            if (null != log)
                            {
                                log.LogError($"Projection {returnValue.Id} did not return any values : {returnValue.Exception}");
                            }
                            #endregion
                        }
                    }
                }


                // when all done - trigger the calling orchestration to come out of hibernation
                if (!string.IsNullOrWhiteSpace(request.CallbackOrchestrationIdentifier))
                {
                }
            }
            else
            {
                response.Message    = $"Unable to read projection request data from context {context.InstanceId}";
                response.FatalError = true;
            }

            return(response);
        }
 public void LogError(Exception ex, string message)
 {
     _functionLogger.LogError(ex, message, _source);
     _redisLogger.Error(ex, message);
 }
Example #11
0
 public void Error(string message)
 {
     _logger.LogError(message);
 }
Example #12
0
        /// <summary>
        /// Process user key presses.
        /// </summary>
        /// <param name="exit">The cancellation token to set if the user requests to quit the application.</param>
        private static void OnKeyPress(CancellationTokenSource exitCts)
        {
            try
            {
                while (!exitCts.IsCancellationRequested)
                {
                    var keyProps = Console.ReadKey();

                    if (keyProps.KeyChar == 'c')
                    {
                        // Set up a default SIP transport.
                        var sipTransport = new SIPTransport();
                        //EnableTraceLogs(sipTransport);

                        var targetUri         = SIPURI.ParseSIPURI(TARGET_DST);
                        int requestedDtmfCode = Crypto.GetRandomInt(4);
                        targetUri.User = requestedDtmfCode.ToString();

                        SIPUserAgent ua = new SIPUserAgent(sipTransport, null, true);
                        CallRecord   cr = new CallRecord {
                            UA = ua, RequestedDtmfCode = requestedDtmfCode, ReceivedDtmfCode = ""
                        };

                        // Place an outgoing call.
                        ua.ClientCallTrying   += (uac, resp) => Log.LogInformation($"{uac.CallDescriptor.To} Trying: {resp.StatusCode} {resp.ReasonPhrase}.");
                        ua.ClientCallRinging  += (uac, resp) => Log.LogInformation($"{uac.CallDescriptor.To} Ringing: {resp.StatusCode} {resp.ReasonPhrase}.");
                        ua.ClientCallFailed   += (uac, err, resp) => Log.LogWarning($"{uac.CallDescriptor.To} Failed: {err}, Status code: {resp?.StatusCode}");
                        ua.ClientCallAnswered += (uac, resp) => Log.LogInformation($"{uac.CallDescriptor.To} Answered: {resp.StatusCode} {resp.ReasonPhrase}.");
                        ua.OnDtmfTone         += (key, duration) =>
                        {
                            cr.ReceivedDtmfCode = cr.ReceivedDtmfCode.Insert(0, key.ToString());
                            Log.LogInformation($"Received DTMF tone {key} {cr.ReceivedDtmfCode}.");
                        };
                        //ua.OnRtpEvent += (evt, hdr) => Log.LogDebug($"transferee rtp event {evt.EventID}, ssrc {hdr.SyncSource}, duration {evt.Duration}, end of event {evt.EndOfEvent}, timestamp {hdr.Timestamp}, marker {hdr.MarkerBit}.");
                        ua.OnCallHungup += (dialog) => Log.LogDebug("Call hungup by remote party.");

                        Task.Run(async() =>
                        {
                            var rtpSession = CreateRtpSession();
                            var callResult = await ua.Call(targetUri.ToString(), null, null, rtpSession);

                            if (!callResult)
                            {
                                Log.LogWarning($"Call to {targetUri} failed.");
                            }
                            else
                            {
                                Log.LogInformation($"Call to {targetUri} was successful.");
                                _calls.TryAdd(ua.Dialogue.CallId, cr);
                            }
                        });
                    }
                    else if (keyProps.KeyChar == 'h')
                    {
                        if (_calls.Count == 0)
                        {
                            Log.LogWarning("There are no active calls.");
                        }
                        else
                        {
                            var oldestCall = _calls.OrderBy(x => x.Value.UA.Dialogue.Inserted).First();
                            Log.LogInformation($"Hanging up call {oldestCall.Key}.");
                            oldestCall.Value.UA.OnCallHungup -= OnHangup;
                            oldestCall.Value.UA.Hangup();
                            _calls.TryRemove(oldestCall.Key, out _);
                        }
                    }
                    else if (keyProps.KeyChar == 'H')
                    {
                        if (_calls.Count == 0)
                        {
                            Log.LogWarning("There are no active calls.");
                        }
                        else
                        {
                            foreach (var call in _calls)
                            {
                                Log.LogInformation($"Hanging up call {call.Key}.");
                                call.Value.UA.OnCallHungup -= OnHangup;
                                call.Value.UA.Hangup();
                            }
                            _calls.Clear();
                        }
                    }
                    else if (keyProps.KeyChar == 'l')
                    {
                        if (_calls.Count == 0)
                        {
                            Log.LogInformation("There are no active calls.");
                        }
                        else
                        {
                            Log.LogInformation("Current call list:");
                            foreach (var call in _calls)
                            {
                                int  duration = Convert.ToInt32(DateTimeOffset.Now.Subtract(call.Value.UA.Dialogue.Inserted).TotalSeconds);
                                uint rtpSent  = (call.Value.UA.MediaSession as RtpAudioSession).RtpPacketsSent;
                                uint rtpRecv  = (call.Value.UA.MediaSession as RtpAudioSession).RtpPacketsReceived;
                                Log.LogInformation($"{call.Key}: {call.Value.UA.Dialogue.RemoteTarget}, req code {call.Value.RequestedDtmfCode}, recvd code {call.Value.ReceivedDtmfCode}, dur {duration}s, rtp sent/recvd {rtpSent}/{rtpRecv}");
                            }
                        }
                    }
                    else if (keyProps.KeyChar == 'q')
                    {
                        // Quit application.
                        Log.LogInformation("Quitting");
                        exitCts.Cancel();
                        break;
                    }
                }
            }
            catch (Exception excp)
            {
                Log.LogError($"Exception OnKeyPress. {excp.Message}.");
            }
        }
        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();
        }
Example #14
0
 public void OnPostLogError()
 {
     _logger.LogError("Какая-то ошибка произошла");
 }
Example #15
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
            {
                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;
                            }
                            else if (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}");
            }
        }
        public static async Task OnGetLeagueSummaryQueryHandler(
            [EventGridTrigger] EventGridEvent eventGridEvent,
            [OrchestrationClient] DurableOrchestrationClient getLeagueSummaryQueryHandlerOrchestrationClient,
            Microsoft.Extensions.Logging.ILogger log
            )
        {
            #region Logging
            if (null != log)
            {
                log.LogDebug("Function triggered in OnGetLeagueSummaryQuery");
            }

            if (null == eventGridEvent)
            {
                // This function should not proceed if there is no event data
                if (null != log)
                {
                    log.LogError("Missing event grid trigger data in OnGetLeagueSummaryQuery");
                }
                return;
            }
            else
            {
                if (null != log)
                {
                    log.LogDebug($"Event grid topic: {eventGridEvent.Topic}");
                    log.LogDebug($"Event grid subject: {eventGridEvent.Subject }");
                    log.LogDebug($"Event grid metadata version: {eventGridEvent.MetadataVersion }");
                    log.LogDebug($"Event grid event type: {eventGridEvent.EventType }");
                    log.LogDebug($"Event Grid Data : {eventGridEvent.Data }");
                }
            }
            #endregion

            try
            {
                #region Logging
                if (null != log)
                {
                    log.LogDebug($"Get the query parameters in OnGetLeagueSummaryQuery");
                    if (null == eventGridEvent.Data)
                    {
                        log.LogError($"The query parameter has no values in OnGetLeagueSummaryQuery");
                        return;
                    }
                }
                #endregion

                // Get the query request details out of the event grid data request
                var jsondata = JsonConvert.SerializeObject(eventGridEvent.Data);
                QueryRequest <Get_League_Summary_Definition> queryRequest = null;
                if (!string.IsNullOrWhiteSpace(jsondata))
                {
                    queryRequest = JsonConvert.DeserializeObject <QueryRequest <Get_League_Summary_Definition> >(jsondata);
                }

                if (null != queryRequest)
                {
                    log.LogInformation($"Running query handler with durable functions orchestration");
                    log.LogInformation($"{queryRequest.QueryName} with league {queryRequest.GetParameters().League_Name}");

                    // Using Azure Durable functions to do the query chaining
                    string instanceId = await getLeagueSummaryQueryHandlerOrchestrationClient.StartNewAsync("OnGetLeagueSummaryQueryHandlerOrchestrator", queryRequest);

                    log.LogInformation($"Started OnGetLeagueSummaryQueryHandlerOrchestrator orchestration with ID = '{instanceId}'.");
                }
                else
                {
                    if (null != log)
                    {
                        log.LogError($"Unable to read query request from eventgrid data: {eventGridEvent.Data} Type: {eventGridEvent.Data.GetType()} ");
                    }
                }
            }
            catch (Exception ex)
            {
                if (null != log)
                {
                    log.LogError(ex.ToString(), ex);
                }
                throw;
            }
        }
Example #17
0
        public async Task ExecuteEvent(GameEvent newEvent)
        {
            ProcessingEvents.TryAdd(newEvent.Id, newEvent);

            // the event has failed already
            if (newEvent.Failed)
            {
                goto skip;
            }

            try
            {
                await newEvent.Owner.ExecuteEvent(newEvent);

                // save the event info to the database
                await _changeHistoryService.Add(newEvent);
            }

            catch (TaskCanceledException)
            {
                _logger.LogDebug("Received quit signal for event id {eventId}, so we are aborting early", newEvent.Id);
            }

            catch (OperationCanceledException)
            {
                _logger.LogDebug("Received quit signal for event id {eventId}, so we are aborting early", newEvent.Id);
            }

            // this happens if a plugin requires login
            catch (AuthorizationException ex)
            {
                newEvent.FailReason = EventFailReason.Permission;
                newEvent.Origin.Tell($"{Utilities.CurrentLocalization.LocalizationIndex["COMMAND_NOTAUTHORIZED"]} - {ex.Message}");
            }

            catch (NetworkException ex)
            {
                newEvent.FailReason = EventFailReason.Exception;
                using (LogContext.PushProperty("Server", newEvent.Owner?.ToString()))
                {
                    _logger.LogError(ex, ex.Message);
                }
            }

            catch (ServerException ex)
            {
                newEvent.FailReason = EventFailReason.Exception;
                using (LogContext.PushProperty("Server", newEvent.Owner?.ToString()))
                {
                    _logger.LogError(ex, ex.Message);
                }
            }

            catch (Exception ex)
            {
                newEvent.FailReason = EventFailReason.Exception;
                Console.WriteLine(Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_EXCEPTION"].FormatExt(newEvent.Owner));
                using (LogContext.PushProperty("Server", newEvent.Owner?.ToString()))
                {
                    _logger.LogError(ex, "Unexpected exception");
                }
            }

skip:
            if (newEvent.Type == EventType.Command && newEvent.ImpersonationOrigin == null)
            {
                var correlatedEvents =
                    ProcessingEvents.Values.Where(ev =>
                                                  ev.CorrelationId == newEvent.CorrelationId && ev.Id != newEvent.Id)
                    .ToList();

                await Task.WhenAll(correlatedEvents.Select(ev =>
                                                           ev.WaitAsync(Utilities.DefaultCommandTimeout, CancellationToken)));

                newEvent.Output.AddRange(correlatedEvents.SelectMany(ev => ev.Output));

                foreach (var correlatedEvent in correlatedEvents)
                {
                    ProcessingEvents.Remove(correlatedEvent.Id, out _);
                }
            }

            // we don't want to remove events that are correlated to command
            if (ProcessingEvents.Values.ToList()?.Count(gameEvent => gameEvent.CorrelationId == newEvent.CorrelationId) == 1)
            {
                ProcessingEvents.Remove(newEvent.Id, out _);
            }

            // tell anyone waiting for the output that we're done
            newEvent.Complete();
            OnGameEventExecuted?.Invoke(this, newEvent);
        }
        public static async Task <Get_League_Summary_Definition_Return> OnGetLeagueSummaryQueryHandlerOrchestrator
            ([OrchestrationTrigger] DurableOrchestrationContext context,
            Microsoft.Extensions.Logging.ILogger log)
        {
            // Get the query definition form the context...
            QueryRequest <Get_League_Summary_Definition> queryRequest = context.GetInput <QueryRequest <Get_League_Summary_Definition> >();

            if (null != queryRequest)
            {
                queryRequest.QueryName = "get-league-summary";

                // Log the query request in its own own query event stream
                Guid queryId = await context.CallActivityAsync <Guid>("GetLeagueSummaryCreateQueryRequestActivity", queryRequest);

                if (queryId.Equals(Guid.Empty))
                {
                    #region Logging
                    if (null != log)
                    {
                        // Unable to get the request details from the orchestration
                        log.LogError("OnGetLeagueSummaryQueryHandlerOrchestrator : Unable to create the query event stream");
                    }
                    #endregion

                    return(null);
                }
                else
                {
                    queryRequest.QueryUniqueIdentifier = queryId;
                    // Save the parameters to the event stream
                    ActivityResponse resp = await context.CallActivityAsync <ActivityResponse>("GetLeagueSummaryLogParametersActivity", queryRequest);

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


                    if (null != resp)
                    {
                        context.SetCustomStatus(resp);
                    }

                    // next validate the query
                    bool valid = await context.CallActivityAsync <bool>("GetLeagueSummaryValidateActivity", queryRequest);

                    if (!valid)
                    {
                        if (null != log)
                        {
                            // Could not run the query as the parameters don't make sense
                            log.LogError($"OnGetLeagueSummaryQueryHandlerOrchestrator : Query parameters are invalid {queryId}");
                        }
                        return(null);
                    }
                    else
                    {
                        // Request all the projections needed to answer this query
                        resp = await context.CallActivityAsync <ActivityResponse>("GetLeagueSummaryQueryProjectionRequestActivity", queryRequest);

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

                        // Run all the outstanding projections for this query
                        resp = await context.CallActivityAsync <ActivityResponse>("GetLeagueSummaryQueryProjectionProcessActivity", queryRequest);

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

                        // Output the results
                        resp = await context.CallActivityAsync <ActivityResponse>("GetLeagueSummaryOutputResultsActivity", queryRequest);

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

                        // Get the results for ourselves to return...to do this the query must be complete...
                        return(await context.CallActivityAsync <Get_League_Summary_Definition_Return>("GetLeagueSummaryGetResultsActivity", queryRequest));
                    }
                }
            }
            else
            {
                if (null != log)
                {
                    // Unable to get the request details from the orchestration
                    log.LogError("OnGetLeagueSummaryQueryHandlerOrchestrator : Unable to get the query request from the context");

                    string contextAsString = context.GetInput <string>();
                    if (!string.IsNullOrWhiteSpace(contextAsString))
                    {
                        log.LogError($"Context was {contextAsString} ");
                    }
                    else
                    {
                        log.LogError($"Context was blank ");
                    }
                }

                return(null);
            }
        }
Example #19
0
 public void LogError(string message, params object[] args) => logger.LogError(message, args);
Example #20
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.

            Log = 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);

            var winAudio = new WindowsAudioEndPoint(new AudioEncoder());

            winAudio.RestrictFormats(formats => formats.Codec == AudioCodecsEnum.PCMU);

            // 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, true);

            userAgent.RemotePutOnHold   += () => Log.LogInformation("Remote call party has placed us on hold.");
            userAgent.RemoteTookOffHold += () => Log.LogInformation("Remote call party took us off hold.");
            userAgent.OnIncomingCall    += async(ua, req) =>
            {
                Log.LogInformation($"Incoming call from {req.Header.From.FriendlyDescription()} at {req.RemoteSIPEndPoint}.");
                var uas = userAgent.AcceptCall(req);

                if (userAgent?.IsCallActive == true)
                {
                    // If we are already on a call return a busy response.
                    Log.LogWarning($"Busy response returned for incoming call request.");
                    uas.Reject(SIPResponseStatusCodesEnum.BusyHere, null);
                }
                else
                {
                    var voipSession = new VoIPMediaSession(winAudio.ToMediaEndPoints());
                    voipSession.AcceptRtpFromAny = true;
                    var answerResult = await userAgent.Answer(uas, voipSession);
                }
            };

            // 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)
                            {
                                var voipSession = new VoIPMediaSession(winAudio.ToMediaEndPoints());
                                voipSession.AcceptRtpFromAny = true;
                                bool callResult = await userAgent.Call(DEFAULT_DESTINATION_SIP_URI, SIP_USERNAME, SIP_PASSWORD, voipSession);

                                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.MediaSession as VoIPMediaSession).TakeOffHold();
                                    userAgent.TakeOffHold();
                                }
                                else
                                {
                                    Log.LogInformation("Placing the remote call party on hold.");
                                    await(userAgent.MediaSession as VoIPMediaSession).PutOnHold();
                                    userAgent.PutOnHold();
                                }
                            }
                            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)
                {
                    Log.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...");

            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 #21
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");
                    }

                    await _availability.Start();
                }
            }
            catch (Exception)
            {
                _logger.LogInformation(LoggingEvents.LidarrArtistCache, "Lidarr is not setup, cannot cache Album");
            }
        }
 /// <inheritdoc />
 public void Error(string format, params object[] args) => _logger.LogError(string.Format(format, args));
Example #23
0
        public async Task <ConversionStatus> ConvertPdf2Swf(string inPdfFilePath, ConversionOptions options, Func <ConversionState, ConversionStatus> checkResultAfterConversion = null)
        {
            var status = new ConversionStatus(ConversionState.ConversionFailed);

            try
            {
                var inputPdf = new FileInfo(inPdfFilePath);
                if (!inputPdf.Exists)
                {
                    status.Message = "Input file doesn't exist. " + inPdfFilePath;
                    _logger.LogError(status.Message);
                    return(status);
                }

                //setting defaults
                var workingDir = options.OutputDirectory ?? inputPdf.DirectoryName;
                _logger.LogDebug($"Starting Conversion for file {inPdfFilePath}. Working dir {workingDir}");
                var optimizedFilePath = Path.Combine(workingDir, options.OutputNamingConventions.BuildOptimizedPdfFileName(inputPdf.Name));
                await OptimizePdfForConverter(inPdfFilePath, optimizedFilePath, status);

                if (status.State == ConversionState.OptimizationFailed)
                {
                    return(status);
                }

                int numberOfPages = await GetNumberOfPages(optimizedFilePath);

                if (numberOfPages == 0)
                {
                    var message = $"Critical failure. Can't detect number of pages for pdf: {optimizedFilePath}";
                    _logger.LogCritical(message);
                    return(new ConversionStatus(ConversionState.ConversionFailed, message));
                }

                var swfFile      = Path.Combine(workingDir, options.OutputNamingConventions.BuildSwfFileName(inputPdf.Name));
                var swfPagedFile = Path.Combine(workingDir, options.OutputNamingConventions.BuildPagedSwfFileName(inputPdf.Name));

                if (options.OverwriteExistingSwfs)
                {
                    CleanFilesBeforeConversion(options, swfFile, swfPagedFile, numberOfPages);
                }

                switch (options.HowToConvert)
                {
                case ConversionPath.OnePdf2OneSwf:
                    status = await PerformOnePdf2OneSwfConversion(options, optimizedFilePath, swfFile, checkResultAfterConversion);

                    break;

                case ConversionPath.OnePdf2PerPageSwf:
                    status = await PerformOnePdf2ManyPagesConversion(options, inPdfFilePath, swfPagedFile, numberOfPages, checkResultAfterConversion);

                    break;

                case ConversionPath.Both:
                    status = await PerformOnePdf2OneSwfConversion(options, optimizedFilePath, swfFile);

                    if (status.State == ConversionState.Converted || status.State == ConversionState.OutputExists)
                    {
                        status = await PerformOnePdf2ManyPagesConversion(options, inPdfFilePath, swfPagedFile, numberOfPages, checkResultAfterConversion, status);
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                status.Message = $"Critical failure. Converting error {ex}";
                status.State   = ConversionState.ConversionFailed;
                _logger.LogCritical(status.Message);
                return(status);
            }

            _logger.LogDebug($"Finishing Conversion for file {inPdfFilePath}. Status: {status.State}");

            return(status);
        }
Example #24
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 #25
0
        /// <summary>
        /// Removes the override event from the site model.
        /// </summary>
        public async Task <OverrideEventResponse> ExecuteAsync(OverrideEventRequestArgument arg)
        {
            Log.LogInformation($"START Remove Override Event Executor: Project={arg.ProjectID}, Asset={arg.AssetID}, Date Range={arg.StartUTC}-{arg.EndUTC}");

            var result = new OverrideEventResponse {
                Success = false
            };

            var siteModel = DIContext.Obtain <ISiteModels>().GetSiteModel(arg.ProjectID);

            if (siteModel == null)
            {
                result.Message = $"Failed to locate site model {arg.ProjectID}";
                Log.LogError(result.Message);
                return(result);
            }

            bool changed = false;

            lock (siteModel)
            {
                if (arg.AssetID == Guid.Empty)
                {
                    //If AssetID not provided, remove all override events for project
                    Log.LogDebug($"Removing override events for all assets in project {arg.ProjectID}");
                    foreach (var machine in siteModel.Machines)
                    {
                        if (RemoveOverrideEventsForMachine(siteModel, machine, arg))
                        {
                            changed = true;
                        }
                    }
                }
                else
                {
                    var machine = siteModel.Machines.Locate(arg.AssetID);
                    if (machine == null)
                    {
                        result.Message = $"Failed to locate machine {arg.AssetID}";
                        Log.LogError(result.Message);
                        return(result);
                    }
                    Log.LogDebug($"Removing override events for asset {arg.AssetID}");
                    changed = RemoveOverrideEventsForMachine(siteModel, machine, arg);
                }

                if (changed)
                {
                    Log.LogDebug($"Notifying grid of changes to project {arg.ProjectID}");
                    // Notify the immutable grid listeners that attributes of this site model have changed.
                    var sender = DIContext.Obtain <ISiteModelAttributesChangedEventSender>();
                    sender.ModelAttributesChanged(SiteModelNotificationEventGridMutability.NotifyImmutable,
                                                  siteModel.ID,
                                                  machineTargetValuesChanged: true);
                }
            }

            if (!changed)
            {
                result.Message = "No override event(s) found to remove";
            }

            result.Success = changed;
            Log.LogInformation($"END Remove Override Event Executor: Project={arg.ProjectID}, Asset={arg.AssetID}, Date Range={arg.StartUTC}-{arg.EndUTC}");

            return(result);
        }
        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 #27
0
        public static async Task MainAsync(string[] args)
        {
            if (args.Length > 0 && string.Equals("dbg", args[0], StringComparison.OrdinalIgnoreCase))
            {
                args = args.Skip(1).ToArray();
                Debugger.Launch();
            }

            NgJob job = null;
            ApplicationInsightsConfiguration applicationInsightsConfiguration = null;
            int exitCode = 0;

            try
            {
                // Get arguments
                var arguments = CommandHelpers.GetArguments(args, 1, out var secretInjector);

                // Ensure that SSLv3 is disabled and that Tls v1.2 is enabled.
                ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

                // Determine the job name
                if (args.Length == 0)
                {
                    throw new ArgumentException("Missing job name argument.");
                }

                var jobName                  = args[0];
                var instanceName             = arguments.GetOrDefault(Arguments.InstanceName, jobName);
                var instrumentationKey       = arguments.GetOrDefault <string>(Arguments.InstrumentationKey);
                var heartbeatIntervalSeconds = arguments.GetOrDefault <int>(Arguments.HeartbeatIntervalSeconds);

                applicationInsightsConfiguration = ConfigureApplicationInsights(
                    instrumentationKey,
                    heartbeatIntervalSeconds,
                    jobName,
                    instanceName,
                    out var telemetryClient,
                    out var telemetryGlobalDimensions);

                var loggerFactory = ConfigureLoggerFactory(applicationInsightsConfiguration);

                InitializeServiceProvider(
                    arguments,
                    secretInjector,
                    applicationInsightsConfiguration,
                    telemetryClient,
                    loggerFactory);

                job = NgJobFactory.GetJob(jobName, loggerFactory, telemetryClient, telemetryGlobalDimensions);
                job.SetSecretInjector(secretInjector);

                // This tells Application Insights that, even though a heartbeat is reported,
                // the state of the application is unhealthy when the exitcode is different from zero.
                // The heartbeat metadata is enriched with the job loop exit code.
                applicationInsightsConfiguration.DiagnosticsTelemetryModule?.AddOrSetHeartbeatProperty(
                    HeartbeatProperty_JobLoopExitCode,
                    exitCode.ToString(),
                    isHealthy: exitCode == 0);

                var cancellationTokenSource = new CancellationTokenSource();
                await job.RunAsync(arguments, cancellationTokenSource.Token);

                exitCode = 0;
            }
            catch (ArgumentException ae)
            {
                exitCode = 1;
                _logger?.LogError("A required argument was not found or was malformed/invalid: {Exception}", ae);

                Console.WriteLine(job != null ? job.GetUsage() : NgJob.GetUsageBase());
            }
            catch (KeyNotFoundException knfe)
            {
                exitCode = 1;
                _logger?.LogError("An expected key was not found. One possible cause of this is required argument has not been provided: {Exception}", knfe);

                Console.WriteLine(job != null ? job.GetUsage() : NgJob.GetUsageBase());
            }
            catch (Exception e)
            {
                exitCode = 1;
                _logger?.LogCritical("A critical exception occured in ng.exe! {Exception}", e);
            }

            applicationInsightsConfiguration.DiagnosticsTelemetryModule?.SetHeartbeatProperty(
                HeartbeatProperty_JobLoopExitCode,
                exitCode.ToString(),
                isHealthy: exitCode == 0);

            Trace.Close();
            applicationInsightsConfiguration?.TelemetryConfiguration.TelemetryChannel.Flush();
        }
Example #28
0
        static void Main()
        {
            Console.WriteLine("SIPSorcery client user agent example.");
            Console.WriteLine("Press ctrl-c to 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)));

            // Un/comment this line to see/hide each SIP message sent and received.
            EnableTraceLogs(sipTransport);

            // To keep things a bit simpler this example only supports a single call at a time and the SIP server user agent
            // acts as a singleton
            SIPUserAgent            userAgent = new SIPUserAgent(sipTransport, null);
            CancellationTokenSource rtpCts    = null; // Cancellation token to stop the RTP stream.
            Socket rtpSocket     = null;
            Socket controlSocket = null;

            // Because this is a server user agent the SIP transport must start listening for client user agents.
            sipTransport.SIPTransportRequestReceived += (SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest) =>
            {
                try
                {
                    if (sipRequest.Header.From != null &&
                        sipRequest.Header.From.FromTag != null &&
                        sipRequest.Header.To != null &&
                        sipRequest.Header.To.ToTag != null)
                    {
                        userAgent.InDialogRequestReceivedAsync(sipRequest).Wait();
                    }
                    if (sipRequest.Method == SIPMethodsEnum.INVITE)
                    {
                        SIPSorcery.Sys.Log.Logger.LogInformation($"Incoming call request: {localSIPEndPoint}<-{remoteEndPoint} {sipRequest.URI}.");

                        // Check there's a codec we support in the INVITE offer.
                        var        offerSdp       = SDP.ParseSDPDescription(sipRequest.Body);
                        IPEndPoint dstRtpEndPoint = SDP.GetSDPRTPEndPoint(sipRequest.Body);
                        RTPSession rtpSession     = null;
                        string     audioFile      = null;

                        if (offerSdp.Media.Any(x => x.Media == SDPMediaTypesEnum.audio && x.HasMediaFormat((int)RTPPayloadTypesEnum.PCMU)))
                        {
                            Log.LogDebug($"Using PCMU RTP media type and audio file {AUDIO_FILE_PCMU}.");
                            rtpSession = new RTPSession((int)RTPPayloadTypesEnum.PCMU, null, null);
                            audioFile  = AUDIO_FILE_PCMU;
                        }

                        if (rtpSession == null)
                        {
                            // Didn't get a match on the codecs we support.
                            SIPResponse noMatchingCodecResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.NotAcceptableHere, null);
                            sipTransport.SendResponse(noMatchingCodecResponse);
                        }
                        else
                        {
                            // If there's already a call in progress hang it up. Of course this is not ideal for a real softphone or server but it
                            // means this example can be kept simpler.
                            if (userAgent?.IsAnswered == true)
                            {
                                userAgent?.Hangup();
                            }
                            rtpCts?.Cancel();

                            UASInviteTransaction uasTransaction = sipTransport.CreateUASTransaction(sipRequest, null);
                            if (userAgent.AcceptCall(uasTransaction))
                            {
                                rtpCts = new CancellationTokenSource();

                                // The RTP socket is listening on IPAddress.Any but the IP address placed into the SDP needs to be one the caller can reach.
                                IPAddress rtpAddress = NetServices.GetLocalAddressForRemote(dstRtpEndPoint.Address);
                                // Initialise an RTP session to receive the RTP packets from the remote SIP server.
                                NetServices.CreateRtpSocket(rtpAddress, RTP_PORT_START, RTP_PORT_END, false, out rtpSocket, out controlSocket);

                                var rtpRecvSession = new RTPSession((int)RTPPayloadTypesEnum.PCMU, null, null);
                                var rtpSendSession = new RTPSession((int)RTPPayloadTypesEnum.PCMU, null, null);
                                rtpSendSession.DestinationEndPoint           = dstRtpEndPoint;
                                rtpRecvSession.OnReceiveFromEndPointChanged += (oldEP, newEP) =>
                                {
                                    Log.LogDebug($"RTP destination end point changed from {oldEP} to {newEP}.");
                                    rtpSendSession.DestinationEndPoint = newEP;
                                };

                                Task.Run(() => RecvRtp(rtpSocket, rtpRecvSession, rtpCts));
                                Task.Run(() => SendRtp(rtpSocket, rtpSendSession, rtpCts));

                                userAgent.Answer(GetSDP(rtpSocket.LocalEndPoint as IPEndPoint));
                            }
                        }
                    }
                    else if (sipRequest.Method == SIPMethodsEnum.SUBSCRIBE)
                    {
                        SIPResponse notAllowededResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.MethodNotAllowed, null);
                        sipTransport.SendResponse(notAllowededResponse);
                    }
                    else if (sipRequest.Method == SIPMethodsEnum.OPTIONS || sipRequest.Method == SIPMethodsEnum.REGISTER)
                    {
                        SIPResponse optionsResponse = SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                        sipTransport.SendResponse(optionsResponse);
                    }
                }
                catch (Exception reqExcp)
                {
                    SIPSorcery.Sys.Log.Logger.LogWarning($"Exception handling {sipRequest.Method}. {reqExcp.Message}");
                }
            };

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

            // 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')
                        {
                            // Initiate a transfer.
                            bool transferResult = await userAgent.Transfer(SIPURI.ParseSIPURI(TRANSFER_DESTINATION_SIP_URI), new TimeSpan(0, 0, TRANSFER_TIMEOUT_SECONDS), exitCts.Token);
                            if (transferResult)
                            {
                                // If the transfer was accepted the original call will already have been hungup.
                                userAgent = null;
                                exitCts.Cancel();
                            }
                            else
                            {
                                Log.LogWarning($"Transfer to {TRANSFER_DESTINATION_SIP_URI} failed.");
                            }
                        }
                        else if (keyProps.KeyChar == 'q')
                        {
                            // Quit application.
                            exitCts.Cancel();
                        }
                    }
                }
                catch (Exception excp)
                {
                    Log.LogError($"Exception Key Press listener. {excp.Message}.");
                }
            });

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

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

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

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

                // Give the final 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();
            }
        }
Example #29
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
            {
                logger.LogDebug($"RunCommand {options.Destination}");

                (var dstEp, var dstUri) = ParseDestination(options.Destination);

                logger.LogDebug($"Destination IP end point {dstEp} and SIP URI {dstUri}");

                int  sendCount = 0;
                bool success   = true;

                do
                {
                    IPAddress  localAddress = (dstEp.Address.AddressFamily == AddressFamily.InterNetworkV6) ? IPAddress.IPv6Any : IPAddress.Any;
                    SIPChannel sipChannel   = null;

                    switch (dstEp.Protocol)
                    {
                    case SIPProtocolsEnum.tcp:
                        sipChannel = new SIPTCPChannel(new IPEndPoint(localAddress, DEFAULT_SIP_CLIENT_PORT));
                        (sipChannel as SIPTCPChannel).DisableLocalTCPSocketsCheck = true;     // Allow sends to listeners on this host.
                        break;

                    case SIPProtocolsEnum.tls:
                        var certificate = new X509Certificate2(@"localhost.pfx", "");
                        sipChannel = new SIPTLSChannel(certificate, new IPEndPoint(localAddress, DEFAULT_SIPS_CLIENT_PORT));
                        break;

                    case SIPProtocolsEnum.udp:
                        sipChannel = new SIPUDPChannel(new IPEndPoint(localAddress, DEFAULT_SIP_CLIENT_PORT));
                        break;

                    case SIPProtocolsEnum.ws:
                        sipChannel = new SIPClientWebSocketChannel();
                        break;

                    case SIPProtocolsEnum.wss:
                        sipChannel = new SIPClientWebSocketChannel();
                        break;

                    default:
                        throw new ApplicationException($"Don't know how to create SIP channel for transport {dstEp.Protocol}.");
                    }

                    SIPTransport sipTransport = new SIPTransport();
                    sipTransport.AddSIPChannel(sipChannel);

                    if (sendCount > 0 && options.Period > 0)
                    {
                        await Task.Delay(options.Period * 1000);
                    }

                    sendCount++;

                    DateTime sendTime = DateTime.Now;
                    var      sendTask = SendOptionsTaskAsync(sipTransport, dstUri);
                    var      result   = await Task.WhenAny(sendTask, Task.Delay(options.Timeout * 1000));

                    TimeSpan duration = DateTime.Now.Subtract(sendTime);

                    if (!sendTask.IsCompleted)
                    {
                        logger.LogWarning($"=> Request to {dstEp} did not get a response on send {sendCount} of {options.Count} after {duration.TotalMilliseconds.ToString("0")}ms.");
                        success = false;
                    }
                    else if (!sendTask.Result)
                    {
                        logger.LogWarning($"=> Request to {dstEp} did not get the expected response on request {sendCount} of {options.Count} after {duration.TotalMilliseconds.ToString("0")}ms.");
                        success = false;
                    }
                    else
                    {
                        logger.LogInformation($"=> Got correct response on send {sendCount} of {options.Count} in {duration.TotalMilliseconds.ToString("0")}ms.");
                    }

                    logger.LogDebug("Shutting down the SIP transport...");
                    sipTransport.Shutdown();

                    if (success == false)
                    {
                        break;
                    }
                }while (sendCount < options.Count);

                DNSManager.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 {((success) ? "successfully" : "with failure")}.");
            }
            catch (Exception excp)
            {
                logger.LogError($"Exception RunCommand. {excp.Message}");
            }
        }
Example #30
0
        public async Task <bool> VerifyAsync(string file, StringBuilder buffer)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }


            var trustProviders = new ISignatureVerificationProvider[]
            {
                new IntegrityVerificationProvider(),
                new SignatureTrustAndValidityVerificationProvider()
            };
            var verifier = new PackageSignatureVerifier(trustProviders);

            var allPackagesVerified = true;

            try
            {
                var result           = 0;
                var packagesToVerify = LocalFolderUtility.ResolvePackageFromPath(file);

                foreach (var packageFile in packagesToVerify)
                {
                    using var package = new PackageArchiveReader(packageFile);
                    var verificationResult = await verifier.VerifySignaturesAsync(package, SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy(), CancellationToken.None);

                    if (verificationResult.IsValid)
                    {
                        allPackagesVerified = true;
                    }
                    else
                    {
                        var logMessages = verificationResult.Results.SelectMany(p => p.Issues).Select(p => p.AsRestoreLogMessage()).ToList();
                        foreach (var msg in logMessages)
                        {
                            buffer.AppendLine(msg.Message);
                        }
                        if (logMessages.Any(m => m.Level >= NuGet.Common.LogLevel.Warning))
                        {
                            var errors   = logMessages.Where(m => m.Level == NuGet.Common.LogLevel.Error).Count();
                            var warnings = logMessages.Where(m => m.Level == NuGet.Common.LogLevel.Warning).Count();

                            buffer.AppendLine($"Finished with {errors} errors and {warnings} warnings.");

                            result = errors;
                        }
                        allPackagesVerified = false;
                    }
                }
            }
            catch (Exception e)
            {
                logger.LogError(e, e.Message);
                return(false);
            }

            return(allPackagesVerified);
        }
Example #31
0
        public static async Task <(bool, AddonData)> ProccessAddonData(HttpClient httpClient, AddonData addonData)
        {
            if (!string.IsNullOrEmpty(addonData.FolderName))
            {
                return(true, addonData);
            }

            bool   found   = false;
            string zipFile = string.Empty;

            try
            {
                zipFile = await Update.DLWithHttpProgress(httpClient, addonData.Downloads[0]);
            }
            catch (Exception e)
            {
                logger.LogError(e, "Something went wrong in " + nameof(ProccessAddonData) + " for " + addonData.ProjectName);
                return(found, addonData);
            }

            if (string.IsNullOrEmpty(zipFile) || !File.Exists(zipFile))
            {
                logger.LogError("No zipFile found for " + addonData.ProjectName);
                return(found, addonData);
            }

            FileInfo fileInfo = new FileInfo(zipFile);

            addonData.Size = fileInfo.Length;

            try
            {
                (int entries, List <string> folders) = Update.UpdateAddon2(zipFile);
                addonData.Files = entries;

                if (folders.Count == 1)
                {
                    addonData.FolderName = folders[0];
                    found = true;
                }
                else
                {
                    foreach (string folder in folders)
                    {
                        string lowered = folder.ToLower();
                        if (PROJECT_URLS.TryGetValue(lowered, out string mapped))
                        {
                            if (mapped.Equals(addonData.ProjectName))
                            {
                                found = true;
                                addonData.FolderName = folder;
                                break;
                            }
                        }
                    }
                    if (!found)
                    {
                        HashSet <string> urlNames = new HashSet <string>()
                        {
                            addonData.ProjectName,
                            addonData.ProjectName.Replace("-", ""),
                            addonData.ProjectName.Replace("_", ""),
                            addonData.ProjectName.Replace("_", "-"),
                            addonData.ProjectName.Replace("-", "_")
                        };
                        foreach (string folder in folders)
                        {
                            string lowered = folder.ToLower();

                            HashSet <string> folderNames = new HashSet <string>()
                            {
                                lowered,
                                lowered.Replace(" ", "-"),
                                lowered.Replace("_", "-")
                            };

                            if (folderNames.Contains(addonData.ProjectName))
                            {
                                found = true;
                                addonData.FolderName = folder;

                                break;
                            }

                            if (urlNames.Contains(lowered))
                            {
                                found = true;
                                addonData.FolderName = folder;

                                break;
                            }
                        }
                    }
                }

                addonData.SubFolders = folders.Where(f => !f.Equals(addonData.FolderName)).ToHashSet();

                if (found)
                {
                    File.Delete(zipFile);
                    Directory.Delete(zipFile.Replace(".zip", ""), true);
                }

                return(found, addonData);
            }
            catch (Exception e)
            {
                logger.LogError(e, "Someting went wrong for " + addonData.ProjectName);
                return(found, addonData);
            }
        }
Example #32
0
        private static async Task WebSocketMessageReceived(WebSocketContext context, RTCPeerConnection pc, string message)
        {
            try
            {
                if (pc.localDescription == null)
                {
                    //logger.LogDebug("Offer SDP: " + message);
                    logger.LogDebug("Offer SDP received.");

                    // Add local media tracks depending on what was offered. Also add local tracks with the same media ID as
                    // the remote tracks so that the media announcement in the SDP answer are in the same order.
                    SDP remoteSdp = SDP.ParseSDPDescription(message);

                    foreach (var ann in remoteSdp.Media)
                    {
                        var capbilities        = FilterCodecs(ann.Media, ann.MediaFormats);
                        MediaStreamTrack track = new MediaStreamTrack(ann.Media, false, capbilities, MediaStreamStatusEnum.RecvOnly);
                        pc.addTrack(track);
                    }

                    pc.setRemoteDescription(new RTCSessionDescriptionInit {
                        sdp = message, type = RTCSdpType.offer
                    });

                    var answer = pc.createAnswer(null);
                    await pc.setLocalDescription(answer);

                    Console.WriteLine(answer.sdp);

                    context.WebSocket.Send(answer.sdp);
                }
                else if (pc.remoteDescription == null)
                {
                    logger.LogDebug("Answer SDP: " + message);
                    var result = pc.setRemoteDescription(new RTCSessionDescriptionInit {
                        sdp = message, type = RTCSdpType.answer
                    });
                    if (result != SetDescriptionResultEnum.OK)
                    {
                        logger.LogWarning($"Failed to set remote description {result}.");
                    }
                }
                else
                {
                    logger.LogDebug("ICE Candidate: " + message);

                    if (string.IsNullOrWhiteSpace(message) || message.Trim().ToLower() == SDP.END_ICE_CANDIDATES_ATTRIBUTE)
                    {
                        logger.LogDebug("End of candidates message received.");
                    }
                    else
                    {
                        var candInit = Newtonsoft.Json.JsonConvert.DeserializeObject <RTCIceCandidateInit>(message);
                        pc.addIceCandidate(candInit);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception WebSocketMessageReceived. " + excp.Message);
            }
        }
Example #33
0
        public static async Task MainAsync(string[] args)
        {
            if (args.Length > 0 && string.Equals("dbg", args[0], StringComparison.OrdinalIgnoreCase))
            {
                args = args.Skip(1).ToArray();
                Debugger.Launch();
            }

            NgJob job = null;

            try
            {
                // Get arguments
                var arguments = CommandHelpers.GetArguments(args, 1);

                // Ensure that SSLv3 is disabled and that Tls v1.2 is enabled.
                ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

                // Determine the job name
                if (args.Length == 0)
                {
                    throw new ArgumentException("Missing job name argument.");
                }

                var jobName = args[0];
                TelemetryConfiguration.Active.TelemetryInitializers.Add(new JobNameTelemetryInitializer(jobName));

                // Configure ApplicationInsights
                ApplicationInsights.Initialize(arguments.GetOrDefault <string>(Arguments.InstrumentationKey));

                // Create an ILoggerFactory
                var loggerConfiguration = LoggingSetup.CreateDefaultLoggerConfiguration(withConsoleLogger: true);
                loggerConfiguration.WriteTo.File("Log.txt", retainedFileCountLimit: 3, fileSizeLimitBytes: 1000000, rollOnFileSizeLimit: true);

                var loggerFactory = LoggingSetup.CreateLoggerFactory(loggerConfiguration, LogEventLevel.Debug);

                // Create a logger that is scoped to this class (only)
                _logger = loggerFactory.CreateLogger <Program>();

                var cancellationTokenSource = new CancellationTokenSource();

                // Create an ITelemetryService
                var telemetryService = new TelemetryService(new TelemetryClient());

                // Allow jobs to set global custom dimensions
                TelemetryConfiguration.Active.TelemetryInitializers.Add(new JobPropertiesTelemetryInitializer(telemetryService));

                job = NgJobFactory.GetJob(jobName, telemetryService, loggerFactory);
                await job.RunAsync(arguments, cancellationTokenSource.Token);
            }
            catch (ArgumentException ae)
            {
                _logger?.LogError("A required argument was not found or was malformed/invalid: {Exception}", ae);

                Console.WriteLine(job != null ? job.GetUsage() : NgJob.GetUsageBase());
            }
            catch (Exception e)
            {
                _logger?.LogCritical("A critical exception occured in ng.exe! {Exception}", e);
            }

            Trace.Close();
            TelemetryConfiguration.Active.TelemetryChannel.Flush();
        }
Example #34
0
        private static async Task WebSocketMessageReceived(WebSocketContext context, RTCPeerConnection pc, string message)
        {
            try
            {
                if (pc.localDescription == null)
                {
                    //logger.LogDebug("Offer SDP: " + message);
                    logger.LogDebug("Offer SDP received.");

                    // Add local media tracks depending on what was offered. Also add local tracks with the same media ID as
                    // the remote tracks so that the media announcement in the SDP answer are in the same order.
                    var offerInit = JsonConvert.DeserializeObject <RTCSessionDescriptionInit>(message, new Newtonsoft.Json.Converters.StringEnumConverter());

                    logger.LogDebug(SDP.ParseSDPDescription(offerInit.sdp).ToString());

                    var res = pc.setRemoteDescription(offerInit);

                    if (res != SetDescriptionResultEnum.OK)
                    {
                        // No point continuing. Something will need to change and then try again.
                        pc.Close("failed to set remote sdp");
                    }
                    else
                    {
                        var answer = pc.createAnswer(_answerOptions);
                        await pc.setLocalDescription(answer);

                        context.WebSocket.Send(JsonConvert.SerializeObject(answer, new Newtonsoft.Json.Converters.StringEnumConverter()));
                    }
                }
                else if (pc.remoteDescription == null)
                {
                    logger.LogDebug("Answer SDP received:");

                    var answerInit = JsonConvert.DeserializeObject <RTCSessionDescriptionInit>(message, new Newtonsoft.Json.Converters.StringEnumConverter());

                    logger.LogDebug(SDP.ParseSDPDescription(answerInit.sdp).ToString());

                    var res = pc.setRemoteDescription(answerInit);
                    if (res != SetDescriptionResultEnum.OK)
                    {
                        // No point continuing. Something will need to change and then try again.
                        pc.Close("failed to set remote sdp");
                    }
                }
                else
                {
                    logger.LogDebug("ICE Candidate: " + message);

                    if (string.IsNullOrWhiteSpace(message) || message.Trim().ToLower() == SDP.END_ICE_CANDIDATES_ATTRIBUTE)
                    {
                        logger.LogDebug("End of candidates message received.");
                    }
                    else
                    {
                        var candInit = Newtonsoft.Json.JsonConvert.DeserializeObject <RTCIceCandidateInit>(message);

                        if (_acceptIceTypes.Count > 0 && !_acceptIceTypes.Any(x => x == RTCIceCandidate.Parse(candInit.candidate).type))
                        {
                            logger.LogDebug($"Ignoring remote ICE candidate as type not in accept list.");
                        }
                        else
                        {
                            pc.addIceCandidate(candInit);
                        }
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception WebSocketMessageReceived. " + excp.Message);
            }
        }