示例#1
0
        private string GetCommandText(Action action)
        {
            ExecAction        execAction        = action as ExecAction;
            ShowMessageAction showMessageAction = action as ShowMessageAction;
            ComHandlerAction  comHandlerAction  = action as ComHandlerAction;
            EmailAction       emailAction       = action as EmailAction;

            if (execAction != null)
            {
                return($"{execAction.Path} {execAction.Arguments}");
            }
            else if (showMessageAction != null)
            {
                return($"Show message: '{showMessageAction.Title}'");
            }
            else if (comHandlerAction != null)
            {
                return($"COM handler: '{comHandlerAction.ClassName}'");
            }
            else if (emailAction != null)
            {
                return($"Send email: '{emailAction.Subject}'");
            }
            else
            {
                return("unknown action.");
            }
        }
        /// <summary>
        /// Execute the given email action for the given alarm.
        /// Sends a post request to Logic App with alarm information
        /// </summary>
        public async Task Execute(IAction action, object metadata)
        {
            if (metadata.GetType() != typeof(AsaAlarmApiModel) ||
                action.GetType() != typeof(EmailAction))
            {
                string errorMessage = "Email action expects metadata to be alarm and action" +
                                      " to be EmailAction, will not send email";
                this.logger.Error(errorMessage, () => { });
                return;
            }

            try
            {
                AsaAlarmApiModel alarm       = (AsaAlarmApiModel)metadata;
                EmailAction      emailAction = (EmailAction)action;
                string           payload     = this.GeneratePayload(emailAction, alarm);
                HttpRequest      httpRequest = new HttpRequest(this.servicesConfig.LogicAppEndpointUrl);
                httpRequest.SetContent(payload);
                IHttpResponse response = await this.httpClient.PostAsync(httpRequest);

                if (!response.IsSuccess)
                {
                    this.logger.Error("Could not execute email action against logic app", () => { });
                }
            }
            catch (JsonException e)
            {
                this.logger.Error("Could not create email payload to send to logic app,", () => new { e });
            }
            catch (Exception e)
            {
                this.logger.Error("Could not execute email action against logic app", () => new { e });
            }
        }
示例#3
0
 public Email(string email, EmailAction action, string templateName, DateTime dateTime)
 {
     this.Email       = email;
     this.EmailAction = action;
     this.TemlateName = templateName;
     this.DateTime    = dateTime;
 }
        /**
         * Generate email payload for given alarm and email action.
         * Creates subject, recipients, and body based on action and alarm
         */
        private string GeneratePayload(EmailAction emailAction, AsaAlarmApiModel alarm)
        {
            string emailTemplate = File.ReadAllText(this.servicesConfig.TemplateFolder + EMAIL_TEMPLATE_FILE_NAME);
            string alarmDate     = DateTimeOffset.FromUnixTimeMilliseconds(alarm.DateCreated).ToString(DATE_FORMAT_STRING);

            emailTemplate = emailTemplate.Replace("${subject}", emailAction.GetSubject());
            emailTemplate = emailTemplate.Replace(
                "${alarmDate}",
                DateTimeOffset.FromUnixTimeMilliseconds(alarm.DateCreated).ToString(DATE_FORMAT_STRING));
            emailTemplate = emailTemplate.Replace("${ruleId}", alarm.RuleId);
            emailTemplate = emailTemplate.Replace("${ruleDescription}", alarm.RuleDescription);
            emailTemplate = emailTemplate.Replace("${ruleSeverity}", alarm.RuleSeverity);
            emailTemplate = emailTemplate.Replace("${deviceId}", alarm.DeviceId);
            emailTemplate = emailTemplate.Replace("${notes}", emailAction.GetNotes());
            emailTemplate = emailTemplate.Replace("${alarmUrl}", this.GenerateRuleDetailUrl(alarm.RuleId));

            EmailActionPayload payload = new EmailActionPayload
            {
                Recipients = emailAction.GetRecipients(),
                Subject    = emailAction.GetSubject(),
                Body       = emailTemplate
            };

            return(JsonConvert.SerializeObject(payload));
        }
 public static IWorkItemAction CreateAction(Sage.Entity.Interfaces.IWorkItemAction data)
 {
     IWorkItemAction action = null;
     switch (data.ActionType)
     {
         case "Email Notification":
             action = new EmailAction();
             // TODO - this needs to eb dynamic
             action.DeliverySystem = new SmtpDeliverySystem(new SmtpSettings
             {
                 EnableSsl = true,
                 SmtpPort = 587,
                 SmtpServer = "smtp.gmail.com",
                 SmtpUser = "******",
                 SmtpUserPassword = "******",
                 EmailAddress = "*****@*****.**",
                 DisplayName = "Saleslogix DTS",
                 IsBodyHtml = false
             }
             );
             break;
         default:
             throw new Exception("Invalid action type " + data.ActionType);
     }
     action.LoadConfiguration(data.ActionValue);
     return action;
 }
示例#6
0
        public override SendEmailResponseBody ExecuteCore()
        {
            string randText = RandomText.GetNum(6);                        //生成6位验证码

            var emailInfo = SendContentConfig.EmailRegisterDesc(randText); //组织发送内容

            string error = "";
            bool   succ  = EmailAction.SendEmail(emailInfo.Item1, emailInfo.Item2, this.request.Email, out error);//开始发送

            if (!succ)
            {
                throw new Exception(error);
            }

            int codeId = User.UserUtility.AddCode(db, CodeType.Register, randText, emailInfo.Item2, this.request.Email); //发送成功后记录验证码

            if (codeId <= 0)
            {
                throw new Exception("Check code send failed.");
            }

            return(new SendEmailResponseBody()
            {
                CurrentEmail = this.request.Email,
                Status = ResultStatus.Success,
                //CheckCode = randText
            });
        }
        public void ManageEmail(EmailAction emailAction)
        {
            switch (emailAction)
            {
            case EmailAction.MarkAsRead:
                Page.YahooMailMessagePage.MarkEmailAsRead();
                Email.EmailRead = true;
                break;

            case EmailAction.MarkAsUnread:
                Page.YahooMailMessagePage.MarkEmailAsUnread();
                Email.EmailRead = false;
                break;

            case EmailAction.Delete:
                Page.YahooMailMessagePage.DeleteEmail();
                Email.EmailFolder = EmailFolder.Trash;
                break;

            case EmailAction.MoveToJunk:
                Page.YahooMailMessagePage.MoveEmailToJunk();
                Email.EmailFolder = EmailFolder.Junk;
                break;

            default:
                throw new NotImplementedException();
            }
        }
示例#8
0
        public async Task <StatusModel> UpdateAsync(EmailRequest request, EmailAction action, EmailFanoutStatus status, CancellationToken cancellationToken)
        {
            await _table.CreateIfNotExistsAsync(null, null, cancellationToken);

            var model = new StatusModel(request, action, status);
            await _table.ExecuteAsync(TableOperation.InsertOrReplace(model), null, null, cancellationToken);

            return(model);
        }
示例#9
0
        public StatusModel(EmailRequest email, EmailAction action, EmailFanoutStatus status)
        {
            Status     = status.ToString();
            ActionId   = action.Id;
            ReceivedAt = email.Timestamp;

            PartitionKey = GetPartitionKey(email);
            RowKey       = GetRowKey(email, action);
        }
示例#10
0
        private bool CanDo(object entityId, EmailAction action)
        {
            var emailId = Convert.ToInt32(entityId);
            var email   = (ImportedEmail)this.repository.Find(emailId);

            return(this.emailPermissionManager.CanDo(
                       action,
                       this.userContext,
                       email));
        }
示例#11
0
        public static string GetEmailAction(RestCommand command, int eMailActionID)
        {
            EmailAction emailAction = EmailActions.GetEmailAction(command.LoginUser, eMailActionID);

            if (emailAction.OrganizationID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            return(emailAction.GetXml("EmailAction", true));
        }
示例#12
0
        public void Should_CreateAction_When_OptionalNotesAreMissing()
        {
            // Arrange
            var parameters = new Dictionary <string, object>()
            {
                { PARAM_SUBJECT_KEY, PARAM_SUBJECT },
                { PARAM_RECIPIENTS_KEY, this.emailArray }
            };

            // Act
            var result = new EmailAction(parameters);

            // Assert
            Assert.Equal(ActionType.Email, result.Type);
            Assert.Equal(string.Empty, result.Parameters[PARAM_NOTES_KEY]);
            Assert.Equal(this.emailArray, result.Parameters[PARAM_RECIPIENTS_KEY]);
        }
        internal static void EditorTest(TaskService ts, System.IO.TextWriter output, params string[] arg)
        {
            try
            {
                const string taskName = "Test";

                // Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();

                /*td.RegistrationInfo.Description = "Test for XP SP3";
                 * td.RegistrationInfo.Author = "incaunu";*/
                td.Triggers.Add(new DailyTrigger()
                {
                    StartBoundary = new DateTime(2014, 1, 15, 9, 0, 0), EndBoundary = DateTime.Today.AddMonths(1)
                });

                /*EventTrigger eTrig = new EventTrigger("Security", "VSSAudit", 25);
                 * eTrig.ValueQueries.Add("Name", "Value");
                 * td.Triggers.Add(eTrig);*/
                //td.Actions.Add(new ExecAction("cmd.exe", "/c \"date /t > c:\\cmd.txt\""));
                EmailAction ea = (EmailAction)td.Actions.Add(new EmailAction("Hi", "*****@*****.**", "[email protected]; [email protected]", "<p>How you been?</p>", "smtp.codeplex.com"));
                ea.HeaderFields.Add("reply-to", "*****@*****.**");
                ea.Attachments = new object[] { (string)new TemporaryScopedFile(), (string)new TemporaryScopedFile() };
                //WriteXml(td, taskName);
                Task t = ts.RootFolder.RegisterTaskDefinition(taskName, td);                 //, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
                System.Converter <DateTime, string> d = delegate(DateTime ints) { return(ints == DateTime.MinValue ? "Never" : ints.ToString()); };
                output.Write("***********************\r\nName: {0}\r\nEnabled: {1}\r\nLastRunTime: {2}\r\nState: {3}\r\nIsActive: {4}\r\nNextRunTime: {5}\r\nShouldHaveRun: {6}\r\nTriggerStart: {7}\r\nTriggerEnd: {8}\r\n",
                             t.Name, t.Enabled, d(t.LastRunTime), t.State, t.IsActive, t.NextRunTime, d(t.LastRunTime), t.Definition.Triggers[0].StartBoundary, t.Definition.Triggers[0].EndBoundary);
                WriteXml(t);

                // Register then show task again
                while (DisplayTask(ts.GetTask(taskName), true) != null)
                {
                    Task t2 = editorForm.Task;
                    output.Write("***********************\r\nName: {0}\r\nEnabled: {1}\r\nLastRunTime: {2}\r\nState: {3}\r\nIsActive: {4}\r\nNextRunTime: {5}\r\nShouldHaveRun: {6}\r\nTriggerStart: {7}\r\nTriggerEnd: {8}\r\n",
                                 t2.Name, t2.Enabled, t2.LastRunTime, t2.State, t2.IsActive, t2.NextRunTime, t2.LastRunTime, t2.Definition.Triggers[0].StartBoundary, t2.Definition.Triggers[0].EndBoundary);
                }

                // Remove the task we just created
                ts.RootFolder.DeleteTask(taskName);
            }
            catch (Exception ex)
            {
                output.WriteLine(ex.ToString());
            }
        }
示例#14
0
        public void Should_CreateAction_When_OptionalNotesAreMissing()
        {
            // Arrange
            var parameters = new Dictionary <string, object>()
            {
                { ParameterSubjectKey, ParameterSubject },
                { ParameterRecipientsKey, this.emailArray },
            };

            // Act
            var result = new EmailAction(parameters);

            // Assert
            Assert.Equal(ActionType.Email, result.Type);
            Assert.Equal(string.Empty, result.Parameters[ParameterNotesKey]);
            Assert.Equal(this.emailArray, result.Parameters[ParameterRecipientsKey]);
        }
示例#15
0
        private static void _parse_email_queue_items(ref IDataReader reader, ref List <EmailQueueItem> retItems)
        {
            while (reader.Read())
            {
                try
                {
                    EmailQueueItem item = new EmailQueueItem();

                    if (!string.IsNullOrEmpty(reader["ID"].ToString()))
                    {
                        item.ID = (long)reader["ID"];
                    }
                    if (!string.IsNullOrEmpty(reader["SenderUserID"].ToString()))
                    {
                        item.SenderUserID = (Guid)reader["SenderUserID"];
                    }
                    if (!string.IsNullOrEmpty(reader["Email"].ToString()))
                    {
                        item.Email = (string)reader["Email"];
                    }
                    if (!string.IsNullOrEmpty(reader["Title"].ToString()))
                    {
                        item.Title = (string)reader["Title"];
                    }
                    if (!string.IsNullOrEmpty(reader["EmailBody"].ToString()))
                    {
                        item.EmailBody = (string)reader["EmailBody"];
                    }

                    EmailAction ac = EmailAction.None;
                    if (Enum.TryParse <EmailAction>(reader["Action"].ToString(), out ac))
                    {
                        item.Action = ac;
                    }

                    retItems.Add(item);
                }
                catch (Exception e) { string s = e.ToString(); }
            }

            if (!reader.IsClosed)
            {
                reader.Close();
            }
        }
示例#16
0
        public void Should_ReturnActionModel_When_ValidActionType()
        {
            // Arrange
            var parameters = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase)
            {
                { PARAM_SUBJECT_KEY, PARAM_SUBJECT },
                { PARAM_NOTES_KEY, PARAM_NOTES },
                { PARAM_RECIPIENTS_KEY, this.emailArray }
            };

            // Act
            var result = new EmailAction(parameters);

            // Assert
            Assert.Equal(ActionType.Email, result.Type);
            Assert.Equal(PARAM_NOTES, result.Parameters[PARAM_NOTES_KEY]);
            Assert.Equal(this.emailArray, result.Parameters[PARAM_RECIPIENTS_KEY]);
        }
示例#17
0
        public void Should_ReturnActionModel_When_ValidActionType()
        {
            // Arrange
            var parameters = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase)
            {
                { ParameterSubjectKey, ParameterSubject },
                { ParameterNotesKey, ParameterNotes },
                { ParameterRecipientsKey, this.emailArray },
            };

            // Act
            var result = new EmailAction(parameters);

            // Assert
            Assert.Equal(ActionType.Email, result.Type);
            Assert.Equal(ParameterNotes, result.Parameters[ParameterNotesKey]);
            Assert.Equal(this.emailArray, result.Parameters[ParameterRecipientsKey]);
        }
示例#18
0
        public void Should_ReturnActionModel_When_ValidActionTypeParametersIsCaseInsensitive()
        {
            // Arrange
            var parameters = new Dictionary <string, object>()
            {
                { "subject", ParameterSubject },
                { "nOtEs", ParameterNotes },
                { "rEcipiEnts", this.emailArray },
            };

            // Act
            var result = new EmailAction(parameters);

            // Assert
            Assert.Equal(ActionType.Email, result.Type);
            Assert.Equal(ParameterNotes, result.Parameters[ParameterNotesKey]);
            Assert.Equal(this.emailArray, result.Parameters[ParameterRecipientsKey]);
        }
示例#19
0
        public void Should_ReturnActionModel_When_ValidActionTypeParametersIsCaseInsensitive()
        {
            // Arrange
            var parameters = new Dictionary <string, object>()
            {
                { "subject", PARAM_SUBJECT },
                { "nOtEs", PARAM_NOTES },
                { "rEcipiEnts", this.emailArray }
            };

            // Act
            var result = new EmailAction(parameters);

            // Assert
            Assert.Equal(ActionType.Email, result.Type);
            Assert.Equal(PARAM_NOTES, result.Parameters[PARAM_NOTES_KEY]);
            Assert.Equal(this.emailArray, result.Parameters[PARAM_RECIPIENTS_KEY]);
        }
示例#20
0
    private string CompraInscripcion(int idProspecto, int idCompra, int patrocinador, int puntos)
    {
        string mensaje = string.Empty;

        try
        {
            ValidaComprasAction action   = new ValidaComprasAction();
            AsociadosModel      asociado = new AsociadosModel();
            EmailAction         email    = new EmailAction();
            asociado                  = action.DatosProspecto(idProspecto);
            asociado.Padre            = action.validaPadre(asociado.Padre, asociado.Lado);
            asociado.Status           = 1;
            asociado.Contrasena       = creaPassword();
            asociado.InicioActivacion = DateTime.Today;
            asociado.FinActivacion    = ValidaFecha(DateTime.Today);
            asociado.FechaInscripcion = DateTime.Today;
            List <string> infoPadre = action.InfoPadre(Convert.ToInt32(asociado.Padre), asociado.Lado);
            asociado.Recorrido      = infoPadre[0];
            asociado.LadosRecorrido = infoPadre[1];
            List <string> infoPatroc = action.InfoPatroc(patrocinador);
            asociado.Historia         = infoPatroc[0];
            asociado.Bodega           = Convert.ToInt32(infoPatroc[1]);
            asociado.Orden            = infoPatroc[2];
            asociado.LadoPatrocinador = LadoPatrocinador(asociado.Recorrido, asociado.LadosRecorrido, patrocinador);
            asociado.Patrocinador     = patrocinador.ToString();
            asociado.PtsMes           = puntos;
            asociado.Rango            = 1;
            asociado.RangoPago        = 1;
            List <string> infoNuevoAsoc = Alias(asociado.Nombre);
            asociado.IdAsociado = Convert.ToInt32(infoNuevoAsoc[0]);
            asociado.Alias      = infoNuevoAsoc[1];
            action.insertaAsociado(asociado);
            email.CorreoBienvenida(asociado);
            action.CambiaIdAsociadoEnCompra(asociado.IdAsociado, idCompra);
            mensaje = "Alta Asociado: " + asociado.IdAsociado + "<br />";
        }
        catch (Exception ex)
        {
            mensaje = "Error: " + ex.Message;
        }
        return(mensaje);
    }
        public async Task EmailAction_CausesPostToLogicApp()
        {
            // Arrange
            JArray emailArray = new JArray(new object[] { "*****@*****.**" });
            Dictionary <string, object> actionParameters = new Dictionary <string, object>
            {
                { "Recipients", emailArray },
                { "Notes", "Test Note" },
                { "Subject", "Test Subject" }
            };
            EmailAction      testAction = new EmailAction(actionParameters);
            AsaAlarmApiModel alarm      = new AsaAlarmApiModel
            {
                DateCreated     = 1539035437937,
                DateModified    = 1539035437937,
                DeviceId        = "Test Device Id",
                MessageReceived = 1539035437937,
                RuleDescription = "Test Rule description",
                RuleId          = "TestRuleId",
                RuleSeverity    = "Warning",
                Actions         = new List <IAction> {
                    testAction
                }
            };

            var response = new HttpResponse(HttpStatusCode.OK, "", null);

            this.httpClientMock.Setup(x => x.PostAsync(It.IsAny <IHttpRequest>())).ReturnsAsync(response);
            List <AsaAlarmApiModel> alarmList = new List <AsaAlarmApiModel> {
                alarm
            };

            // Act
            await this.actionManager.ExecuteAlarmActions(alarmList);

            // Assert
            this.httpClientMock.Verify(x => x.PostAsync(It.IsAny <IHttpRequest>()));
        }
示例#22
0
 public static string GetRowKey(EmailRequest email, EmailAction action)
 // user provided content. will contain non-allowed chars
 => Checksum.Calculate($"{email.Email.From.Email}_{email.Email.Date}_{action.Id}");
示例#23
0
 public void TestActions()
 {
     var emailAction = new EmailAction();
     //emailAction.Execute();
 }
示例#24
0
        public IActionResult EventProcesor(
            [FromRoute(Name = "event")] string eventName,
            [FromRoute(Name = "access")] string accessKey,
            [FromQuery] string value1,
            [FromQuery] string value2,
            [FromQuery] string value3)
        {
            if (accessKey != _SITE_AccessKey)
            {
                _logger.LogError($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Invalid key: {accessKey}");
                return(BadRequest());
            }

            try
            {
                if (eventName == "xo")
                {
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: xo (execute order), Value1: {value1}, Value2: {value2}, Value3: {value3}");

                    var recipients = new string[]
                    {
                        "*****@*****.**"
                    };
                    foreach (var recipient in recipients)
                    {
                        var emailAction = new EmailAction
                        {
                            Addresses = new string[] { recipient },
                            Subject   = "Execute Request: Result",
                            Body      = $"v1: {value1}\r\nv2: {value2}\r\nv2: {value3}\r\n"
                        };
                        _notify.EmailActions.Add(emailAction.Id, emailAction);
                        _logger.LogInformation($"EmailAction queued: {eventName} for {recipient}");
                    }

                    return(Ok("Accepted"));
                }

                if (eventName == "mdet1")
                {
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: motion1 (motion detector test)");

                    var webhookEvent = new WebhookAction
                    {
                        Url           = string.Format(_IFTTT_BaseAddress, eventName + "_ack", _IFTTT_WebhookAccessKey),
                        Attempts      = 0,
                        PerishSeconds = 120,
                        Payload       = string.Empty
                    };
                    _notify.WebHookActions.Add(webhookEvent.Id, webhookEvent);
                    _logger.LogInformation($"Action queued: motion_detected ({webhookEvent.Id})");

                    var recipients = new string[]
                    {
                        "*****@*****.**",
                        "*****@*****.**"
                    };
                    foreach (var recipient in recipients)
                    {
                        var emailAction = new EmailAction
                        {
                            Addresses = new string[] { recipient },
                            Subject   = "Motion Detector Test: Result",
                            Body      = "A motion detector test was triggered by an incoming webhook"
                        };
                        _notify.EmailActions.Add(emailAction.Id, emailAction);
                        _logger.LogInformation($"EmailAction queued: {eventName} for {recipient}");
                    }
                    return(Ok("Accepted"));
                }

                if (eventName == "led_on")
                {
                    _flash.LightVisibility = Flash.LightState.On;
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: led_on (LED on)");

#if USE_GPIO
                    GpioController controller = new GpioController(_flash.PinScheme);
                    controller.OpenPin(_flash.LedPin, PinMode.Output);
                    controller.Write(_flash.LedPin, PinValue.High);
#endif
                    return(Ok("Accepted"));
                }

                if (eventName == "led_off")
                {
                    _flash.LightVisibility = Flash.LightState.Off;
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: led_off (LED off)");
                    return(Ok("Accepted"));
                }

                if (eventName == "led_toggle")
                {
                    _flash.LightVisibility = (
                        _flash.LightVisibility == Flash.LightState.Flashing ? Flash.LightState.Off :
                        (_flash.LightVisibility == Flash.LightState.On ? Flash.LightState.Off : Flash.LightState.On)
                        );
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: led_toggle (LED toggle)");
                    return(Ok("Accepted"));
                }

                if (eventName == "led_flash")
                {
                    _flash.LightVisibility = Flash.LightState.Flashing;
                    _flash.FlashingMode    = Flash.FlashMode.Fast;
                    var phrase = value2.ToLower().Replace("\"", string.Empty).Trim();
                    if (_flash.FlashPhrases.ContainsKey(phrase))
                    {
                        _flash.FlashingMode = _flash.FlashPhrases[phrase];
                    }
                    _flash.FlashIndex = 0;
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: led_flash ({_flash.FlashingMode}) with phrase ({value2})");
                    return(Ok("Accepted"));
                }
                _logger.LogError($"Unknown event requested: {eventName}");
                return(NotFound("Unknown request"));
            }
            catch (Exception err)
            {
                _logger.LogCritical($"Unhandled exception: {err.Message}");
                return(StatusCode(500, err.Message));
            }
        }
        internal static void ShortTest(TaskService ts, System.IO.TextWriter output, params string[] arg)
        {
            // Get the service on the local machine
            try
            {
                /*string sub = "<QueryList><Query Id=\"0\" Path=\"Microsoft-Windows-TaskScheduler/Operational\">" +
                 *      "<Select Path=\"Microsoft-Windows-TaskScheduler/Operational\">" +
                 *      "*[System[Provider[@Name='Microsoft-Windows-TaskScheduler'] and (Computer='dahall1') and (Level=0 or Level=4) and (Task=100 or Task=101) and (EventID=129) and Security[@UserID='AMERICAS\\dahall'] and TimeCreated[timediff(@SystemTime) &lt;= 86400000]]]" +
                 *      "*[EventData[Data[@Name='TaskName']='\\Maint' and Data[@Name='EventCode']='0']]" +
                 *      "</Select>" +
                 *      "</Query></QueryList>";
                 * using (var ed = new EventActionFilterEditor() { Subscription = sub })
                 * {
                 *      ed.ShowDialog();
                 * }
                 * return;*/

                /*Action<string> d = delegate(string s) { var ar = s.Split('|'); foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(ar[2], @"\(A;(?<Flag>\w*);(?<Right>\w*);(?<Guid>\w*);(?<OIGuid>\w*);(?<Acct>[\w\-\d]*)(?:;[^\)]*)?\)")) output.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", ar[0], ar[1], m.Groups["Flag"], m.Groups["Right"], m.Groups["Guid"], m.Groups["OIGuid"], m.Groups["Acct"]); };
                 * FolderTaskAction(ts.RootFolder, delegate(TaskFolder f) { d("F|" + f.Name + "|" + f.GetSecurityDescriptorSddlForm()); }, delegate(Task s) { d("T|" + s.Name + "|" + s.GetSecurityDescriptorSddlForm()); });
                 * return;*/

                //FolderTaskAction(ts.RootFolder, null, delegate(Task tsk) { if (tsk.Definition.Triggers.ContainsType(typeof(CustomTrigger))) output.WriteLine(tsk.Path); });

                // Create a new task definition and assign properties
                const string   taskName = "Test";
                TaskDefinition td       = ts.NewTask();
                td.RegistrationInfo.Documentation = "Does something";
                td.Settings.ExecutionTimeLimit    = TimeSpan.Zero;
                //td.Principal.LogonType = TaskLogonType.InteractiveToken;

                // Add a cron trigger
                //td.Triggers.AddRange(Trigger.FromCronFormat("15 */6 */30 * *"));

                // Add a trigger that will fire the task at this time every other day
                DailyTrigger dt = (DailyTrigger)td.Triggers.Add(new DailyTrigger {
                    DaysInterval = 2
                });
                dt.Repetition.Duration = TimeSpan.FromHours(4);
                dt.Repetition.Interval = TimeSpan.FromHours(1);

                // Add a trigger that will fire every week on Friday
                td.Triggers.Add(new WeeklyTrigger {
                    StartBoundary = DateTime.Today + TimeSpan.FromHours(2), DaysOfWeek = DaysOfTheWeek.Friday, Enabled = false
                });

                // Add message and email actions
                if (ts.HighestSupportedVersion >= new Version(1, 2))
                {
                    ShowMessageAction sm = (ShowMessageAction)td.Actions.AddNew(TaskActionType.ShowMessage);
                    sm.Title       = "title";
                    sm.MessageBody = "body";

                    EmailAction ma = new EmailAction("Subject", "*****@*****.**", "[email protected]; [email protected]", "Body", "mail.google.com")
                    {
                        Bcc = "*****@*****.**", Cc = "*****@*****.**"
                    };
                    ma.Attachments = new object[] { (string)new TemporaryScopedFile() };
                    ma.HeaderFields.Add("N1", "V1");
                    ma.HeaderFields.Add("N2", "V2");
                    td.Actions.Add(ma);
                }

                // Add an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
                output.WriteLine(td.XmlText);
                Task t = ts.RootFolder.RegisterTaskDefinition(taskName, td);                 //, TaskCreation.CreateOrUpdate, "username", "password", TaskLogonType.Password);
                t.Enabled = false;

                System.Threading.Thread.Sleep(1000);
                output.WriteLine("LastTime & Result: {0} ({1:x})", t.LastRunTime == DateTime.MinValue ? "Never" : t.LastRunTime.ToString("g"), t.LastTaskResult);
                output.WriteLine("NextRunTime: {0:g}", t.NextRunTime);
                //DisplayTask(t, true);
                using (var dlg = new TaskOptionsEditor {
                    Editable = true
                })
                {
                    dlg.Initialize(t);
                    dlg.ShowDialog();
                }

                // Retrieve the task, add a trigger and save it.
                //t = ts.GetTask(taskName);
                //ts.RootFolder.DeleteTask(taskName);
                //td = t.Definition;

                /*td.Triggers.Clear();
                 * WeeklyTrigger wt = td.Triggers.AddNew(TaskTriggerType.Weekly) as WeeklyTrigger;
                 * wt.DaysOfWeek = DaysOfTheWeek.Friday;
                 * ((ExecAction)td.Actions[0]).Path = "calc.exe";
                 *
                 * t = ts.RootFolder.RegisterTaskDefinition(taskName, td);
                 * output.WriteLine("Principal: {1}; Triggers: {0}", t.Definition.Triggers, t.Definition.Principal);*/
                ts.RootFolder.DeleteTask(taskName);
            }
            catch (Exception ex)
            {
                output.WriteLine(ex.ToString());
            }
        }
示例#26
0
        private async Task ProcessAsync(EmailRequest request, EmailAction action, CancellationToken cancellationToken)
        {
            var properties = action.Properties;

            switch (action.Type)
            {
            case ActionType.Archive:
                // one folder per day is fine for now
                if (!DateTimeOffset.TryParse(request.Timestamp, out DateTimeOffset ts))
                {
                    // some dates are not parsable, just use todays date
                    // not 100% perfect (retried or delayed emails) might have wrong date
                    // but only archival mode
                    ts = DateTimeOffset.UtcNow;
                }
                var id = $"{ts:yyyy-MM}/{request.Timestamp:dd}/{request.Timestamp:HH-mm-ss}_{request.Email.From.Email} - {request.Email.Subject}";

                var name          = $"{id}.json";
                var containerName = action.Properties.Property("containerName").Value.ToString();
                await _blobStorageService.UploadAsync(containerName, name, JsonConvert.SerializeObject(request.Email, Formatting.Indented), cancellationToken);

                // save all attachments in subfolder
                var   tasks = Task.WhenAll(request.Email.Attachments.Select(a => _blobStorageService.UploadAsync(containerName, $"{id} (Attachments)/{a.FileName}", Convert.FromBase64String(a.Base64Data), cancellationToken)));
                await tasks;
                if (tasks.Exception != null)
                {
                    throw tasks.Exception;
                }

                break;

            case ActionType.Forward:
            {
                var secretName = action.Properties.Property("webhook")?.Value?.ToObject <SecretObject>()?.SecretName ?? throw new KeyNotFoundException($"Could not find secretName of webhook in action {action.Id}");
                var webhookUrl = await _keyVaultHelper.GetSecretAsync(secretName, cancellationToken);

                request.Body.Position = 0;
                var r = await _httpClient.PostStreamAsync(webhookUrl, request.Body, cancellationToken);

                if (r.StatusCode != HttpStatusCode.OK &&
                    r.StatusCode != HttpStatusCode.Accepted)
                {
                    throw new WebhookException($"Failed calling webhook {action.Id}");
                }
            }
            break;

            case ActionType.Webhook:
            {
                var secretName = action.Properties.Property("webhook")?.Value?.ToObject <SecretObject>()?.SecretName ?? throw new KeyNotFoundException($"Could not find secretName of webhook in action {action.Id}");
                var webhookUrl = await _keyVaultHelper.GetSecretAsync(secretName, cancellationToken);

                string Format(string text) => text
                .Replace("%sender%", request.Email.From.Email)
                .Replace("%subject%", request.Email.Subject)
                .Replace("%body%", request.Email.Text ?? request.Email.Html)
                .Replace("\"%attachments%\"", request.Email.Attachments != null ? JsonConvert.SerializeObject(request.Email.Attachments) : "null");

                var json = action.Properties.Property("body")?.Value?.ToString();
                json = Format(json);

                var r = await _httpClient.PostAsync(webhookUrl, json, cancellationToken);

                if (r.StatusCode != HttpStatusCode.OK &&
                    r.StatusCode != HttpStatusCode.Accepted)
                {
                    throw new WebhookException($"Failed calling webhook {action.Id}");
                }
            }
            break;

            case ActionType.Email:
            {
                var secretName  = action.Properties.Property("sendgrid")?.Value?.ToObject <SecretObject>()?.SecretName ?? throw new KeyNotFoundException($"Could not find secretName of email in action {action.Id}");
                var domain      = action.Properties.Property("domain")?.Value?.ToString() ?? throw new KeyNotFoundException($"Could not find domain of email in action {action.Id}");
                var targetEmail = action.Properties.Property("targetEmail")?.Value?.ToString() ?? throw new KeyNotFoundException($"Could not find targetEmail of email in action {action.Id}");

                var sendgridKey = await _keyVaultHelper.GetSecretAsync(secretName, cancellationToken);

                var sendgridClient = new SendGridClient(sendgridKey);
                // only add section if CC emails exist
                var prefix = "";
                if (request.Email.Cc.Length > 0)
                {
                    var newLine = "\r\n";
                    if (!string.IsNullOrEmpty(request.Email.Html))
                    {
                        newLine += "<br>";
                    }

                    if (request.Email.Cc.Any())
                    {
                        prefix += $"CC: {string.Join("; ", request.Email.Cc.Select(x => x.Email))}";
                    }
                    prefix += newLine + "__________";
                }

                // mail can be sent to multiple targets - our domain may not be the first and may even appear multiple times (same address or various domain addresses)
                // -> match first with domain name
                var emails = request.Email.To.Select(e => e.Email)
                             .Concat((request.Email.Cc ?? new EmailAddress[0]).Select(c => c.Email))
                             .ToArray();

                domain = domain.StartsWith("@") ? domain.Substring(1) : domain;
                var fromEmail = emails.FirstOrDefault(e => e.EndsWith($"@{domain}", StringComparison.InvariantCultureIgnoreCase)) ?? $"unknown@{domain}";
                string EnsureNotEmpty(string message)
                {
                    // pgp signed emails have no content but attachments only;
                    // seems to be this bug
                    // https://github.com/sendgrid/sendgrid-nodejs/issues/435
                    return(string.IsNullOrEmpty(message) ? " " : message);
                }

                var mail = MailHelper.CreateSingleEmail(new EmailAddress(fromEmail), new EmailAddress(targetEmail), request.Email.Subject, EnsureNotEmpty(prefix + request.Email.Text), EnsureNotEmpty(prefix + request.Email.Html));
                // causes the reply button to magically replace "fromEmail" with the email of the original author -> respond gets sent to the correct person
                mail.ReplyTo = request.Email.From;
                foreach (var attachment in request.Email.Attachments)
                {
                    mail.AddAttachment(new Attachment
                        {
                            ContentId = attachment.ContentId,
                            Content   = attachment.Base64Data,
                            Filename  = attachment.FileName,
                            Type      = attachment.ContentType
                        });
                }
                var response = await sendgridClient.SendEmailAsync(mail, cancellationToken);

                if (response.StatusCode != HttpStatusCode.Accepted)
                {
                    var errorResponse = await response.Body.ReadAsStringAsync();

                    throw new BadRequestException($"Sendgrid did not accept. The response was: {response.StatusCode}." + Environment.NewLine + errorResponse);
                }
            }
            break;

            default:
                throw new ArgumentOutOfRangeException($"Unsupported type {action.Type}");
            }
        }