From 5e86c1df5f479ea62876ced6a5ec19a784f2eb7b Mon Sep 17 00:00:00 2001 From: Halil ibrahim Kalkan Date: Tue, 12 Jun 2018 18:59:45 +0300 Subject: [PATCH] Added new string extension: GetBytes --- .../System/AbpStringExtensions.cs | 20 +++++++++++++++ .../System/StringExtensions_Tests.cs | 25 ++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/Volo.Abp.Core/System/AbpStringExtensions.cs b/src/Volo.Abp.Core/System/AbpStringExtensions.cs index de869fad35..d97d8326a3 100644 --- a/src/Volo.Abp.Core/System/AbpStringExtensions.cs +++ b/src/Volo.Abp.Core/System/AbpStringExtensions.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; +using JetBrains.Annotations; using Volo.Abp; namespace System @@ -404,5 +405,24 @@ namespace System return str.Left(maxLength - postfix.Length) + postfix; } + + /// + /// Converts given string to a byte array using encoding. + /// + public static byte[] GetBytes(this string str) + { + return str.GetBytes(Encoding.UTF8); + } + + /// + /// Converts given string to a byte array using the given + /// + public static byte[] GetBytes([NotNull] this string str, [NotNull] Encoding encoding) + { + Check.NotNull(str, nameof(str)); + Check.NotNull(encoding, nameof(encoding)); + + return encoding.GetBytes(str); + } } } \ No newline at end of file diff --git a/test/Volo.Abp.Core.Tests/System/StringExtensions_Tests.cs b/test/Volo.Abp.Core.Tests/System/StringExtensions_Tests.cs index 853c2cbb83..3246372e21 100644 --- a/test/Volo.Abp.Core.Tests/System/StringExtensions_Tests.cs +++ b/test/Volo.Abp.Core.Tests/System/StringExtensions_Tests.cs @@ -1,4 +1,5 @@ -using Shouldly; +using System.Text; +using Shouldly; using Volo.Abp.Localization; using Xunit; @@ -193,6 +194,28 @@ namespace System "MyValue2".ToEnum().ShouldBe(MyEnum.MyValue2); } + [Theory] + [InlineData("")] + [InlineData("MyStringİ")] + public void GetBytes_Test(string str) + { + var bytes = str.GetBytes(); + bytes.ShouldNotBeNull(); + bytes.Length.ShouldBeGreaterThan(0); + Encoding.UTF8.GetString(bytes).ShouldBe(str); + } + + [Theory] + [InlineData("")] + [InlineData("MyString")] + public void GetBytes_With_Encoding_Test(string str) + { + var bytes = str.GetBytes(Encoding.ASCII); + bytes.ShouldNotBeNull(); + bytes.Length.ShouldBeGreaterThan(0); + Encoding.ASCII.GetString(bytes).ShouldBe(str); + } + private enum MyEnum { MyValue1,