public string GenerateSql(string eql, string parameters) { ValidationException validation = new ValidationException(); List <DataSourceParameter> dsParams = ProcessParametersText(parameters); List <EqlParameter> eqlParams = new List <EqlParameter>(); foreach (var dsPar in dsParams) { eqlParams.Add(ConvertDataSourceParameterToEqlParameter(dsPar)); } EqlBuilder builder = new EqlBuilder(eql); var result = builder.Build(eqlParams); if (result.Errors.Count > 0) { foreach (var err in result.Errors) { if (err.Line.HasValue || err.Column.HasValue) { validation.AddError("eql", $"{err.Message} [{err.Line},{err.Column}]"); } else { validation.AddError("eql", err.Message); } } } validation.CheckAndThrow(); return(result.Sql); }
/// <summary> /// Creates new application /// </summary> /// <param name="id"></param> /// <param name="name"></param> /// <param name="label"></param> /// <param name="description"></param> /// <param name="iconClass"></param> /// <param name="author"></param> /// <param name="color"></param> /// <param name="weight"></param> /// <param name="access"></param> /// <param name="transaction"></param> public void CreateApplication(Guid id, string name, string label, string description, string iconClass, string author, string color, int weight, List <Guid> access, NpgsqlTransaction transaction = null) { ValidationException ex = new ValidationException(); var app = repository.GetById(id, transaction); if (app != null) { ex.AddError("id", "There is an existing application with same identifier."); } if (string.IsNullOrWhiteSpace(name)) { ex.AddError("name", "Application name is not specified."); } else { app = repository.GetByName(name, transaction); if (app != null) { ex.AddError("name", "There is an existing application with same name. Application name has to be unique."); } } if (string.IsNullOrWhiteSpace(label)) { ex.AddError("label", "Application label is not specified."); } ex.CheckAndThrow(); repository.InsertApplication(id, name, label, description, iconClass, author, color, weight, access, transaction); }
public IActionResult SetTaskRecurrenceOnPost(RecordDetailsPageModel pageModel) { ValidationException valEx = new ValidationException(); if (!pageModel.HttpContext.Request.Form.ContainsKey("recurrence_template")) { valEx.AddError("recurrence_template", "Recurrence settings missing in post data"); throw valEx; } EntityRecord taskRecord = (EntityRecord)pageModel.DataModel.GetProperty("Record"); if (taskRecord["start_time"] == null) { valEx.AddError("start_time", "Start time should be specified before set task recurrence"); } if (taskRecord["end_time"] == null) { valEx.AddError("end_time", "End time should be specified before set task recurrence"); } valEx.CheckAndThrow(); RecurrenceTemplate recurrenceData = JsonConvert.DeserializeObject <RecurrenceTemplate>(pageModel.HttpContext.Request.Form["recurrence_template"]); return(null); }
public void QueueEmail(List <EmailAddress> recipients, EmailAddress sender, string subject, string textBody, string htmlBody, EmailPriority priority = EmailPriority.Normal) { ValidationException ex = new ValidationException(); if (recipients == null || recipients.Count == 0) { ex.AddError("recipientEmail", "Recipient is not specified."); } else { foreach (var recipient in recipients) { if (recipient == null) { ex.AddError("recipientEmail", "Recipient is not specified."); } else { if (string.IsNullOrEmpty(recipient.Address)) { ex.AddError("recipientEmail", "Recipient email is not specified."); } else if (!recipient.Address.IsEmail()) { ex.AddError("recipientEmail", "Recipient email is not valid email address."); } } } } if (string.IsNullOrEmpty(subject)) { ex.AddError("subject", "Subject is required."); } ex.CheckAndThrow(); Email email = new Email(); email.Id = Guid.NewGuid(); email.Sender = sender ?? new EmailAddress { Address = DefaultSenderEmail, Name = DefaultSenderName }; email.ReplyToEmail = DefaultReplyToEmail; email.Recipients = recipients; email.Subject = subject; email.ContentHtml = htmlBody; email.ContentText = textBody; email.CreatedOn = DateTime.UtcNow; email.SentOn = null; email.Priority = priority; email.Status = EmailStatus.Pending; email.ServerError = string.Empty; email.ScheduledOn = email.CreatedOn; email.RetriesCount = 0; email.ServiceId = Id; new SmtpInternalService().SaveEmail(email); }
public void SaveRole(ErpRole role) { if (role == null) throw new ArgumentNullException(nameof(role)); RecordManager recMan = new RecordManager(); EntityRecord record = new EntityRecord(); var allRoles = GetAllRoles(); ErpRole existingRole = allRoles.SingleOrDefault(x => x.Id == role.Id); ValidationException valEx = new ValidationException(); if (existingRole != null) { record["id"] = role.Id; record["description"] = role.Description; if (existingRole.Name != role.Name) { record["name"] = role.Name; if (string.IsNullOrWhiteSpace(role.Name)) valEx.AddError("name", "Name is required."); else if (allRoles.Any(x => x.Name == role.Name)) valEx.AddError("name", "Role with same name already exists"); } valEx.CheckAndThrow(); var response = recMan.UpdateRecord("role", record); if (!response.Success) throw new Exception(response.Message); } else { record["id"] = role.Id; record["description"] = role.Description; record["name"] = role.Name; if (string.IsNullOrWhiteSpace(role.Name)) valEx.AddError("name", "Name is required."); else if (allRoles.Any(x => x.Name == role.Name)) valEx.AddError("name", "Role with same name already exists"); valEx.CheckAndThrow(); var response = recMan.CreateRecord("role", record); if (!response.Success) throw new Exception(response.Message); } }
private void ThrowValidationException <T>(Expression <Func <T, object> > property, string message) where T : class { var ex = new ValidationException(); ex.AddError <T>(property, message); throw ex; }
public IActionResult OnPost() { if (!ModelState.IsValid) { throw new Exception("Antiforgery check failed."); } var initResult = Init(); if (initResult != null) { return(initResult); } InitEntitySelectOptions(); try { ValidationException valEx = new ValidationException(); if (string.IsNullOrWhiteSpace(ConnectionString)) { valEx.AddError("ConnectionString", "Original database connection string is required."); ShowResults = false; throw valEx; } var conString = ConnectionString; if (!ConnectionString.Contains(";")) { NpgsqlConnectionStringBuilder builder = new NpgsqlConnectionStringBuilder(ErpSettings.ConnectionString); builder.Database = ConnectionString; conString = builder.ToString(); } var cgService = new CodeGenService(); var result = cgService.EvaluateMetaChanges(conString, IncludeRecordsEntityIdList, IncludeEntityMeta, IncludeEntityRelations, IncludeUserRoles, IncludeApplications); Code = result.Code; Changes = result.Changes; ShowResults = true; } catch (ValidationException valEx) { Validation.Message = valEx.Message; Validation.Errors.AddRange(valEx.Errors); ShowResults = false; } catch (Exception ex) { Validation.Message = ex.Message; Validation.AddError("", ex.Message); ShowResults = false; } BeforeRender(); return(Page()); }
public void QueueEmail(string toName, string toEmail, string subject, string textBody, string htmlBody, EmailPriority priority) { ValidationException ex = new ValidationException(); if (string.IsNullOrEmpty(toEmail)) { ex.AddError("toEmail", "ToEmail is not specified."); } else if (toEmail.IsEmail()) { ex.AddError("toEmail", "ToEmail is not valid email address."); } if (string.IsNullOrEmpty(subject)) { ex.AddError("subject", "Subject is required."); } ex.CheckAndThrow(); Email email = new Email(); email.Id = Guid.NewGuid(); email.FromEmail = DefaultFromEmail; email.FromName = DefaultFromName; email.ReplyToEmail = DefaultReplyToEmail; email.ToEmail = toEmail; email.ToName = toName; email.Subject = subject; email.ContentHtml = htmlBody; email.ContentText = textBody; email.CreatedOn = DateTime.UtcNow; email.SentOn = null; email.Priority = priority; email.Status = EmailStatus.Pending; email.ServerError = string.Empty; email.ScheduledOn = email.CreatedOn; email.RetriesCount = 0; email.ServiceId = Id; new SmtpInternalService().SaveEmail(email); }
/// <summary> /// Deletes application with all related data /// </summary> /// <param name="id"></param> /// <param name="transaction"></param> public void DeleteApplication(Guid id, NpgsqlTransaction transaction = null, bool cascade = true) { ValidationException vex = new ValidationException(); var app = repository.GetById(id, transaction); if (app == null) { vex.AddError("id", "There is no application with specified identifier."); } vex.CheckAndThrow(); if (transaction == null) { using (NpgsqlConnection con = new NpgsqlConnection(ErpSettings.ConnectionString)) { NpgsqlTransaction trans = null; try { con.Open(); trans = con.BeginTransaction(); DeleteApplicationInternal(id, cascade, trans); trans.Commit(); } catch (Exception) { if (trans != null) { trans.Rollback(); } throw; } finally { con.Close(); } } } else { DeleteApplicationInternal(id, cascade, transaction); } }
public IActionResult SetTaskRecurrenceOnPost(RecordDetailsPageModel pageModel) { ValidationException valEx = new ValidationException(); if (!pageModel.HttpContext.Request.Form.ContainsKey("recurrence_template")) { valEx.AddError("recurrence_template", "Recurrence settings missing in post data"); throw valEx; } DateTime startTime = DateTime.Today; DateTime endTime = DateTime.Today; if (!pageModel.HttpContext.Request.Form.ContainsKey("start_time")) { valEx.AddError("start_time", "Start time is required"); } else if (!DateTime.TryParse(pageModel.HttpContext.Request.Form["start_time"], out startTime)) { valEx.AddError("start_time", "Start time is required"); } if (!pageModel.HttpContext.Request.Form.ContainsKey("end_time")) { valEx.AddError("end_time", "End time is required"); } else if (!DateTime.TryParse(pageModel.HttpContext.Request.Form["start_time"], out endTime)) { valEx.AddError("end_time", "End time is required"); } valEx.CheckAndThrow(); if (startTime < DateTime.Today) { valEx.AddError("start_time", "Start time should be today or any future date."); } //because in this case we post dates, we need to move time to the end of the day endTime = endTime.AddHours(23).AddMinutes(59).AddSeconds(59); if (endTime <= startTime) { valEx.AddError("end_time", "End time should be today or any future date."); } //todo validate status ?? //todo validate completed on ?? valEx.CheckAndThrow(); //EntityRecord taskRecord = (EntityRecord)pageModel.DataModel.GetProperty("Record"); //if (taskRecord["recurrence_id"] == null) //{ // Guid recurrenceId = Guid.NewGuid(); // RecurrenceTemplate recurrenceData = JsonConvert.DeserializeObject<RecurrenceTemplate>(pageModel.HttpContext.Request.Form["recurrence_template"]); // var occurrences = recurrenceData.CalculateOccurrences(startTime, endTime, startTime, startTime.AddYears(5) ); // foreach (var o in occurrences) // { // var ocStartTime = o.Period.StartTime.AsDateTimeOffset.DateTime; // var ocEndTime = o.Period.EndTime.AsDateTimeOffset.DateTime; // EntityRecord newTask = new EntityRecord(); // newTask["id"] = Guid.NewGuid(); // newTask["start_time"] = ocStartTime; // newTask["end_time"] = ocEndTime; // newTask["l_scope"] = taskRecord["l_scope"]; // newTask["subject"] = taskRecord["subject"]; // newTask["body"] = taskRecord["body"]; // newTask["owner_id"] = taskRecord["owner_id"]; // newTask["created_on"] = taskRecord["created_on"]; // newTask["created_by"] = taskRecord["created_by"]; // newTask["completed_on"] = null; // newTask["parent_id"] = taskRecord["parent_id"]; // newTask["status_id"] = taskRecord["status_id"]; // ??set always as pending // newTask["priority"] = taskRecord["priority"]; // newTask["type_id"] = taskRecord["type_id"]; // newTask["key"] = Guid.NewGuid().ToString(); //set as unique guid text, post create hook will update it // newTask["x_billable_minutes"] = 0; // newTask["x_nonbillable_minutes"] = 0; // newTask["estimated_minutes"] = taskRecord["estimated_minutes"]; // newTask["timelog_started_on"] = null; // newTask["recurrence_id"] = recurrenceId; // newTask["reserve_time"] = taskRecord["reserve_time"]; // newTask["recurrence_template"] = JsonConvert.SerializeObject(recurrenceData); // //Debug.WriteLine($"{o.Period.StartTime}-{o.Period.EndTime}"); // } //} //else //{ // //UPDATE RECURRENCE CHAIN //} return(null); }
public IActionResult TestSmtpServiceOnPost(RecordDetailsPageModel pageModel) { SmtpService smtpService = null; string recipientEmail = string.Empty; string subject = string.Empty; string content = string.Empty; ValidationException valEx = new ValidationException(); if (pageModel.HttpContext.Request.Form == null) { valEx.AddError("form", "Smtp service test page missing form tag"); valEx.CheckAndThrow(); } if (!pageModel.HttpContext.Request.Form.ContainsKey("recipient_email")) { valEx.AddError("recipient_email", "Recipient email is not specified."); } else { recipientEmail = pageModel.HttpContext.Request.Form["recipient_email"]; if (string.IsNullOrWhiteSpace(recipientEmail)) { valEx.AddError("recipient_email", "Recipient email is not specified"); } else if (!recipientEmail.IsEmail()) { valEx.AddError("recipient_email", "Recipient email is not a valid email address"); } } if (!pageModel.HttpContext.Request.Form.ContainsKey("subject")) { valEx.AddError("subject", "Subject is not specified"); } else { subject = pageModel.HttpContext.Request.Form["subject"]; if (string.IsNullOrWhiteSpace(subject)) { valEx.AddError("subject", "Subject is required"); } } if (!pageModel.HttpContext.Request.Form.ContainsKey("content")) { valEx.AddError("content", "Content is not specified"); } else { content = pageModel.HttpContext.Request.Form["content"]; if (string.IsNullOrWhiteSpace(content)) { valEx.AddError("content", "Content is required"); } } var smtpServiceId = pageModel.DataModel.GetProperty("Record.id") as Guid?; if (smtpServiceId == null) { valEx.AddError("serviceId", "Invalid smtp service id"); } else { smtpService = new EmailServiceManager().GetSmtpService(smtpServiceId.Value); if (smtpService == null) { valEx.AddError("serviceId", "Smtp service with specified id does not exist"); } } List <string> attachments = new List <string>(); if (pageModel.HttpContext.Request.Form.ContainsKey("attachments")) { var ids = pageModel.HttpContext.Request.Form["attachments"].ToString().Split(",", StringSplitOptions.RemoveEmptyEntries).Select(x => new Guid(x)); foreach (var id in ids) { var fileRecord = new EqlCommand("SELECT name,path FROM user_file WHERE id = @id", new EqlParameter("id", id)).Execute().FirstOrDefault(); if (fileRecord != null) { attachments.Add((string)fileRecord["path"]); } } } //we set current record to store properties which don't exist in current entity EntityRecord currentRecord = pageModel.DataModel.GetProperty("Record") as EntityRecord; currentRecord["recipient_email"] = recipientEmail; currentRecord["subject"] = subject; currentRecord["content"] = content; pageModel.DataModel.SetRecord(currentRecord); valEx.CheckAndThrow(); try { EmailAddress recipient = new EmailAddress(recipientEmail); smtpService.SendEmail(recipient, subject, string.Empty, content, attachments: attachments); pageModel.TempData.Put("ScreenMessage", new ScreenMessage() { Message = "Email was successfully sent", Type = ScreenMessageType.Success, Title = "Success" }); var returnUrl = pageModel.HttpContext.Request.Query["returnUrl"]; return(new RedirectResult($"/mail/services/smtp/r/{smtpService.Id}/details?returnUrl={returnUrl}")); } catch (Exception ex) { valEx.AddError("", ex.Message); valEx.CheckAndThrow(); return(null); } }
private dynamic ParsePostData() { var formData = HttpContext.Request.Form; dynamic rec = new ExpandoObject(); ValidationException validation = new ValidationException(); DataSourceManager dsMan = new DataSourceManager(); DataSourceBase dataSource = null; rec.IsDeleteAction = false; //handle delete if (formData.ContainsKey("action") && formData["action"] == "delete") { rec.IsDeleteAction = true; rec.PageDataSourceId = (Guid?)null; if (formData.ContainsKey("page_datasource_id") && !string.IsNullOrWhiteSpace(formData["page_datasource_id"])) { Guid pageDataSourceId; if (Guid.TryParse(formData["page_datasource_id"], out pageDataSourceId)) { rec.PageDataSourceId = pageDataSourceId; } else { validation.AddError("page_datasource_id", "Specified page data source id is not in valid GUID format."); } } validation.CheckAndThrow(); return(rec); } //continue with create or update parse rec.PageDataSourceId = (Guid?)null; if (formData.ContainsKey("page_datasource_id") && !string.IsNullOrWhiteSpace(formData["page_datasource_id"])) { Guid pageDataSourceId; if (Guid.TryParse(formData["page_datasource_id"], out pageDataSourceId)) { rec.PageDataSourceId = pageDataSourceId; } else { validation.AddError("page_datasource_id", "Specified page data source id is not in valid GUID format."); } } if (formData.ContainsKey("page_id") && !string.IsNullOrWhiteSpace(formData["page_id"])) { Guid pageId; if (Guid.TryParse(formData["page_id"], out pageId)) { rec.PageId = pageId; } else { validation.AddError("page_id", "Specified page id is not in valid GUID format."); } } else { validation.AddError("page_id", "Page id is not specified."); } if (formData.ContainsKey("datasource_id") && !string.IsNullOrWhiteSpace(formData["datasource_id"])) { Guid datasourceId; if (Guid.TryParse(formData["datasource_id"], out datasourceId)) { rec.DataSourceId = datasourceId; dataSource = dsMan.Get(datasourceId); if (dataSource == null) { validation.AddError("datasource_id", "Specified datasource id is not found in database."); } } else { validation.AddError("datasource_id", "Specified datasource id is not in valid GUID format."); } } else { validation.AddError("datasource_id", "Datasource id is not specified."); } if (formData.ContainsKey("page_datasource_name") && !string.IsNullOrWhiteSpace(formData["page_datasource_name"])) { rec.Name = formData["page_datasource_name"]; } else { validation.AddError("page_datasource_name", "Page datasource name is not specified."); } validation.CheckAndThrow(); List <DataSourceParameter> parameters = new List <DataSourceParameter>(); foreach (var par in dataSource.Parameters) { var htmlKey = "@_" + par.Name; if (formData.Keys.Contains(htmlKey) && !string.IsNullOrWhiteSpace(formData[htmlKey])) { DataSourceParameter parameter = new DataSourceParameter(); parameter.Name = par.Name; parameter.Type = par.Type; parameter.Value = formData[htmlKey]; parameters.Add(parameter); } } rec.Parameters = parameters; return(rec); }
public void QueueEmail(EmailAddress recipient, EmailAddress sender, string replyTo, string subject, string textBody, string htmlBody, EmailPriority priority = EmailPriority.Normal, List <string> attachments = null) { ValidationException ex = new ValidationException(); if (recipient == null) { ex.AddError("recipientEmail", "Recipient is not specified."); } else { var address = recipient.Address; if (address.StartsWith("cc:")) { address = address.Substring(3); } if (address.StartsWith("bcc:")) { address = address.Substring(4); } if (string.IsNullOrEmpty(address)) { ex.AddError("recipientEmail", "Recipient email is not specified."); } else if (!address.IsEmail()) { ex.AddError("recipientEmail", "Recipient email is not valid email address."); } } if (!string.IsNullOrWhiteSpace(replyTo)) { if (!replyTo.IsEmail()) { ex.AddError("recipientEmail", "Reply To email is not valid email address."); } } if (string.IsNullOrEmpty(subject)) { ex.AddError("subject", "Subject is required."); } ex.CheckAndThrow(); Email email = new Email(); email.Id = Guid.NewGuid(); email.Sender = sender ?? new EmailAddress { Address = DefaultSenderEmail, Name = DefaultSenderName }; if (string.IsNullOrWhiteSpace(replyTo)) { email.ReplyToEmail = DefaultReplyToEmail; } else { email.ReplyToEmail = replyTo; } email.Recipients = new List <EmailAddress> { recipient }; email.Subject = subject; email.ContentHtml = htmlBody; email.ContentText = textBody; email.CreatedOn = DateTime.UtcNow; email.SentOn = null; email.Priority = priority; email.Status = EmailStatus.Pending; email.ServerError = string.Empty; email.ScheduledOn = email.CreatedOn; email.RetriesCount = 0; email.ServiceId = Id; email.Attachments = new List <string>(); if (attachments != null && attachments.Count > 0) { DbFileRepository fsRepository = new DbFileRepository(); foreach (var att in attachments) { var filepath = att; if (!filepath.StartsWith("/")) { filepath = "/" + filepath; } filepath = filepath.ToLowerInvariant(); if (filepath.StartsWith("/fs")) { filepath = filepath.Substring(3); } var file = fsRepository.Find(filepath); if (file == null) { throw new Exception($"Attachment file '{filepath}' not found."); } email.Attachments.Add(filepath); } } new SmtpInternalService().SaveEmail(email); }
public void SendEmail(EmailAddress recipient, string subject, string textBody, string htmlBody, List <string> attachments) { ValidationException ex = new ValidationException(); if (recipient == null) { ex.AddError("recipientEmail", "Recipient is not specified."); } else { if (string.IsNullOrEmpty(recipient.Address)) { ex.AddError("recipientEmail", "Recipient email is not specified."); } else if (!recipient.Address.IsEmail()) { ex.AddError("recipientEmail", "Recipient email is not valid email address."); } } if (string.IsNullOrEmpty(subject)) { ex.AddError("subject", "Subject is required."); } ex.CheckAndThrow(); var message = new MimeMessage(); if (!string.IsNullOrWhiteSpace(DefaultSenderName)) { message.From.Add(new MailboxAddress(DefaultSenderName, DefaultSenderEmail)); } else { message.From.Add(new MailboxAddress(DefaultSenderEmail)); } if (!string.IsNullOrWhiteSpace(recipient.Name)) { message.To.Add(new MailboxAddress(recipient.Name, recipient.Address)); } else { message.To.Add(new MailboxAddress(recipient.Address)); } if (!string.IsNullOrWhiteSpace(DefaultReplyToEmail)) { message.ReplyTo.Add(new MailboxAddress(DefaultReplyToEmail)); } message.Subject = subject; var bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = htmlBody; bodyBuilder.TextBody = textBody; if (attachments != null && attachments.Count > 0) { foreach (var att in attachments) { var filepath = att; if (!filepath.StartsWith("/")) { filepath = "/" + filepath; } filepath = filepath.ToLowerInvariant(); if (filepath.StartsWith("/fs")) { filepath = filepath.Substring(3); } DbFileRepository fsRepository = new DbFileRepository(); var file = fsRepository.Find(filepath); var bytes = file.GetBytes(); var extension = Path.GetExtension(filepath).ToLowerInvariant(); new FileExtensionContentTypeProvider().Mappings.TryGetValue(extension, out string mimeType); var attachment = new MimePart(mimeType) { Content = new MimeContent(new MemoryStream(bytes)), ContentDisposition = new ContentDisposition(ContentDisposition.Attachment), ContentTransferEncoding = ContentEncoding.Base64, FileName = Path.GetFileName(filepath) }; bodyBuilder.Attachments.Add(attachment); } } SmtpInternalService.ProcessHtmlContent(bodyBuilder); message.Body = bodyBuilder.ToMessageBody(); using (var client = new SmtpClient()) { //accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect(Server, Port, ConnectionSecurity); if (!string.IsNullOrWhiteSpace(Username)) { client.Authenticate(Username, Password); } client.Send(message); client.Disconnect(true); } Email email = new Email(); email.Id = Guid.NewGuid(); email.Sender = new EmailAddress { Address = DefaultSenderEmail, Name = DefaultSenderName }; email.ReplyToEmail = DefaultReplyToEmail; email.Recipients = new List <EmailAddress> { recipient }; email.Subject = subject; email.ContentHtml = htmlBody; email.ContentText = textBody; email.CreatedOn = DateTime.UtcNow; email.SentOn = email.CreatedOn; email.Priority = EmailPriority.Normal; email.Status = EmailStatus.Sent; email.ServerError = string.Empty; email.ScheduledOn = null; email.RetriesCount = 0; email.ServiceId = Id; if (attachments != null && attachments.Count > 0) { DbFileRepository fsRepository = new DbFileRepository(); foreach (var att in attachments) { var filepath = att; if (!filepath.StartsWith("/")) { filepath = "/" + filepath; } filepath = filepath.ToLowerInvariant(); if (filepath.StartsWith("/fs")) { filepath = filepath.Substring(3); } var file = fsRepository.Find(filepath); if (file == null) { throw new Exception($"Attachment file '{filepath}' not found."); } email.Attachments.Add(filepath); } } new SmtpInternalService().SaveEmail(email); }
public void SendEmail(EmailAddress recipient, string subject, string textBody, string htmlBody) { ValidationException ex = new ValidationException(); if (recipient == null) { ex.AddError("recipientEmail", "Recipient is not specified."); } else { if (string.IsNullOrEmpty(recipient.Address)) { ex.AddError("recipientEmail", "Recipient email is not specified."); } else if (!recipient.Address.IsEmail()) { ex.AddError("recipientEmail", "Recipient email is not valid email address."); } } if (string.IsNullOrEmpty(subject)) { ex.AddError("subject", "Subject is required."); } ex.CheckAndThrow(); var message = new MimeMessage(); if (!string.IsNullOrWhiteSpace(DefaultSenderName)) { message.From.Add(new MailboxAddress(DefaultSenderName, DefaultSenderEmail)); } else { message.From.Add(new MailboxAddress(DefaultSenderEmail)); } if (!string.IsNullOrWhiteSpace(recipient.Name)) { message.To.Add(new MailboxAddress(recipient.Name, recipient.Address)); } else { message.To.Add(new MailboxAddress(recipient.Address)); } if (!string.IsNullOrWhiteSpace(DefaultReplyToEmail)) { message.ReplyTo.Add(new MailboxAddress(DefaultReplyToEmail)); } message.Subject = subject; var bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = htmlBody; bodyBuilder.TextBody = textBody; message.Body = bodyBuilder.ToMessageBody(); using (var client = new SmtpClient()) { //accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect(Server, Port, ConnectionSecurity); if (!string.IsNullOrWhiteSpace(Username)) { client.Authenticate(Username, Password); } client.Send(message); client.Disconnect(true); } Email email = new Email(); email.Id = Guid.NewGuid(); email.Sender = new EmailAddress { Address = DefaultSenderEmail, Name = DefaultSenderName }; email.ReplyToEmail = DefaultReplyToEmail; email.Recipients = new List <EmailAddress> { recipient }; email.Subject = subject; email.ContentHtml = htmlBody; email.ContentText = textBody; email.CreatedOn = DateTime.UtcNow; email.SentOn = email.CreatedOn; email.Priority = EmailPriority.Normal; email.Status = EmailStatus.Sent; email.ServerError = string.Empty; email.ScheduledOn = null; email.RetriesCount = 0; email.ServiceId = Id; new SmtpInternalService().SaveEmail(email); }
public ClsUserDetails CheckUserIDPassword(string userID, string password) { ValidationException valex = new ValidationException(); UserMaster Table = new UserMaster(); if (userID.IsNullOrWhiteSpace() && password.IsNullOrWhiteSpace()) { valex.AddError("Please Enter UserID And Password"); } else if (userID.IsNullOrWhiteSpace()) { valex.AddError("Please Enter UserID"); } else if (password.IsNullOrWhiteSpace()) { valex.AddError("Please Enter Password"); } if (valex.errorList.IsNotEmpty()) { throw valex; } DataSet ds = Table.GetUserDetailsByCredentials(userID, Encrypt(password)); if (IsvalidDataset(ds)) { if (ds.Tables[0].Rows[0]["nID"].IsNotNull()) { int id = ds.Tables[0].Rows[0]["nID"].ToString().ToInt(); if (id > 0) { ClsUserDetails details = new ClsUserDetails(); //details.UserRowID = id; if (ds.Tables[0].Rows[0]["nID"].IsNotNull()) { details.UserID = ds.Tables[0].Rows[0]["nID"].ToString(); } if (ds.Tables[0].Rows[0]["cFullName"].IsNotNull()) { details.UserName = ds.Tables[0].Rows[0]["cFullName"].ToString(); } if (ds.Tables[0].Rows[0]["cShortID"].IsNotNull()) { details.ShortID = ds.Tables[0].Rows[0]["cShortID"].ToString(); } if (ds.Tables[0].Rows[0]["cMailId"].IsNotNull()) { details.Email = ds.Tables[0].Rows[0]["cMailId"].ToString(); } if (ds.Tables[0].Rows[0]["cContactNumber"].IsNotNull()) { details.ContactNo = ds.Tables[0].Rows[0]["cContactNumber"].ToString(); } if (ds.Tables[0].Rows[0]["cPassword"].IsNotNull()) { details.Password = Decrypt(ds.Tables[0].Rows[0]["cPassword"].ToString()); } if (ds.Tables[0].Rows[0]["nLevelID"].IsNotNull()) { details.LeveID = Convert.ToInt32(ds.Tables[0].Rows[0]["nLevelID"].ToString()); } if (ds.Tables[0].Rows[0]["nDesignationID"].IsNotNull()) { details.DesignationID = Convert.ToInt32(ds.Tables[0].Rows[0]["nDesignationID"].ToString()); } if (ds.Tables[0].Rows[0]["nDepartmentID"].IsNotNull()) { details.DepartmentID = Convert.ToInt32(ds.Tables[0].Rows[0]["nDepartmentID"].ToString()); } return(details); } } } else { valex.AddError("Incorrect User Name or Password"); throw valex; } return(null); }
public void UpdateUserDetails(int argnID, string argUsername, string argUserShortID, string argPassword, int argDepartID, string argContactNumber, string argEmail, int argDesignationID, int argLevelID, int argCreatedBy) { ValidationException error = new ValidationException(); UserMaster Table = new UserMaster(); if (Validations.IsEmpty(argUserShortID)) { error.AddError("Enter Short ID"); } if (Validations.IsEmpty(argUsername)) { error.AddError("Enter User Name"); } if (Validations.IsEmpty(argPassword)) { error.AddError("Enter Password"); } if (Validations.IsEmpty(argContactNumber)) { error.AddError("Enter ContactNumber"); } if (Validations.IsEmpty(argEmail)) { error.AddError("Enter Email"); } if (!Validations.IsEmail(argEmail, true).IsValid) { error.AddError("Enter Valid Email ID"); } if (!Validations.IsNumber(argContactNumber)) { error.AddError("Enter Number only"); } if (!error.isValid) { throw error; } DataSet DSUserCheck = Table.CheckshortID(argUsername); if (DSUserCheck != null && DSUserCheck.Tables.Count > 0) { if (int.Parse(DSUserCheck.Tables[0].Rows[0]["Cnt"].ToString()) > 0) { throw new UserNonAvailabiltyException(); } else { Table.Connection.beginTransact(); } } try { Table.UpdateUserDetails(argnID, argUsername, argUserShortID, argPassword.Encrypt(), argDepartID, argContactNumber, argEmail, argDesignationID, argLevelID, argCreatedBy); Table.Connection.commit(); } catch (Exception ex) { Table.Connection.rollback(); throw ex; } }
public DatabaseDataSource Update(Guid id, string name, string description, int weight, string eql, string parameters) { ValidationException validation = new ValidationException(); if (string.IsNullOrWhiteSpace(eql)) { throw new ArgumentException(nameof(eql)); } List <EqlParameter> eqlParams = new List <EqlParameter>(); List <DataSourceParameter> dsParams = new List <DataSourceParameter>(); if (!string.IsNullOrWhiteSpace(parameters)) { dsParams = ProcessParametersText(parameters); foreach (var dsPar in dsParams) { eqlParams.Add(ConvertDataSourceParameterToEqlParameter(dsPar)); } } EqlBuilder builder = new EqlBuilder(eql); var result = builder.Build(eqlParams); if (result.Errors.Count > 0) { foreach (var err in result.Errors) { if (err.Line.HasValue || err.Column.HasValue) { validation.AddError("eql", $"{err.Message} [{err.Line},{err.Column}]"); } else { validation.AddError("eql", err.Message); } } } validation.CheckAndThrow(); foreach (var par in result.Parameters) { if (!eqlParams.Any(x => x.ParameterName == par.ParameterName)) { validation.AddError("parameters", $"Parameter '{par.ParameterName}' is missing."); } } validation.CheckAndThrow(); DatabaseDataSource ds = new DatabaseDataSource(); ds.Id = id; ds.Name = name; ds.Description = description; ds.EqlText = eql; ds.SqlText = result.Sql; ds.EntityName = result.FromEntity.Name; ds.Parameters.AddRange(dsParams); ds.Fields.AddRange(ProcessFieldsMeta(result.Meta)); if (string.IsNullOrWhiteSpace(ds.Name)) { validation.AddError("name", "Name is required."); } else { var existingDS = GetDatabaseDataSourceByName(ds.Name); if (existingDS != null && existingDS.Id != ds.Id) { validation.AddError("name", "Another DataSource with same name already exists."); } } if (string.IsNullOrWhiteSpace(ds.EqlText)) { validation.AddError("eql", "Eql is required."); } if (string.IsNullOrWhiteSpace(ds.SqlText)) { validation.AddError("sql", "Sql is required."); } validation.CheckAndThrow(); rep.Update(ds.Id, ds.Name, ds.Description, ds.Weight, ds.EqlText, ds.SqlText, JsonConvert.SerializeObject(ds.Parameters), JsonConvert.SerializeObject(ds.Fields), ds.EntityName); RemoveFromCache(); return(GetDatabaseDataSourceById(ds.Id)); }
public List <EntityRecord> GetTimelogData(int year, int month, Guid?accountId) { ValidationException valEx = new ValidationException(); if (month > 12 || month <= 0) { valEx.AddError("month", "Invalid month."); } if (year <= 0) { valEx.AddError("year", "Invalid year."); } List <EqlParameter> eqlParams; if (accountId.HasValue) { eqlParams = new List <EqlParameter>() { new EqlParameter("id", accountId.Value) }; var eqlResult = new EqlCommand("SELECT * FROM account WHERE id = @id ", eqlParams).Execute(); if (!eqlResult.Any()) { valEx.AddError("accountId", $"Account with ID:{accountId} not found."); } } valEx.CheckAndThrow(); /// load timelog records from database DateTime fromDate = new DateTime(year, month, 1); DateTime toDate = new DateTime(year, month, DateTime.DaysInMonth(year, month)); eqlParams = new List <EqlParameter>() { new EqlParameter("from_date", fromDate), new EqlParameter("to_date", toDate), new EqlParameter("scope", "projects"), }; string eql = @"SELECT id,is_billable,l_related_records,minutes FROM timelog WHERE logged_on >= @from_date AND logged_on <= @to_date AND l_scope CONTAINS @scope" ; var timelogRecords = new EqlCommand(eql, eqlParams).Execute(); HashSet <Guid> setOfTasksWithTimelog = new HashSet <Guid>(); foreach (var timelog in timelogRecords) { List <Guid> ids = JsonConvert.DeserializeObject <List <Guid> >((string)timelog["l_related_records"]); Guid taskId = ids[0]; timelog["task_id"] = taskId; if (!setOfTasksWithTimelog.Contains(taskId)) { setOfTasksWithTimelog.Add(taskId); } } //load all tasks eqlParams = new List <EqlParameter>(); eql = @"SELECT id,subject, $project_nn_task.id, $project_nn_task.name,$project_nn_task.account_id, $task_type_1n_task.label FROM task"; var tasks = new EqlCommand(eql, eqlParams).Execute(); //process tasks - split records for projects - filter by account - filter by timelog EntityRecordList processedTasks = new EntityRecordList(); foreach (var task in tasks) { //skip task that has no timelog record if (!setOfTasksWithTimelog.Contains((Guid)task["id"])) { continue; } List <EntityRecord> taskProjects = (List <EntityRecord>)task["$project_nn_task"]; //skip tasks with no project if (taskProjects.Count == 0) { continue; } //split tasks to projects if more than one project is related to task foreach (var project in taskProjects) { if (accountId != null) { if ((Guid)project["account_id"] == accountId) { task["project"] = project; processedTasks.Add(task); } } else { task["project"] = project; processedTasks.Add(task); } } } tasks = processedTasks; tasks.TotalCount = processedTasks.Count; List <EntityRecord> result = new List <EntityRecord>(); foreach (var task in tasks) { EntityRecord rec = new EntityRecord(); rec["task_id"] = task["id"]; rec["project_id"] = ((EntityRecord)task["project"])["id"]; rec["task_subject"] = task["subject"]; rec["project_name"] = ((EntityRecord)task["project"])["name"]; rec["task_type"] = ((List <EntityRecord>)task["$task_type_1n_task"])[0]["label"]; rec["billable_minutes"] = (decimal)0; rec["non_billable_minutes"] = (decimal)0; //during development //rec["task"] = task; //rec["project"] = (EntityRecord)task["project"]; foreach (var timelog in timelogRecords) { if ((Guid)timelog["task_id"] != (Guid)task["id"]) { continue; } if ((bool)timelog["is_billable"]) { rec["billable_minutes"] = (decimal)rec["billable_minutes"] + (decimal)timelog["minutes"]; } else { rec["non_billable_minutes"] = (decimal)rec["non_billable_minutes"] + (decimal)timelog["minutes"]; } } result.Add(rec); } return(result); }
public IActionResult TestSmtpServiceOnPost(RecordDetailsPageModel pageModel) { SmtpService smtpService = null; string recipientEmail = string.Empty; string subject = string.Empty; string content = string.Empty; ValidationException valEx = new ValidationException(); if (pageModel.HttpContext.Request.Form == null) { valEx.AddError("form", "Smtp service test page missing form tag"); valEx.CheckAndThrow(); } if (!pageModel.HttpContext.Request.Form.ContainsKey("recipient_email")) { valEx.AddError("recipient_email", "Recipient email is not specified."); } else { recipientEmail = pageModel.HttpContext.Request.Form["recipient_email"]; if (string.IsNullOrWhiteSpace(recipientEmail)) { valEx.AddError("recipient_email", "Recipient email is not specified"); } else if (!recipientEmail.IsEmail()) { valEx.AddError("recipient_email", "Recipient email is not a valid email address"); } } if (!pageModel.HttpContext.Request.Form.ContainsKey("subject")) { valEx.AddError("subject", "Subject is not specified"); } else { subject = pageModel.HttpContext.Request.Form["subject"]; if (string.IsNullOrWhiteSpace(subject)) { valEx.AddError("subject", "Subject is required"); } } if (!pageModel.HttpContext.Request.Form.ContainsKey("content")) { valEx.AddError("content", "Content is not specified"); } else { content = pageModel.HttpContext.Request.Form["content"]; if (string.IsNullOrWhiteSpace(content)) { valEx.AddError("content", "Content is required"); } } var smtpServiceId = pageModel.DataModel.GetProperty("Record.id") as Guid?; if (smtpServiceId == null) { valEx.AddError("serviceId", "Invalid smtp service id"); } else { smtpService = new ServiceManager().GetSmtpService(smtpServiceId.Value); if (smtpService == null) { valEx.AddError("serviceId", "Smtp service with specified id does not exist"); } } //we set current record to store properties which don't exist in current entity EntityRecord currentRecord = pageModel.DataModel.GetProperty("Record") as EntityRecord; currentRecord["recipient_email"] = recipientEmail; currentRecord["subject"] = subject; currentRecord["content"] = content; pageModel.DataModel.SetRecord(currentRecord); valEx.CheckAndThrow(); try { smtpService.SendEmail(string.Empty, recipientEmail, subject, string.Empty, content); pageModel.TempData.Put("ScreenMessage", new ScreenMessage() { Message = "Email was successfully sent", Type = ScreenMessageType.Success, Title = "Success" }); var returnUrl = pageModel.HttpContext.Request.Query["returnUrl"]; return(new RedirectResult($"/mail/services/smtp/r/{smtpService.Id}/details?returnUrl={returnUrl}")); } catch (Exception ex) { valEx.AddError("", ex.Message); valEx.CheckAndThrow(); return(null); } }
public IActionResult OnPost() { if (!ModelState.IsValid) { throw new Exception("Antiforgery check failed."); } var initResult = Init(); if (initResult != null) { return(initResult); } InitPage(); try { Id = Plan.Id; Plan.Name = Name; Plan.StartDate = StartDate; Plan.EndDate = EndDate; Plan.Type = Type; if (StartDate.HasValue) { Plan.StartDate = StartDate.ConvertAppDateToUtc(); } else { Plan.StartDate = null; } if (EndDate.HasValue) { Plan.EndDate = EndDate.ConvertAppDateToUtc(); } else { Plan.EndDate = null; } if (StartTimespan.HasValue) { StartTimespan = StartTimespan.ConvertAppDateToUtc(); Plan.StartTimespan = StartTimespan.Value.Hour * 60 + StartTimespan.Value.Minute; } else { Plan.StartTimespan = null; } if (EndTimespan.HasValue) { EndTimespan = EndTimespan.ConvertAppDateToUtc(); Plan.EndTimespan = EndTimespan.Value.Hour * 60 + EndTimespan.Value.Minute; if (Plan.EndTimespan == 0) { Plan.EndTimespan = 1440; } } else { Plan.EndTimespan = null; } Plan.IntervalInMinutes = IntervalInMinutes; Plan.Enabled = Enabled; Plan.ScheduledDays.ScheduledOnMonday = false; Plan.ScheduledDays.ScheduledOnTuesday = false; Plan.ScheduledDays.ScheduledOnWednesday = false; Plan.ScheduledDays.ScheduledOnThursday = false; Plan.ScheduledDays.ScheduledOnFriday = false; Plan.ScheduledDays.ScheduledOnSaturday = false; Plan.ScheduledDays.ScheduledOnSunday = false; foreach (var schDay in ScheduledDays) { if (DayOfWeek.Monday.ToString() == schDay) { Plan.ScheduledDays.ScheduledOnMonday = true; } if (DayOfWeek.Tuesday.ToString() == schDay) { Plan.ScheduledDays.ScheduledOnTuesday = true; } if (DayOfWeek.Wednesday.ToString() == schDay) { Plan.ScheduledDays.ScheduledOnWednesday = true; } if (DayOfWeek.Thursday.ToString() == schDay) { Plan.ScheduledDays.ScheduledOnThursday = true; } if (DayOfWeek.Friday.ToString() == schDay) { Plan.ScheduledDays.ScheduledOnFriday = true; } if (DayOfWeek.Saturday.ToString() == schDay) { Plan.ScheduledDays.ScheduledOnSaturday = true; } if (DayOfWeek.Sunday.ToString() == schDay) { Plan.ScheduledDays.ScheduledOnSunday = true; } } ValidationException valEx = new ValidationException(); if (string.IsNullOrWhiteSpace(Name)) { valEx.AddError("Name", "Name is required field and cannot be empty."); } if (Plan.StartDate >= Plan.EndDate) { valEx.AddError("StartDate", "Start date must be before end date."); valEx.AddError("EndDate", "End date must be greater than start date."); } if ((Plan.Type == SchedulePlanType.Daily || Plan.Type == SchedulePlanType.Interval) && !Plan.ScheduledDays.HasOneSelectedDay()) { valEx.AddError("ScheduledDays", "At least one day have to be selected for schedule days field."); } if (Plan.Type == SchedulePlanType.Interval && (Plan.IntervalInMinutes <= 0 || Plan.IntervalInMinutes > 1440)) { valEx.AddError("IntervalInMinutes", "The value of Interval in minutes field must be greater than 0 and less or equal than 1440."); } valEx.CheckAndThrow(); if (Plan.Enabled) { Plan.NextTriggerTime = ScheduleManager.Current.FindSchedulePlanNextTriggerDate(Plan); } else { Plan.NextTriggerTime = null; } ScheduleManager.Current.UpdateSchedulePlan(Plan); BeforeRender(); return(Redirect(ReturnUrl)); } catch (ValidationException ex) { Validation.Message = ex.Message; Validation.Errors = ex.Errors; BeforeRender(); return(Page()); } }
public void SaveUser(ErpUser user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } RecordManager recMan = new RecordManager(); EntityRelationManager relMan = new EntityRelationManager(); EntityRecord record = new EntityRecord(); ErpUser existingUser = GetUser(user.Id); ValidationException valEx = new ValidationException(); if (existingUser != null) { record["id"] = user.Id; if (existingUser.Username != user.Username) { record["username"] = user.Username; if (string.IsNullOrWhiteSpace(user.Username)) { valEx.AddError("username", "Username is required."); } else if (GetUserByUsername(user.Username) != null) { valEx.AddError("username", "Username is already registered to another user. It must be unique."); } } if (existingUser.Email != user.Email) { record["email"] = user.Email; if (string.IsNullOrWhiteSpace(user.Email)) { valEx.AddError("email", "Email is required."); } else if (GetUser(user.Email) != null) { valEx.AddError("email", "Email is already registered to another user. It must be unique."); } else if (!IsValidEmail(user.Email)) { valEx.AddError("email", "Email is not valid."); } } if (existingUser.Password != user.Password && !string.IsNullOrWhiteSpace(user.Password)) { record["password"] = user.Password; } if (existingUser.Enabled != user.Enabled) { record["enabled"] = user.Enabled; } if (existingUser.Verified != user.Verified) { record["verified"] = user.Verified; } if (existingUser.FirstName != user.FirstName) { record["first_name"] = user.FirstName; } if (existingUser.LastName != user.LastName) { record["last_name"] = user.LastName; } if (existingUser.Image != user.Image) { record["image"] = user.Image; } record["$user_role.id"] = user.Roles.Select(x => x.Id).ToList(); valEx.CheckAndThrow(); var response = recMan.UpdateRecord("user", record); if (!response.Success) { throw new Exception(response.Message); } } else { record["id"] = user.Id; record["email"] = user.Email; record["username"] = user.Username; record["first_name"] = user.FirstName; record["last_name"] = user.LastName; record["enabled"] = user.Enabled; record["verified"] = user.Verified; record["image"] = user.Image; record["preferences"] = JsonConvert.SerializeObject(user.Preferences ?? new ErpUserPreferences()); if (string.IsNullOrWhiteSpace(user.Username)) { valEx.AddError("username", "Username is required."); } else if (GetUserByUsername(user.Username) != null) { valEx.AddError("username", "Username is already registered to another user. It must be unique."); } if (string.IsNullOrWhiteSpace(user.Email)) { valEx.AddError("email", "Email is required."); } else if (GetUser(user.Email) != null) { valEx.AddError("email", "Email is already registered to another user. It must be unique."); } else if (!IsValidEmail(user.Email)) { valEx.AddError("email", "Email is not valid."); } if (string.IsNullOrWhiteSpace(user.Password)) { valEx.AddError("password", "Password is required."); } else { record["password"] = user.Password; } record["$user_role.id"] = user.Roles.Select(x => x.Id).ToList(); valEx.CheckAndThrow(); var response = recMan.CreateRecord("user", record); if (!response.Success) { throw new Exception(response.Message); } } }