Skip to content

Commit

Permalink
MessageConfig.FileBaseDir will now be checked for an absolute path
Browse files Browse the repository at this point in the history
  • Loading branch information
axunonb committed Sep 6, 2018
1 parent c31eedf commit 88ea355
Show file tree
Hide file tree
Showing 9 changed files with 139 additions and 26 deletions.
53 changes: 37 additions & 16 deletions MailMergeLib/MessageConfig.cs
@@ -1,4 +1,5 @@
using System.Globalization;
using System;
using System.Globalization;
using System.IO;
using System.Text;
using MimeKit;
Expand All @@ -12,11 +13,13 @@ namespace MailMergeLib
[YAXSerializableType(FieldsToSerialize = YAXSerializationFields.AttributedFieldsOnly, Options = YAXSerializationOptions.DontSerializeNullObjects)]
public class MessageConfig
{
private string _fileBaseDirectory = Path.GetTempPath();

/// <summary>
/// CTOR for MailMergeMessage configuration.
/// </summary>
public MessageConfig()
{}
{ }

/// <summary>
/// Content transfer encoding for text like HTML.
Expand Down Expand Up @@ -69,7 +72,25 @@ private string CultureInfoName
/// It is useful for retrieval of inline attachments (linked resources of the HTML body).
/// </summary>
[YAXSerializableField]
public string FileBaseDirectory { get; set; } = Path.GetTempPath();
public string FileBaseDirectory
{
get => _fileBaseDirectory;
set
{
if (string.IsNullOrWhiteSpace(value))
{
_fileBaseDirectory = Path.GetTempPath();
return;
}

if (!Tools.IsFullPath(value))
{
throw new ArgumentException($"{value} is not a full path for property {nameof(FileBaseDirectory)}.");
}

_fileBaseDirectory = value;
}
}

/// <summary>
/// If true, empty or illegal recipient addresses will be discarded.
Expand Down Expand Up @@ -136,18 +157,18 @@ private string StandardFromAddressText
#region *** Equality ***
protected bool Equals(MessageConfig other)
{
return TextTransferEncoding == other.TextTransferEncoding &&
BinaryTransferEncoding == other.BinaryTransferEncoding &&
Equals(CharacterEncoding, other.CharacterEncoding) &&
Equals(CultureInfo, other.CultureInfo) &&
string.Equals(FileBaseDirectory, other.FileBaseDirectory) &&
IgnoreIllegalRecipientAddresses == other.IgnoreIllegalRecipientAddresses &&
return TextTransferEncoding == other.TextTransferEncoding &&
BinaryTransferEncoding == other.BinaryTransferEncoding &&
Equals(CharacterEncoding, other.CharacterEncoding) &&
Equals(CultureInfo, other.CultureInfo) &&
string.Equals(FileBaseDirectory, other.FileBaseDirectory) &&
IgnoreIllegalRecipientAddresses == other.IgnoreIllegalRecipientAddresses &&
IgnoreMissingInlineAttachments == other.IgnoreMissingInlineAttachments &&
IgnoreMissingFileAttachments == other.IgnoreMissingFileAttachments &&
Priority == other.Priority &&
Equals(StandardFromAddress, other.StandardFromAddress) &&
string.Equals(Organization, other.Organization) &&
string.Equals(Xmailer, other.Xmailer) &&
Equals(StandardFromAddress, other.StandardFromAddress) &&
string.Equals(Organization, other.Organization) &&
string.Equals(Xmailer, other.Xmailer) &&
SmartFormatterConfig.Equals(other.SmartFormatterConfig);
}

Expand All @@ -164,22 +185,22 @@ public override bool Equals(object obj)
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((MessageConfig) obj);
return Equals((MessageConfig)obj);
}

public override int GetHashCode()
{
unchecked
{
var hashCode = (int) TextTransferEncoding;
hashCode = (hashCode * 397) ^ (int) BinaryTransferEncoding;
var hashCode = (int)TextTransferEncoding;
hashCode = (hashCode * 397) ^ (int)BinaryTransferEncoding;
hashCode = (hashCode * 397) ^ (CharacterEncoding != null ? CharacterEncoding.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (CultureInfo != null ? CultureInfo.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (FileBaseDirectory != null ? FileBaseDirectory.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ IgnoreIllegalRecipientAddresses.GetHashCode();
hashCode = (hashCode * 397) ^ IgnoreMissingInlineAttachments.GetHashCode();
hashCode = (hashCode * 397) ^ IgnoreMissingFileAttachments.GetHashCode();
hashCode = (hashCode * 397) ^ (int) Priority;
hashCode = (hashCode * 397) ^ (int)Priority;
hashCode = (hashCode * 397) ^ (StandardFromAddress != null ? StandardFromAddress.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Organization != null ? Organization.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Xmailer != null ? Xmailer.GetHashCode() : 0);
Expand Down
20 changes: 20 additions & 0 deletions MailMergeLib/Tools.cs
Expand Up @@ -12,6 +12,26 @@ namespace MailMergeLib
/// </summary>
public static class Tools
{
/// <summary>
/// Checks whether the given path is a full path
/// </summary>
/// <remarks>
/// Accepts X:\ and \\UNC\PATH, rejects empty string, \ and X:
/// </remarks>
/// <param name="path"></param>
/// <returns>Returns true if the path is absolute, else false.</returns>
public static bool IsFullPath(string path)
{
if (string.IsNullOrWhiteSpace(path) || path.IndexOfAny(Path.GetInvalidPathChars()) != -1 || !Path.IsPathRooted(path))
return false;

var pathRoot = Path.GetPathRoot(path);
if (pathRoot.Length <= 2) // Accepts X:\ and \\UNC\PATH, rejects empty string, \ and X:
return false;

return !(pathRoot == path && pathRoot.StartsWith("\\\\") && pathRoot.IndexOf('\\', 2) == -1); // A UNC server name without a share name (e.g "\\NAME") is invalid
}

/// <summary>
/// Combines the specified filename with the basename of
/// to form a full path to file or directory.
Expand Down
2 changes: 1 addition & 1 deletion UnitTests/MessageFactory.cs
Expand Up @@ -89,7 +89,7 @@ public static MailMergeMessage GetMessageWithAllPropertiesSet()
mmm.FileAttachments.Add(new FileAttachment(Path.GetFullPath(Path.Combine(TestFileFolders.FilesAbsPath, PdfFile)), "information.pdf"));
mmm.StringAttachments.Add(new StringAttachment("some content", "content.txt"));
mmm.Headers.Add(HeaderId.Comments, "some comments for header");
mmm.Config = new MessageConfig()
mmm.Config = new MailMergeLib.MessageConfig()
{
FileBaseDirectory = TestFileFolders.FilesAbsPath,
CharacterEncoding = Encoding.UTF32,
Expand Down
33 changes: 33 additions & 0 deletions UnitTests/Message_Config.cs
@@ -0,0 +1,33 @@
using System;
using System.IO;
using MailMergeLib;
using NUnit.Framework;

namespace UnitTests
{
[TestFixture]
public class Message_Config
{
private MessageConfig _msgConfig = new MessageConfig();
private string _tempPath = Path.GetTempPath();

[TestCase(" \t", "?")]
[TestCase(" ", "?")]
[TestCase("", "?")]
[TestCase(null, "?")]
[TestCase("\\noFullPath", null)]
[TestCase("C:\\some\\path\\to\\folder", "C:\\some\\path\\to\\folder")]
public void SetFileBaseDirectory(string path, string expected)
{
if (expected == "?") expected = Path.GetTempPath();
if (expected == null)
{
Assert.Throws<ArgumentException>(() => _msgConfig.FileBaseDirectory = path);
return;
}

_msgConfig.FileBaseDirectory = path;
Assert.AreEqual(expected, _msgConfig.FileBaseDirectory);
}
}
}
2 changes: 1 addition & 1 deletion UnitTests/Settings_Serialization.cs
Expand Up @@ -42,7 +42,7 @@ public void Setup()
ConvertCharacterStringLiterals = true
},
Xmailer = "MailMergeLib 5",
FileBaseDirectory = "Path-to-Base-Dir",
FileBaseDirectory = "C:\\Path-to-Base-Dir", // must be a full path, not necessarily existing
TextTransferEncoding = ContentEncoding.QuotedPrintable,
BinaryTransferEncoding = ContentEncoding.UUEncode
},
Expand Down
8 changes: 4 additions & 4 deletions UnitTests/TestFiles/Msg01.xml
Expand Up @@ -54,7 +54,7 @@
<BinaryTransferEncoding>Base64</BinaryTransferEncoding>
<CharacterEncoding>utf-32</CharacterEncoding>
<CultureInfo>de-DE</CultureInfo>
<FileBaseDirectory>d:\Documents\Visual Studio 2015\Projects\MailMergeLib-5\UnitTests\bin\Debug\..\..\TestFiles\</FileBaseDirectory>
<FileBaseDirectory>C:\</FileBaseDirectory>
<IgnoreIllegalRecipientAddresses>False</IgnoreIllegalRecipientAddresses>
<IgnoreMissingInlineAttachments>True</IgnoreMissingInlineAttachments>
<IgnoreMissingFileAttachments>True</IgnoreMissingFileAttachments>
Expand All @@ -71,12 +71,12 @@
</Config>
<FileAttachments>
<FileAttachment>
<Filename>d:\Documents\Visual Studio 2015\Projects\MailMergeLib-5\UnitTests\bin\Debug\..\..\TestFiles\LogFile.log</Filename>
<Filename>..\..\TestFiles\LogFile.log</Filename>
<DisplayName>Log file from {Date:yyyy-MM-dd}.log</DisplayName>
<MimeType>text/plain</MimeType>
</FileAttachment>
<FileAttachment>
<Filename>d:\Documents\Visual Studio 2015\Projects\MailMergeLib-5\UnitTests\bin\Debug\..\..\TestFiles\Sample.pdf</Filename>
<Filename>..\..\TestFiles\Sample.pdf</Filename>
<DisplayName>information.pdf</DisplayName>
<MimeType>application/pdf</MimeType>
</FileAttachment>
Expand All @@ -90,7 +90,7 @@
</StringAttachments>
<ExternalInlineAttachments>
<FileAttachment>
<Filename>d:\Documents\Visual Studio 2015\Projects\MailMergeLib-5\UnitTests\bin\Debug\..\..\TestFiles\error.jpg</Filename>
<Filename>..\..\TestFiles\error.jpg</Filename>
<DisplayName>error-image.jpg</DisplayName>
<MimeType>image/jpeg</MimeType>
</FileAttachment>
Expand Down
2 changes: 1 addition & 1 deletion UnitTests/TestFiles/Msg02.xml
Expand Up @@ -54,7 +54,7 @@
<BinaryTransferEncoding>Base64</BinaryTransferEncoding>
<CharacterEncoding>utf-32</CharacterEncoding>
<CultureInfo>de-DE</CultureInfo>
<FileBaseDirectory>d:\Documents\Visual Studio 2015\Projects\MailMergeLib-5\UnitTests\bin\Debug\..\..\TestFiles\</FileBaseDirectory>
<FileBaseDirectory>C:\</FileBaseDirectory>
<IgnoreIllegalRecipientAddresses>False</IgnoreIllegalRecipientAddresses>
<IgnoreMissingInlineAttachments>True</IgnoreMissingInlineAttachments>
<IgnoreMissingFileAttachments>True</IgnoreMissingFileAttachments>
Expand Down
40 changes: 38 additions & 2 deletions UnitTests/Tools.cs
@@ -1,15 +1,51 @@
using System;
using System.IO;
using System.Text;
using MailMergeLib;
using MimeKit;
using NUnit.Framework;

namespace UnitTests
{
[TestFixture]
public class Tools
{
[Test]
[TestCase(@"C:\dir\file.ext", true)]
[TestCase(@"C:\dir\", true)]
[TestCase(@"C:\dir", true)]
[TestCase(@"C:\", true)]
[TestCase(@"\\unc\share\dir\file.ext", true)]
[TestCase(@"\\unc\share", true)]
[TestCase(@"file.ext", false)]
[TestCase(@"dir\file.ext", false)]
[TestCase(@"\dir\file.ext", false)]
[TestCase(@"C:", false)]
[TestCase(@"C:dir\file.ext", false)]
[TestCase(@"\dir", false)] // An "absolute", but not "full" path
[TestCase(null, false, false)]
[TestCase("", false, false)]
[TestCase(" ", false, false)]
[TestCase(@"C:\inval|d", false, false)]
[TestCase(@"\\is_this_a_dir_or_a_hostname", false, false)]
public static void IsFullPath(string path, bool expectedIsFull, bool expectedIsValid = true)
{
Assert.AreEqual(expectedIsFull, MailMergeLib.Tools.IsFullPath(path), "IsFullPath('" + path + "')");

if (expectedIsFull)
{
Assert.AreEqual(path, Path.GetFullPath(path));
}
else if (expectedIsValid)
{
Assert.AreNotEqual(path, Path.GetFullPath(path));
}
else
{
Assert.That(() => Path.GetFullPath(path), Throws.Exception);
}
}



[Test]
[TestCase(null, null, "")]
[TestCase(null, "", null)]
Expand Down
5 changes: 4 additions & 1 deletion UnitTests/UnitTests.csproj
Expand Up @@ -77,6 +77,7 @@
<Compile Include="EmailValidator.cs" />
<Compile Include="FileMessageStore_Serialization.cs" />
<Compile Include="FileMessageInfo.cs" />
<Compile Include="Message_Config.cs" />
<Compile Include="MessageInfo.cs" />
<Compile Include="Message_Variables.cs" />
<Compile Include="Message_Templates.cs" />
Expand All @@ -94,14 +95,16 @@
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<None Include="TestFiles\LogFile.log" />
<None Include="TestFiles\Sample.pdf" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<ItemGroup>
<Content Include="TestFiles\error.jpg" />
<Content Include="TestFiles\LogFile.txt" />
<Content Include="TestFiles\Msg01.xml" />
<Content Include="TestFiles\Msg02.xml" />
<Content Include="TestFiles\TextForHtmlConverter.html" />
<Content Include="TestFiles\SameImageSeveralTimes.html" />
<Content Include="TestFiles\Mailtext.html" />
Expand Down

0 comments on commit 88ea355

Please sign in to comment.