Ejemplo n.º 1
0
        /// <summary>
        /// Start windows service
        /// </summary>
        public void Start()
        {
            try
            {
                ProcessTask = Task.Run(() =>
                {
                    try
                    {
                        //Build config for webserver
                        var config = new ConfigurationBuilder()
                                     .SetBasePath(AppContext.BaseDirectory)
                                     .AddEnvironmentVariables()
                                     .AddCommandLine(Arguments)
                                     .AddJsonFile("appsettings.json", optional: false)
                                     .Build();

                        if (RunAsService)
                        {
                            var certificatePathSection     = config.GetSection("Kestrel:EndPoints:Https:Certificate:Path");
                            var certificatePasswordSection = config.GetSection("Kestrel:EndPoints:Https:Certificate:Password");
                            if (certificatePathSection.Value == null)
                            {
                                var appdata    = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                                var certFolder = Path.Combine(appdata, "AnalyticsGate", "AGCR", "certificates");
                                var passKey    = Path.Combine(certFolder, "AGRRoot.key");
                                var passDat    = Path.Combine(certFolder, "AGRRoot.keypas");
                                var crypter    = new TextCrypter(passKey);
                                var password   = crypter.DecryptText(File.ReadAllText(passDat));
                                certificatePathSection.Value     = Path.Combine(certFolder, "AGRRoot.pfx");
                                certificatePasswordSection.Value = password;
                            }
                        }

                        //Start the web server
                        CreateHostBuilder(Arguments)
                        .UseKestrel()
                        .UseConfiguration(config)
                        .UseContentRoot(Directory.GetCurrentDirectory())
                        .ConfigureLogging(logging =>
                        {
                            logging.ClearProviders();
                            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                        })
                        .UseNLog()
                        .Build()
                        .Run();
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }, cts.Token);
            }
            catch (Exception ex)
            {
                throw new Exception("Web service startup failed.", ex);
            }
        }
Ejemplo n.º 2
0
        private SerConfig CreateEngineConfig(QlikRequest request, SessionInfo session)
        {
            logger.Debug($"Resolve script '{request.JsonScript}' for engine config...");
            var jsonStr = request.JsonScript;

            //Make full JSON for Engine
            logger.Debug("Auto replacement to normal json structure...");
            if (!jsonStr.ToLowerInvariant().Contains("\"reports\":"))
            {
                jsonStr = $"\"reports\":[{jsonStr}]";
            }

            if (!jsonStr.ToLowerInvariant().Contains("\"tasks\":"))
            {
                jsonStr = $"\"tasks\":[{{{jsonStr}}}]";
            }

            if (!jsonStr.Trim().StartsWith("{"))
            {
                jsonStr = $"{{{jsonStr}";
            }

            if (!jsonStr.Trim().EndsWith("}"))
            {
                jsonStr = $"{jsonStr}}}";
            }

            logger.Debug("Search for connections for the engine config...");
            dynamic serJsonConfig = JObject.Parse(jsonStr);
            var     tasks         = serJsonConfig?.tasks ?? new JArray();

            foreach (var task in tasks)
            {
                var reports = task?.reports ?? new JArray();
                foreach (var report in reports)
                {
                    var    userConnections = new JArray();
                    JToken connections     = report?.connections;
                    if (connections.Type == JTokenType.Object)
                    {
                        userConnections.Add(report?.connections);
                    }
                    else if (connections.Type == JTokenType.Array)
                    {
                        userConnections = report?.connections;
                    }
                    else
                    {
                        logger.Error($"No valid connection type '{connections.Type}'.");
                    }
                    var newUserConnections = new List <JToken>();
                    for (int i = 0; i < userConnections.Count; i++)
                    {
                        var mergeConnection     = userConnections[i] as JObject;
                        var credType            = Options.Config?.Connection?.Credentials?.Type ?? QlikCredentialType.JWT;
                        var connectorConnection = JObject.FromObject(CreateConnection(credType, session));
                        connectorConnection.Merge(mergeConnection, new JsonMergeSettings()
                        {
                            MergeNullValueHandling = MergeNullValueHandling.Ignore
                        });
                        newUserConnections.Add(connectorConnection);
                    }

                    report.connections = new JArray(newUserConnections);
                    if (report.distribute is JObject distribute)
                    {
                        var children = distribute?.Children().Children()?.ToList() ?? new List <JToken>();
                        foreach (dynamic child in children)
                        {
                            var connection = child.connections ?? null;
                            if (connection == null)
                            {
                                child.connections = new JArray(newUserConnections);
                            }
                            else if (connection?.ToString() == "@CONFIGCONNECTION@")
                            {
                                child.connections = new JArray(newUserConnections);
                            }
                            var childProp = (child as JObject).Parent as JProperty;
                            if (childProp?.Name?.StartsWith("hub") ?? false)
                            {
                                if (child?.owner == null)
                                {
                                    child.owner = session.User.ToString();
                                }
                            }
                            else if (childProp?.Name?.StartsWith("mail") ?? false)
                            {
                                if (child?.mailServer != null)
                                {
                                    if (child?.mailServer?.privateKey == null)
                                    {
                                        child.mailServer.privateKey = Options?.Config?.Connection?.Credentials?.PrivateKey;
                                    }
                                }
                            }
                        }
                    }

                    var privateKey = Options.Config?.Connection?.Credentials?.PrivateKey ?? null;
                    if (!String.IsNullOrEmpty(privateKey))
                    {
                        // For file access
                        lock (threadObject)
                        {
                            var path    = HelperUtilities.GetFullPathFromApp(privateKey);
                            var crypter = new TextCrypter(path);
                            var value   = report?.template?.outputPassword ?? null;
                            if (value == null)
                            {
                                value = report?.template?.outputpassword ?? null;
                            }
                            if (value != null)
                            {
                                string password = value.ToString();
                                if (value.Type == JTokenType.Boolean)
                                {
                                    password = password.ToLowerInvariant();
                                }
                                bool useBase64Password = report?.template?.useBase64Password ?? false;
                                if (useBase64Password == true)
                                {
                                    report.template.outputPassword = crypter.DecryptText(password);
                                }
                                else
                                {
                                    report.template.outputPassword = password;
                                }
                            }
                        }
                    }
                }
            }

            //Resolve @PROPERTYNAME@ and @("
            var jsonResolver     = new JsonConfigResolver(serJsonConfig.ToString());
            var jsonResult       = jsonResolver.Resolve();
            var serConfiguration = JsonConvert.DeserializeObject <SerConfig>(jsonResult);

            return(serConfiguration);
        }
Ejemplo n.º 3
0
        public void SendMails()
        {
            try
            {
                logger.Debug("Summarized mails...");
                foreach (var mailcache in MailCaches)
                {
                    var summarizedMail = GetMailFromSummarizedMailList(mailcache.Settings);
                    if (summarizedMail == null)
                    {
                        logger.Debug("Create new mail for summarized mail list...");
                        var mailTo   = mailcache.Settings?.To?.Replace(";", ",")?.TrimEnd(',') ?? "No mail recipient was specified.";
                        var mailFrom = mailcache.Settings?.MailServer?.From ?? "No sender was specified.";
                        summarizedMail = new MailMessage(mailFrom, mailTo)
                        {
                            BodyEncoding    = Encoding.UTF8,
                            SubjectEncoding = Encoding.UTF8,
                            Subject         = mailcache.Settings?.Subject?.Trim() ?? "No subject was specified.",
                        };

                        var ccAddresses = mailcache.Settings?.Cc?.Replace(";", ",")?.TrimEnd(',');
                        if (!String.IsNullOrEmpty(ccAddresses))
                        {
                            summarizedMail.CC.Add(ccAddresses);
                        }

                        var bccAddresses = mailcache.Settings?.Bcc?.Replace(";", ",")?.TrimEnd(',');
                        if (!String.IsNullOrEmpty(bccAddresses))
                        {
                            summarizedMail.Bcc.Add(bccAddresses);
                        }

                        var msgBody = mailcache.Settings?.Message?.Trim() ?? String.Empty;
                        switch (mailcache.Settings?.MailType ?? EMailType.TEXT)
                        {
                        case EMailType.TEXT:
                            msgBody = msgBody.Replace("{n}", Environment.NewLine);
                            break;

                        case EMailType.HTML:
                            summarizedMail.IsBodyHtml = true;
                            break;

                        case EMailType.MARKDOWN:
                            summarizedMail.IsBodyHtml = true;
                            msgBody = Markdown.ToHtml(msgBody);
                            break;

                        default:
                            throw new Exception($"Unknown mail type {mailcache.Settings?.MailType}.");
                        }
                        msgBody = msgBody.Trim();
                        logger.Debug($"Set mail body '{msgBody}'...");
                        summarizedMail.Body = msgBody;
                        if (mailcache.Settings.SendAttachment)
                        {
                            logger.Debug($"Attachment report files...");
                            AddReportstoMail(summarizedMail, mailcache.Report);
                        }
                        else
                        {
                            logger.Debug($"Use no mail attachment...");
                        }
                        SummarizedMails.Add(summarizedMail);
                    }
                    else
                    {
                        logger.Debug("Duplicate Mail settings was found in summarized mail list...");
                        if (mailcache.Settings.SendAttachment)
                        {
                            logger.Debug($"Attachment report files...");
                            AddReportstoMail(summarizedMail, mailcache.Report);
                        }
                        else
                        {
                            logger.Debug($"Use no mail attachment...");
                        }
                    }
                }

                var mailServers = MailCaches.Select(c => c.Settings).Select(s => s.MailServer).GroupBy(s => s.Host).Select(s => s.First()).ToList();
                logger.Debug($"Send {SummarizedMails.Count} Mails over {MailCaches.Count} mail servers...");
                foreach (var mailServer in mailServers)
                {
                    var mailResult = new MailResult();

                    try
                    {
                        foreach (var summarizedMail in SummarizedMails)
                        {
                            using var client = new SmtpClient(mailServer.Host, mailServer.Port);
                            var priateKeyPath = HelperUtilities.GetFullPathFromApp(mailServer.PrivateKey);
                            if (!File.Exists(priateKeyPath))
                            {
                                logger.Debug("No private key path found...");
                            }

                            if (!String.IsNullOrEmpty(mailServer.Username) && !String.IsNullOrEmpty(mailServer.Password))
                            {
                                logger.Debug($"Set mail server credential for user '{mailServer.Username}'...");
                                var password = mailServer.Password;
                                if (mailServer.UseBase64Password && File.Exists(priateKeyPath))
                                {
                                    logger.Debug($"Use private key path {priateKeyPath}...");
                                    var textCrypter = new TextCrypter(priateKeyPath);
                                    password = textCrypter.DecryptText(password);
                                }
                                client.Credentials = new NetworkCredential(mailServer.Username, password);
                            }
                            else
                            {
                                logger.Debug($"No mail server credential found...");
                            }

                            if (mailServer.UseSsl)
                            {
                                logger.Debug($"Use SSL for mail sending...");
                                client.EnableSsl = true;
                            }

                            if (mailServer.UseCertificate && File.Exists(priateKeyPath))
                            {
                                var certifcateFolder = Path.GetDirectoryName(priateKeyPath);
                                logger.Info($"Search for email certificates with name 'mailcert.*' in folder '{certifcateFolder}'...");
                                var certFiles = Directory.GetFiles(certifcateFolder, "mailcert.*", SearchOption.TopDirectoryOnly);
                                foreach (var certFile in certFiles)
                                {
                                    logger.Debug($"Load certificate '{certFile}'.");
                                    var x509File = new X509Certificate2(certFile);
                                    logger.Debug($"Add certificate '{certFile}'.");
                                    client.ClientCertificates.Add(x509File);
                                }
                            }

                            if (summarizedMail.To.Count > 0)
                            {
                                var delay = 0;
                                if (mailServer.SendDelay > 0)
                                {
                                    delay = mailServer.SendDelay * 1000;
                                    logger.Debug($"Wait {delay} milliseconds for the mail to be sent...");
                                }

                                Task.Delay(delay).ContinueWith(r =>
                                {
                                    logger.Debug("Send mail package...");
                                    client.Send(summarizedMail);

                                    mailResult.Message     = "The mail was sent successfully.";
                                    mailResult.Success     = true;
                                    mailResult.TaskName    = JobResult.TaskName;
                                    mailResult.ReportState = GetFormatedState();
                                }).Wait();
                            }
                            else
                            {
                                mailResult.Message = "Mail without mail Address could not be sent.";
                                logger.Error(mailResult.Message);
                                mailResult.Success     = false;
                                mailResult.TaskName    = JobResult.TaskName;
                                mailResult.ReportState = "ERROR";
                                JobResult.Exception    = ReportException.GetException(mailResult.Message);
                                JobResult.Status       = TaskStatusInfo.ERROR;
                            }

                            client.Dispose();
                            Results.Add(mailResult);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex, $"The delivery via 'Mail' failed with server '{mailServer.Host}'.");
                        JobResult.Exception    = ReportException.GetException(ex);
                        JobResult.Status       = TaskStatusInfo.ERROR;
                        mailResult.Success     = false;
                        mailResult.ReportState = "ERROR";
                        mailResult.TaskName    = JobResult.TaskName;
                        mailResult.Message     = JobResult?.Exception?.FullMessage ?? null;
                        Results.Add(mailResult);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "The delivery via 'Mail' failed.");
                JobResult.Exception = ReportException.GetException(ex);
                JobResult.Status    = TaskStatusInfo.ERROR;
                var errorResult = new MailResult()
                {
                    Success     = false,
                    ReportState = "ERROR",
                    TaskName    = JobResult?.TaskName ?? "Unknown Task",
                    Message     = JobResult?.Exception?.FullMessage ?? null
                };
                Results.Add(errorResult);
            }
        }