Пример #1
0
        public ConfigFile Load()
        {
            ConfigFile ConfigContent = new ConfigFile();

            _loggerService.Debug("get configuration file...");

            string filePath = Environment.GetEnvironmentVariable("RAWCMSCONFIG", EnvironmentVariableTarget.Process);

            if (string.IsNullOrEmpty(filePath))
            {
                return(null);
            }

            _loggerService.Debug($"Config file: {filePath}");

            try
            {   // Open the text file using a stream reader.
                using (StreamReader sr = new StreamReader(filePath))
                {
                    string data = sr.ReadToEnd();
                    ConfigContent = new ConfigFile(data);

                    _loggerService.Debug($"config loaded.");
                }
            }
            catch (Exception e)
            {
                _loggerService.Error("The file could not be read:", e);
            }
            return(ConfigContent);
        }
Пример #2
0
        public List <string> GetRows(string documentPath, ICollection <string> stopWords = null, string[] skipWords = null)
        {
            try
            {
                _logger.Info("=== ENTERING PDF DOCUMENT EXTRACTOR ===");
                _logger.Debug("Retrieving document stored at : " + documentPath);

                using (PdfReader reader = new PdfReader(documentPath))
                {
                    _logger.Info(documentPath + " successfully retrieved.");

                    _logger.Debug("Preparing to read and process PDF content of " + documentPath);
                    ITextExtractionStrategy strategy    = new LocationTextExtractionStrategy();
                    List <string>           parsedLines = new List <string>();

                    _logger.Info("PDF stream successfully read: " + documentPath);

                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        string page = PdfTextExtractor.GetTextFromPage(reader, i, strategy);

                        if (skipWords != null && skipWords.Any(s => page.Contains(s)))
                        {
                            continue;
                        }

                        parsedLines.AddRange(page.Split('\n'));
                    }

                    if (_patternMatcher == null)
                    {
                        _patternMatcher = new NullPatternMatcher();
                    }

                    if (stopWords != null)
                    {
                        parsedLines = parsedLines.TakeWhile(line => !stopWords.Any(line.Contains))
                                      .Union(_patternMatcher.GetMatchedRows(parsedLines))
                                      .ToList();
                    }

                    _logger.Info(documentPath + " PDF stream successfully processed");
                    _logger.Info(parsedLines.Count + " rows processed and retrieved.");

                    return(parsedLines);
                }
            }
            catch (ArgumentOutOfRangeException ex)
            {
                _logger.Error("ArgumentOutOfRangeException occurred: " + ex);
            }
            catch (Exception exception)
            {
                _logger.Error("Unknown exception occurred: " + exception);
            }

            return(new List <string>());
        }
Пример #3
0
        private async Task <bool> TryConnectAsync()
        {
            AppConfiguration appConfiguration = configurationService.GetConfiguration <AppConfiguration>();

            IMqttClientOptions options = new MqttClientOptionsBuilder()
                                         .WithCleanSession()
                                         .WithClientId("主客户端 ID: 001")
                                         .WithCredentials("AD*米妮*斯托蕾塔", "^P@$$W0&D$")
                                         .WithTcpServer("localhost", appConfiguration.ListenPort)
                                         .Build();

            client.UseConnectedHandler(e => { logger.Debug("Successfully connected to: {0}", e.AuthenticateResult.ResultCode); })
            .UseDisconnectedHandler(async e =>
            {
                logger.Warn("### DISCONNECTED FROM SERVER ###");
                await Task.Delay(2000);

                try
                {
                    if (CancellationTokenSource.IsCancellationRequested)
                    {
                        logger.Debug("### CancellationRequested ###");
                        return;
                    }
                    await client.ConnectAsync(options, CancellationTokenSource.Token);
                }
                catch
                {
                    logger.Error("### RECONNECTING FAILED ###");
                }
            })
            .UseApplicationMessageReceivedHandler(e =>
            {
#if DEBUG
                string message =
                    "\r\n### RECEIVED APPLICATION MESSAGE ###\r\n" +
                    $"+ Topic = {e.ApplicationMessage.Topic}\r\n" +
                    $"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}\r\n" +
                    $"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}\r\n" +
                    $"+ Retain = {e.ApplicationMessage.Retain}\r\n";

                System.Diagnostics.Debug.WriteLine(message);
#endif
                ExecuteMessage(e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
            });

            try
            {
                await client.ConnectAsync(options, CancellationTokenSource.Token);

                return(true);
            }
            catch (Exception ex)
            {
                logger.Error("Could not connect to server: {0}", ex.Message);
                return(false);
            }
        }
Пример #4
0
        public void PreExposureDetected(ExposureConfiguration exposureConfiguration, long enVersion)
        {
            _loggerService.Debug("PreExposureDetected");

            if (exposureConfiguration == null)
            {
                _loggerService.Error("PreExposureDetected is called but exposureConfiguration is null.");
            }
        }
        public async Task <ActionResult <Entity.PaySlip> > CreatePaySlipAsync(Employee employee)
        {
            _loggerService.Info($"Begin Create Pay Slip Async.");
            _loggerService.Debug($"Begin Create Pay Slip Async. payload: {employee}");

            var paySlip = await _paySlipService.CreatePaySlipAsync(employee);

            _loggerService.Info($"End Create Pay Slip Async.");
            _loggerService.Debug($"End Create Pay Slip Async. payload: {paySlip}");

            return(paySlip);
        }
Пример #6
0
 public void Debug(string format, params object[] param)
 {
     if ((_enabled & LoggerEventTypes.Debug) > 0)
     {
         _logger.Debug(format, param);
     }
 }
Пример #7
0
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            switch (logLevel)
            {
            case LogLevel.Information:
                _quickloggerInstance.Info(_categoryName, $"{_categoryName}[{eventId.Id}] - {formatter(state, exception)}");
                break;

            case LogLevel.Error:
                _quickloggerInstance.Error(_categoryName, $"{_categoryName}[{eventId.Id}] - {formatter(state, exception)}");
                break;

            case LogLevel.Warning:
                _quickloggerInstance.Warning(_categoryName, $"{_categoryName}[{eventId.Id}] -  {formatter(state, exception)}");
                break;

            case LogLevel.Critical:
                _quickloggerInstance.Critical(_categoryName, $"{_categoryName}[{eventId.Id}] - {formatter(state, exception)}");
                break;

            case LogLevel.Debug:
                _quickloggerInstance.Debug(_categoryName, $"{_categoryName}[{eventId.Id}] - {formatter(state, exception)}");
                break;

            case LogLevel.Trace:
                _quickloggerInstance.Trace(_categoryName, $"{_categoryName}[{eventId.Id}] - {formatter(state, exception)}");
                break;
            }
        }
Пример #8
0
        public async Task <bool?> MoveImagesAsync(string serverIp, int serverPort, string serverAET, string localAET, string destAET, string studyInstanceUid, string seriesInstanceUid = null)
        {
            bool?success = null;

            DicomCMoveRequest request = string.IsNullOrEmpty(seriesInstanceUid) ?
                                        RequestFactory.CreateCMoveByStudyUID(destAET, studyInstanceUid) :
                                        RequestFactory.CreateCMoveBySeriesUID(destAET, studyInstanceUid, seriesInstanceUid);

            request.OnResponseReceived += (req, res) =>
            {
                if (res.Status.State == DicomState.Pending)
                {
                    logger.Info("Sending is in progress. please wait: " + res.Remaining.ToString());
                }
                else if (res.Status.State == DicomState.Success)
                {
                    logger.Info("Sending successfully finished.");
                    success = true;
                }
                else if (res.Status.State == DicomState.Failure)
                {
                    logger.Info("Error sending datasets: " + res.Status.Description);
                    success = false;
                }
                logger.Debug("C-MOVE response status. " + res.Status.Description);
            };

            DicomClient client = new DicomClient(serverIp, serverPort, false, localAET, serverAET);
            await client.AddRequestAsync(request);

            await client.SendAsync();

            return(success);
        }
Пример #9
0
        // POST /api/Register - Register User
        public async Task <bool> PostRegisterUserAsync()
        {
#if TEST_BACKTASK
            loggerService.StartMethod();
            loggerService.Debug(" skip /register ");
            loggerService.EndMethod();
            return(true);
#endif

            loggerService.StartMethod();
            try
            {
                string url     = AppSettings.Instance.ApiUrlBase + "/register";
                var    content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
                var    result  = await PostAsync(url, content);

                if (result != null)
                {
                    loggerService.EndMethod();
                    return(true);
                }
            }
            catch (HttpRequestException ex)
            {
                loggerService.Exception("Failed to register user.", ex);
            }

            loggerService.EndMethod();
            return(false);
        }
Пример #10
0
 public void Debug(string message)
 {
     if (_service != null)
     {
         var detail = GetDebugDetail(message);
         _service.Debug(detail);
     }
 }
Пример #11
0
        public static void Debug(string message)
        {
            if (_loggerService == null)
            {
                return;
            }

            _loggerService.Debug(message);
        }
Пример #12
0
        public string GetToken(LoginOptions opts)
        {
            //string baseUrl = ClientConfig.GetValue<string>("BaseUrl");

            string url = $"{opts.ServerUrl}/connect/token";

            _loggerService.Debug($"Server url: {url}");

            if (!_rawCmsService.Ping(url))
            {
                _loggerService.Error("host not found.");
                return(string.Empty);
            }

            //create RestSharp client and POST request object
            RestClient  client  = new RestClient(url);
            RestRequest request = new RestRequest(Method.POST);

            //add GetToken() API method parameters
            request.Parameters.Clear();
            request.AddParameter("grant_type", "password");

            request.AddParameter("username", opts.Username);
            request.AddParameter("password", opts.Password);

            request.AddParameter("client_id", opts.ClientId);
            request.AddParameter("client_secret", opts.ClientSecret);
            request.AddParameter("scoope", "openid");

            //make the API request and get the response
            IRestResponse response = client.Execute(request);
            TokenResponse res      = Newtonsoft.Json.JsonConvert.DeserializeObject <TokenResponse>(response.Content);

            if (response.IsSuccessful)
            {
                _loggerService.Debug("Success response token");
                return(res.access_token);
            }
            else
            {
                _loggerService.Warn("Unable to get valid token.");
                throw new ExceptionToken(res.error, res.error_description);
            }
        }
Пример #13
0
        /// <summary>
        /// 参考
        /// https://github.com/fo-dicom/fo-dicom-samples/blob/master/Desktop/Worklist%20SCU/Program.cs
        /// </summary>
        /// <param name="serverIp">Remote IP</param>
        /// <param name="serverPort">Remote Port</param>
        /// <param name="serverAET">Remote AET</param>
        /// <param name="localAET">Local AET</param>
        /// <param name="modality">Modality</param>
        /// <returns>Dataset</returns>
        public async Task <List <DicomDataset> > GetAllItemsFromWorklistAsync(string serverIp, int serverPort, string serverAET, string localAET, string modality = null)
        {
            List <DicomDataset> worklistItems = new List <DicomDataset>();

            DicomCFindRequest worklistRequest = RequestFactory.CreateWorklistQuery(null, null, localAET, null, modality
                                                                                   //, new DicomDateRange(DateTime.Today, DateTime.Today.AddHours(23).AddMinutes(59).AddSeconds(59))  // 时间限制:当天 00:00:00 ~ 23:59:59
                                                                                   );

            worklistRequest.OnResponseReceived += (request, response) =>
            {
                if (!response.HasDataset)
                {
                    if (response.Status == DicomStatus.Success)
                    {
                        Logger.Debug("Worklist response END.");
                    }
                    else
                    {
                        Logger.Debug("Worklist response has [NO DATASET].");
                    }

                    return;
                }

                if (response.Status != DicomStatus.Success &&
                    response.Status != DicomStatus.Pending &&
                    response.Status != DicomStatus.QueryRetrieveOptionalKeysNotSupported)
                {
                    Logger.Error("Worklist response error - [{0}]", response.Status);
                    return;
                }

                worklistItems.Add(response.Dataset);
            };

            DicomClient client = new DicomClient(serverIp, serverPort, false, localAET, serverAET);

            await client.AddRequestAsync(worklistRequest);

            await client.SendAsync();

            return(worklistItems);
        }
Пример #14
0
        public async Task <(HttpStatusCode, IList <DiagnosisKeyEntry>)> GetDiagnosisKeysListAsync(string url, CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await _httpClient.GetAsync(url, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();

                _loggerService.Debug(content);

                return(response.StatusCode, JsonConvert.DeserializeObject <List <DiagnosisKeyEntry> >(content));
            }
            else
            {
                _loggerService.Debug($"GetDiagnosisKeysListAsync {response.StatusCode}");
            }

            return(response.StatusCode, new List <DiagnosisKeyEntry>());
        }
Пример #15
0
        private async Task <ExposureDataResponse?> UploadExposureDataAsync(
            ExposureRequest exposureRequest,
            string exposureDataCollectServerEndpoint
            )
        {
            _loggerService.StartMethod();
            _loggerService.Debug($"exposureDataCollectServerEndpoint: {exposureDataCollectServerEndpoint}");

            try
            {
                var requestJson = exposureRequest.ToJsonString();

                _loggerService.Info(requestJson);

                var httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json");

                Uri uri = new Uri(exposureDataCollectServerEndpoint);

                HttpResponseMessage response = await _httpClient.PutAsync(uri, httpContent);

                if (response.IsSuccessStatusCode)
                {
                    var responseJson = await response.Content.ReadAsStringAsync();

                    _loggerService.Debug($"response {responseJson}");

                    return(JsonConvert.DeserializeObject <ExposureDataResponse>(responseJson));
                }
                else
                {
                    _loggerService.Info($"UploadExposureDataAsync {response.StatusCode}");
                    return(null);
                }
            }
            finally
            {
                _loggerService.EndMethod();
            }
        }
Пример #16
0
        public SimpleMqttService([Inject(Key = "filelogger")] ILoggerService loggerService)
        {
            logger = loggerService;
            users  = new Dictionary <string, string>()
            {
                { "AD*米妮*斯托蕾塔", "^P@$$W0&D$" }
            };

            server = new MqttFactory().CreateMqttServer();
            server.UseApplicationMessageReceivedHandler(e =>
            {
                string message =
                    "\r\n### RECEIVED APPLICATION MESSAGE ###\r\n" +
                    $"+ Topic = {e.ApplicationMessage.Topic}\r\n" +
                    $"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}\r\n" +
                    $"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}\r\n" +
                    $"+ Retain = {e.ApplicationMessage.Retain}\r\n";

                logger.Info(message);
            }).UseClientConnectedHandler(e => { logger.Debug($"[{e.ClientId}] Connected."); })
            .UseClientDisconnectedHandler(e => { logger.Debug($"[{e.ClientId}] Disconnected."); });
        }
Пример #17
0
        public override void Schedule()
        {
            _loggerService.StartMethod();

            var result = BGTaskScheduler.Shared.Register(BGTASK_IDENTIFIER, null, task =>
            {
                _loggerService.Info("Background task has been started.");

                ScheduleBgTask();

                var cancellationTokenSource = new CancellationTokenSource();
                task.ExpirationHandler      = cancellationTokenSource.Cancel;

                _ = Task.Run(async() =>
                {
                    try
                    {
                        await ExposureDetectionAsync(cancellationTokenSource);
                        task.SetTaskCompleted(true);
                    }
                    catch (OperationCanceledException exception)
                    {
                        _loggerService.Exception($"Background task canceled.", exception);
                        task.SetTaskCompleted(false);
                    }
                    catch (Exception exception)
                    {
                        _loggerService.Exception($"Exception", exception);
                        task.SetTaskCompleted(false);
                    }
                    finally
                    {
                        cancellationTokenSource.Dispose();
                    }
                }, cancellationTokenSource.Token);
            });

            if (result)
            {
                _loggerService.Debug("BGTaskScheduler.Shared.Register succeeded.");
            }
            else
            {
                _loggerService.Info("BGTaskScheduler.Shared.Register failed.");
            }

            ScheduleBgTask();

            _loggerService.EndMethod();
        }
Пример #18
0
        public IRestResponse GetData(ListRequest req)
        {
            string url = $"{req.Url}/api/CRUD/{req.Collection}";

            _loggerService.Debug($"Service url: {url}");

            RestClient  client  = new RestClient(url);
            RestRequest request = new RestRequest(Method.GET)
            {
                //request headers
                RequestFormat = DataFormat.Json
            };

            request.AddHeader("Content-Type", "application/json");

            //add parameters and token to request
            request.Parameters.Clear();
            if (!string.IsNullOrEmpty(req.RawQuery))
            {
                request.AddParameter("rawQuery", req.RawQuery);
            }
            request.AddParameter("pageNumber", req.PageNumber);
            request.AddParameter("pageSize", req.PageSize);

            //request.AddParameter("Authorization", "Bearer " + req.Token, ParameterType.HttpHeader);

            // log request
            var fullUrl = client.BuildUri(request);

            _loggerService.Debug($"request URI: {fullUrl}");

            //make the API request and get a response
            IRestResponse response = client.Execute(request);

            return(response);
        }
Пример #19
0
        public TDbContext Get <TDbContext>(ILoggerService loggerService = null) where TDbContext : DbContext, IContext, new()
        {
            if (_dbContext == null || _dbContextType != typeof(TDbContext) || loggerService != null)
            {
                var db = new TDbContext();
                if (loggerService != null)
                {
                    db.Database.Log = (string message) => loggerService.Debug(message);
                }

                return(db);
            }

            return((TDbContext)_dbContext);
        }
Пример #20
0
        public async Task <bool> StartAsync(int port)
        {
            if (server.IsStarted)
            {
                return(true);
            }

            Port = port;
            IMqttServerOptions options = new MqttServerOptionsBuilder()
                                         .WithApplicationMessageInterceptor(cv => { cv.AcceptPublish = true; })
                                         .WithConnectionValidator(cv =>
            {
                if (cv.ClientId.Length < 10)
                {
                    cv.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                    return;
                }

                if (!users.ContainsKey(cv.Username) ||
                    users[cv.Username] != cv.Password)
                {
                    cv.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    return;
                }

                cv.ReasonCode = MqttConnectReasonCode.Success;
            })
                                         .WithEncryptionSslProtocol(System.Security.Authentication.SslProtocols.Tls12)
                                         .WithDefaultEndpointPort(port)
                                         .WithSubscriptionInterceptor(cv => { cv.AcceptSubscription = true; })
                                         .Build();

            try
            {
                await server.StartAsync(options);

                logger.Debug("Mqtt server is running at: {0}", port);
                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(false);
            }
        }
        protected override void OnBefore(IInvocation invocation)
        {
            var logParameters = invocation.Method.GetParameters()
                                .Select((t, i) => new LogParameter
            {
                Name  = t.Name,
                Type  = t.ParameterType.Name,
                Value = invocation.Arguments[i]
            }).ToList();

            var logDetail = new LogDetail
            {
                FullName      = invocation.Method.DeclaringType == null ? null : invocation.Method.DeclaringType.Name,
                MethodName    = invocation.Method.Name,
                LogParameters = logParameters
            };

            _loggerService.Debug(logDetail);
        }
Пример #22
0
        public void Run()
        {
            Commands.Add(new Get());
            Commands.Add(new Send());
            Commands.Add(new GetChat());
            Commands.Add(new GetInfo());
            Commands.Add(new LoginCommand());
            Commands.Add(new RegisterCommand());
            Commands.Add(new ErrorCommand());

            IsRun = true;
            var config = _container.Resolve <ConfigService>().GetConfig();

            if (config is null)
            {
                _logger.Warning("Остановка сервера....");
                IsRun = false;
                return;
            }
            _logger.Warning($"Запуск сервера по адресу {config.Connect.Ip}:{config.Connect.Port}...");
            _logger.Debug("Привязка ip и port...");
            try
            {
                var ipAddress      = IPAddress.Parse(config.Connect.Ip);
                var listener       = new TcpListener(ipAddress, config.Connect.Port);
                var connectService = _container.Resolve <ConnectService>();
                Task.Run(() =>
                {
                    connectService.StartCheckConnect(listener);
                });

                Task.Run((() =>
                {
                    _checker.StartService();
                }));
            }
            catch (Exception e)
            {
                IsRun = false;
                _logger.Error("Произошла ошибка при привязке ip и port", e);
                return;
            }
        }
Пример #23
0
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            string message = formatter != null?formatter(state, exception) : state.ToString();

            if (string.IsNullOrWhiteSpace(message) && exception != null)
            {
                message = exception.Message;
            }

            switch (logLevel)
            {
            case LogLevel.Error:
                _quickloggerInstance.Error(_categoryName, $"{_categoryName}[{eventId.Id}] - {message}");
                break;

            case LogLevel.Warning:
                _quickloggerInstance.Warning(_categoryName, $"{_categoryName}[{eventId.Id}] - {message}");
                break;

            case LogLevel.Critical:
                _quickloggerInstance.Critical(_categoryName, $"{_categoryName}[{eventId.Id}] - {message}");
                break;

            case LogLevel.Debug:
                _quickloggerInstance.Debug(_categoryName, $"{_categoryName}[{eventId.Id}] - {message}");
                break;

            case LogLevel.Trace:
                _quickloggerInstance.Trace(_categoryName, $"{_categoryName}[{eventId.Id}] - {message}");
                break;

            default:
                _quickloggerInstance.Info(_categoryName, $"{_categoryName}[{eventId.Id}] - {message}");
                break;
            }
        }
Пример #24
0
        public IActionResult Authenticate([FromBody] AuthenticateRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var user = _userService.Authenticate(request);

            if (user == null)
            {
                return(Unauthorized());
            }

            var role = _userService.GetUserRole(user.UserId);

            if (role != null)
            {
                user.Role = role.ToList();
            }
            var claims = new[]
            {
                new Claim(ClaimTypes.Sid, user.UserId.ToString()),
                new Claim(ClaimTypes.Name, user.OriginalUserName),
                new Claim(ClaimTypes.UserData, JsonHelper.SerializeObject <AuthenticateResponse>(user))
            };

            foreach (var _role in user.Role)
            {
                claims.Append(new Claim(ClaimTypes.Role, _role.RoleName));
            }
            var jwtResult = _jwtAuthManagerService.GenerateTokens(user.UserName, claims, DateTime.Now);

            _loggerService.Debug($"User [{user.UserName}] logged in the system.");

            user.AccessToken  = jwtResult.AccessToken;
            user.RefreshToken = jwtResult.RefreshToken;
            return(Ok(user));
        }
Пример #25
0
        private async Task SendExposureDataAsync(
            string idempotencyKey,
            ExposureData exposureData
            )
        {
            _loggerService.StartMethod();

            SendEventLogState sendEventLogState = _userDataRepository.GetSendEventLogState();
            bool isEnabled = sendEventLogState == SendEventLogState.Enable;

            if (!isEnabled)
            {
                _loggerService.Debug($"Send event-log function is not enabled.");
                _loggerService.EndMethod();
                return;
            }

            await _serverConfigurationRepository.LoadAsync();

            string exposureDataCollectServerEndpoint = _serverConfigurationRepository.EventLogApiEndpoint;

            _loggerService.Debug($"exposureDataCollectServerEndpoint: {exposureDataCollectServerEndpoint}");

            try
            {
                var contentJson = exposureData.ToJsonString();

                var eventLog = new V1EventLogRequest.EventLog()
                {
                    HasConsent = isEnabled,
                    Epoch      = _dateTimeUtility.UtcNow.ToUnixEpoch(),
                    Type       = "ExposureData",
                    Subtype    = "Debug",
                    Content    = contentJson,
                };
                var eventLogs = new[] { eventLog };

                var request = new V1EventLogRequest()
                {
                    IdempotencyKey = idempotencyKey,
                    Platform       = _essentialsService.Platform,
                    AppPackageName = _essentialsService.AppPackageName,
                    EventLogs      = eventLogs,
                };

                request.DeviceVerificationPayload = await _deviceVerifier.VerifyAsync(request);

                var requestJson = request.ToJsonString();

                var httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json");

                Uri uri = new Uri(exposureDataCollectServerEndpoint);

                HttpResponseMessage response = await _httpClient.PutAsync(uri, httpContent);

                if (response.IsSuccessStatusCode)
                {
                    var responseJson = await response.Content.ReadAsStringAsync();

                    _loggerService.Debug($"{responseJson}");
                }
                else
                {
                    _loggerService.Info($"UploadExposureDataAsync {response.StatusCode}");
                }
            }
            finally
            {
                _loggerService.EndMethod();
            }
        }
Пример #26
0
        public List <string> GetRows(string documentPath, ICollection <string> stopWords = null, string[] skipWords = null)
        {
            var memoryStream = new MemoryStream();

            try
            {
                _logger.Info("=== ENTERING WORD DOCUMENT EXTRACTOR ===");

                _logger.Debug("Retrieving document stored at : " + documentPath);
                Document document = new Document(documentPath);
                _logger.Info(documentPath + " successfully retrieved.");

                _logger.Debug("Converting and saving document " + documentPath + " as PDF in memory.");

                ThrowIfTimedOut(
                    () => document.SaveToFile(memoryStream, FileFormat.PDF),
                    TimeSpan.FromSeconds(10)
                    );

                _logger.Info(documentPath + " successfully converted to PDF.");
                memoryStream.Position = 0;

                using (PdfReader reader = new PdfReader(memoryStream))
                {
                    _logger.Debug("Preparing to read and process PDF content of " + documentPath);
                    ITextExtractionStrategy strategy    = new LocationTextExtractionStrategy();
                    List <string>           parsedLines = new List <string>();

                    _logger.Info("PDF stream successfully read: " + documentPath);

                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        string page = PdfTextExtractor.GetTextFromPage(reader, i, strategy);

                        if (skipWords != null && skipWords.Any(s => page.Contains(s)))
                        {
                            continue;
                        }

                        parsedLines.AddRange(page.Split('\n'));
                    }

                    if (_patternMatcher == null)
                    {
                        _patternMatcher = new NullPatternMatcher();
                    }

                    if (stopWords != null)
                    {
                        parsedLines = parsedLines.TakeWhile(line => !stopWords.Any(line.Contains))
                                      .Union(_patternMatcher.GetMatchedRows(parsedLines))
                                      .ToList();
                    }

                    _logger.Info(documentPath + " PDF stream successfully processed");
                    _logger.Info(parsedLines.Count + " rows processed and retrieved.");

                    return(parsedLines);
                }
            }
            catch (ArgumentOutOfRangeException ex)
            {
                _logger.Error("ArgumentOutOfRangeException occurred: " + ex);
            }
            catch (Exception exception)
            {
                _logger.Error("Unknown exception occurred: " + exception);
            }
            finally
            {
                memoryStream.Dispose();
            }

            return(new List <string>());
        }
Пример #27
0
        private int RunInsertOptionsCode(InsertOptions opts)
        {
            bool   Verbose    = opts.Verbose;
            bool   Recursive  = opts.Recursive;
            bool   DryRun     = opts.DryRun;
            bool   Pretty     = opts.Pretty;
            string collection = opts.Collection;
            string filePath   = opts.FilePath;
            string folderPath = opts.FolderPath;

            // setting log/console Output
            _loggerService.SetVerbose(Verbose);
            _loggerService.SetPretty(Pretty);

            // check token befare action..
            ConfigFile config = _configService.Load();

            if (config == null)
            {
                _loggerService.Warn("No configuratin file found. Please login before continue.");
                _loggerService.Warn("Program aborted.");
                return(0);
            }

            string token = config.Token;

            if (string.IsNullOrEmpty(token))
            {
                _loggerService.Warn("No token found. Please login before continue.");
                _loggerService.Warn("Program aborted.");
                return(0);
            }
            ;

            _loggerService.Debug($"Working into collection: {collection}");

            Dictionary <string, List <string> > listFile = new Dictionary <string, List <string> >();

            // pass a file to options
            if (!string.IsNullOrEmpty(filePath))
            {
                // check if file exists
                if (!File.Exists(filePath))
                {
                    _loggerService.Warn($"File not found: {filePath}");
                    return(0);
                }

                // check if file is valid json

                int check = _rawCmsService.CheckJSON(filePath);

                if (check != 0)
                {
                    _loggerService.Warn("Json is not well-formatted. Skip file.");
                    return(0);
                }
                List <string> filelist = new List <string>
                {
                    filePath
                };
                listFile.Add(collection, filelist);
            }
            else if (!string.IsNullOrEmpty(folderPath))
            {
                string cwd = Directory.GetCurrentDirectory();
                _loggerService.Info($"Current working directory: {cwd}");

                // get all file from folder
                if (!Directory.Exists(folderPath))
                {
                    _loggerService.Warn($"File not found: {filePath}");
                    return(0);
                }

                // This path is a directory
                // get first level path,
                // folder => collection
                DirectoryInfo   dInfo   = new DirectoryInfo(folderPath);
                DirectoryInfo[] subdirs = dInfo.GetDirectories();

                foreach (DirectoryInfo subDir in subdirs)
                {
                    _rawCmsService.ProcessDirectory(Recursive, listFile, subDir.FullName, subDir.Name);
                }
            }
            else
            {
                _loggerService.Warn("At least one of the two options -f (file) or -d (folder) is mandatory.");
                return(0);
            }

            _rawCmsService.ElaborateQueue(listFile, config, Pretty);

            _loggerService.Info($"Processing file complete.");
            return(0);
        }
        private async Task <ExposureConfiguration> GetExposureConfigurationInternalAsync()
        {
            _loggerService.StartMethod();

            ExposureConfiguration currentExposureConfiguration = null;

            if (File.Exists(_currentExposureConfigurationPath))
            {
                _loggerService.Debug("ExposureConfiguration file is found.");

                try
                {
                    string exposureConfigurationAsJson = await LoadAsync(_currentExposureConfigurationPath);

                    currentExposureConfiguration = JsonConvert.DeserializeObject <ExposureConfiguration>(exposureConfigurationAsJson);

                    _loggerService.Info("Cached:" + exposureConfigurationAsJson);

                    if (!IsDownloadedExposureConfigurationOutdated(AppConstants.ExposureConfigurationFileDownloadCacheRetentionDays))
                    {
                        _loggerService.EndMethod();
                        return(currentExposureConfiguration);
                    }
                    else
                    {
                        _loggerService.Info($"ExposureConfiguration is found but the file is outdated.");
                    }
                }
                catch (IOException exception)
                {
                    _loggerService.Exception("IOException. ExposureConfiguration file has been deleted.", exception);
                    RemoveExposureConfigurationInternal();
                }
                catch (JsonException exception)
                {
                    _loggerService.Exception("JsonException. ExposureConfiguration file has been deleted.", exception);
                    RemoveExposureConfigurationInternal();
                }
            }

            // Cache not exist (first time. probably...)
            if (currentExposureConfiguration is null)
            {
                currentExposureConfiguration = CreateDefaultConfiguration();
                SetExposureConfigurationDownloadedDateTime(_dateTimeUtility.UtcNow);
                SetIsDiagnosisKeysDataMappingConfigurationUpdated(true);
            }

            await _serverConfigurationRepository.LoadAsync();

            string url = _serverConfigurationRepository.ExposureConfigurationUrl;

            ExposureConfiguration newExposureConfiguration = null;

            var response = await _httpClient.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                string exposureConfigurationAsJson = await response.Content.ReadAsStringAsync();

                try
                {
                    newExposureConfiguration = JsonConvert.DeserializeObject <ExposureConfiguration>(exposureConfigurationAsJson);

                    _loggerService.Info("Downloaded:" + exposureConfigurationAsJson);

                    SetExposureConfigurationDownloadedDateTime(_dateTimeUtility.UtcNow);
                }
                catch (JsonException exception)
                {
                    _loggerService.Exception("JsonException.", exception);
                }
            }
            else
            {
                _loggerService.Warning($"Download ExposureConfiguration failed from {url}");
            }

            if (newExposureConfiguration is null)
            {
                _loggerService.EndMethod();
                return(currentExposureConfiguration);
            }

            if (IsUpdatedDiagnosisKeysDataMapping(currentExposureConfiguration, newExposureConfiguration))
            {
                if (IsExposureConfigurationOutdated(AppConstants.MinimumDiagnosisKeysDataMappingApplyIntervalDays))
                {
                    currentExposureConfiguration = newExposureConfiguration;
                    SetIsDiagnosisKeysDataMappingConfigurationUpdated(true);
                }
                else
                {
                    _loggerService.Info($"DiagnosisKeysDataMappingConfig has been changed but not updated, because current configuration is updated in {AppConstants.MinimumDiagnosisKeysDataMappingApplyIntervalDays} days.");
                }
            }
            else
            {
                currentExposureConfiguration = newExposureConfiguration;
            }

            string tmpFilePath = Path.Combine(_configDir, Guid.NewGuid().ToString());

            try
            {
                await SaveAsync(
                    JsonConvert.SerializeObject(currentExposureConfiguration, Formatting.Indented),
                    tmpFilePath
                    );

                Swap(tmpFilePath, _currentExposureConfigurationPath);

                return(currentExposureConfiguration);
            }
            finally
            {
                File.Delete(tmpFilePath);

                _loggerService.EndMethod();
            }
        }
        private async Task InternalExposureDetectionAsync(CancellationTokenSource cancellationTokenSource = null)
        {
            bool isEnabled = await _exposureNotificationApiService.IsEnabledAsync();

            if (!isEnabled)
            {
                _loggerService.Info($"EN API is not enabled.");
                return;
            }

            IEnumerable <int> statuseCodes = await _exposureNotificationApiService.GetStatusCodesAsync();

            bool isActivated = statuseCodes.Contains(ExposureNotificationStatus.Code_Android.ACTIVATED)
                               | statuseCodes.Contains(ExposureNotificationStatus.Code_iOS.Active);

            if (!isActivated)
            {
                _loggerService.Info($"EN API is not ACTIVATED.");
                return;
            }

            var cancellationToken = cancellationTokenSource?.Token ?? default(CancellationToken);

            await _serverConfigurationRepository.LoadAsync();

            bool canConfirmExposure = true;
            bool isMaxPerDayExposureDetectionAPILimitReached = false;

            foreach (var region in _serverConfigurationRepository.Regions)
            {
                _loggerService.Info($"Region: {region}");

                var diagnosisKeyListProvideServerUrl = _serverConfigurationRepository.GetDiagnosisKeyListProvideServerUrl(region);

                _loggerService.Info($"diagnosisKeyListProvideServerUrl: {diagnosisKeyListProvideServerUrl}");

                List <string> downloadedFileNameList = new List <string>();
                try
                {
                    var tmpDir = PrepareDir(region);

                    var(httpStatus, diagnosisKeyEntryList) = await _diagnosisKeyRepository.GetDiagnosisKeysListAsync(
                        diagnosisKeyListProvideServerUrl,
                        cancellationToken
                        );

                    if (httpStatus != HttpStatusCode.OK)
                    {
                        _loggerService.Info($"URL: {diagnosisKeyListProvideServerUrl}, Response StatusCode: {httpStatus}");
                        canConfirmExposure = false;
                        continue;
                    }

                    var lastProcessTimestamp = await _userDataRepository.GetLastProcessDiagnosisKeyTimestampAsync(region);

                    _loggerService.Info($"Region: {region}, lastProcessTimestamp: {lastProcessTimestamp}");

                    var targetDiagnosisKeyEntryList = FilterDiagnosisKeysAfterLastProcessTimestamp(diagnosisKeyEntryList, lastProcessTimestamp);

                    if (targetDiagnosisKeyEntryList.Count() == 0)
                    {
                        _loggerService.Info($"No new diagnosis-key found on {diagnosisKeyListProvideServerUrl}");
                        continue;
                    }

                    _loggerService.Info($"{targetDiagnosisKeyEntryList.Count()} new keys found.");

                    foreach (var diagnosisKeyEntry in targetDiagnosisKeyEntryList)
                    {
                        string filePath = await _diagnosisKeyRepository.DownloadDiagnosisKeysAsync(diagnosisKeyEntry, tmpDir, cancellationToken);

                        _loggerService.Info($"URL {diagnosisKeyEntry.Url} have been downloaded.");

                        downloadedFileNameList.Add(filePath);
                    }

                    var downloadedFileNames = string.Join("\n", downloadedFileNameList);
                    _loggerService.Debug(downloadedFileNames);

                    await _exposureNotificationApiService.ProvideDiagnosisKeysAsync(
                        downloadedFileNameList,
                        cancellationTokenSource
                        );

                    // Save LastProcessDiagnosisKeyTimestamp after ProvideDiagnosisKeysAsync was succeeded.
                    var latestProcessTimestamp = targetDiagnosisKeyEntryList
                                                 .Select(diagnosisKeyEntry => diagnosisKeyEntry.Created)
                                                 .Max();
                    await _userDataRepository.SetLastProcessDiagnosisKeyTimestampAsync(region, latestProcessTimestamp);

                    _userDataRepository.SetLastConfirmedDate(_dateTimeUtility.UtcNow);
                    _userDataRepository.SetCanConfirmExposure(true);
                    _userDataRepository.SetIsMaxPerDayExposureDetectionAPILimitReached(isMaxPerDayExposureDetectionAPILimitReached);
                }
                catch (ENException exception)
                {
                    canConfirmExposure = false;
                    isMaxPerDayExposureDetectionAPILimitReached = CheckMaxPerDayExposureDetectionAPILimitReached(exception);
                    _loggerService.Exception($"ENExcepiton occurred, Code:{exception.Code}, Message:{exception.Message}", exception);
                    throw;
                }
                catch (Exception exception)
                {
                    canConfirmExposure = false;
                    _loggerService.Exception($"Exception occurred: {region}", exception);
                    throw;
                }
                finally
                {
                    RemoveFiles(downloadedFileNameList);
                    _userDataRepository.SetCanConfirmExposure(canConfirmExposure);
                    _userDataRepository.SetIsMaxPerDayExposureDetectionAPILimitReached(isMaxPerDayExposureDetectionAPILimitReached);
                }
            }
        }
Пример #30
0
 protected virtual void OnElement(Timestamped <IElement> element)
 {
     _logger.Debug("{0}: OnElement ({1}): {2}", Id, element.Timestamp, element.Value);
 }