Skip to content

Commit

Permalink
fixes in EmailServiceEntity after merge
Browse files Browse the repository at this point in the history
  • Loading branch information
olmobrutall committed Oct 25, 2022
1 parent adb455f commit d9d219a
Show file tree
Hide file tree
Showing 15 changed files with 197 additions and 196 deletions.
8 changes: 4 additions & 4 deletions Signum.Engine.Extensions/Mailing/EmailLogic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public static EmailConfigurationEmbedded Configuration

static Func<EmailTemplateEntity?, Lite<Entity>?, EmailMessageEntity?, EmailSenderConfigurationEntity> getEmailSenderConfiguration = null!;

public static Polymorphic<Func<EmailSenderServiceConfigurationEntity, EmailSenderConfigurationEntity, BaseEmailSender>> EmailSenders = new ();
public static Polymorphic<Func<EmailServiceEntity, EmailSenderConfigurationEntity, BaseEmailSender>> EmailSenders = new ();
public static BaseEmailSender GetEmailSender(EmailMessageEntity email)
{
var template = email.Template?.Try(t => EmailTemplateLogic.EmailTemplatesLazy.Value.GetOrThrow(t));
Expand Down Expand Up @@ -77,9 +77,9 @@ public static void Start(

EmailLogic.getEmailSenderConfiguration = getEmailSenderConfiguration;

EmailSenders.Register((SmtpEntity s, EmailSenderConfigurationEntity c) => new SmtpSender(c, s));
EmailSenders.Register((MicrosoftGraphEntity s, EmailSenderConfigurationEntity c) => new MicrosoftGraphSender(c, s));
EmailSenders.Register((ExchangeWebServiceEntity s, EmailSenderConfigurationEntity c) => new ExchangeWebServiceSender(c, s));
EmailSenders.Register((SmtpEmailServiceEntity s, EmailSenderConfigurationEntity c) => new SmtpSender(c, s));
EmailSenders.Register((MicrosoftGraphEmailServiceEntity s, EmailSenderConfigurationEntity c) => new MicrosoftGraphSender(c, s));
EmailSenders.Register((ExchangeWebServiceEmailServiceEntity s, EmailSenderConfigurationEntity c) => new ExchangeWebServiceSender(c, s));

EmailGraph.Register();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ public static class EmailSenderConfigurationLogic

public static void Start(SchemaBuilder sb, Func<string, string>? encryptPassword = null, Func<string, string>? decryptPassword = null)
{
sb.Settings.AssertImplementedBy((EmailSenderConfigurationEntity o) => o.Service, typeof(SmtpEntity));
sb.Settings.AssertImplementedBy((EmailSenderConfigurationEntity o) => o.Service, typeof(ExchangeWebServiceEntity));
sb.Settings.AssertImplementedBy((EmailSenderConfigurationEntity o) => o.Service, typeof(MicrosoftGraphEntity));
sb.Settings.AssertImplementedBy((EmailSenderConfigurationEntity o) => o.Service, typeof(SmtpEmailServiceEntity));
sb.Settings.AssertImplementedBy((EmailSenderConfigurationEntity o) => o.Service, typeof(ExchangeWebServiceEmailServiceEntity));
sb.Settings.AssertImplementedBy((EmailSenderConfigurationEntity o) => o.Service, typeof(MicrosoftGraphEmailServiceEntity));

if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
Expand All @@ -27,6 +27,7 @@ public static void Start(SchemaBuilder sb, Func<string, string>? encryptPassword
DecryptPassword = decryptPassword;

sb.Include<EmailSenderConfigurationEntity>()
.WithDeletePart(a => a.Service, handleOnSaving: esc => true)
.WithQuery(() => s => new
{
Entity = s,
Expand Down Expand Up @@ -56,15 +57,15 @@ public static void Start(SchemaBuilder sb, Func<string, string>? encryptPassword

public static SmtpClient GenerateSmtpClient(this Lite<EmailSenderConfigurationEntity> config)
{
return (config.RetrieveFromCache().Service as SmtpEntity).ThrowIfNull("No SMTP config").GenerateSmtpClient();
return (config.RetrieveFromCache().Service as SmtpEmailServiceEntity).ThrowIfNull("No SMTP config").GenerateSmtpClient();
}

public static EmailSenderConfigurationEntity RetrieveFromCache(this Lite<EmailSenderConfigurationEntity> config)
{
return SmtpConfigCache.Value.GetOrThrow(config);
}

public static SmtpClient GenerateSmtpClient(this SmtpEntity config)
public static SmtpClient GenerateSmtpClient(this SmtpEmailServiceEntity config)
{
if (config.DeliveryMethod != SmtpDeliveryMethod.Network)
{
Expand Down
138 changes: 69 additions & 69 deletions Signum.Engine.Extensions/Mailing/Senders/ExchangeSender.cs
Original file line number Diff line number Diff line change
@@ -1,76 +1,76 @@
using Signum.Entities.Mailing;
using Signum.Engine.Authorization;
using Signum.Engine.Files;
using Microsoft.Exchange.WebServices.Data;
using Signum.Entities.Mailing;
using Signum.Engine.Authorization;
using Signum.Engine.Files;
using Microsoft.Exchange.WebServices.Data;

namespace Signum.Engine.Mailing.Senders;

public class ExchangeWebServiceSender : BaseEmailSender
{
ExchangeWebServiceEntity exchange;
namespace Signum.Engine.Mailing.Senders;

public ExchangeWebServiceSender(EmailSenderConfigurationEntity senderConfig, ExchangeWebServiceEntity service) : base(senderConfig)
public class ExchangeWebServiceSender : BaseEmailSender
{
ExchangeWebServiceEmailServiceEntity exchange;

public ExchangeWebServiceSender(EmailSenderConfigurationEntity senderConfig, ExchangeWebServiceEmailServiceEntity service) : base(senderConfig)
{
exchange = service;
}

protected override void SendInternal(EmailMessageEntity email)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.UseDefaultCredentials = exchange.UseDefaultCredentials;
service.Credentials = exchange.Username.HasText() ? new WebCredentials(exchange.Username, exchange.Password) : null;
//service.TraceEnabled = true;
//service.TraceFlags = TraceFlags.All;

if (exchange.Url.HasText())
service.Url = new Uri(exchange.Url);
else
service.AutodiscoverUrl(email.From.EmailAddress, RedirectionUrlValidationCallback);

EmailMessage message = new EmailMessage(service);

foreach (var a in email.Attachments.Where(a => a.Type == EmailAttachmentType.Attachment))
{
var fa = message.Attachments.AddFileAttachment(a.File.FileName, a.File.GetByteArray());
fa.ContentId = a.ContentId;
}
message.ToRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.To).Select(r => r.ToEmailAddress()).ToList());
message.CcRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Cc).Select(r => r.ToEmailAddress()).ToList());
message.BccRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Bcc).Select(r => r.ToEmailAddress()).ToList());
message.Subject = email.Subject;
message.Body = new MessageBody(email.IsBodyHtml ? BodyType.HTML : BodyType.Text, email.Body.Text);
message.Send();
}

protected virtual bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
return redirectionUri.Scheme == "https";
}
}

public static class ExchangeExtensions
{
public static EmailAddress ToEmailAddress(this EmailAddressEmbedded address)
{
if (address.DisplayName.HasText())
return new EmailAddress(address.DisplayName, address.EmailAddress);

return new EmailAddress(address.EmailAddress);
}

public static EmailAddress ToEmailAddress(this EmailRecipientEmbedded recipient)
{
if (!EmailLogic.Configuration.SendEmails)
throw new InvalidOperationException("EmailConfigurationEmbedded.SendEmails is set to false");

if (recipient.DisplayName.HasText())
return new EmailAddress(recipient.DisplayName, EmailLogic.Configuration.OverrideEmailAddress.DefaultText(recipient.EmailAddress));

return new EmailAddress(EmailLogic.Configuration.OverrideEmailAddress.DefaultText(recipient.EmailAddress));
}
}
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.UseDefaultCredentials = exchange.UseDefaultCredentials;
service.Credentials = exchange.Username.HasText() ? new WebCredentials(exchange.Username, exchange.Password) : null;
//service.TraceEnabled = true;
//service.TraceFlags = TraceFlags.All;

if (exchange.Url.HasText())
service.Url = new Uri(exchange.Url);
else
service.AutodiscoverUrl(email.From.EmailAddress, RedirectionUrlValidationCallback);

EmailMessage message = new EmailMessage(service);

foreach (var a in email.Attachments.Where(a => a.Type == EmailAttachmentType.Attachment))
{
var fa = message.Attachments.AddFileAttachment(a.File.FileName, a.File.GetByteArray());
fa.ContentId = a.ContentId;
}
message.ToRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.To).Select(r => r.ToEmailAddress()).ToList());
message.CcRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Cc).Select(r => r.ToEmailAddress()).ToList());
message.BccRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Bcc).Select(r => r.ToEmailAddress()).ToList());
message.Subject = email.Subject;
message.Body = new MessageBody(email.IsBodyHtml ? BodyType.HTML : BodyType.Text, email.Body.Text);
message.Send();
}

protected virtual bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
return redirectionUri.Scheme == "https";
}
}

public static class ExchangeExtensions
{
public static EmailAddress ToEmailAddress(this EmailAddressEmbedded address)
{
if (address.DisplayName.HasText())
return new EmailAddress(address.DisplayName, address.EmailAddress);

return new EmailAddress(address.EmailAddress);
}

public static EmailAddress ToEmailAddress(this EmailRecipientEmbedded recipient)
{
if (!EmailLogic.Configuration.SendEmails)
throw new InvalidOperationException("EmailConfigurationEmbedded.SendEmails is set to false");

if (recipient.DisplayName.HasText())
return new EmailAddress(recipient.DisplayName, EmailLogic.Configuration.OverrideEmailAddress.DefaultText(recipient.EmailAddress));

return new EmailAddress(EmailLogic.Configuration.OverrideEmailAddress.DefaultText(recipient.EmailAddress));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ namespace Signum.Engine.Mailing.Senders;
public class MicrosoftGraphSender : BaseEmailSender
{
public static long MicrosoftGraphFileSizeLimit = 3 * 1024 * 1024;
MicrosoftGraphEntity microsoftGraph;
MicrosoftGraphEmailServiceEntity microsoftGraph;

public MicrosoftGraphSender(EmailSenderConfigurationEntity senderConfig, MicrosoftGraphEntity service) : base(senderConfig)
public MicrosoftGraphSender(EmailSenderConfigurationEntity senderConfig, MicrosoftGraphEmailServiceEntity service) : base(senderConfig)
{
microsoftGraph = service;
}
Expand Down Expand Up @@ -170,7 +170,7 @@ public static IDisposable OverrideAuthenticationProvider(IAuthenticationProvider
return new Disposable(() => AuthenticationProvider.Value = old);
}

public static IAuthenticationProvider GetAuthProvider(this MicrosoftGraphEntity microsoftGraph, string[]? scopes = null)
public static IAuthenticationProvider GetAuthProvider(this MicrosoftGraphEmailServiceEntity microsoftGraph, string[]? scopes = null)
{
if (AuthenticationProvider.Value is var ap && ap != null)
return ap;
Expand Down
4 changes: 2 additions & 2 deletions Signum.Engine.Extensions/Mailing/Senders/SmtpSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ namespace Signum.Engine.Mailing.Senders;
public class SmtpSender: BaseEmailSender
{

SmtpEntity smtp;
SmtpEmailServiceEntity smtp;

public SmtpSender(EmailSenderConfigurationEntity senderConfig, SmtpEntity service) : base(senderConfig)
public SmtpSender(EmailSenderConfigurationEntity senderConfig, SmtpEmailServiceEntity service) : base(senderConfig)
{
smtp = service;
}
Expand Down
46 changes: 22 additions & 24 deletions Signum.Entities.Extensions/Mailing/EmailSenderConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ static EmailSenderConfigurationEntity()
DescriptionManager.ExternalEnums.Add(typeof(SmtpDeliveryFormat), m => m.Name);
DescriptionManager.ExternalEnums.Add(typeof(SmtpDeliveryMethod), m => m.Name);
DescriptionManager.ExternalEnums.Add(typeof(ExchangeVersion), m => m.Name);

}

[UniqueIndex]
Expand All @@ -24,29 +25,23 @@ static EmailSenderConfigurationEntity()
[NoRepeatValidator]
public MList<EmailRecipientEmbedded> AdditionalRecipients { get; set; } = new MList<EmailRecipientEmbedded>();

[ImplementedBy(typeof(SmtpEntity), typeof(ExchangeWebServiceEntity), typeof(MicrosoftGraphEntity))]
public EmailSenderServiceConfigurationEntity Service { get; set; }
[ImplementedBy(typeof(SmtpEmailServiceEntity), typeof(ExchangeWebServiceEmailServiceEntity), typeof(MicrosoftGraphEmailServiceEntity))]
public EmailServiceEntity Service { get; set; }

public override string ToString() => $"{Name} - {Service}";
[AutoExpressionField]
public override string ToString() => As.Expression(() => Name);

protected override string? ChildPropertyValidation(ModifiableEntity sender, PropertyInfo pi)
{
if (sender == DefaultFrom && pi.Name == nameof(DefaultFrom.AzureUserId))
{
if (DefaultFrom.AzureUserId == null && Service is MicrosoftGraphEntity microsoftGraph)
if (DefaultFrom.AzureUserId == null && Service is MicrosoftGraphEmailServiceEntity microsoftGraph)
return ValidationMessage._0IsMandatoryWhen1IsSet.NiceToString(pi.NiceName(), NicePropertyName(() => microsoftGraph));
}

return base.ChildPropertyValidation(sender, pi);
}

protected override bool IsPropertyReadonly(PropertyInfo pi)
{
if (!IsNew && pi.Name == nameof(Service))
return true;

return base.IsPropertyReadonly(pi);
}
public EmailSenderConfigurationEntity Clone()
{
return new EmailSenderConfigurationEntity
Expand All @@ -66,14 +61,16 @@ public static class EmailSenderConfigurationOperation
public static readonly ConstructSymbol<EmailSenderConfigurationEntity>.From<EmailSenderConfigurationEntity> Clone;
}

public abstract class EmailSenderServiceConfigurationEntity : Entity
public abstract class EmailServiceEntity : Entity
{
public abstract EmailSenderServiceConfigurationEntity Clone();
public abstract EmailServiceEntity Clone();
}

[EntityKind(EntityKind.Part, EntityData.Master)]
public class SmtpEntity : EmailSenderServiceConfigurationEntity
public class SmtpEmailServiceEntity : EmailServiceEntity
{


public SmtpDeliveryFormat DeliveryFormat { get; set; }

public SmtpDeliveryMethod DeliveryMethod { get; set; }
Expand All @@ -83,7 +80,7 @@ public class SmtpEntity : EmailSenderServiceConfigurationEntity
[StringLengthValidator(Min = 3, Max = 300), FileNameValidator]
public string? PickupDirectoryLocation { get; set; }

static StateValidator<SmtpEntity, SmtpDeliveryMethod> stateValidator = new StateValidator<SmtpEntity, SmtpDeliveryMethod>(
static StateValidator<SmtpEmailServiceEntity, SmtpDeliveryMethod> stateValidator = new StateValidator<SmtpEmailServiceEntity, SmtpDeliveryMethod>(
a => a.DeliveryMethod, a => a.Network, a => a.PickupDirectoryLocation)
{
{SmtpDeliveryMethod.Network, true, null },
Expand All @@ -96,15 +93,14 @@ public class SmtpEntity : EmailSenderServiceConfigurationEntity
return stateValidator.Validate(this, pi) ?? base.PropertyValidation(pi);
}

public override SmtpEntity Clone()
public override SmtpEmailServiceEntity Clone()
{
return new SmtpEntity
return new SmtpEmailServiceEntity
{
DeliveryFormat = DeliveryFormat,
DeliveryMethod = DeliveryMethod,
Network = Network?.Clone(),
PickupDirectoryLocation = PickupDirectoryLocation

};
}
}
Expand Down Expand Up @@ -162,8 +158,10 @@ public enum CertFileType
}

[EntityKind(EntityKind.Part, EntityData.Master)]
public class ExchangeWebServiceEntity : EmailSenderServiceConfigurationEntity
public class ExchangeWebServiceEmailServiceEntity : EmailServiceEntity
{


public ExchangeVersion ExchangeVersion { get; set; }

[StringLengthValidator(Max = 300)]
Expand All @@ -177,9 +175,9 @@ public class ExchangeWebServiceEntity : EmailSenderServiceConfigurationEntity

public bool UseDefaultCredentials { get; set; } = true;

public override ExchangeWebServiceEntity Clone()
public override ExchangeWebServiceEmailServiceEntity Clone()
{
return new ExchangeWebServiceEntity
return new ExchangeWebServiceEmailServiceEntity
{
ExchangeVersion = ExchangeVersion,
Url = Url,
Expand All @@ -192,7 +190,7 @@ public override ExchangeWebServiceEntity Clone()
}

[EntityKind(EntityKind.Part, EntityData.Master)]
public class MicrosoftGraphEntity : EmailSenderServiceConfigurationEntity
public class MicrosoftGraphEmailServiceEntity : EmailServiceEntity
{
public bool UseActiveDirectoryConfiguration { get; set; }

Expand Down Expand Up @@ -221,9 +219,9 @@ public class MicrosoftGraphEntity : EmailSenderServiceConfigurationEntity

return base.PropertyValidation(pi);
}
public override MicrosoftGraphEntity Clone()
public override MicrosoftGraphEmailServiceEntity Clone()
{
return new MicrosoftGraphEntity
return new MicrosoftGraphEmailServiceEntity
{
UseActiveDirectoryConfiguration = UseActiveDirectoryConfiguration,
Azure_ApplicationID = Azure_ApplicationID,
Expand Down
Loading

2 comments on commit d9d219a

@olmobrutall
Copy link
Collaborator Author

@olmobrutall olmobrutall commented on d9d219a Oct 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cleanup in EmailSenderConfigurationEntity

⚠️ READ THIS OR YOUR APP WILL STOP SENDING E-MAILS!

This refactoring made by @rezanos (Thanks!) splits the different embedded entities in EmailSenderConfigurationEntity into a proper ImpementedBy of different part entities inheriting from the abstract class EmailServiceEntity:

BEFORE

[EntityKind(EntityKind.Shared, EntityData.Master)]
public class EmailSenderConfigurationEntity : Entity
{
   //...
   public SmtpEmbedded? SMTP { get; set; }
   public ExchangeWebServiceEmbedded? Exchange { get; set; }
   public MicrosoftGraphEmbedded? MicrosoftGraph { get; set; }
}

AFTER

[EntityKind(EntityKind.Shared, EntityData.Master)]
public class EmailSenderConfigurationEntity : Entity
{

   //...
   [ImplementedBy(typeof(SmtpEmailServiceEntity), typeof(ExchangeWebServiceEmailServiceEntity), typeof(MicrosoftGraphEmailServiceEntity))]
    public EmailServiceEntity Service { get; set; }
   //...
}

Not many changes are expected in your code, except for fixing EnvironmentTest or some CSharp Migrations manually.

The SQL Migration however is a little bit complicated, so here is the script that migrates the information from the embedded to the new part entities that needs to be inserted appropiately in your SQL Script.

ALTER TABLE mailing.EmailSenderConfiguration ADD [ServiceID_SmtpEmailService] INT NULL;
ALTER TABLE mailing.EmailSenderConfiguration ADD [ServiceID_ExchangeWebServiceEmailService] INT NULL;
ALTER TABLE mailing.EmailSenderConfiguration ADD [ServiceID_MicrosoftGraphEmailService] INT NULL;
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [SMTP_HasValue];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [SMTP_DeliveryFormatID];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [SMTP_DeliveryMethodID];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [SMTP_Network_HasValue];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [SMTP_Network_Host];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [SMTP_Network_Port];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [SMTP_Network_Username];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [SMTP_Network_Password];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [SMTP_Network_UseDefaultCredentials];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [SMTP_Network_EnableSSL];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [SMTP_PickupDirectoryLocation];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [Exchange_HasValue];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [Exchange_ExchangeVersionID];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [Exchange_Url];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [Exchange_Username];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [Exchange_Password];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [Exchange_UseDefaultCredentials];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [MicrosoftGraph_HasValue];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [MicrosoftGraph_UseActiveDirectoryConfiguration];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [MicrosoftGraph_Azure_ApplicationID];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [MicrosoftGraph_Azure_DirectoryID];
--ALTER TABLE mailing.EmailSenderConfiguration DROP COLUMN [MicrosoftGraph_Azure_ClientSecret];

CREATE TABLE mailing.SmtpEmailService(
ID INT IDENTITY NOT NULL,
Ticks BIGINT NOT NULL,
DeliveryFormatID INT NOT NULL,
DeliveryMethodID INT NOT NULL,
[Network_HasValue] BIT NOT NULL,
[Network_Host] NVARCHAR(100) NULL,
[Network_Port] INT NULL,
[Network_Username] NVARCHAR(100) NULL,
[Network_Password] NVARCHAR(100) NULL,
[Network_UseDefaultCredentials] BIT NULL,
[Network_EnableSSL] BIT NULL,
PickupDirectoryLocation NVARCHAR(300) NULL,
CONSTRAINT [PK_mailing_SmtpEmailService] PRIMARY KEY CLUSTERED (ID ASC)
);

GO
SET IDENTITY_INSERT mailing.SmtpEmailService ON;  
INSERT INTO mailing.SmtpEmailService(
ID,
Ticks,
DeliveryFormatID,
DeliveryMethodID,
[Network_HasValue],
[Network_Host],
[Network_Port],
[Network_Username],
[Network_Password],
[Network_UseDefaultCredentials],
[Network_EnableSSL],
PickupDirectoryLocation)
SELECT 
ID,
Ticks,
[SMTP_DeliveryFormatID],
[SMTP_DeliveryMethodID],
[SMTP_Network_HasValue],
[SMTP_Network_Host],
[SMTP_Network_Port],
[SMTP_Network_Username],
[SMTP_Network_Password],
[SMTP_Network_UseDefaultCredentials],
[SMTP_Network_EnableSSL],
[SMTP_PickupDirectoryLocation]
FROM 
mailing.EmailSenderConfiguration
WHERE SMTP_HasValue = 1
SET IDENTITY_INSERT mailing.SmtpEmailService OFF;  

GO

EXEC SP_RENAME 'mailing.[EmailSenderConfigurationSMTP_Network_ClientCertificationFiles]' , 'SmtpEmailServiceNetwork_ClientCertificationFiles';
-- Column mailing.[SmtpEmailServiceNetwork_ClientCertificationFiles].ParentID was referencing mailing.EmailSenderConfiguration but not references mailing.SmtpEmailService. An update is needed?
--UPDATE sesnccf
--SET ParentID =  -- get mailing.SmtpEmailService id from esc.Id
--FROM mailing.[SmtpEmailServiceNetwork_ClientCertificationFiles] sesnccf
--JOIN mailing.EmailSenderConfiguration esc ON sesnccf.ParentID = esc.Id



CREATE TABLE mailing.ExchangeWebServiceEmailService(
ID INT IDENTITY NOT NULL,
Ticks BIGINT NOT NULL,
ExchangeVersionID INT NOT NULL,
Url NVARCHAR(300) NULL,
Username NVARCHAR(100) NULL,
Password NVARCHAR(100) NULL,
UseDefaultCredentials BIT NOT NULL,
CONSTRAINT [PK_mailing_ExchangeWebServiceEmailService] PRIMARY KEY CLUSTERED (ID ASC)
);

GO

SET IDENTITY_INSERT mailing.ExchangeWebServiceEmailService ON;  
INSERT INTO mailing.ExchangeWebServiceEmailService(
ID,
Ticks,
ExchangeVersionID,
Url,
Username,
Password,
UseDefaultCredentials)
SELECT 
ID,
Ticks,
[Exchange_ExchangeVersionID],
[Exchange_Url],
[Exchange_Username],
[Exchange_Password],
[Exchange_UseDefaultCredentials]
FROM 
mailing.EmailSenderConfiguration
WHERE [Exchange_HasValue] = 1
SET IDENTITY_INSERT mailing.ExchangeWebServiceEmailService OFF;  





CREATE TABLE mailing.MicrosoftGraphEmailService(
ID INT IDENTITY NOT NULL,
Ticks BIGINT NOT NULL,
UseActiveDirectoryConfiguration BIT NOT NULL,
[Azure_ApplicationID] UNIQUEIDENTIFIER NULL,
[Azure_DirectoryID] UNIQUEIDENTIFIER NULL,
[Azure_ClientSecret] NVARCHAR(100) NULL,
CONSTRAINT [PK_mailing_MicrosoftGraphEmailService] PRIMARY KEY CLUSTERED (ID ASC)
);

GO

SET IDENTITY_INSERT mailing.MicrosoftGraphEmailService ON;  
INSERT INTO mailing.MicrosoftGraphEmailService(
ID,
Ticks,
UseActiveDirectoryConfiguration,
[Azure_ApplicationID],
[Azure_DirectoryID],
[Azure_ClientSecret])
SELECT 
ID,
Ticks,
[MicrosoftGraph_UseActiveDirectoryConfiguration],
[MicrosoftGraph_Azure_ApplicationID],
[MicrosoftGraph_Azure_DirectoryID],
[MicrosoftGraph_Azure_ClientSecret]
FROM 
mailing.EmailSenderConfiguration
WHERE [MicrosoftGraph_HasValue] = 1
SET IDENTITY_INSERT mailing.MicrosoftGraphEmailService OFF;  

GO
UPDATE mailing.EmailSenderConfiguration
SET 
[ServiceID_SmtpEmailService] = CASE WHEN SMTP_HasValue = 1 THEN ID ELSE null END,
[ServiceID_ExchangeWebServiceEmailService]  = CASE WHEN [Exchange_HasValue] = 1 THEN ID ELSE null END,
[ServiceID_MicrosoftGraphEmailService] = CASE WHEN [MicrosoftGraph_HasValue] = 1 THEN ID ELSE null END

GO

Additionally, EmailMessageEntity has a new SentBy fields pointing to the EmailSenderConfigurationEntity that was used. This script will work only in the simple case of having one EmailSenderConfigurationEntity. Otherwise, keep the field null or think is something better for your application.

ALTER TABLE mailing.EmailMessage ADD SentByID INT NULL;

GO

UPDATE mailing.EmailMessage
SET SentByID = (SELECT Max(Id) FROM mailing.EmailSenderConfiguration)  -- Consider something better here!!  

Conclusion

This change makes has three benefits:

  • The new structure prevents configuring more than one service at the same time, a situation that was resolved previously by having some dirty priority system.
  • The new structure allows creating your own EmailServiceEntity and implement your own logic inheriting from BaseEmailSender and registering it in EmailLogic.EmailSenders.

Enjoy!

@rezanos
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks to you @olmobrutall for your always great collaboration 😃 🙏
🚀 🎉

Please sign in to comment.