Пример #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 ItemEntity GetItem(string itemId, ref string responseMessage)
        {
            try
            {
                if (!ValidateItemIdParameter(itemId))
                {
                    return(null);
                }

                var item = _externalService.GetItem(itemId, ref responseMessage);
                if (item != null)
                {
                    string responseMessageNotNecessary = string.Empty;
                    item.ItemLargeDescription = _externalService.GetItemLargeDescription(itemId, ref responseMessageNotNecessary);
                }

                return(item);
            }
            catch (System.Exception ex)
            {
                _logger.Error(ex);
                responseMessage = ex.Message;
                return(null);
            }
        }
Пример #3
0
        public async Task <ActionResult <InfProductRespObj> > GetAllProduct()
        {
            try
            {
                var user = await _serverRequest.UserDataAsync();

                var createdBy = user.UserName;
                var response  = _repo.GetAllProduct();
                return(new InfProductRespObj
                {
                    InfProducts = response,
                });
            }
            catch (Exception ex)
            {
                var errorCode = ErrorID.Generate(5);
                _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new InfProductRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                        }
                    }
                });
            }
        }
Пример #4
0
        public DateTime?GetDateTime(string key)
        {
            lock (this)
            {
                loggerService.StartMethod();
                loggerService.Info($"key={key}, type={typeof(DateTime)}");

                if (!ContainsKey(key))
                {
                    loggerService.Info($"{key} is not contained.");
                    loggerService.EndMethod();
                    return(null);
                }

                var userDefaults = NSUserDefaults.StandardUserDefaults;
                try
                {
                    var valueString = userDefaults.StringForKey(key);
                    var value       = DateTime.Parse(valueString);
                    loggerService.EndMethod();
                    return(value);
                }
                catch (Exception)
                {
                    loggerService.Error($"Failed to get value of {key}.");
                    loggerService.EndMethod();
                    return(null);
                }
            }
        }
Пример #5
0
        /// <summary>
        /// 从文件头得到远程文件的长度
        /// </summary>
        /// <param name="url">download url</param>
        /// <returns>remote file size</returns>
        private long GetRemoteFileSize(string url)
        {
            long length = 0;

            HttpWebRequest  req = null;
            HttpWebResponse rsp = null;

            try
            {
                req = (HttpWebRequest)WebRequest.Create(url);
                rsp = (HttpWebResponse)req.GetResponse();
                if (rsp.StatusCode == HttpStatusCode.OK)
                {
                    length = rsp.ContentLength;
                }
            }
            catch (Exception ex)
            {
                loggerService.Error(ex, "获取远程文件大小失败。");
                DownloadError(ex);
            }
            finally
            {
                if (rsp != null)
                {
                    rsp.Close();
                }
                if (req != null)
                {
                    req.Abort();
                }
            }

            return(length);
        }
Пример #6
0
        public async Task <List <DicomDataset> > QueryPatients(string serverIp, int serverPort, string serverAET, string localAET, string patientId = null, string patientName = null)
        {
            List <DicomDataset> patients = new List <DicomDataset>();

            DicomCFindRequest request = RequestFactory.CreatePatientQuery(patientId, patientName);

            request.OnResponseReceived += (req, res) =>
            {
                if (res.Status == DicomStatus.Success ||
                    res.Status == DicomStatus.Pending)
                {
                    if (res.HasDataset)
                    {
                        patients.Add(res.Dataset);
                    }
                    else
                    {
                        logger.Error("Query Patients response has no dataset.");
                    }
                }
                else
                {
                    logger.Error("Query Patients failure. Status - [{0}]", res.Status);
                }
            };

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

            await client.SendAsync();

            return(patients);
        }
Пример #7
0
        public DateTime?GetDateTime(string key)
        {
            lock (this)
            {
                loggerService.StartMethod();
                loggerService.Info($"key={key}, type={typeof(DateTime)}");

                if (!ContainsKey(key))
                {
                    loggerService.Info($"{key} is not contained.");
                    loggerService.EndMethod();
                    return(null);
                }

                var context    = Android.App.Application.Context;
                var preference = context.GetSharedPreferences(context.PackageName, Android.Content.FileCreationMode.Private);
                try
                {
                    var valueString = preference.GetString(key, null);
                    var value       = DateTime.Parse(valueString);
                    loggerService.EndMethod();
                    return(value);
                }
                catch (Exception)
                {
                    loggerService.Error($"Failed to get value of {key}");
                    loggerService.EndMethod();
                    return(null);
                }
            }
        }
Пример #8
0
        public async Task <IActionResult> GetAllProducts()
        {
            try
            {
                if (User.Identity.IsAuthenticated)
                {
                    var product = await productService.GetProduct();

                    if (product == null)
                    {
                        return(NotFound());
                    }

                    return(Ok(product));
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                _loggerService.Error(ex);
                return(BadRequest());
            }
        }
Пример #9
0
        private bool TryLoadingArguments()
        {
            var args = Environment.GetCommandLineArgs();

            if (args.Length != 2)
            {
                return(false);
            }

            if (!File.Exists(args[1]))
            {
                var message = $"Sorry, '{args[1]}' could not be found";
                _loggerService.Error(message);
                MessageBox.Show(message);
                return(false);
            }

            if (Path.GetExtension(args[1]) == ".cpmodproj")
            {
                _ = OpenProjectAsync(args[1]);
                return(true);
            }

            if (Enum.TryParse <ERedExtension>(Path.GetExtension(args[1]).Substring(1), out var _))
            {
                _ = OpenFileAsync(new FileModel(args[1], null));
                return(true);
            }

            var message2 = $"Sorry, {Path.GetExtension(args[1])} files aren't supported by WolvenKit";

            _loggerService.Error(message2);
            MessageBox.Show(message2);
            return(false);
        }
Пример #10
0
        public void AddDeal(Trader buyer, Trader seller, Share share)
        {
            {
                if (buyer.Balance < 0)
                {
                    _loggerService.Error(
                        new ArgumentException($"An attempt {buyer} to buy a share with a negative balance"));
                    return;
                }

                if (!seller.SharesCollection.Contains(share))
                {
                    _loggerService.Error(
                        new ArgumentException($"An attempt {seller} to sell a share not belonging to the seller"));
                    return;
                }

                seller.SharesCollection.Remove(share);
                seller.Balance += share.Price;

                buyer.SharesCollection.Add(share);
                buyer.Balance -= share.Price;

                share.Owner = buyer;

                RegisterDeal(buyer, seller, share);
            }
        }
Пример #11
0
        public override void OnSave(object parameter)
        {
            using var fs = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite);
            using var bw = new StreamWriter(fs);
            bw.Write(Document.Text);

            try
            {
                if (Serialization.Deserialize(Document.Text, out var dict))
                {
                    TweakDocument = dict;
                    GenerateEntries();
                }
            }
            catch (Exception e)
            {
                _loggerService.Error(e);
            }

            _loggerService.Success($"{this.FilePath} saved.");

            //dbg
            //var deltaFilePath = $"{FilePath}.bin";
            //var db = new TweakDB();
            //foreach (var item in Flats)
            //{
            //    db.Add(item.Name, item.Value);
            //}
            //db.Save(deltaFilePath);
        }
Пример #12
0
 public async Task <ActionResult <ReportRespObj> > GetLoanApplicationFee(string ApplicationRef)
 {
     try
     {
         var response = _reportService.GetLoanApplicationFee(ApplicationRef);
         return(new ReportRespObj
         {
             ProductFees = response,
             Status = new APIResponseStatus {
                 IsSuccessful = true, Message = new APIResponseMessage {
                     FriendlyMessage = "Successful"
                 }
             }
         });
     }
     catch (Exception ex)
     {
         var errorCode = ErrorID.Generate(5);
         _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
         return(new ReportRespObj
         {
             Status = new APIResponseStatus {
                 IsSuccessful = false, Message = new APIResponseMessage {
                     FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                 }
             }
         });
     }
 }
Пример #13
0
 public void Error(string message)
 {
     if (_service != null)
     {
         var detail = GetExceptionDetail(message);
         _service.Error(detail);
     }
 }
Пример #14
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>());
        }
Пример #15
0
        public void ElaborateQueue(Dictionary <string, List <string> > listFile, ConfigFile config, bool pretty)
        {
            int totalfile      = listFile.Sum(x => x.Value.Count);
            int partialOfTotal = 0;

            foreach (KeyValuePair <string, List <string> > c in listFile)
            {
                int progress = 0;

                foreach (string item in c.Value)
                {
                    _loggerService.Info($"Processing file {++progress} of {c.Value.Count} in collection: {c.Key}");

                    string contentFile = File.ReadAllText(item);

                    _loggerService.Request(contentFile);

                    IRestResponse responseRawCMS = CreateElement(new CreateRequest
                    {
                        Collection = c.Key,
                        Data       = contentFile,
                        Token      = config.Token,
                        Url        = config.ServerUrl
                    });

                    _loggerService.Debug($"RawCMS response code: {responseRawCMS.StatusCode}");

                    if (!responseRawCMS.IsSuccessful)
                    {
                        //log.Error($"Error occurred: \n{responseRawCMS.Content}");
                        _loggerService.Error($"Error: {responseRawCMS.ErrorMessage}");
                    }
                    else
                    {
                        _loggerService.Response(responseRawCMS.Content);
                    }

                    //switch (responseRawCMS.ResponseStatus)
                    //{
                    //    case RestSharp.ResponseStatus.Completed:
                    //        log.Response(responseRawCMS.Content);

                    //        break;

                    //    case RestSharp.ResponseStatus.None:
                    //    case RestSharp.ResponseStatus.Error:
                    //    case RestSharp.ResponseStatus.TimedOut:
                    //    case RestSharp.ResponseStatus.Aborted:

                    //    default:
                    //        log.Error($"Error response: {responseRawCMS.ErrorMessage}");
                    //        break;
                    //}

                    _loggerService.Info($"File processed\n\tCollection progress: {progress} of {c.Value.Count}\n\tTotal progress: {++partialOfTotal} of {totalfile}\n\tFile: {item}\n\tCollection: {c.Key}");
                }
            }
        }
Пример #16
0
        public static void Error(string message)
        {
            if (_loggerService == null)
            {
                return;
            }

            _loggerService.Error(message);
        }
Пример #17
0
        private async void UpdateService_DownloadError(Exception ex)
        {
            string content = string.Format(
                i18NService.GetXmlStringByKey("ToastDownloadUpdateResult"),
                i18NService.GetXmlStringByKey("Failed"));

            loggerService.Error(ex, content);

            await Execute.OnUIThreadAsync(() => notificationService.ShowToastAsync(content, new TimeSpan(0, 0, 3), Controls.ToastType.Error));
        }
        public async Task <ActionResult <CompanyStructureDefinitionRespObj> > GetAllCompanyStructDef()
        {
            try
            {
                var list = await _compRepo.GetAllCompanyStructureDefinitionAsync();

                return(Ok(new CompanyStructureDefinitionRespObj
                {
                    CompanyStructureDefinitions = list.Select(x => new CompanyStructureDefinitionObj
                    {
                        UpdatedOn = x.UpdatedOn,
                        UpdatedBy = x.UpdatedBy,
                        Active = x.Active,
                        CreatedOn = x.CreatedOn,
                        CreatedBy = x.CreatedBy,
                        Definition = x.Definition,
                        Deleted = x.Deleted,
                        Description = x.Description,
                        OperatingLevel = x.OperatingLevel,
                        IsMultiCompany = x.IsMultiCompany,
                        StructureDefinitionId = x.StructureDefinitionId,
                        StructureLevel = x.StructureLevel
                    }).ToList(),
                    Status = new APIResponseStatus
                    {
                        IsSuccessful = true,
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = list.Count() > 0 ? null : "Search Complete! No record found"
                        }
                    }
                }));
            }
            catch (Exception ex)
            {
                #region Log error to file
                var errorCode = ErrorID.Generate(4);
                _logger.Error($"ErrorID : GetAllCompanyStructDef{errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new CompanyStructureDefinitionRespObj
                {
                    Status = new APIResponseStatus
                    {
                        IsSuccessful = false,
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = "Error occured!! Unable to process request",
                            MessageId = errorCode,
                            TechnicalMessage = $"ErrorID : GetAllCompanyStructDef{errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                        }
                    }
                });

                #endregion
            }
        }
Пример #19
0
        public async Task <bool> SendEmail(EmailDto emailDto)
        {
            try
            {
                var client = new SendGridClient(_apikey);
                var from   = new EmailAddress(_fromEmailId, _senderName);
                var to     = new EmailAddress(emailDto.ToEmailAddress, emailDto.ToName);

                var substitutions = new List <Dictionary <string, string> > {
                };

                _commonTokens = _commonTokens ?? new List <Token>();

                #region token replacement for subject and body

                //replacing common tokens in subject
                emailDto.Subject =
                    _tokenHelperService.Replace(emailDto.Subject, _commonTokens, true);
                //replacing email specific tokens in subject
                emailDto.Subject =
                    _tokenHelperService.Replace(emailDto.Subject, emailDto.EmailSpecificTokens, true);

                //replacing common tokens in body
                emailDto.Body = _tokenHelperService.Replace(emailDto.Body, _commonTokens, true);
                //replacing email specific tokens in body
                emailDto.Body = _tokenHelperService.Replace(emailDto.Body, emailDto.EmailSpecificTokens, true);

                #endregion

                var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from,
                                                                           new List <EmailAddress> {
                    to
                }, emailDto.Subject, string.Empty, emailDto.Body);

                var response = await client.SendEmailAsync(msg);

                return(response.StatusCode == System.Net.HttpStatusCode.Accepted);
            }
            catch (AggregateException ae)
            {
                foreach (var e in ae.InnerExceptions)
                {
                    // Handle the custom exception.
                    await _loggerService
                    .Error(e, "Aggregate exception thrown - " + e.Message, e.StackTrace);
                }
            }
            catch (Exception ex)
            {
                await _loggerService.Error(ex, ex.Message, null);
            }
            return(false);
        }
Пример #20
0
 public void Create(Speciality speciality)
 {
     try
     {
         _context.Specialties.Add(speciality);
         _context.SaveChanges();
     }
     catch (Exception e)
     {
         _loggerService.Error($"{e}");
         throw;
     }
 }
Пример #21
0
        public async Task <UpdatePPELPORegResp> CreateUpdateLPOForAdditionAsync(List <UpdatePPELPO> request)
        {
            var response = new UpdatePPELPORegResp {
                Status = new APIResponseStatus {
                    IsSuccessful = true, Message = new APIResponseMessage()
                }
            };

            try
            {
                var    gosGatewayClient = _httpClientFactory.CreateClient("GOSDEFAULTGATEWAY");
                string authorization    = _accessor.HttpContext.Request.Headers["Authorization"];
                gosGatewayClient.DefaultRequestHeaders.Add("Authorization", authorization);

                var jsonContent = JsonConvert.SerializeObject(request);
                var buffer      = Encoding.UTF8.GetBytes(jsonContent);
                var byteContent = new ByteArrayContent(buffer);
                byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");



                var result = await gosGatewayClient.PostAsync(ApiRoutes.PPEServerEndpoint.UPDATE_LPO, byteContent);

                var resultString = await result.Content.ReadAsStringAsync();

                response = JsonConvert.DeserializeObject <UpdatePPELPORegResp>(resultString);
                if (!result.IsSuccessStatusCode)
                {
                    response.Status.IsSuccessful            = false;
                    response.Status.Message.FriendlyMessage = $"{result.ReasonPhrase}  {(int)result.StatusCode}  {result.Content}";
                    return(response);
                    //throw new Exception($"{response}");
                }

                if (!response.Status.IsSuccessful)
                {
                    response.Status = response.Status;
                    return(response);
                }
                return(response);
            }
            catch (Exception ex)
            {
                #region Log error
                var errorCode = ErrorID.Generate(4);
                _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                throw ex;
                #endregion
            }
        }
        public bool Execute()
        {
            if (Monitor.TryEnter(_lock))
            {
                try
                {
                    var transactionToExecute = _groupTransactionRepository.GetTransactionsToExecute();

                    if (transactionToExecute.Count == 0)
                    {
                        return(true);
                    }

                    if (_synchronizationService.TryCapture(SynchronizedServiceType.DataSynchronization,
                                                           Guid.NewGuid(), out var token))
                    {
                        try
                        {
                            foreach (var transaction in transactionToExecute)
                            {
                                if (!ExecuteTransaction(transaction))
                                {
                                    break;
                                }
                            }

                            return(true);
                        }
                        finally
                        {
                            _synchronizationService.Release(token);
                        }
                    }
                }
                catch (Exception e)
                {
                    OnError?.Invoke(this, e);

                    _logger?.Error(
                        $"Exception was thrown during execution of the '{nameof(IGroupTransactionExecutionService)}'",
                        e);
                }
                finally
                {
                    Monitor.Exit(_lock);
                }
            }

            return(false);
        }
Пример #23
0
 public async Task <ActionResult <LookupRespObj> > GetAllFrequencyTypes()
 {
     try
     {
         var response = _repo.GetAllFrequencyTypes();
         return(new LookupRespObj
         {
             LookUp = response,
             Status = new APIResponseStatus {
                 IsSuccessful = true, Message = new APIResponseMessage {
                     FriendlyMessage = "Successful"
                 }
             }
         });
     }
     catch (Exception ex)
     {
         var errorCode = ErrorID.Generate(5);
         _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
         return(new LookupRespObj
         {
             Status = new APIResponseStatus {
                 IsSuccessful = false, Message = new APIResponseMessage {
                     FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                 }
             }
         });
     }
 }
Пример #24
0
        private IArchiveManager LoadArchiveManager()
        {
            if (_archiveManager != null && _archiveManager.IsManagerLoaded)
            {
                return(_archiveManager);
            }

            _loggerService.Info("Loading Archive Manager ... ");
            try
            {
                var sw = new Stopwatch();
                sw.Start();

                _archiveManager.LoadGameArchives(new FileInfo(_settingsManager.CP77ExecutablePath));

                sw.Stop();
                var ms = sw.ElapsedMilliseconds;
            }
            catch (Exception e)
            {
                _loggerService.Error(e);
                throw;
            }
            finally
            {
                _loggerService.Success("Finished loading Archive Manager.");
            }

#pragma warning disable 162
            return(_archiveManager);

#pragma warning restore 162
        }
Пример #25
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;
            }
        }
Пример #26
0
        public async Task <HttpStatusCode> PutSelfExposureKeysAsync(DiagnosisSubmissionParameter request)
        {
            loggerService.StartMethod();

            try
            {
                await serverConfigurationRepository.LoadAsync();

                var diagnosisKeyRegisterApiUrls = serverConfigurationRepository.DiagnosisKeyRegisterApiUrls;
                if (diagnosisKeyRegisterApiUrls.Count() == 0)
                {
                    loggerService.Error("DiagnosisKeyRegisterApiUrls count 0");
                    throw new InvalidOperationException("DiagnosisKeyRegisterApiUrls count 0");
                }
                else if (diagnosisKeyRegisterApiUrls.Count() > 1)
                {
                    loggerService.Warning("Multi DiagnosisKeyRegisterApiUrl are detected.");
                }

                var url     = diagnosisKeyRegisterApiUrls.First();
                var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");

                return(await PutAsync(url, content));
            }
            finally
            {
                loggerService.EndMethod();
            }
        }
Пример #27
0
        private static async Task <int> RunProcessAsync(ILoggerService loggerService, Process process, params string[] commands)
        {
            var result = -1;
            //process.OutputDataReceived += (s, ea) => Console.WriteLine(ea.Data);
            //process.ErrorDataReceived += (s, ea) => Console.WriteLine("ERR: " + ea.Data);
            var errorLog = new List <string>();

            process.ErrorDataReceived += (sender, e) =>
            {
                if (!string.IsNullOrEmpty(e.Data))
                {
                    errorLog.Add(e.Data);
                    loggerService.Error($"ERR: {e.Data}");
                }
            };
            //process.OutputDataReceived += (sender, e) =>
            //    { loggerService.LogString($"O: {e.Data}", Logtype.Normal); };

            var started = process.Start();

            if (!started)
            {
                //you may allow for the process to be re-used (started = false)
                //but I'm not sure about the guarantees of the Exited event in such a case
                throw new InvalidOperationException("Could not start process: " + process);
            }
            else
            {
                process.BeginErrorReadLine();
                //process.BeginOutputReadLine();

                if (commands != null && commands.Length > 0)
                {
                    var stream = process.StandardInput;

                    for (var i = 0; i < commands.Length; i++)
                    {
                        stream.WriteLine(commands[i]);

                        await Task.Delay(10).ConfigureAwait(false);
                    }

                    stream.Close();
                }

                process.WaitForExit();
                result = process.ExitCode;
                if (errorLog.Any())
                {
                    result = 1;
                }
                //loggerService.LogString($"Process exited with code {result}", Logtype.Important);
                //await process.WaitForExitAsync();
            }

            //process.BeginOutputReadLine();
            //process.BeginErrorReadLine();

            return(result);
        }
Пример #28
0
        private async Task GetExposureNotificationConfig()
        {
            loggerService.StartMethod();
            try
            {
                string     container  = AppSettings.Instance.BlobStorageContainerName;
                string     url        = AppSettings.Instance.CdnUrlBase + $"{container}/Configration.json";
                HttpClient httpClient = httpClientService.Create();
                Task <HttpResponseMessage> response = httpClient.GetAsync(url);
                HttpResponseMessage        result   = await response;
                if (result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    loggerService.Info("Success to download configuration");
                    var content = await result.Content.ReadAsStringAsync();

                    preferencesService.SetValue(PreferenceKey.ExposureNotificationConfiguration, content);
                }
                else
                {
                    loggerService.Error("Fail to download configuration");
                }
            }
            catch (Exception ex)
            {
                loggerService.Exception("Failed download of exposure notification configuration.", ex);
            }
            finally
            {
                loggerService.EndMethod();
            }
        }
Пример #29
0
 public IResult SendMail(EmailSenderModel model)
 {
     try
     {
         var to      = model.To;
         var subject = model.Subject;
         var body    = model.Body;
         var mail    = new MailMessage();
         mail.To.Add(to);
         mail.Subject    = subject;
         mail.Body       = body;
         mail.From       = new MailAddress("*****@*****.**");
         mail.IsBodyHtml = false;
         var smtp = new SmtpClient
         {
             Port = 587,
             UseDefaultCredentials = false,
             EnableSsl             = true,
             Credentials           = new System.Net.NetworkCredential("*****@*****.**", "TR1923")
         };
         smtp.Host = "smtp.gmail.com";
         smtp.Send(mail);
         return(new SuccessResult("Mail send success"));
     }
     catch (Exception)
     {
         _loggerService.Error("Error to send mail");
         return(new ErrorResult("Error to send mail!"));
     }
 }
Пример #30
0
        private void AddOrUpdateDicomItem(DicomDataset dataset, DicomVR vr, DicomTag tag, string[] values)
        {
            string charset = _currentFile.Dataset.GetSingleValueOrDefault(DicomTag.SpecificCharacterSet, "ISO_IR 192");

            try
            {
                if (vr == DicomVR.OB || vr == DicomVR.UN)
                {
                    byte[] temp = new byte[values.Length];
                    for (int i = 0; i < values.Length; i++)
                    {
                        temp[i] = byte.Parse(values[i]);
                    }
                    dataset.AddOrUpdate(vr, tag, DicomEncoding.GetEncoding(charset), temp);
                }
                else
                {
                    dataset.AddOrUpdate(vr, tag, DicomEncoding.GetEncoding(charset), values);
                }
            }
            catch (System.Exception e)
            {
                _logger.Error(e);
                return;
            }

            _currentItem.UpdateItem(dataset.GetDicomItem <DicomElement>(tag));
        }