Ejemplo n.º 1
0
        public void Create(Task model)
        {
            SchedulerClient             client = GetClient();
            JobCreateOrUpdateParameters p      = GetParams(model);
            bool errorOccured = false;

            try
            {
                JobCreateOrUpdateResponse result = client.Jobs.CreateOrUpdate(GetJobId(model), p);

                try
                {
                    JobUpdateStateResponse resultState = client.Jobs.UpdateState(GetJobId(model), new JobUpdateStateParameters(model.Active ? JobState.Enabled : JobState.Disabled));
                }
                catch (Hyak.Common.CloudException e)
                {
                    OmniusException.Log(e, OmniusLogSource.Cortex);
                    errorOccured = true;
                }
            }
            catch (Hyak.Common.CloudException e)
            {
                OmniusException.Log(e, OmniusLogSource.Cortex);
                errorOccured = true;
            }
            if (!errorOccured)
            {
                OmniusInfo.Log($"Succesfully created task to open {model.Url} at {model.Start_Date.ToString()}", OmniusLogSource.Cortex);
            }
        }
Ejemplo n.º 2
0
        private void Execute(string cmdText)
        {
            outputs.Clear();
            errors.Clear();

            try
            {
                Process          process   = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                //startInfo.WindowStyle = ProcessWindowStyle.Hidden;

                startInfo.FileName               = "cmd.exe";
                startInfo.Arguments              = "/c " + cmdText;
                startInfo.CreateNoWindow         = false;
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError  = true;
                startInfo.UseShellExecute        = false;
                process.StartInfo           = startInfo;
                process.EnableRaisingEvents = true;

                /*process.Exited += OnExecuteDone;
                 * process.OutputDataReceived += OnOutput;
                 * process.ErrorDataReceived += OnError;*/
                process.Start();

                /*process.BeginOutputReadLine();
                 * process.BeginErrorReadLine();
                 * process.WaitForExit();*/
            }
            catch (Exception e)
            {
                OmniusException.Log(e, OmniusLogSource.Cortex, app);
            }
        }
Ejemplo n.º 3
0
        public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message)
        {
            COREobject core    = COREobject.i;
            DBEntities context = core.Context;

            try
            {
                string dbName    = (string)vars["dbName"];
                string tableName = (string)vars["TableName"];
                JToken data      = (JToken)vars["Data"];
                object where = (object)vars["Where"];

                if (where == null || (where is String && string.IsNullOrEmpty((string)where)))
                {
                    throw new Exception(string.Format("{0}: where is missing. You must provide where clausule or rethingDB item id", Name));
                }

                ExtDB dbInfo = context.ExtDBs.Where(d => d.DB_Alias == dbName).SingleOrDefault();
                if (dbInfo == null)
                {
                    throw new Exception(string.Format("{0}: Integration was not found", Name));
                }

                NexusExtDBBaseService service;
                switch (dbInfo.DB_Type)
                {
                case ExtDBType.RethinkDB:
                    service = new NexusExtDBRethingService(dbInfo);
                    break;

                default:
                    service = (new NexusExtDBService(dbInfo.DB_Server, dbInfo.DB_Alias)).NewQuery("");
                    break;
                }

                NexusExtDBResult result = service.Update(tableName, data, where);

                if (result.Errors == 0)
                {
                    outputVars["Result"] = result.Replaced;
                    outputVars["Error"]  = false;
                }
                else
                {
                    outputVars["Result"] = result.FirstError;
                    outputVars["Error"]  = true;

                    OmniusException.Log(result.FirstError, OmniusLogSource.Nexus, null, core.Application, core.User);
                }
            }
            catch (Exception e)
            {
                string errorMsg = e.Message;
                OmniusException.Log(e, OmniusLogSource.Nexus, core.Application, core.User);
                outputVars["Result"] = String.Empty;
                outputVars["Error"]  = true;
            }
        }
Ejemplo n.º 4
0
        public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message)
        {
            COREobject core    = COREobject.i;
            DBEntities context = core.Context;

            try
            {
                string dbName    = (string)vars["dbName"];
                string tableName = (string)vars["TableName"];
                JToken data      = (JToken)vars["Data"];

                ExtDB dbInfo = context.ExtDBs.Where(d => d.DB_Alias == dbName).SingleOrDefault();
                if (dbInfo == null)
                {
                    throw new Exception(string.Format("{0}: Integration was not found", Name));
                }

                NexusExtDBBaseService service;
                switch (dbInfo.DB_Type)
                {
                case ExtDBType.RethinkDB:
                    service = new NexusExtDBRethingService(dbInfo);
                    break;

                default:
                    service = (new NexusExtDBService(dbInfo.DB_Server, dbInfo.DB_Alias)).NewQuery("");
                    break;
                }

                NexusExtDBResult result = service.Insert(tableName, data);

                if (result.Errors == 0)
                {
                    outputVars["Result"] = result.GeneratedKeys.Count > 0 ? result.GeneratedKeys[0] : "";
                    outputVars["Error"]  = false;
                }
                else
                {
                    outputVars["Result"] = result.FirstError;
                    outputVars["Error"]  = true;

                    OmniusException.Log(result.FirstError, OmniusLogSource.Nexus, null, core.Application, core.User);
                }
            }
            catch (Exception e)
            {
                OmniusException.Log(e, OmniusLogSource.Nexus, core.Application, core.User);
                outputVars["Result"] = String.Empty;
                outputVars["Error"]  = true;
            }
        }
Ejemplo n.º 5
0
        public void Prepare(string templateName, Object model)
        {
            data = model;

            EmailTemplate template = e.EmailTemplates.Single(t => t.Name == templateName);

            plcs = template.PlaceholderList.OrderBy(p => p.Num_Order).ToList();
            EmailTemplateContent contentModel = template.ContentList.Single(t => t.LanguageId == (int)mailerLanguage);

            string subject = SetData(contentModel.Subject);
            string content = SetData(contentModel.Content);

            mail = new MailMessage();
            mail.BodyEncoding = UTF8Encoding.UTF8;
            mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

            if (!string.IsNullOrWhiteSpace(contentModel.From_Email))
            {
                mail.From = new MailAddress(contentModel.From_Email, contentModel.From_Name);
            }
            else
            {
                OmniusException.Log("Nutno vyplnit email odesílatele.");
            }

            if (!string.IsNullOrWhiteSpace(subject))
            {
                mail.Subject = subject;
            }

            if (!string.IsNullOrWhiteSpace(content))
            {
                mail.Body = content;
            }

            if (template.Is_HTML)
            {
                mail.IsBodyHtml = true;
                if (!string.IsNullOrWhiteSpace(contentModel.Content_Plain))
                {
                    string contentPlain = SetData(contentModel.Content_Plain);
                    mail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(contentPlain, Encoding.UTF8, MediaTypeNames.Text.Plain));
                }
                mail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content, Encoding.UTF8, MediaTypeNames.Text.Html));
            }
        }
Ejemplo n.º 6
0
        public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message)
        {
            string hostname = (string)vars["Hostname"];
            int    port     = (int)vars["Port"];
            string userName = (string)vars["Username"];
            string password = (string)vars["Password"];
            string command  = (string)vars["Command"];

            try
            {
                using (var client = new SshClient(hostname, port, userName, password)) {
                    client.Connect();
                    var result = client.RunCommand(command);
                    client.Disconnect();
                }
            }
            catch (Exception e)
            {
                COREobject core = COREobject.i;
                OmniusException.Log(e, OmniusLogSource.Nexus, core.Application, core.User);
                outputVars["Result"] = String.Empty;
                outputVars["Error"]  = true;
            }
        }
Ejemplo n.º 7
0
        public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message)
        {
            COREobject core    = COREobject.i;
            DBEntities context = core.Context;

            try
            {
                string dbName    = (string)vars["dbName"];
                string tableName = (string)vars["TableName"];

                ExtDB dbInfo = context.ExtDBs.Where(d => d.DB_Alias == dbName).SingleOrDefault();
                if (dbInfo == null)
                {
                    throw new Exception(string.Format("{0}: Integration was not found", Name));
                }

                bool isOrderedByIndex = (vars.ContainsKey("OrderByIndex")) ? Convert.ToBoolean(vars["OrderByIndex"]) : false;

                NexusExtDBBaseService service;
                switch (dbInfo.DB_Type)
                {
                case ExtDBType.RethinkDB:
                    service = new NexusExtDBRethingService(dbInfo);
                    break;

                default:
                    service = (new NexusExtDBService(dbInfo.DB_Server, dbInfo.DB_Alias)).NewQuery("").Select("*");
                    break;
                }

                var query = service.From(tableName);

                if (service is NexusExtDBRethingService && vars.ContainsKey("OrderBy"))
                {
                    string orderBy = (string)vars["OrderBy"];
                    if (!string.IsNullOrEmpty(orderBy))
                    {
                        query = isOrderedByIndex ? query.OrderBy($"index:{orderBy}") : query.OrderBy(orderBy);
                    }
                }
                int condCount = vars.Keys.Where(k => k.StartsWith("CondColumn[") && k.EndsWith("]")).Count();
                if (condCount > 0)
                {
                    JArray cond = new JArray();
                    // setConditions
                    for (int i = 0; i < condCount; i++)
                    {
                        string condOperator = vars.ContainsKey($"CondOperator[{i}]") ? (string)vars[$"CondOperator[{i}]"] : "eq";
                        string condColumn   = (string)vars[$"CondColumn[{i}]"];
                        object condValue    = vars[$"CondValue[{i}]"];

                        var c = new JObject();
                        c["column"]   = condColumn;
                        c["operator"] = condOperator;
                        c["value"]    = JToken.FromObject(condValue);

                        cond.Add(c);
                    }
                    query = query.Where(cond);
                }

                if (service is NexusExtDBService && vars.ContainsKey("OrderBy"))
                {
                    string orderBy = (string)vars["OrderBy"];
                    if (!string.IsNullOrEmpty(orderBy))
                    {
                        query = query.OrderBy(orderBy);
                    }
                }

                if (vars.ContainsKey("Limit"))
                {
                    query = query.Limit((int)vars["Limit"]);
                }
                if (vars.ContainsKey("Skip"))
                {
                    query = query.Offset((int)vars["Skip"]);
                }

                var data = query.FetchAll();
                outputVars["Result"] = data;
                outputVars["Error"]  = false;
            }
            catch (Exception e)
            {
                OmniusException.Log(e, OmniusLogSource.Nexus, core.Application, core.User);
                outputVars["Result"] = String.Empty;
                outputVars["Error"]  = true;
            }
        }
Ejemplo n.º 8
0
        public void RunSender()
        {
            DateTime          now  = DateTime.UtcNow;
            List <EmailQueue> rows = e.EmailQueueItems.Where(m => m.Date_Send_After <= now && m.Status != EmailQueueStatus.error).ToList();

            foreach (EmailQueue row in rows)
            {
                try
                {
                    JToken m = JToken.Parse(row.Message);

                    mail      = new MailMessage();
                    mail.From = new MailAddress((string)m["From"]["Address"], (string)m["From"]["DisplayName"]);

                    foreach (JToken replyTo in m["ReplyToList"])
                    {
                        mail.ReplyToList.Add(new MailAddress((string)replyTo["Address"], (string)replyTo["DisplayName"]));
                    }
                    foreach (JToken to in m["To"])
                    {
                        mail.To.Add(new MailAddress((string)to["Address"], (string)to["DisplayName"]));
                    }
                    foreach (JToken bcc in m["Bcc"])
                    {
                        mail.Bcc.Add(new MailAddress((string)bcc["Address"], (string)bcc["DisplayName"]));
                    }
                    foreach (JToken cc in m["CC"])
                    {
                        mail.CC.Add(new MailAddress((string)cc["Address"], (string)cc["DisplayName"]));
                    }
                    mail.Priority = (MailPriority)((int)m["Priority"]);
                    mail.DeliveryNotificationOptions = (DeliveryNotificationOptions)((int)m["DeliveryNotificationOptions"]);
                    mail.Subject = (string)m["Subject"];
                    mail.Body    = (string)m["Body"];
                    mail.BodyTransferEncoding = (System.Net.Mime.TransferEncoding)((int)m["BodyTransferEncoding"]);
                    mail.IsBodyHtml           = (bool)m["IsBodyHtml"];

                    if (m["AlternateViews"].Children().Count() > 0)
                    {
                        foreach (JObject view in m["AlternateViews"].Children())
                        {
                            mail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(view["Content"].ToString(), Encoding.UTF8, view["Type"]["MediaType"].ToString()));
                        }
                    }

                    attachmentList = JArray.Parse(row.AttachmentList);

                    bool sent = SendMail(row.Application, false);
                    if (sent)
                    {
                        e.EmailQueueItems.Remove(row);
                    }
                    else
                    {
                        row.Status = EmailQueueStatus.error;
                    }
                }
                catch (Exception ex)
                {
                    OmniusException.Log(ex, OmniusLogSource.Hermes);
                }
            }

            e.SaveChanges();
            client.Dispose();
        }
Ejemplo n.º 9
0
        public bool SendMail(Application application = null, bool disposeClient = true)
        {
            if (mail.To.Count + mail.Bcc.Count == 0)
            {
                return(true);
            }
            bool   result;
            string smtpError = "";

            if (attachmentList.Count() > 0)
            {
                mail.Attachments.Clear();
                for (int i = 0; i < attachmentList.Count(); i++)
                {
                    Attachment att;
                    if (!attachmentList[i].GetType().Equals(typeof(JValue)))
                    {
                        FileMetadata fileInfo = e.FileMetadataRecords.Find((int)attachmentList[i]["Key"]);
                        try {
                            byte[] data        = fileInfo.CachedCopy.Blob;
                            Stream fileContent = new MemoryStream(data);

                            att = new Attachment(fileContent, fileInfo.Filename);
                        }
                        catch (NullReferenceException ex)
                        {
                            OmniusException.Log($"Odeslání e-mailu se nezdařilo - příloha <b>{attachmentList[i]["Value"].ToString()}</b> nebyla nalezena", OmniusLogSource.Hermes, ex, application);
                            return(false);
                        }
                    }
                    else
                    {
                        string path = attachmentList[i].ToString();
                        att = new Attachment(path);
                    }
                    mail.Attachments.Add(att);
                }
            }

            try {
                client.Send(mail);
                result = true;
            }
            catch (Exception e)
            {
                result    = false;
                smtpError = e.Message;
            }

            // Uložíme do logu
            EmailLog log = new EmailLog();

            log.Content    = HermesUtils.SerializeMailMessage(mail, Formatting.Indented);
            log.DateSend   = DateTime.UtcNow;
            log.Status     = result ? EmailSendStatus.success : EmailSendStatus.failed;
            log.SMTP_Error = smtpError;

            e.EmailLogItems.Add(log);
            e.SaveChanges();

            OmniusLog.Log($"Odeslání e-mailu \"{mail.Subject}\" (<a href=\"/Hermes/Log/Detail/{log.Id}\" title=\"Detail e-mailu\">detail e-mailu</a>)", (result ? OmniusLogLevel.Info : OmniusLogLevel.Error), OmniusLogSource.Hermes, application);

            if (disposeClient)
            {
                client.Dispose();
            }

            return(result);
        }
Ejemplo n.º 10
0
        public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message)
        {
            try
            {
                /// INIT
                COREobject core    = COREobject.i;
                DBEntities context = core.Context;
                var        service = context.WSs.First(c => c.Name == (string)vars["WsName"]);

                /// input
                string        method        = (string)vars["Method"];
                List <object> customHeaders = vars.ContainsKey("CustomHeaders") ? (List <object>)vars["CustomHeaders"] : new List <object>();
                string        endpoint      = vars.ContainsKey("Endpoint") ? (string)vars["Endpoint"] : "";
                string        rpcVersion    = vars.ContainsKey("RpcVersion") ? (string)vars["RpcVersion"] : "2.0";
                object        parameters;
                if (vars.ContainsKey("Params"))
                {
                    parameters = (string)vars["Params"];
                }
                else
                {
                    int ParamsCount = vars.Keys.Where(k => k.StartsWith("ParamsName[") && k.EndsWith("]")).Count();
                    parameters = new Dictionary <string, object>();
                    for (int i = 0; i < ParamsCount; i++)
                    {
                        (parameters as Dictionary <string, object>).Add(vars[$"ParamsName[{i}]"].ToString(), vars[$"ParamsValue[{i}]"]);
                    }
                }

                /// Create request
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                var httpWebRequest = (HttpWebRequest)WebRequest.Create($"{service.REST_Base_Url.TrimEnd('/')}/{endpoint.TrimEnd('/')}");
                httpWebRequest.Method      = "POST";
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Accept      = "application/json";
                httpWebRequest.KeepAlive   = false;

                // authorize
                if (!string.IsNullOrEmpty(service.Auth_User))
                {
                    httpWebRequest.Credentials = new NetworkCredential(service.Auth_User, service.Auth_Password);
                }
                //if (service != null && !string.IsNullOrEmpty(service.Auth_User))
                //{
                //    string authEncoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{service.Auth_User}:{service.Auth_Password}"));
                //    httpWebRequest.Headers.Add("Authorization", $"Basic {authEncoded}");
                //}

                // customHeaders
                foreach (string header in customHeaders)
                {
                    httpWebRequest.Headers.Add(header);
                }


                /// Build inputJson
                JsonObject call = new JsonObject();
                call["jsonrpc"] = rpcVersion;
                call["id"]      = GenerateJsonId();
                call["method"]  = method;
                call["params"]  = parameters;

                byte[] postJsonBytes = Encoding.UTF8.GetBytes(call.ToString());
                httpWebRequest.ContentLength = postJsonBytes.Length;
                httpWebRequest.GetRequestStream().Write(postJsonBytes, 0, postJsonBytes.Length);

                /// Response
                // Example form of the response {"jsonrpc": "2.0", "result": 19, "id": 3}
                var response = httpWebRequest.GetResponse();

                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader responseReader = new StreamReader(responseStream))
                    {
                        var outputJToken = (JObject)JToken.Parse(responseReader.ReadToEnd());

                        outputVars["Result"] = outputJToken["result"];
                        outputVars["Error"]  = outputJToken["Error"];
                    }
                }
            }
            catch (Exception e)
            {
                string     errorMsg = e.Message;
                COREobject core     = (COREobject)vars["__CORE__"];
                OmniusException.Log(e, OmniusLogSource.Nexus, core.Application, core.User);
                outputVars["Result"] = String.Empty;
                outputVars["Error"]  = true;
            }
        }