├── test ├── Common.Test │ ├── Resources │ │ └── TextFile.txt │ ├── Model │ │ └── PersonModel.cs │ ├── Extension │ │ ├── LongExtensionTest.cs │ │ ├── DateTimeExtensionTest.cs │ │ ├── EnumExtensionTest.cs │ │ ├── ObjectExtensionTest.cs │ │ └── StringExtensionTest.cs │ ├── packages.config │ ├── Serialize │ │ ├── Dynamic │ │ │ ├── DynamicXmlTest.cs │ │ │ └── DynamicJsonTest.cs │ │ ├── XmlCDATAElementTest.cs │ │ ├── SerializerFactoryTest.cs │ │ ├── JsonSerializerTest.cs │ │ └── XmlSerializerTest.cs │ ├── Log │ │ └── LoggerServiceTest.cs │ ├── Security │ │ └── ParamsSignerTest.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Net │ │ └── HttpReqeustClientTest.cs │ └── Common.Test.csproj ├── Common.Serializer.JsonNet.Test │ ├── Model │ │ └── PersonModel.cs │ ├── packages.config │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── JsonNetJsonSerializerTest.cs │ └── Common.Serializer.JsonNet.Test.csproj └── Common.Logger.Log4Net.Test │ ├── packages.config │ ├── Log4NetLoggerTest.cs │ ├── AppBuilderExtensionTest.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── Conf │ └── log4net.conf │ └── Common.Logger.Log4Net.Test.csproj ├── .nuget ├── nuget.exe └── NuGet.Config ├── Globals ├── Wlitsoft.Framework.snk └── AuthorInfo.cs ├── src ├── NuGet │ ├── Common │ │ └── Common.nuspec │ ├── Common.Logger.Log4Net │ │ └── Common.Logger.Log4Net.nuspec │ └── Common.Serializer.JsonNet │ │ └── Common.Serializer.JsonNet.nuspec ├── Common │ ├── Globals │ │ ├── Wlitsoft.Framework.snk │ │ └── VersionInfo.cs │ ├── Properties │ │ ├── AssemblyInfo.cs │ │ ├── Resource.Designer.cs │ │ └── Resource.resx │ ├── Core │ │ ├── SerializeType.cs │ │ ├── ISerializer.cs │ │ ├── ILog.cs │ │ └── IDistributedCache.cs │ ├── Net │ │ ├── HttpPostDataType.cs │ │ ├── HttpPostDataDictionary.cs │ │ └── HttpReqeustClient.cs │ ├── Extension │ │ ├── LongExtension.cs │ │ ├── DateTimeExtension.cs │ │ ├── HttpResponseMessageExtension.cs │ │ ├── ObjectExtension.cs │ │ ├── EnumExtension.cs │ │ └── StringExtension.cs │ ├── Exception │ │ ├── ObjectNullException.cs │ │ └── StringNullOrEmptyException.cs │ ├── App.cs │ ├── Security │ │ ├── ParamsSigner.cs │ │ └── StringEncrypt.cs │ ├── Log │ │ ├── EmptyLogger.cs │ │ └── LoggerSerivce.cs │ ├── AppBuilder.cs │ ├── Serialize │ │ ├── SerializerService.cs │ │ ├── JsonSerializer.cs │ │ ├── XmlSerializer.cs │ │ ├── XmlCDATAElement.cs │ │ └── Dynamic │ │ │ ├── DynamicXml.cs │ │ │ └── DynamicJson.cs │ └── Common.csproj ├── Common.Logger.Log4Net │ ├── Globals │ │ ├── Wlitsoft.Framework.snk │ │ └── VersionInfo.cs │ ├── packages.config │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── AppBuilderExtension.cs │ ├── Log4NetLogger.cs │ └── Common.Logger.Log4Net.csproj └── Common.Serializer.JsonNet │ ├── Globals │ ├── Wlitsoft.Framework.snk │ └── VersionInfo.cs │ ├── packages.config │ ├── Properties │ └── AssemblyInfo.cs │ ├── JsonNetJsonSerializer.cs │ └── Common.Serializer.JsonNet.csproj ├── .gitignore ├── appveyor.yml ├── .gitattributes ├── README.md ├── Wlitsoft.Framework.Common.sln └── LICENSE /test/Common.Test/Resources/TextFile.txt: -------------------------------------------------------------------------------- 1 | hello world -------------------------------------------------------------------------------- /.nuget/nuget.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wlitsoft/Common/HEAD/.nuget/nuget.exe -------------------------------------------------------------------------------- /Globals/Wlitsoft.Framework.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wlitsoft/Common/HEAD/Globals/Wlitsoft.Framework.snk -------------------------------------------------------------------------------- /src/NuGet/Common/Common.nuspec: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wlitsoft/Common/HEAD/src/NuGet/Common/Common.nuspec -------------------------------------------------------------------------------- /src/Common/Globals/Wlitsoft.Framework.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wlitsoft/Common/HEAD/src/Common/Globals/Wlitsoft.Framework.snk -------------------------------------------------------------------------------- /src/Common.Logger.Log4Net/Globals/Wlitsoft.Framework.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wlitsoft/Common/HEAD/src/Common.Logger.Log4Net/Globals/Wlitsoft.Framework.snk -------------------------------------------------------------------------------- /src/Common.Serializer.JsonNet/Globals/Wlitsoft.Framework.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wlitsoft/Common/HEAD/src/Common.Serializer.JsonNet/Globals/Wlitsoft.Framework.snk -------------------------------------------------------------------------------- /src/NuGet/Common.Logger.Log4Net/Common.Logger.Log4Net.nuspec: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wlitsoft/Common/HEAD/src/NuGet/Common.Logger.Log4Net/Common.Logger.Log4Net.nuspec -------------------------------------------------------------------------------- /src/Common.Logger.Log4Net/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /src/NuGet/Common.Serializer.JsonNet/Common.Serializer.JsonNet.nuspec: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wlitsoft/Common/HEAD/src/NuGet/Common.Serializer.JsonNet/Common.Serializer.JsonNet.nuspec -------------------------------------------------------------------------------- /src/Common.Serializer.JsonNet/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /test/Common.Test/Model/PersonModel.cs: -------------------------------------------------------------------------------- 1 | namespace Common.Test.Model 2 | { 3 | /// 4 | /// 人模型。 5 | /// 6 | public class PersonModel 7 | { 8 | /// 9 | /// 姓名。 10 | /// 11 | public string Name { get; set; } 12 | 13 | /// 14 | /// 年龄。 15 | /// 16 | public int Age { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | [Oo]bj/ 2 | [Bb]in/ 3 | TestResults/ 4 | _ReSharper.*/ 5 | packages/ 6 | artifacts/ 7 | PublishProfiles/ 8 | *.user 9 | *.suo 10 | *.cache 11 | *.docstates 12 | _ReSharper.* 13 | *net45.csproj 14 | *net451.csproj 15 | *k10.csproj 16 | *.psess 17 | *.vsp 18 | *.pidb 19 | *.userprefs 20 | *DS_Store 21 | *.ncrunchsolution 22 | *.*sdf 23 | *.ipch 24 | *.sln.ide 25 | project.lock.json 26 | .vs 27 | .build/ 28 | .testPublish/ 29 | /.nuget/Output 30 | -------------------------------------------------------------------------------- /test/Common.Serializer.JsonNet.Test/Model/PersonModel.cs: -------------------------------------------------------------------------------- 1 | namespace Common.JsonNet.JsonSerializer.Test.Model 2 | { 3 | /// 4 | /// 人模型。 5 | /// 6 | public class PersonModel 7 | { 8 | /// 9 | /// 姓名。 10 | /// 11 | public string Name { get; set; } 12 | 13 | /// 14 | /// 年龄。 15 | /// 16 | public int Age { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 1.0.{build} 2 | image: Visual Studio 2017 3 | branches: 4 | only: 5 | - master 6 | configuration: Release 7 | platform: Any CPU 8 | before_build: 9 | nuget restore Wlitsoft.Framework.Common.sln 10 | test: off 11 | 12 | artifacts: 13 | - path: '.nuget\Output\*.nupkg' 14 | deploy: 15 | - provider: NuGet 16 | api_key: 17 | secure: lhREP5b+1caZPUhktJQ1Brjj0SWjeF7sdP/NKK1PLnK1vt2zqTOkovA04fF19zZ/ 18 | artifact: /.*\.nupkg/ 19 | on: 20 | branch: master 21 | -------------------------------------------------------------------------------- /.nuget/NuGet.Config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /test/Common.Test/Extension/LongExtensionTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Wlitsoft.Framework.Common.Extension; 3 | using Xunit; 4 | 5 | namespace Common.Test.Extension 6 | { 7 | public class LongExtensionTest 8 | { 9 | [Fact] 10 | public void ToDateTimeTest() 11 | { 12 | long testUnixTimestamp = 1482648300; 13 | DateTime testUnixDateTime = testUnixTimestamp.ToDateTime(); 14 | 15 | Assert.Equal(Convert.ToDateTime("2016-12-25 14:45:00"), testUnixDateTime); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /test/Common.Test/Extension/DateTimeExtensionTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Wlitsoft.Framework.Common.Extension; 3 | using Xunit; 4 | 5 | namespace Common.Test.Extension 6 | { 7 | public class DateTimeExtensionTest 8 | { 9 | [Fact] 10 | public void GetUnixTimestampTest() 11 | { 12 | DateTime testDateTime = Convert.ToDateTime("2016-12-25 14:45:00"); 13 | long testUnixTimestamp = testDateTime.GetUnixTimestamp(); 14 | 15 | Assert.Equal(1482648300, testUnixTimestamp); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /test/Common.Test/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /test/Common.Serializer.JsonNet.Test/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /test/Common.Test/Serialize/Dynamic/DynamicXmlTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Wlitsoft.Framework.Common.Serialize.Dynamic; 7 | using Xunit; 8 | 9 | namespace Common.Test.Serialize.Dynamic 10 | { 11 | public class DynamicXmlTest 12 | { 13 | [Fact] 14 | public void Test01() 15 | { 16 | string xml = @"abc"; 17 | dynamic obj = new DynamicXml(xml); 18 | 19 | Assert.NotNull(obj); 20 | Assert.Equal("abc", obj.e1.Value); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Common/Globals/VersionInfo.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 在此定义项目版本的信息。 4 | * 5 | * 6 | *********************************************************************************************************************/ 7 | 8 | using System.Reflection; 9 | 10 | // 程序集的版本信息由下面四个值组成: 11 | // 12 | // 主版本 13 | // 次版本 14 | // 内部版本号 15 | // 修订号 16 | // 17 | // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, 18 | // 方法是按如下所示使用“*”: 19 | // [assembly: AssemblyVersion("1.0.*")] 20 | 21 | [assembly: AssemblyVersion("1.0.0")] 22 | [assembly: AssemblyFileVersion("1.0.2016.1217")] -------------------------------------------------------------------------------- /src/Common.Logger.Log4Net/Globals/VersionInfo.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 在此定义项目版本的信息。 4 | * 5 | * 6 | *********************************************************************************************************************/ 7 | 8 | using System.Reflection; 9 | 10 | // 程序集的版本信息由下面四个值组成: 11 | // 12 | // 主版本 13 | // 次版本 14 | // 内部版本号 15 | // 修订号 16 | // 17 | // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, 18 | // 方法是按如下所示使用“*”: 19 | // [assembly: AssemblyVersion("1.0.*")] 20 | 21 | [assembly: AssemblyVersion("1.0.3")] 22 | [assembly: AssemblyFileVersion("1.0.2017.0722")] -------------------------------------------------------------------------------- /src/Common.Serializer.JsonNet/Globals/VersionInfo.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 在此定义项目版本的信息。 4 | * 5 | * 6 | *********************************************************************************************************************/ 7 | 8 | using System.Reflection; 9 | 10 | // 程序集的版本信息由下面四个值组成: 11 | // 12 | // 主版本 13 | // 次版本 14 | // 内部版本号 15 | // 修订号 16 | // 17 | // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, 18 | // 方法是按如下所示使用“*”: 19 | // [assembly: AssemblyVersion("1.0.*")] 20 | 21 | [assembly: AssemblyVersion("1.0.3")] 22 | [assembly: AssemblyFileVersion("1.0.2017.0722")] -------------------------------------------------------------------------------- /src/Common/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的一般信息由以下 5 | // 控制。更改这些特性值可修改 6 | // 与程序集关联的信息。 7 | #if DEBUG 8 | [assembly: AssemblyTitle("Wlitsoft.Framework.Common 调试版")] 9 | #else 10 | [assembly: AssemblyTitle("Wlitsoft.Framework.Common 发行版")] 11 | #endif 12 | [assembly: AssemblyDescription("Wlitsoft 框架 - 公共程序集")] 13 | [assembly: AssemblyCulture("")] 14 | 15 | //将 ComVisible 设置为 false 将使此程序集中的类型 16 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 17 | //请将此类型的 ComVisible 特性设置为 true。 18 | [assembly: ComVisible(false)] 19 | 20 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 21 | [assembly: Guid("6c3df461-2f2c-4ab9-912f-72de259d311e")] 22 | 23 | -------------------------------------------------------------------------------- /src/Common.Serializer.JsonNet/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的一般信息由以下 5 | // 控制。更改这些特性值可修改 6 | // 与程序集关联的信息。 7 | #if DEBUG 8 | [assembly: AssemblyTitle("Wlitsoft.Framework.WeixinSDK.Config 调试版")] 9 | #else 10 | [assembly: AssemblyTitle("Wlitsoft.Framework.WeixinSDK.Config 发行版")] 11 | #endif 12 | [assembly: AssemblyDescription("Wlitsoft 框架 - 微信公众平台开发工具包配置")] 13 | [assembly: AssemblyCulture("")] 14 | 15 | //将 ComVisible 设置为 false 将使此程序集中的类型 16 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 17 | //请将此类型的 ComVisible 特性设置为 true。 18 | [assembly: ComVisible(false)] 19 | 20 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 21 | [assembly: Guid("b57f3331-a875-40d2-8802-21104e28cc32")] 22 | -------------------------------------------------------------------------------- /src/Common/Core/SerializeType.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 序列化类型。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月03日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | namespace Wlitsoft.Framework.Common.Core 10 | { 11 | /// 12 | /// 序列化类型。 13 | /// 14 | public enum SerializeType 15 | { 16 | /// 17 | /// Xml。 18 | /// 19 | Xml, 20 | 21 | /// 22 | /// Json。 23 | /// 24 | Json 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Common.Logger.Log4Net/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的一般信息由以下 5 | // 控制。更改这些特性值可修改 6 | // 与程序集关联的信息。 7 | #if DEBUG 8 | [assembly: AssemblyTitle("Wlitsoft.Framework.Common.Logger.Log4Net 调试版")] 9 | #else 10 | [assembly: AssemblyTitle("Wlitsoft.Framework.Common.Logger.Log4Net 发行版")] 11 | #endif 12 | [assembly: AssemblyDescription("Wlitsoft 框架 - 公共程序集 log4net 日志记录者")] 13 | [assembly: AssemblyCulture("")] 14 | 15 | //将 ComVisible 设置为 false 将使此程序集中的类型 16 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 17 | //请将此类型的 ComVisible 特性设置为 true。 18 | [assembly: ComVisible(false)] 19 | 20 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 21 | [assembly: Guid("d8786051-5c80-49d3-a8af-9711da5cd49e")] 22 | -------------------------------------------------------------------------------- /test/Common.Logger.Log4Net.Test/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /test/Common.Test/Log/LoggerServiceTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Wlitsoft.Framework.Common.Core; 7 | using Wlitsoft.Framework.Common.Log; 8 | using Xunit; 9 | 10 | namespace Common.Test.Log 11 | { 12 | /// 13 | /// 日志服务测试。 14 | /// 15 | public class LoggerServiceTest 16 | { 17 | [Fact] 18 | public void GetLoggerTest() 19 | { 20 | LoggerService loggerService = new LoggerService(); 21 | ILog logger = loggerService.GetLogger(); 22 | 23 | Assert.NotNull(logger); 24 | Assert.IsType(logger); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Globals/AuthorInfo.cs: -------------------------------------------------------------------------------- 1 | /************************************************************************************************** 2 | * 描述: 3 | * 在此定义项目作者的信息。 4 | * 5 | * 6 | **************************************************************************************************/ 7 | 8 | using System; 9 | using System.Reflection; 10 | using System.Resources; 11 | 12 | [assembly: AssemblyCompany("Wlitsoft")] 13 | [assembly: AssemblyCopyright("Copyright Wlitsoft 2012 - 2017")] 14 | [assembly: AssemblyTrademark("Copyright © Copyright")] 15 | [assembly: AssemblyProduct("Wlitsoft 框架")] 16 | 17 | #if DEBUG 18 | [assembly: AssemblyConfiguration("DEBUG")] 19 | #else 20 | [assembly: AssemblyConfiguration("RELEASE")] 21 | #endif 22 | 23 | [assembly: CLSCompliant(true)] 24 | [assembly: NeutralResourcesLanguage("zh-CN")] -------------------------------------------------------------------------------- /test/Common.Test/Security/ParamsSignerTest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Wlitsoft.Framework.Common.Security; 3 | using Xunit; 4 | 5 | namespace Common.Test.Security 6 | { 7 | public class ParamsSignerTest 8 | { 9 | 10 | [Fact] 11 | public void GetSignTest() 12 | { 13 | ParamsSigner paramsSigner = new ParamsSigner("wlitsoft"); 14 | 15 | Dictionary paramsDic = new Dictionary 16 | { 17 | {"p1", "v1"}, 18 | {"p2", "v2"} 19 | }; 20 | 21 | paramsSigner.Params = paramsDic; 22 | string sign = paramsSigner.GetSign(); 23 | 24 | Assert.NotNull(sign); 25 | Assert.True(sign.Length > 0); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Common/Net/HttpPostDataType.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * Http 提交数据类型。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月06日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | namespace Wlitsoft.Framework.Common.Net 10 | { 11 | /// 12 | /// Http 提交数据类型。 13 | /// 14 | public enum HttpPostDataType 15 | { 16 | /// 17 | /// 文本。 18 | /// 19 | Text, 20 | 21 | /// 22 | /// 文件路径。 23 | /// 24 | FilePath, 25 | 26 | /// 27 | /// 文件流。 28 | /// 29 | FileStream 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /test/Common.Test/Extension/EnumExtensionTest.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using Wlitsoft.Framework.Common.Extension; 3 | using Xunit; 4 | 5 | namespace Common.Test.Extension 6 | { 7 | public class EnumExtensionTest 8 | { 9 | [Fact] 10 | public void GetDescriptionTest() 11 | { 12 | Sex sex = Sex.Nan; 13 | string text = sex.GetDescription(); 14 | 15 | Assert.Equal("男", text); 16 | } 17 | 18 | [Fact] 19 | public void GetEnumItemByDescriptionTest() 20 | { 21 | Sex sex = EnumExtension.GetEnumItemByDescription("男"); 22 | 23 | Assert.Equal(Sex.Nan, sex); 24 | } 25 | } 26 | 27 | public enum Sex 28 | { 29 | [Description("男")] 30 | Nan, 31 | 32 | [Description("女")] 33 | Nv 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /test/Common.Logger.Log4Net.Test/Log4NetLoggerTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using Wlitsoft.Framework.Common.Logger.Log4Net; 4 | using Xunit; 5 | 6 | namespace Common.Log4Net.Logger.Test 7 | { 8 | public class Log4NetLoggerTest 9 | { 10 | [Fact] 11 | public void CreateLoggerTest() 12 | { 13 | log4net.ILog log = log4net.LogManager.GetLogger("test"); 14 | Log4NetLogger logger = new Log4NetLogger(log); 15 | 16 | Assert.NotNull(logger); 17 | } 18 | 19 | [Fact] 20 | public void InfoTest() 21 | { 22 | log4net.Config.XmlConfigurator.Configure(new FileInfo("./Conf/log4net.conf")); 23 | log4net.ILog log = log4net.LogManager.GetLogger("Test"); 24 | Log4NetLogger logger = new Log4NetLogger(log); 25 | logger.Info($"Test{DateTime.Now}"); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /test/Common.Logger.Log4Net.Test/AppBuilderExtensionTest.cs: -------------------------------------------------------------------------------- 1 | using Wlitsoft.Framework.Common; 2 | using Wlitsoft.Framework.Common.Core; 3 | using Wlitsoft.Framework.Common.Logger.Log4Net; 4 | using Xunit; 5 | 6 | namespace Common.Log4Net.Logger.Test 7 | { 8 | public class AppBuilderExtensionTest 9 | { 10 | [Fact] 11 | public void SetLog4NetLoggerByXmlConfigTest() 12 | { 13 | App.Builder.SetLog4NetLoggerByXmlConfig("./Conf/log4net.conf"); 14 | ILog log = App.LoggerService.GetLogger("Test"); 15 | 16 | Assert.NotNull(log); 17 | Assert.IsType(log); 18 | } 19 | 20 | [Fact] 21 | public void DebugTest() 22 | { 23 | App.Builder.SetLog4NetLoggerByXmlConfig("./Conf/log4net.conf"); 24 | ILog log = App.LoggerService.GetLogger("Test"); 25 | 26 | log.Debug("Debug Info"); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/Common.Test/Serialize/Dynamic/DynamicJsonTest.cs: -------------------------------------------------------------------------------- 1 | using Common.Test.Model; 2 | using Wlitsoft.Framework.Common.Serialize.Dynamic; 3 | using Xunit; 4 | 5 | namespace Common.Test.Serialize.Dynamic 6 | { 7 | public class DynamicJsonTest 8 | { 9 | [Fact] 10 | public void ParseTest() 11 | { 12 | string json = "{\"e1\":\"abc\"}"; 13 | dynamic jsonObj = DynamicJson.Parse(json); 14 | 15 | Assert.NotNull(jsonObj); 16 | Assert.Equal("abc", jsonObj.e1); 17 | } 18 | 19 | [Fact] 20 | public void SerializeTest() 21 | { 22 | PersonModel model = new PersonModel() 23 | { 24 | Name = "p1", 25 | Age = 21 26 | }; 27 | string json = DynamicJson.Serialize(model); 28 | 29 | Assert.NotNull(json); 30 | Assert.True(json.Length > 0); 31 | 32 | Assert.True(json.Contains("21")); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.doc diff=astextplain 2 | *.DOC diff=astextplain 3 | *.docx diff=astextplain 4 | *.DOCX diff=astextplain 5 | *.dot diff=astextplain 6 | *.DOT diff=astextplain 7 | *.pdf diff=astextplain 8 | *.PDF diff=astextplain 9 | *.rtf diff=astextplain 10 | *.RTF diff=astextplain 11 | 12 | *.jpg binary 13 | *.png binary 14 | *.gif binary 15 | 16 | *.cs text=auto diff=csharp 17 | *.vb text=auto 18 | *.resx text=auto 19 | *.c text=auto 20 | *.cpp text=auto 21 | *.cxx text=auto 22 | *.h text=auto 23 | *.hxx text=auto 24 | *.py text=auto 25 | *.rb text=auto 26 | *.java text=auto 27 | *.html text=auto 28 | *.htm text=auto 29 | *.css text=auto 30 | *.scss text=auto 31 | *.sass text=auto 32 | *.less text=auto 33 | *.js text=auto 34 | *.lisp text=auto 35 | *.clj text=auto 36 | *.sql text=auto 37 | *.php text=auto 38 | *.lua text=auto 39 | *.m text=auto 40 | *.asm text=auto 41 | *.erl text=auto 42 | *.fs text=auto 43 | *.fsx text=auto 44 | *.hs text=auto 45 | 46 | *.csproj text=auto 47 | *.vbproj text=auto 48 | *.fsproj text=auto 49 | *.dbproj text=auto 50 | *.sln text=auto eol=crlf 51 | -------------------------------------------------------------------------------- /test/Common.Test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("Common.Test")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Common.Test")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | //将 ComVisible 设置为 false 将使此程序集中的类型 18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("f3e5778c-7f16-4900-98ab-3686557bbeee")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 33 | // 方法是按如下所示使用“*”: : 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /test/Common.Logger.Log4Net.Test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("Common.Log4Net.Logger.Test")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Common.Log4Net.Logger.Test")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | //将 ComVisible 设置为 false 将使此程序集中的类型 18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("4111a247-4a0c-4c11-924a-a69a85e342d7")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 33 | // 方法是按如下所示使用“*”: : 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/Common/Extension/LongExtension.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * long 类型扩展方法静态类。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月25日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using System; 11 | 12 | namespace Wlitsoft.Framework.Common.Extension 13 | { 14 | /// 15 | /// long 类型扩展方法静态类。 16 | /// 17 | public static class LongExtension 18 | { 19 | #region 将给定 Unix 时间戳转换为 时间 20 | 21 | /// 22 | /// 将给定 Unix 时间戳转换为 时间。 23 | /// 24 | /// Unix 时间戳。 25 | /// 时间。 26 | public static DateTime ToDateTime(this long unixTimestamp) 27 | { 28 | long value = (unixTimestamp + 8 * 60 * 60) * 10000000; 29 | return DateTimeExtension.UnixStartDateTime.AddTicks(value); 30 | } 31 | 32 | #endregion 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test/Common.Serializer.JsonNet.Test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("Common.JsonNet.JsonSerializer.Test")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Common.JsonNet.JsonSerializer.Test")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | //将 ComVisible 设置为 false 将使此程序集中的类型 18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("5a69aa59-1b8a-4fcf-a595-4ad76ce321fc")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 33 | // 方法是按如下所示使用“*”: : 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/Common/Exception/ObjectNullException.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 当对象为空引用的时候引发的异常。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月01日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | using System; 10 | 11 | namespace Wlitsoft.Framework.Common.Exception 12 | { 13 | /// 14 | /// 当对象为空引用的时候引发的异常。 15 | /// 16 | public class ObjectNullException : ArgumentNullException 17 | { 18 | #region 构造方法 19 | 20 | /// 21 | /// 使用参数名称初始化 类的新实例。 22 | /// 23 | /// 24 | public ObjectNullException(string paraName) 25 | : base(paraName) 26 | { 27 | 28 | } 29 | 30 | #endregion 31 | 32 | #region ArgumentException 成员 33 | 34 | /// 35 | /// 获取描述当前异常的消息。 36 | /// 37 | public override string Message => string.Format(Properties.Resource.ObjectNullExceptionMsg, base.ParamName); 38 | 39 | #endregion 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Common/Extension/DateTimeExtension.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * DateTime 类型扩展方法静态类。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月25日 新建 7 | *********************************************************************************************************************/ 8 | 9 | using System; 10 | 11 | namespace Wlitsoft.Framework.Common.Extension 12 | { 13 | /// 14 | /// DateTime 类型扩展方法静态类。 15 | /// 16 | public static class DateTimeExtension 17 | { 18 | #region 公共属性 19 | 20 | /// 21 | /// Unix 开始时间。 22 | /// 23 | public static DateTime UnixStartDateTime = new DateTime(1970, 1, 1); 24 | 25 | #endregion 26 | 27 | #region 将给定 DateTime 时间转换为 Unix 时间戳。 28 | 29 | /// 30 | /// 将给定 DateTime 时间转换为 Unix 时间戳。 31 | /// 32 | /// DateTime 时间。 33 | /// Unix 时间戳。 34 | public static long GetUnixTimestamp(this DateTime dateTime) 35 | { 36 | return (dateTime.Ticks - UnixStartDateTime.Ticks) / 10000000 - 8 * 60 * 60; 37 | } 38 | 39 | #endregion 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Common/Exception/StringNullOrEmptyException.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 当字符串为空或空引用的时候引发的异常。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月01日 新建 7 | * 作者:李亮 时间:2016年12月25日 修正 异常信息参数名称读取错误问题。 8 | *********************************************************************************************************************/ 9 | using System; 10 | 11 | namespace Wlitsoft.Framework.Common.Exception 12 | { 13 | /// 14 | /// 当字符串为空或空引用的时候引发的异常。 15 | /// 16 | public class StringNullOrEmptyException : ArgumentException 17 | { 18 | #region 构造方法 19 | 20 | /// 21 | /// 使用参数名称初始化 类的新实例。 22 | /// 23 | /// 24 | public StringNullOrEmptyException(string paraName) 25 | : base(string.Empty, paraName) 26 | { 27 | 28 | } 29 | 30 | #endregion 31 | 32 | #region ArgumentException 成员 33 | 34 | /// 35 | /// 获取描述当前异常的消息。 36 | /// 37 | public override string Message => string.Format(Properties.Resource.StringNullOrEmptyExceptionMsg, base.ParamName); 38 | 39 | #endregion 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /test/Common.Test/Extension/ObjectExtensionTest.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 对象扩展方法静态类 测试。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月04日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using Common.Test.Model; 11 | using Wlitsoft.Framework.Common.Extension; 12 | using Xunit; 13 | 14 | namespace Common.Test.Extension 15 | { 16 | /// 17 | /// 对象扩展方法静态类 测试。 18 | /// 19 | public class ObjectExtensionTest 20 | { 21 | private readonly PersonModel _model; 22 | 23 | public ObjectExtensionTest() 24 | { 25 | _model = new PersonModel() 26 | { 27 | Name = "Common", 28 | Age = 5 29 | }; 30 | } 31 | 32 | [Fact] 33 | public void ToJsonStringTest() 34 | { 35 | string json = _model.ToJsonString(); 36 | 37 | Assert.NotNull(json); 38 | Assert.True(json.Length > 0); 39 | } 40 | 41 | [Fact] 42 | public void ToXmlStringTest() 43 | { 44 | string xml = _model.ToXmlString(); 45 | 46 | Assert.NotNull(xml); 47 | Assert.True(xml.Length > 0); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Wlitsoft.Framework.Common 2 | [![Build status](https://ci.appveyor.com/api/projects/status/a8op6vx5r19uatve?svg=true)](https://ci.appveyor.com/project/Wlitsoft/common-nr225) 3 | 4 | ​该项目是一个开发中经常使用的功能类库,封装了对象序列化反序列化、网络请求、参数加密、日志、缓存接口、以及常用的字符串操作等。 5 | 6 | ## NuGet 7 | 8 | 包名称 | 当前版本 | 9 | -------- | :------------ | 10 | Wlitsoft.Framework.Common | [![NuGet](https://img.shields.io/nuget/v/Wlitsoft.Framework.Common.svg)](https://www.nuget.org/packages/Wlitsoft.Framework.Common) 11 | Wlitsoft.Framework.Common.Logger.Log4Net | [![NuGet](https://img.shields.io/nuget/v/Wlitsoft.Framework.Common.Logger.Log4Net.svg)](https://www.nuget.org/packages/Wlitsoft.Framework.Common.Logger.Log4Net) 12 | Wlitsoft.Framework.Common.Serializer.JsonNet | [![NuGet](https://img.shields.io/nuget/v/Wlitsoft.Framework.Common.Serializer.JsonNet.svg)](https://www.nuget.org/packages/Wlitsoft.Framework.Common.Serializer.JsonNet) 13 | 14 | ## 相关配置 15 | 16 | 在应用初始化代码中可以操作以下配置: 17 | 18 | > 添加序列化者 19 | 20 | 例:将默认的 Json 序列化者修改为 JSON.Net 实现。 21 | 22 | `App.Builder.AddSerializer(SerializeType.Json, new JsonNetJsonSerializer());` 23 | 24 | 25 | 26 | > 以 xml 配置文件的方式设置 log4net 日志记录者 27 | 28 | `App.Builder.SetLog4NetLoggerByXmlConfig("~/Config/log4net.conf");` 29 | 30 | 31 | 32 | > 设置分布式缓存 33 | 34 | 例:将分布式缓存实现为 Redis 分布式缓存实现 35 | 36 | `App.Builder.App.Builder.SetDistributedCache(new RedisCache());` 37 | 38 | 注:RedisCache 详见 Caching 项目。 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/Common/Core/ISerializer.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 序列化者接口。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月03日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | using System; 10 | 11 | namespace Wlitsoft.Framework.Common.Core 12 | { 13 | /// 14 | /// 序列化者接口。 15 | /// 16 | public interface ISerializer 17 | { 18 | /// 19 | /// 获取序列化类型。 20 | /// 21 | SerializeType SerializeType { get; } 22 | 23 | /// 24 | /// 将一个对象序列化成一个字符串。 25 | /// 26 | /// 要序列化的对象。 27 | /// 序列化后的字符串。 28 | string Serialize(object obj); 29 | 30 | /// 31 | /// 将一个字符串反序列化为一个对象。 32 | /// 33 | /// 要反序序列化的对象类型。 34 | /// 要反序列化的字符串。 35 | /// 反序列化得到的对象。 36 | object Deserialize(Type objType, string str); 37 | 38 | /// 39 | /// 将一个字符串反序列化为一个对象。 40 | /// 41 | /// 要反序列化的字符串。 42 | /// 反序列化得到的对象。 43 | T Deserialize(string str); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Common/App.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 应用。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月17日 新建 7 | * 作者:李亮 时间:2016年12月17日 编辑 添加 获取分布式缓存 属性。 8 | *********************************************************************************************************************/ 9 | 10 | using Wlitsoft.Framework.Common.Core; 11 | using Wlitsoft.Framework.Common.Log; 12 | using Wlitsoft.Framework.Common.Serialize; 13 | 14 | namespace Wlitsoft.Framework.Common 15 | { 16 | /// 17 | /// 应用。 18 | /// 19 | public class App 20 | { 21 | /// 22 | /// 获取序列化服务。 23 | /// 24 | public static SerializerService SerializerService { get; private set; } 25 | 26 | /// 27 | /// 获取日志服务。 28 | /// 29 | public static LoggerService LoggerService { get; private set; } 30 | 31 | /// 32 | /// 获取分布式缓存。 33 | /// 34 | public static IDistributedCache DistributedCache { get; internal set; } 35 | 36 | /// 37 | /// 获取应用构造者。 38 | /// 39 | public static AppBuilder Builder { get; private set; } 40 | 41 | /// 42 | /// 初始化 的静态实例。 43 | /// 44 | static App() 45 | { 46 | SerializerService = new SerializerService(); 47 | LoggerService = new LoggerService(); 48 | Builder = new AppBuilder(); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Common.Logger.Log4Net/AppBuilderExtension.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 应用 构造 静态扩展类。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月18日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using System.Collections.Generic; 11 | using System.IO; 12 | using System.Linq; 13 | using log4net; 14 | using log4net.Config; 15 | using Wlitsoft.Framework.Common.Exception; 16 | 17 | namespace Wlitsoft.Framework.Common.Logger.Log4Net 18 | { 19 | /// 20 | /// 应用 构造 静态扩展类。 21 | /// 22 | public static class AppBuilderExtension 23 | { 24 | /// 25 | /// 以 xml 配置文件的方式设置 log4net 日志记录者。 26 | /// 27 | /// 应用构造。 28 | /// 配置文件路径。 29 | public static void SetLog4NetLoggerByXmlConfig(this AppBuilder appBuilder, string configFilePath) 30 | { 31 | #region 参数校验 32 | 33 | if (string.IsNullOrEmpty(configFilePath)) 34 | throw new StringNullOrEmptyException(nameof(configFilePath)); 35 | 36 | #endregion 37 | 38 | FileInfo configFileInfo = new FileInfo(configFilePath); 39 | 40 | //校验配置文件是否存在。 41 | if (!configFileInfo.Exists) 42 | throw new System.Exception($"路径({configFilePath})的文件未被发现。"); 43 | 44 | XmlConfigurator.Configure(configFileInfo); 45 | List logs = LogManager.GetCurrentLoggers().ToList(); 46 | foreach (ILog log in logs) 47 | { 48 | appBuilder.AddLogger(log.Logger.Name, new Log4NetLogger(log)); 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /test/Common.Test/Serialize/XmlCDATAElementTest.cs: -------------------------------------------------------------------------------- 1 | using System.Xml.Serialization; 2 | using Wlitsoft.Framework.Common.Extension; 3 | using Wlitsoft.Framework.Common.Serialize; 4 | using Xunit; 5 | 6 | namespace Common.Test.Serialize 7 | { 8 | public class XmlCDATAElementTest 9 | { 10 | /// 11 | /// 一个用于测试的 Xml 字符串。 12 | /// 13 | private const string _xml = @" 14 | Hello World!]]> 15 | this is a string 16 | "; 17 | 18 | [Fact] 19 | public void XmlCDATAElementSerializableTest() 20 | { 21 | XmlCDATAElementTestModel model = new XmlCDATAElementTestModel() 22 | { 23 | Element1 = "

Hello World!

", 24 | Str = "this is a string" 25 | }; 26 | 27 | string expectedXml = _xml.FormatXmlString(); 28 | string actualXml = model.ToXmlString().FormatXmlString(); 29 | Assert.Equal(expectedXml, actualXml); 30 | } 31 | 32 | [Fact] 33 | public void XmlCDATAElementDeserializeTest() 34 | { 35 | XmlCDATAElementTestModel model = _xml.ToXmlObject(); 36 | Assert.Equal("

Hello World!

", model.Element1.Value); 37 | } 38 | } 39 | 40 | /// 41 | /// Xml CDATA 元素 序列化/反序列化测试类 测试模型。 42 | /// 43 | [XmlRoot("xml")] 44 | public class XmlCDATAElementTestModel 45 | { 46 | /// 47 | /// 获取或设置元素1。 48 | /// 49 | public XmlCDATAElement Element1 { get; set; } 50 | 51 | /// 52 | /// 获取或设置一个字符串。 53 | /// 54 | public string Str { get; set; } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Common/Core/ILog.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 日志接口。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月17日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | namespace Wlitsoft.Framework.Common.Core 11 | { 12 | /// 13 | /// 日志接口。 14 | /// 15 | public interface ILog 16 | { 17 | /// 18 | /// 记录一般信息。 19 | /// 20 | /// 日志信息。 21 | void Info(object message); 22 | 23 | /// 24 | /// 记录调试级别日志信息。 25 | /// 26 | /// 日志信息。 27 | void Debug(object message); 28 | 29 | /// 30 | /// 记录调试级别日志信息包括异常堆栈信息。 31 | /// 32 | /// 日志信息。 33 | /// 异常对象。 34 | void Debug(object message, System.Exception ex); 35 | 36 | /// 37 | /// 记录系统错误级别日志信息。 38 | /// 39 | /// 日志信息。 40 | void Error(object message); 41 | 42 | /// 43 | /// 记录系统错误级别日志信息包括异常堆栈信息。 44 | /// 45 | /// 日志信息。 46 | /// 异常对象。 47 | void Error(object message, System.Exception ex); 48 | 49 | /// 50 | /// 记录致命级别日志信息。 51 | /// 52 | /// 日志信息。 53 | void Fatal(object message); 54 | 55 | /// 56 | /// 记录致命级别日志信息包括异常堆栈信息。 57 | /// 58 | /// 日志信息。 59 | /// 异常对象。 60 | void Fatal(object message, System.Exception ex); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/Common/Extension/HttpResponseMessageExtension.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 包含状态码和数据的 HTTP 相应消息扩展静态类。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月06日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using System.IO; 11 | using System.Net.Http; 12 | 13 | namespace Wlitsoft.Framework.Common.Extension 14 | { 15 | /// 16 | /// 包含状态码和数据的 HTTP 相应消息扩展静态类。 17 | /// 18 | public static class HttpResponseMessageExtension 19 | { 20 | /// 21 | /// 获取 字符串结果。 22 | /// 23 | /// 包含状态码和数据的 HTTP 相应消息。 24 | /// 一个 字符串。 25 | public static string GetResultString(this HttpResponseMessage httpResponseMessage) 26 | { 27 | return httpResponseMessage.Content.ReadAsStringAsync().Result; 28 | } 29 | 30 | /// 31 | /// 获取 流结果。 32 | /// 33 | /// 包含状态码和数据的 HTTP 相应消息。 34 | /// 一个 流。 35 | public static Stream GetResultStream(this HttpResponseMessage httpResponseMessage) 36 | { 37 | return httpResponseMessage.Content.ReadAsStreamAsync().Result; 38 | } 39 | 40 | /// 41 | /// 获取 数组结果。 42 | /// 43 | /// 包含状态码和数据的 HTTP 相应消息。 44 | /// 一个 数组。 45 | public static byte[] GetResultBytes(this HttpResponseMessage httpResponseMessage) 46 | { 47 | return httpResponseMessage.Content.ReadAsByteArrayAsync().Result; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /test/Common.Test/Serialize/SerializerFactoryTest.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 序列化者工厂 测试。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月04日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using Wlitsoft.Framework.Common.Core; 11 | using Wlitsoft.Framework.Common.Serialize; 12 | using Xunit; 13 | 14 | namespace Common.Test.Serialize 15 | { 16 | /// 17 | /// 序列化者配置 测试。 18 | /// 19 | public class SerializerFactoryTest 20 | { 21 | [Fact] 22 | public void GetSerializerTest() 23 | { 24 | SerializerService sf = new SerializerService(); 25 | ISerializer serializer = sf.GetSerializer(SerializeType.Json); 26 | 27 | Assert.NotNull(serializer); 28 | Assert.True(serializer.SerializeType == SerializeType.Json); 29 | } 30 | 31 | [Fact] 32 | public void SetSerializerTest() 33 | { 34 | //SerializerService sf = new SerializerService(); 35 | //sf 36 | // .SetSerializer(SerializeType.Xml, new XmlSerializer()) 37 | // .SetSerializer(SerializeType.Json, new JsonSerializer()); 38 | } 39 | 40 | [Fact] 41 | public void GetJsonSerializerTest() 42 | { 43 | SerializerService sf = new SerializerService(); 44 | ISerializer serializer = sf.GetJsonSerializer(); 45 | 46 | Assert.NotNull(serializer); 47 | Assert.True(serializer.SerializeType == SerializeType.Json); 48 | } 49 | 50 | [Fact] 51 | public void GetXmlSerializerTest() 52 | { 53 | SerializerService sf = new SerializerService(); 54 | ISerializer serializer = sf.GetXmlSerializer(); 55 | 56 | Assert.NotNull(serializer); 57 | Assert.True(serializer.SerializeType == SerializeType.Xml); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/Common/Extension/ObjectExtension.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 对象扩展方法静态类。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月04日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using Wlitsoft.Framework.Common.Core; 11 | using Wlitsoft.Framework.Common.Exception; 12 | 13 | namespace Wlitsoft.Framework.Common.Extension 14 | { 15 | /// 16 | /// 对象扩展方法静态类。 17 | /// 18 | public static class ObjectExtension 19 | { 20 | 21 | #region 将给定对象 () 转换成 JSON 字符串的表示形式 22 | 23 | /// 24 | /// 将给定对象()转换成 JSON 字符串的表示形式。 25 | /// 26 | /// 准备进行转换的对象。 27 | /// 转换后生成的 JSON 字符串。 28 | public static string ToJsonString(this object obj) 29 | { 30 | #region 参数校验 31 | 32 | if (obj == null) 33 | throw new ObjectNullException(nameof(obj)); 34 | 35 | #endregion 36 | 37 | ISerializer serializer = App.SerializerService.GetJsonSerializer(); 38 | return serializer.Serialize(obj); 39 | } 40 | 41 | #endregion 42 | 43 | #region 将给定对象 () 转换成 XML 字符串的表示形式 44 | 45 | /// 46 | /// 将给定对象 () 转换成 XML 字符串的表示形式。 47 | /// 48 | /// 准备进行转换的对象。 49 | /// 转换后生成的 XML 字符串。 50 | public static string ToXmlString(this object obj) 51 | { 52 | #region 参数校验 53 | 54 | if (obj == null) 55 | throw new ObjectNullException(nameof(obj)); 56 | 57 | #endregion 58 | 59 | ISerializer serializer = App.SerializerService.GetXmlSerializer(); 60 | return serializer.Serialize(obj); 61 | } 62 | 63 | #endregion 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /test/Common.Test/Serialize/JsonSerializerTest.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * Json 序列化/反序列化 测试。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月03日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | using Common.Test.Model; 10 | using Wlitsoft.Framework.Common.Core; 11 | using Wlitsoft.Framework.Common.Serialize; 12 | using Xunit; 13 | 14 | namespace Common.Test.Serialize 15 | { 16 | /// 17 | /// Json 序列化/反序列化 测试。 18 | /// 19 | public class JsonSerializerTest 20 | { 21 | private readonly ISerializer _serializer; 22 | 23 | private readonly string _json = "{\"Age\":5,\"Name\":\"Common\"}"; 24 | 25 | public JsonSerializerTest() 26 | { 27 | _serializer = new JsonSerializer(); 28 | } 29 | 30 | [Fact] 31 | public void GetSerializeTypeTest() 32 | { 33 | Assert.True(_serializer.SerializeType == SerializeType.Json); 34 | } 35 | 36 | [Fact] 37 | public void SerializeTest() 38 | { 39 | PersonModel model = new PersonModel() 40 | { 41 | Name = "Common", 42 | Age = 5 43 | }; 44 | 45 | string json = _serializer.Serialize(model); 46 | 47 | Assert.NotNull(json); 48 | Assert.True(json.Length > 0); 49 | } 50 | 51 | [Fact] 52 | public void DeserializeTest() 53 | { 54 | PersonModel model = (PersonModel)_serializer.Deserialize(typeof(PersonModel), _json); 55 | 56 | Assert.NotNull(model); 57 | Assert.Equal("Common", model.Name); 58 | Assert.Equal(5, model.Age); 59 | } 60 | 61 | [Fact] 62 | public void Deserialize_TTest() 63 | { 64 | PersonModel model = _serializer.Deserialize(_json); 65 | 66 | Assert.NotNull(model); 67 | Assert.Equal("Common", model.Name); 68 | Assert.Equal(5, model.Age); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/Common/Security/ParamsSigner.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 参数签名者。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月09日 新建 7 | *********************************************************************************************************************/ 8 | 9 | using System.Collections.Generic; 10 | using System.Linq; 11 | using System.Text; 12 | using Wlitsoft.Framework.Common.Extension; 13 | 14 | namespace Wlitsoft.Framework.Common.Security 15 | { 16 | /// 17 | /// 参数签名者。 18 | /// 19 | public class ParamsSigner 20 | { 21 | #region 公共属性 22 | 23 | /// 24 | /// 获取或设置约定的秘钥。 25 | /// 26 | public string SecretKey { get; set; } 27 | 28 | /// 29 | /// 获取或设置要前面的参数集合。 30 | /// 31 | public IDictionary Params { get; set; } 32 | 33 | #endregion 34 | 35 | #region 构造方法 36 | 37 | /// 38 | /// 初始化 类的新实例。 39 | /// 40 | /// 约定的秘钥。 41 | public ParamsSigner(string secretKey) 42 | { 43 | this.SecretKey = secretKey; 44 | this.Params = new Dictionary(); 45 | } 46 | 47 | #endregion 48 | 49 | #region 获得签名字符串 50 | 51 | /// 52 | /// 获得签名字符串。 53 | /// 54 | /// 签名字符串。 55 | public string GetSign() 56 | { 57 | StringBuilder sb = new StringBuilder(); 58 | 59 | //参数名ASCII码从小到大排序。 60 | var sortedParmas = this.Params.OrderBy(d => d.Key); 61 | foreach (var item in sortedParmas) 62 | { 63 | //如果参数值为空则跳过。 64 | if (string.IsNullOrEmpty(item.Value)) 65 | continue; 66 | 67 | sb.AppendFormat($"{item.Key}={item.Value}&"); 68 | } 69 | sb.AppendFormat($"key={this.SecretKey}"); 70 | return sb.ToString().GetMD5(Encoding.UTF8); 71 | } 72 | 73 | #endregion 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /test/Common.Serializer.JsonNet.Test/JsonNetJsonSerializerTest.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * JsonNet Json 序列化/反序列化 测试。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月04日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using Common.JsonNet.JsonSerializer.Test.Model; 11 | using Wlitsoft.Framework.Common.Core; 12 | using Wlitsoft.Framework.Common.Serializer.JsonNet; 13 | using Xunit; 14 | 15 | namespace Common.JsonNet.JsonSerializer.Test 16 | { 17 | /// 18 | /// JsonNet Json 序列化/反序列化 测试。 19 | /// 20 | public class JsonNetJsonSerializerTest 21 | { 22 | private readonly ISerializer _serializer; 23 | 24 | private readonly string _json = "{\"Age\":5,\"Name\":\"Common\"}"; 25 | 26 | public JsonNetJsonSerializerTest() 27 | { 28 | _serializer = new JsonNetJsonSerializer(); 29 | } 30 | 31 | [Fact] 32 | public void GetSerializeTypeTest() 33 | { 34 | Assert.True(_serializer.SerializeType == SerializeType.Json); 35 | } 36 | 37 | [Fact] 38 | public void SerializeTest() 39 | { 40 | PersonModel model = new PersonModel() 41 | { 42 | Name = "Common", 43 | Age = 5 44 | }; 45 | 46 | string json = _serializer.Serialize(model); 47 | 48 | Assert.NotNull(json); 49 | Assert.True(json.Length > 0); 50 | } 51 | 52 | [Fact] 53 | public void DeserializeTest() 54 | { 55 | PersonModel model = (PersonModel)_serializer.Deserialize(typeof(PersonModel), _json); 56 | 57 | Assert.NotNull(model); 58 | Assert.Equal("Common", model.Name); 59 | Assert.Equal(5, model.Age); 60 | } 61 | 62 | [Fact] 63 | public void Deserialize_TTest() 64 | { 65 | PersonModel model = _serializer.Deserialize(_json); 66 | 67 | Assert.NotNull(model); 68 | Assert.Equal("Common", model.Name); 69 | Assert.Equal(5, model.Age); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /test/Common.Test/Serialize/XmlSerializerTest.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * Xml 序列化/反序列化 测试。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月03日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | using Common.Test.Model; 10 | using Wlitsoft.Framework.Common.Core; 11 | using Wlitsoft.Framework.Common.Serialize; 12 | using Xunit; 13 | 14 | namespace Common.Test.Serialize 15 | { 16 | /// 17 | /// Xml 序列化/反序列化 测试。 18 | /// 19 | public class XmlSerializerTest 20 | { 21 | private readonly ISerializer _serializer; 22 | 23 | private readonly string _xml = @" 24 | < Name > Common 25 | < Age > 5 26 | "; 27 | 28 | public XmlSerializerTest() 29 | { 30 | _serializer = new XmlSerializer(); 31 | } 32 | 33 | [Fact] 34 | public void GetSerializeTypeTest() 35 | { 36 | Assert.True(_serializer.SerializeType == SerializeType.Xml); 37 | } 38 | 39 | [Fact] 40 | public void SerializeTest() 41 | { 42 | PersonModel model = new PersonModel() 43 | { 44 | Name = "Common", 45 | Age = 5 46 | }; 47 | 48 | string xml = _serializer.Serialize(model); 49 | 50 | Assert.NotNull(xml); 51 | Assert.True(xml.Length > 0); 52 | } 53 | 54 | [Fact] 55 | public void DeserializeTest() 56 | { 57 | 58 | PersonModel model = (PersonModel)_serializer.Deserialize(typeof(PersonModel), _xml); 59 | 60 | Assert.NotNull(model); 61 | Assert.Equal("Common", model.Name); 62 | Assert.Equal(5, model.Age); 63 | } 64 | 65 | [Fact] 66 | public void Deserialize_TTest() 67 | { 68 | PersonModel model = _serializer.Deserialize(_xml); 69 | 70 | Assert.NotNull(model); 71 | Assert.Equal("Common", model.Name); 72 | Assert.Equal(5, model.Age); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Common/Log/EmptyLogger.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 空的日志记录者。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月17日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using Wlitsoft.Framework.Common.Core; 11 | 12 | namespace Wlitsoft.Framework.Common.Log 13 | { 14 | /// 15 | /// 空的日志记录者。 16 | /// 17 | public class EmptyLogger : ILog 18 | { 19 | #region ILog 成员 20 | 21 | /// 22 | /// 记录一般信息。 23 | /// 24 | /// 日志信息。 25 | public void Info(object message) 26 | { 27 | 28 | } 29 | 30 | /// 31 | /// 记录调试级别日志信息。 32 | /// 33 | /// 日志信息。 34 | public void Debug(object message) 35 | { 36 | 37 | } 38 | 39 | /// 40 | /// 记录调试级别日志信息包括异常堆栈信息。 41 | /// 42 | /// 日志信息。 43 | /// 异常对象。 44 | public void Debug(object message, System.Exception ex) 45 | { 46 | 47 | } 48 | 49 | /// 50 | /// 记录系统错误级别日志信息。 51 | /// 52 | /// 日志信息。 53 | public void Error(object message) 54 | { 55 | 56 | } 57 | 58 | /// 59 | /// 记录系统错误级别日志信息包括异常堆栈信息。 60 | /// 61 | /// 日志信息。 62 | /// 异常对象。 63 | public void Error(object message, System.Exception ex) 64 | { 65 | 66 | } 67 | 68 | /// 69 | /// 记录致命级别日志信息。 70 | /// 71 | /// 日志信息。 72 | public void Fatal(object message) 73 | { 74 | 75 | } 76 | 77 | /// 78 | /// 记录致命级别日志信息包括异常堆栈信息。 79 | /// 80 | /// 日志信息。 81 | /// 异常对象。 82 | public void Fatal(object message, System.Exception ex) 83 | { 84 | 85 | } 86 | 87 | #endregion 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/Common/Extension/EnumExtension.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 枚举类型扩展方法静态类。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月25日 新建 7 | *********************************************************************************************************************/ 8 | using System; 9 | using System.Collections.Generic; 10 | using System.ComponentModel; 11 | using System.Linq; 12 | using System.Reflection; 13 | using Wlitsoft.Framework.Common.Exception; 14 | 15 | namespace Wlitsoft.Framework.Common.Extension 16 | { 17 | /// 18 | /// 枚举类型扩展方法静态类。 19 | /// 20 | public static class EnumExtension 21 | { 22 | /// 23 | /// 获取枚举项上的 标记信息。 24 | /// 25 | /// 枚举项。 26 | /// 标记信息。 27 | public static string GetDescription(this Enum enumItem) 28 | { 29 | Type enumType = enumItem.GetType(); 30 | FieldInfo fi = enumType.GetField(enumItem.ToString()); 31 | IEnumerable desAttrs = fi.GetCustomAttributes(false); 32 | 33 | //如果未找到则, 34 | if (!desAttrs.Any()) 35 | throw new System.Exception(string.Format(Properties.Resource.EnumItemNotFoundDescription, enumItem)); 36 | 37 | return desAttrs.First().Description; 38 | } 39 | 40 | /// 41 | /// 根据枚举项上的描述信息获取指定的枚举项。 42 | /// 43 | /// 枚举类型。 44 | /// 枚举项描述信息。 45 | /// 获取到的枚举项。 46 | public static TEnum GetEnumItemByDescription(string des) 47 | { 48 | 49 | #region 参数校验 50 | 51 | if (string.IsNullOrEmpty(des)) 52 | throw new StringNullOrEmptyException(nameof(des)); 53 | 54 | #endregion 55 | 56 | Type enumType = typeof(TEnum); 57 | FieldInfo[] finfos = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); 58 | FieldInfo info = finfos.FirstOrDefault(p => p.GetCustomAttribute(false).Description == des); 59 | if (info == null) 60 | throw new System.Exception($"在枚举({enumType.FullName})中,未发现描述为“{des}”的枚举项。"); 61 | 62 | return (TEnum)Enum.Parse(enumType, info.Name); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Common/AppBuilder.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 应用 构造。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月18日 新建 7 | * 作者:李亮 时间:2016年12月31日 编辑 添加 设置分布式缓存 方法。 8 | *********************************************************************************************************************/ 9 | 10 | using Wlitsoft.Framework.Common.Core; 11 | using Wlitsoft.Framework.Common.Exception; 12 | 13 | namespace Wlitsoft.Framework.Common 14 | { 15 | /// 16 | /// 应用 构造。 17 | /// 18 | public class AppBuilder 19 | { 20 | #region 添加序列化者 21 | 22 | /// 23 | /// 添加序列化者。 24 | /// 25 | /// 序列化类型。 26 | /// 序列化者接口。 27 | public void AddSerializer(SerializeType type, ISerializer serializer) 28 | { 29 | #region 参数校验 30 | 31 | if (serializer == null) 32 | throw new ObjectNullException(nameof(serializer)); 33 | 34 | #endregion 35 | 36 | App.SerializerService.SetSerializer(type, serializer); 37 | } 38 | 39 | #endregion 40 | 41 | #region 添加日志记录者 42 | 43 | /// 44 | /// 添加日志记录者。 45 | /// 46 | /// 日志记录者名称。 47 | /// 日志接口。 48 | public void AddLogger(string name, ILog logger) 49 | { 50 | #region 参数校验 51 | 52 | if (string.IsNullOrEmpty(name)) 53 | throw new StringNullOrEmptyException(nameof(name)); 54 | 55 | if (logger == null) 56 | throw new ObjectNullException(nameof(logger)); 57 | 58 | #endregion 59 | 60 | App.LoggerService.SetLogger(name, logger); 61 | } 62 | 63 | #endregion 64 | 65 | #region 设置分布式缓存 66 | 67 | /// 68 | /// 设置分布式缓存。 69 | /// 70 | /// 分布式缓存实例。 71 | /// 72 | public AppBuilder SetDistributedCache(IDistributedCache cache) 73 | { 74 | #region 参数校验 75 | 76 | if (cache == null) 77 | throw new ObjectNullException(nameof(cache)); 78 | 79 | #endregion 80 | 81 | App.DistributedCache = cache; 82 | return this; 83 | } 84 | 85 | #endregion 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/Common/Security/StringEncrypt.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 字符串加密。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月07日 新建 7 | *********************************************************************************************************************/ 8 | using System; 9 | using System.Security.Cryptography; 10 | using System.Text; 11 | 12 | namespace Wlitsoft.Framework.Common.Security 13 | { 14 | /// 15 | /// 文本加密。 16 | /// 17 | public class StringEncrypt 18 | { 19 | #region 私有属性 20 | 21 | //字符串。 22 | private readonly string _str; 23 | 24 | //字符串编码。 25 | private readonly Encoding _encoding; 26 | 27 | #endregion 28 | 29 | #region 构造方法 30 | 31 | /// 32 | /// 初始化 类的新实例。 33 | /// 34 | /// 要加密的字符串。 35 | public StringEncrypt(string str) 36 | : this(str, Encoding.UTF8) 37 | { 38 | 39 | } 40 | 41 | /// 42 | /// 初始化 类的新实例。 43 | /// 44 | /// 要加密的字符串。 45 | /// 字符串编码。 46 | public StringEncrypt(string str, Encoding encoding) 47 | { 48 | this._str = str; 49 | this._encoding = encoding; 50 | } 51 | 52 | #endregion 53 | 54 | #region 获取32位大写 MD5 加密字符串 55 | 56 | /// 57 | /// 获取32位大写 MD5 加密字符串。 58 | /// 59 | /// 加密字符串。 60 | public string GetMD5() 61 | { 62 | using (MD5 md5 = MD5.Create()) 63 | { 64 | byte[] bytes = md5.ComputeHash(this._encoding.GetBytes(this._str)); 65 | return BitConverter.ToString(bytes).Replace("-", "").ToUpper(); 66 | } 67 | } 68 | 69 | #endregion 70 | 71 | #region 获取大写 SHA1 加密字符串 72 | 73 | /// 74 | /// 获取大写 MD5 加密字符串。 75 | /// 76 | /// 加密字符串。 77 | public string GetSHA1() 78 | { 79 | using (SHA1 sha1 = SHA1.Create()) 80 | { 81 | byte[] bytes = sha1.ComputeHash(this._encoding.GetBytes(this._str)); 82 | return BitConverter.ToString(bytes).Replace("-", "").ToUpper(); 83 | } 84 | } 85 | 86 | #endregion 87 | 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/Common.Serializer.JsonNet/JsonNetJsonSerializer.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * JsonNet Json 序列化/反序列化。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月04日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using System; 11 | using Newtonsoft.Json; 12 | using Wlitsoft.Framework.Common.Core; 13 | using Wlitsoft.Framework.Common.Exception; 14 | 15 | namespace Wlitsoft.Framework.Common.Serializer.JsonNet 16 | { 17 | /// 18 | /// JsonNet Json 序列化/反序列化。 19 | /// 20 | public class JsonNetJsonSerializer : ISerializer 21 | { 22 | #region ISerializer 成员 23 | 24 | /// 25 | /// 获取序列化类型。 26 | /// 27 | public SerializeType SerializeType => SerializeType.Json; 28 | 29 | /// 30 | /// 将一个对象序列化成一个字符串。 31 | /// 32 | /// 要序列化的对象。 33 | /// 序列化后的字符串。 34 | public string Serialize(object obj) 35 | { 36 | #region 参数校验 37 | 38 | if (obj == null) 39 | throw new ObjectNullException(nameof(obj)); 40 | 41 | #endregion 42 | 43 | return JsonConvert.SerializeObject(obj); 44 | } 45 | 46 | /// 47 | /// 将一个字符串反序列化为一个对象。 48 | /// 49 | /// 要反序序列化的对象类型。 50 | /// 要反序列化的字符串。 51 | /// 反序列化得到的对象。 52 | public object Deserialize(Type objType, string str) 53 | { 54 | #region 参数校验 55 | 56 | if (objType == null) 57 | throw new ObjectNullException(nameof(objType)); 58 | 59 | if (string.IsNullOrEmpty(str)) 60 | throw new StringNullOrEmptyException(nameof(str)); 61 | 62 | #endregion 63 | 64 | return JsonConvert.DeserializeObject(str, objType); 65 | } 66 | 67 | /// 68 | /// 将一个字符串反序列化为一个对象。 69 | /// 70 | /// 要反序列化的字符串。 71 | /// 反序列化得到的对象。 72 | public T Deserialize(string str) 73 | { 74 | #region 参数校验 75 | 76 | if (string.IsNullOrEmpty(str)) 77 | throw new StringNullOrEmptyException(nameof(str)); 78 | 79 | #endregion 80 | 81 | return JsonConvert.DeserializeObject(str); 82 | } 83 | 84 | #endregion 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /test/Common.Logger.Log4Net.Test/Conf/log4net.conf: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /src/Common/Net/HttpPostDataDictionary.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * Http 提交数据字典。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月06日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | using System.Collections.Generic; 10 | using System.IO; 11 | using System.Net.Http; 12 | using Wlitsoft.Framework.Common.Exception; 13 | 14 | namespace Wlitsoft.Framework.Common.Net 15 | { 16 | /// 17 | /// Http 提交数据字典。 18 | /// 19 | public class HttpPostDataDictionary : Dictionary> 20 | { 21 | 22 | /// 23 | /// 添加文本数据。 24 | /// 25 | /// HTTP 内容的名称。 26 | /// 文本值。 27 | public void AddText(string name, string value) 28 | { 29 | #region 参数校验 30 | 31 | if (string.IsNullOrEmpty(name)) 32 | throw new StringNullOrEmptyException(nameof(name)); 33 | 34 | if (string.IsNullOrEmpty(value)) 35 | throw new StringNullOrEmptyException(nameof(value)); 36 | 37 | #endregion 38 | 39 | this.Add(name, new KeyValuePair(HttpPostDataType.Text, value)); 40 | } 41 | 42 | /// 43 | /// 添加文件数据。 44 | /// 45 | /// HTTP 内容的名称。 46 | /// 文件路径。 47 | public void AddFile(string name, string filePath) 48 | { 49 | #region 参数校验 50 | 51 | if (string.IsNullOrEmpty(name)) 52 | throw new StringNullOrEmptyException(nameof(name)); 53 | 54 | if (string.IsNullOrEmpty(filePath)) 55 | throw new StringNullOrEmptyException(nameof(filePath)); 56 | 57 | #endregion 58 | 59 | throw new System.NotImplementedException(); 60 | } 61 | 62 | /// 63 | /// 添加文件流。 64 | /// 65 | /// HTTP 内容的名称。 66 | /// 文件流。 67 | public void AddFile(string name, FileStream fileStream) 68 | { 69 | #region 参数校验 70 | 71 | if (string.IsNullOrEmpty(name)) 72 | throw new StringNullOrEmptyException(nameof(name)); 73 | 74 | if (fileStream == null) 75 | throw new ObjectNullException(nameof(fileStream)); 76 | 77 | #endregion 78 | 79 | this.Add(name, new KeyValuePair(HttpPostDataType.FileStream, fileStream)); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/Common/Log/LoggerSerivce.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 日志服务。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月17日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using System.Collections.Generic; 11 | using System.Linq; 12 | using Wlitsoft.Framework.Common.Core; 13 | using Wlitsoft.Framework.Common.Exception; 14 | 15 | namespace Wlitsoft.Framework.Common.Log 16 | { 17 | /// 18 | /// 日志服务。 19 | /// 20 | public class LoggerService 21 | { 22 | //日志记录者。 23 | internal static Dictionary Loggers; 24 | 25 | //默认的日志记录者名称。 26 | internal static string DefaultLoggerName; 27 | 28 | #region 构造方法 29 | 30 | static LoggerService() 31 | { 32 | Loggers = new Dictionary(); 33 | DefaultLoggerName = "default"; 34 | } 35 | 36 | #endregion 37 | 38 | #region 公共方法 39 | 40 | /// 41 | /// 获取默认的 实例。 42 | /// 43 | /// 一个 类型的对象实例。 44 | public ILog GetLogger() 45 | { 46 | return this.GetLogger(DefaultLoggerName); 47 | } 48 | 49 | /// 50 | /// 获取一个 的实例。 51 | /// 日志记录者名称。 52 | /// 53 | /// 一个 类型的对象实例。 54 | public ILog GetLogger(string name) 55 | { 56 | #region 参数校验 57 | 58 | if (string.IsNullOrEmpty(name)) 59 | throw new StringNullOrEmptyException(nameof(name)); 60 | 61 | #endregion 62 | 63 | //如果为空,则初始化一个空的日志记录者。 64 | if (!Loggers.Any()) 65 | return new EmptyLogger(); 66 | 67 | return Loggers[name]; 68 | } 69 | 70 | /// 71 | /// 设置日志记录者。 72 | /// 73 | /// 日志记录者名称。 74 | /// 日志记录者。 75 | internal void SetLogger(string name, ILog logger) 76 | { 77 | #region 参数校验 78 | 79 | if (string.IsNullOrEmpty(name)) 80 | throw new StringNullOrEmptyException(nameof(name)); 81 | 82 | if (logger == null) 83 | throw new ObjectNullException(nameof(logger)); 84 | 85 | #endregion 86 | 87 | //如果存在则移除, 88 | if (Loggers.ContainsKey(name)) 89 | Loggers.Remove(name); 90 | 91 | Loggers.Add(name, logger); 92 | } 93 | 94 | #endregion 95 | 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/Common/Serialize/SerializerService.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 序列化服务。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月03日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | using System.Collections.Generic; 10 | using Wlitsoft.Framework.Common.Core; 11 | using Wlitsoft.Framework.Common.Exception; 12 | 13 | namespace Wlitsoft.Framework.Common.Serialize 14 | { 15 | /// 16 | /// 序列化服务。 17 | /// 18 | public class SerializerService 19 | { 20 | #region 私有属性 21 | 22 | private static readonly Dictionary Serializers = new Dictionary(); 23 | 24 | #endregion 25 | 26 | #region 构造方法 27 | 28 | /// 29 | /// 初始化 的静态实例。 30 | /// 31 | static SerializerService() 32 | { 33 | Serializers.Add(SerializeType.Xml, new XmlSerializer()); 34 | Serializers.Add(SerializeType.Json, new JsonSerializer()); 35 | } 36 | 37 | #endregion 38 | 39 | #region 公共方法 40 | 41 | /// 42 | /// 获取一个 的实例。 43 | /// 44 | /// 序列化类型。 45 | /// 一个 类型的对象实例。 46 | public ISerializer GetSerializer(SerializeType type) 47 | { 48 | return Serializers[type]; 49 | } 50 | 51 | /// 52 | /// 设置序列化者。 53 | /// 54 | /// 序列化类型。 55 | /// 序列化者。 56 | internal SerializerService SetSerializer(SerializeType type, ISerializer serializer) 57 | { 58 | #region 参数校验 59 | 60 | if (serializer == null) 61 | throw new ObjectNullException(nameof(serializer)); 62 | 63 | #endregion 64 | 65 | //如果存在则更新, 66 | if (Serializers.ContainsKey(type)) 67 | Serializers[type] = serializer; 68 | else 69 | Serializers.Add(type, serializer); 70 | 71 | return this; 72 | } 73 | 74 | /// 75 | /// 获取 Json 序列化者。 76 | /// 77 | /// 78 | public ISerializer GetJsonSerializer() 79 | { 80 | return GetSerializer(SerializeType.Json); 81 | } 82 | 83 | /// 84 | /// 获取 Xml 序列化者。 85 | /// 86 | /// 87 | public ISerializer GetXmlSerializer() 88 | { 89 | return GetSerializer(SerializeType.Xml); 90 | } 91 | 92 | #endregion 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /test/Common.Test/Extension/StringExtensionTest.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 字符串类型扩展方法静态类 测试。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月04日 新建 7 | *********************************************************************************************************************/ 8 | 9 | using Common.Test.Model; 10 | using Wlitsoft.Framework.Common.Extension; 11 | using Xunit; 12 | 13 | namespace Common.Test.Extension 14 | { 15 | /// 16 | /// 字符串类型扩展方法静态类 测试。 17 | /// 18 | public class StringExtensionTest 19 | { 20 | [Fact] 21 | public void ToJsonObjectTest() 22 | { 23 | const string json = "{\"Age\":5,\"Name\":\"Common\"}"; 24 | 25 | PersonModel model = json.ToJsonObject(); 26 | 27 | Assert.NotNull(model); 28 | Assert.Equal("Common", model.Name); 29 | Assert.Equal(5, model.Age); 30 | } 31 | 32 | [Fact] 33 | public void ToXmlObject_TTest() 34 | { 35 | const string xml = @" 36 | Common 37 | 5 38 | "; 39 | 40 | PersonModel model = xml.ToXmlObject(); 41 | 42 | Assert.NotNull(model); 43 | Assert.Equal("Common", model.Name); 44 | Assert.Equal(5, model.Age); 45 | } 46 | 47 | [Fact] 48 | public void ToXmlObjectTest() 49 | { 50 | const string xml = @" 51 | Common 52 | 5 53 | "; 54 | 55 | PersonModel model = (PersonModel)xml.ToXmlObject(typeof(PersonModel)); 56 | 57 | Assert.NotNull(model); 58 | Assert.Equal("Common", model.Name); 59 | Assert.Equal(5, model.Age); 60 | } 61 | 62 | [Fact] 63 | public void GetMD5Test() 64 | { 65 | string str = "hello"; 66 | 67 | string expected = "5D41402ABC4B2A76B9719D911017C592"; 68 | string actual = str.GetMD5(); 69 | 70 | Assert.Equal(expected, actual); 71 | } 72 | 73 | [Fact] 74 | public void GetSHA1Test() 75 | { 76 | string str = "hello"; 77 | 78 | string expected = "AAF4C61DDCC5E8A2DABEDE0F3B482CD9AEA9434D"; 79 | string actual = str.GetSHA1(); 80 | 81 | Assert.Equal(expected, actual); 82 | } 83 | 84 | [Fact] 85 | public void NewNonceStrTest() 86 | { 87 | string nonceStr = StringExtension.NewNonceStr(20); 88 | 89 | Assert.NotNull(nonceStr); 90 | Assert.Equal(20, nonceStr.Length); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/Common/Serialize/JsonSerializer.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * Json 序列化/反序列化。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月03日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | using System; 10 | using System.IO; 11 | using System.Runtime.Serialization.Json; 12 | using System.Text; 13 | using Wlitsoft.Framework.Common.Core; 14 | using Wlitsoft.Framework.Common.Exception; 15 | 16 | namespace Wlitsoft.Framework.Common.Serialize 17 | { 18 | /// 19 | /// Json 序列化/反序列化。 20 | /// 21 | public class JsonSerializer : ISerializer 22 | { 23 | #region ISerializer 成员 24 | 25 | /// 26 | /// 获取序列化类型。 27 | /// 28 | public SerializeType SerializeType { get; } = SerializeType.Json; 29 | 30 | /// 31 | /// 将一个对象序列化成一个字符串。 32 | /// 33 | /// 要序列化的对象。 34 | /// 序列化后的字符串。 35 | public string Serialize(object obj) 36 | { 37 | #region 参数校验 38 | 39 | if (obj == null) 40 | throw new ObjectNullException(nameof(obj)); 41 | 42 | #endregion 43 | 44 | using (var ms = new MemoryStream()) 45 | { 46 | new DataContractJsonSerializer(obj.GetType()).WriteObject(ms, obj); 47 | return Encoding.UTF8.GetString(ms.ToArray()); 48 | } 49 | 50 | } 51 | 52 | /// 53 | /// 将一个字符串反序列化为一个对象。 54 | /// 55 | /// 要反序序列化的对象类型。 56 | /// 要反序列化的字符串。 57 | /// 反序列化得到的对象。 58 | public object Deserialize(Type objType, string str) 59 | { 60 | #region 参数校验 61 | 62 | if (objType == null) 63 | throw new ObjectNullException(nameof(objType)); 64 | 65 | if (string.IsNullOrEmpty(str)) 66 | throw new StringNullOrEmptyException(nameof(str)); 67 | 68 | #endregion 69 | 70 | using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(str))) 71 | { 72 | return new DataContractJsonSerializer(objType).ReadObject(ms); 73 | } 74 | } 75 | 76 | /// 77 | /// 将一个字符串反序列化为一个对象。 78 | /// 79 | /// 要反序列化的字符串。 80 | /// 反序列化得到的对象。 81 | public T Deserialize(string str) 82 | { 83 | #region 参数校验 84 | 85 | if (string.IsNullOrEmpty(str)) 86 | throw new StringNullOrEmptyException(nameof(str)); 87 | 88 | #endregion 89 | 90 | return (T)this.Deserialize(typeof(T), str); 91 | } 92 | 93 | #endregion 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /test/Common.Test/Net/HttpReqeustClientTest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using Wlitsoft.Framework.Common.Extension; 4 | using Wlitsoft.Framework.Common.Net; 5 | using Xunit; 6 | 7 | namespace Common.Test.Net 8 | { 9 | /// 10 | /// Http 请求客户端 测试。 11 | /// 12 | public class HttpReqeustClientTest 13 | { 14 | 15 | [Fact] 16 | public void HttpGetStringTest() 17 | { 18 | HttpReqeustClient client = new HttpReqeustClient(); 19 | string result = client.HttpGetString("http://localhost:5000/api/apitest/get"); 20 | 21 | Assert.NotNull(result); 22 | Assert.True(result.Length > 0); 23 | 24 | string[] resultObj = result.ToJsonObject(); 25 | Assert.NotNull(resultObj); 26 | Assert.Equal("value1", resultObj[0]); 27 | 28 | } 29 | 30 | [Fact] 31 | public void HttpGetStringHasParaTest() 32 | { 33 | HttpReqeustClient client = new HttpReqeustClient(); 34 | string result = client.HttpGetString("http://localhost:5000/api/apitest/get/1"); 35 | 36 | Assert.NotNull(result); 37 | Assert.True(result.Length > 0); 38 | Assert.Equal("1", result); 39 | } 40 | 41 | [Fact] 42 | public void HttpPostTest() 43 | { 44 | const string url = "http://localhost:5000/api/apitest/post"; 45 | HttpReqeustClient client = new HttpReqeustClient(); 46 | 47 | Dictionary postData = new Dictionary 48 | { 49 | {"p1", "v1"}, 50 | {"p2", "v2"} 51 | }; 52 | 53 | string result = client.HttpPost(url, postData); 54 | 55 | Assert.NotNull(result); 56 | Assert.True(result.Length > 0); 57 | } 58 | 59 | [Fact] 60 | public void HttpSetHeadersTest() 61 | { 62 | HttpReqeustClient client = new HttpReqeustClient(); 63 | client.Headers.Add("User-Agent", "HttpReqeustClient"); 64 | 65 | string result = client.HttpGetString("http://localhost:5000/api/apitest/GetHttpHeaders"); 66 | 67 | Assert.NotNull(result); 68 | Assert.True(result.Length > 0); 69 | Assert.True(result.Contains("HttpReqeustClient")); 70 | } 71 | 72 | [Fact] 73 | public void FileUploadTest() 74 | { 75 | const string url = "http://localhost:5000/api/apitest/FileUpload"; 76 | const string filePath = "Resources/TextFile1.txt"; 77 | HttpReqeustClient client = new HttpReqeustClient(); 78 | 79 | using (FileStream fileStream = File.OpenRead(filePath)) 80 | { 81 | HttpPostDataDictionary postData = new HttpPostDataDictionary(); 82 | postData.AddFile("file", fileStream); 83 | 84 | string result = client.HttpPost(url, postData); 85 | Assert.NotNull(result); 86 | Assert.True(result.Length > 0); 87 | } 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/Common/Core/IDistributedCache.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 分布式缓存接口。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月31日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using System; 11 | 12 | namespace Wlitsoft.Framework.Common.Core 13 | { 14 | /// 15 | /// 分布式缓存接口。 16 | /// 17 | public interface IDistributedCache 18 | { 19 | /// 20 | /// 获取缓存。 21 | /// 22 | /// 缓存类型。 23 | /// 缓存键值。 24 | /// 获取到的缓存。 25 | T Get(string key); 26 | 27 | /// 28 | /// 设置缓存。 29 | /// 30 | /// 缓存类型。 31 | /// 缓存键值。 32 | /// 要缓存的对象。 33 | void Set(string key, T value); 34 | 35 | /// 36 | /// 设置缓存。 37 | /// 38 | /// 缓存类型。 39 | /// 缓存键值。 40 | /// 要缓存的对象。 41 | /// 过期时间。 42 | void Set(string key, T value, TimeSpan expiredTime); 43 | 44 | /// 45 | /// 判断指定键值的缓存是否存在。 46 | /// 47 | /// 缓存键值。 48 | /// 一个布尔值,表示缓存是否存在。 49 | bool Exists(string key); 50 | 51 | /// 52 | /// 移除指定键值的缓存。 53 | /// 54 | /// 缓存键值。 55 | bool Remove(string key); 56 | 57 | /// 58 | /// 获取 Hash 表中的缓存。 59 | /// 60 | /// 缓存类型。 61 | /// 缓存键值。 62 | /// 要获取的 hash 字段。 63 | /// 获取到的缓存。 64 | T GetHash(string key, string hashField); 65 | 66 | /// 67 | /// 设置 缓存到 Hash 表。 68 | /// 69 | /// 缓存类型。 70 | /// 缓存键值。 71 | /// 要设置的 hash 字段。 72 | /// 要设置的 hash 值。 73 | void SetHash(string key, string hashField, T hashValue); 74 | 75 | /// 76 | /// 判断指定键值的 Hash 缓存是否存在。 77 | /// 78 | /// 缓存键值。 79 | /// hash 字段。 80 | /// 一个布尔值,表示缓存是否存在。 81 | bool ExistsHash(string key, string hashField); 82 | 83 | /// 84 | /// 删除 hash 表中的指定字段的缓存。 85 | /// 86 | /// 缓存键值。 87 | /// hash 字段。 88 | /// 一个布尔值,表示缓存是否删除成功。 89 | bool DeleteHash(string key, string hashField); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/Common.Logger.Log4Net/Log4NetLogger.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * log4net 日志记录者。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月18日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using ILog = Wlitsoft.Framework.Common.Core.ILog; 11 | 12 | namespace Wlitsoft.Framework.Common.Logger.Log4Net 13 | { 14 | /// 15 | /// log4net 日志记录者。 16 | /// 17 | public class Log4NetLogger : ILog 18 | { 19 | //log4net日志。 20 | private readonly log4net.ILog _log; 21 | 22 | #region 构造方法 23 | 24 | /// 25 | /// 初始化 类的新实例。 26 | /// log4net 日志记录者。 27 | /// 28 | public Log4NetLogger(log4net.ILog log) 29 | { 30 | this._log = log; 31 | } 32 | 33 | #endregion 34 | 35 | #region ILog 成员 36 | 37 | /// 38 | /// 记录一般信息。 39 | /// 40 | /// 日志信息。 41 | public void Info(object message) 42 | { 43 | this._log.Info(message); 44 | } 45 | 46 | /// 47 | /// 记录调试级别日志信息。 48 | /// 49 | /// 日志信息。 50 | public void Debug(object message) 51 | { 52 | this._log.Debug(message); 53 | } 54 | 55 | /// 56 | /// 记录调试级别日志信息包括异常堆栈信息。 57 | /// 58 | /// 日志信息。 59 | /// 异常对象。 60 | public void Debug(object message, System.Exception ex) 61 | { 62 | this._log.Debug(message, ex); 63 | } 64 | 65 | /// 66 | /// 记录系统错误级别日志信息。 67 | /// 68 | /// 日志信息。 69 | public void Error(object message) 70 | { 71 | this._log.Error(message); 72 | } 73 | 74 | /// 75 | /// 记录系统错误级别日志信息包括异常堆栈信息。 76 | /// 77 | /// 日志信息。 78 | /// 异常对象。 79 | public void Error(object message, System.Exception ex) 80 | { 81 | this._log.Error(message, ex); 82 | } 83 | 84 | /// 85 | /// 记录致命级别日志信息。 86 | /// 87 | /// 日志信息。 88 | public void Fatal(object message) 89 | { 90 | _log.Fatal(message); 91 | } 92 | 93 | /// 94 | /// 记录致命级别日志信息包括异常堆栈信息。 95 | /// 96 | /// 日志信息。 97 | /// 异常对象。 98 | public void Fatal(object message, System.Exception ex) 99 | { 100 | _log.Fatal(message, ex); 101 | } 102 | 103 | #endregion 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/Common/Properties/Resource.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // 此代码由工具生成。 4 | // 运行时版本:4.0.30319.42000 5 | // 6 | // 对此文件的更改可能会导致不正确的行为,并且如果 7 | // 重新生成代码,这些更改将会丢失。 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace Wlitsoft.Framework.Common.Properties { 12 | using System; 13 | 14 | 15 | /// 16 | /// 一个强类型的资源类,用于查找本地化的字符串等。 17 | /// 18 | // 此类是由 StronglyTypedResourceBuilder 19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 20 | // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen 21 | // (以 /str 作为命令选项),或重新生成 VS 项目。 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resource { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resource() { 33 | } 34 | 35 | /// 36 | /// 返回此类使用的缓存的 ResourceManager 实例。 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Wlitsoft.Framework.Common.Properties.Resource", typeof(Resource).Assembly); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// 使用此强类型资源类,为所有资源查找 51 | /// 重写当前线程的 CurrentUICulture 属性。 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | 63 | /// 64 | /// 查找类似 在枚举项({0})未找到 Description 标记信息。 的本地化字符串。 65 | /// 66 | internal static string EnumItemNotFoundDescription { 67 | get { 68 | return ResourceManager.GetString("EnumItemNotFoundDescription", resourceCulture); 69 | } 70 | } 71 | 72 | /// 73 | /// 查找类似 参数“{0}”不能为空引用(null)。 的本地化字符串。 74 | /// 75 | internal static string ObjectNullExceptionMsg { 76 | get { 77 | return ResourceManager.GetString("ObjectNullExceptionMsg", resourceCulture); 78 | } 79 | } 80 | 81 | /// 82 | /// 查找类似 参数“{0}”不能为空字符串(String.Empty)或空引用(null)参数“{0}”不能为空字符串(String.Empty)或空引用(null)。 的本地化字符串。 83 | /// 84 | internal static string StringNullOrEmptyExceptionMsg { 85 | get { 86 | return ResourceManager.GetString("StringNullOrEmptyExceptionMsg", resourceCulture); 87 | } 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/Common/Serialize/XmlSerializer.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * Xml 序列化/反序列化。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月03日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | using System; 10 | using System.IO; 11 | using System.Text; 12 | using System.Xml; 13 | using System.Xml.Serialization; 14 | using Wlitsoft.Framework.Common.Core; 15 | using Wlitsoft.Framework.Common.Exception; 16 | 17 | namespace Wlitsoft.Framework.Common.Serialize 18 | { 19 | /// 20 | /// Xml 序列化/反序列化。 21 | /// 22 | public class XmlSerializer : ISerializer 23 | { 24 | #region ISerializer 成员 25 | 26 | /// 27 | /// 获取序列化类型。 28 | /// 29 | public SerializeType SerializeType { get; } = SerializeType.Xml; 30 | 31 | /// 32 | /// 将一个对象序列化成一个字符串。 33 | /// 34 | /// 要序列化的对象。 35 | /// 序列化后的字符串。 36 | public string Serialize(object obj) 37 | { 38 | #region 参数校验 39 | 40 | if (obj == null) 41 | throw new ObjectNullException(nameof(obj)); 42 | 43 | #endregion 44 | 45 | System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); 46 | 47 | //去除默认的命名空间声明。 48 | XmlSerializerNamespaces xmlNamespaces = new XmlSerializerNamespaces(); 49 | xmlNamespaces.Add("", ""); 50 | 51 | XmlWriterSettings settings = new XmlWriterSettings(); 52 | settings.OmitXmlDeclaration = true; 53 | settings.Indent = true; 54 | settings.NewLineChars = "\r\n"; 55 | settings.IndentChars = " "; 56 | 57 | MemoryStream outStream = new MemoryStream(); 58 | using (XmlWriter writer = XmlWriter.Create(outStream, settings)) 59 | { 60 | serializer.Serialize(writer, obj, xmlNamespaces); 61 | } 62 | 63 | outStream.Position = 0; 64 | using (StreamReader reader = new StreamReader(outStream)) 65 | { 66 | return reader.ReadToEnd(); 67 | } 68 | } 69 | 70 | /// 71 | /// 将一个字符串反序列化为一个对象。 72 | /// 73 | /// 要反序序列化的对象类型。 74 | /// 要反序列化的字符串。 75 | /// 反序列化得到的对象。 76 | public object Deserialize(Type objType, string str) 77 | { 78 | #region 参数校验 79 | 80 | if (objType == null) 81 | throw new ObjectNullException(nameof(objType)); 82 | 83 | if (string.IsNullOrEmpty(str)) 84 | throw new StringNullOrEmptyException(nameof(str)); 85 | 86 | #endregion 87 | 88 | System.Xml.Serialization.XmlSerializer mySerializer = new System.Xml.Serialization.XmlSerializer(objType); 89 | using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str))) 90 | { 91 | using (StreamReader sr = new StreamReader(ms)) 92 | { 93 | return mySerializer.Deserialize(sr); 94 | } 95 | } 96 | } 97 | 98 | /// 99 | /// 将一个字符串反序列化为一个对象。 100 | /// 101 | /// 要反序列化的字符串。 102 | /// 反序列化得到的对象。 103 | public T Deserialize(string str) 104 | { 105 | #region 参数校验 106 | 107 | if (string.IsNullOrEmpty(str)) 108 | throw new StringNullOrEmptyException(nameof(str)); 109 | 110 | #endregion 111 | 112 | return (T)this.Deserialize(typeof(T), str); 113 | } 114 | 115 | #endregion 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/Common/Serialize/XmlCDATAElement.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * Xml CDATA 元素。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月23日 新建 7 | *********************************************************************************************************************/ 8 | using System.Xml; 9 | using System.Xml.Schema; 10 | using System.Xml.Serialization; 11 | 12 | namespace Wlitsoft.Framework.Common.Serialize 13 | { 14 | /// 15 | /// Xml CDATA 元素。 16 | /// 17 | public class XmlCDATAElement : IXmlSerializable 18 | { 19 | #region 公共属性 20 | 21 | /// 22 | /// 获取或设置 元素文本值。 23 | /// 24 | public string Value { get; set; } 25 | 26 | #endregion 27 | 28 | #region 构造方法 29 | 30 | /// 31 | /// 初始化 类的新实例。 32 | /// 33 | public XmlCDATAElement() 34 | { 35 | 36 | } 37 | 38 | /// 39 | /// 根据内容文本值初始化 类的新实例。 40 | /// 41 | /// 内容文本值。 42 | public XmlCDATAElement(string value) 43 | { 44 | this.Value = value; 45 | } 46 | 47 | #endregion 48 | 49 | #region 操作符重载 50 | 51 | /// 52 | /// 。 53 | /// 54 | /// Xml CDATA 元素对象。 55 | /// 一个字符串。 56 | public static implicit operator string(XmlCDATAElement element) 57 | { 58 | return (element == null) ? null : element.Value; 59 | } 60 | 61 | /// 62 | /// 。 63 | /// 64 | /// 一个字符串。 65 | /// Xml CDATA 元素对象。 66 | public static implicit operator XmlCDATAElement(string value) 67 | { 68 | return new XmlCDATAElement(value); 69 | } 70 | 71 | #endregion 72 | 73 | #region IXmlSerializable 成员 74 | 75 | /// 76 | /// 此方法是保留方法,请不要使用。 在实现 IXmlSerializable 接口时,应从此方法返回 null(在 Visual Basic 中为 Nothing),如果需要指定自定义架构,应向该类应用 。 77 | /// 78 | /// 79 | /// 80 | /// ,描述由 方法产生并由 方法使用的对象的 XML 表示形式。 81 | /// 82 | public XmlSchema GetSchema() 83 | { 84 | return null; 85 | } 86 | 87 | /// 88 | /// 从对象的 XML 表示形式生成该对象。 89 | /// 90 | /// 对象从中进行反序列化的 流。 91 | public void ReadXml(XmlReader reader) 92 | { 93 | this.Value = reader.ReadElementContentAsString(); 94 | } 95 | 96 | /// 97 | /// 将对象转换为其 XML 表示形式。 98 | /// 99 | /// 对象要序列化为的 流。 100 | public void WriteXml(XmlWriter writer) 101 | { 102 | writer.WriteCData(this.Value); 103 | } 104 | 105 | #endregion 106 | 107 | #region Object 成员 108 | 109 | /// 110 | /// 返回表示当前对象的字符串。 111 | /// 112 | /// 113 | /// 114 | /// 表示当前对象的字符串。 115 | /// 116 | /// 2 117 | public override string ToString() 118 | { 119 | return this.Value; 120 | } 121 | 122 | #endregion 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/Common.Serializer.JsonNet/Common.Serializer.JsonNet.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {B57F3331-A875-40D2-8802-21104E28CC32} 8 | Library 9 | Properties 10 | Wlitsoft.Framework.Common.Serializer.JsonNet 11 | Wlitsoft.Framework.Common.Serializer.JsonNet 12 | v4.5.2 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | bin\Debug\Wlitsoft.Framework.Common.Serializer.JsonNet.xml 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | bin\Release\Wlitsoft.Framework.Common.Serializer.JsonNet.XML 33 | 34 | 35 | true 36 | 37 | 38 | Globals\Wlitsoft.Framework.snk 39 | 40 | 41 | 42 | ..\..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll 43 | True 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | Globals\AuthorInfo.cs 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | {6c3df461-2f2c-4ab9-912f-72de259d311e} 69 | Common 70 | 71 | 72 | 73 | 74 | xcopy /y $(ProjectDir)\bin\$(ConfigurationName)\$(TargetName).dll $(SolutionDir)\src\NuGet\$(ProjectName)\lib\net45\ 75 | xcopy /y $(ProjectDir)\bin\$(ConfigurationName)\$(TargetName).xml $(SolutionDir)\src\NuGet\$(ProjectName)\lib\net45\ 76 | 77 | $(SolutionDir)\.nuget\nuget.exe pack $(SolutionDir)\src\NuGet\$(ProjectName)\$(ProjectName).nuspec -OutputDirectory $(SolutionDir)\.nuget\Output 78 | 79 | 86 | -------------------------------------------------------------------------------- /src/Common.Logger.Log4Net/Common.Logger.Log4Net.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {D8786051-5C80-49D3-A8AF-9711DA5CD49E} 8 | Library 9 | Properties 10 | Wlitsoft.Framework.Common.Logger.Log4Net 11 | Wlitsoft.Framework.Common.Logger.Log4Net 12 | v4.5.2 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | bin\Debug\Wlitsoft.Framework.Common.Logger.Log4Net.xml 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | bin\Release\Wlitsoft.Framework.Common.Logger.Log4Net.XML 33 | 34 | 35 | true 36 | 37 | 38 | Globals\Wlitsoft.Framework.snk 39 | 40 | 41 | 42 | ..\..\packages\log4net.2.0.5\lib\net45-full\log4net.dll 43 | True 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | Globals\AuthorInfo.cs 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | {6c3df461-2f2c-4ab9-912f-72de259d311e} 66 | Common 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | xcopy /y $(ProjectDir)\bin\$(ConfigurationName)\$(TargetName).dll $(SolutionDir)\src\NuGet\$(ProjectName)\lib\net45\ 76 | xcopy /y $(ProjectDir)\bin\$(ConfigurationName)\$(TargetName).xml $(SolutionDir)\src\NuGet\$(ProjectName)\lib\net45\ 77 | 78 | $(SolutionDir)\.nuget\nuget.exe pack $(SolutionDir)\src\NuGet\$(ProjectName)\$(ProjectName).nuspec -OutputDirectory $(SolutionDir)\.nuget\Output 79 | 80 | 87 | -------------------------------------------------------------------------------- /test/Common.Serializer.JsonNet.Test/Common.Serializer.JsonNet.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {5A69AA59-1B8A-4FCF-A595-4AD76CE321FC} 8 | Library 9 | Properties 10 | Common.JsonNet.JsonSerializer.Test 11 | Common.JsonNet.JsonSerializer.Test 12 | v4.5.2 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | ..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll 43 | True 44 | 45 | 46 | ..\..\packages\xunit.assert.2.1.0\lib\dotnet\xunit.assert.dll 47 | True 48 | 49 | 50 | ..\..\packages\xunit.extensibility.core.2.1.0\lib\dotnet\xunit.core.dll 51 | True 52 | 53 | 54 | ..\..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll 55 | True 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | {b57f3331-a875-40d2-8802-21104e28cc32} 66 | Common.Serializer.JsonNet 67 | 68 | 69 | {6c3df461-2f2c-4ab9-912f-72de259d311e} 70 | Common 71 | 72 | 73 | 74 | 75 | 76 | 77 | 84 | -------------------------------------------------------------------------------- /src/Common/Serialize/Dynamic/DynamicXml.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 动态 Xml 对象。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年12月23日 新建 7 | *********************************************************************************************************************/ 8 | 9 | using System.Collections.Generic; 10 | using System.Linq; 11 | using System.Dynamic; 12 | using System.Xml.Linq; 13 | using System.Collections; 14 | 15 | 16 | namespace Wlitsoft.Framework.Common.Serialize.Dynamic 17 | { 18 | /// 19 | /// 动态 Xml 对象。 20 | /// 21 | public class DynamicXml : DynamicObject, IEnumerable 22 | { 23 | //元素。 24 | private readonly List _elements; 25 | 26 | #region 构造方法 27 | 28 | /// 29 | /// 根据 xml 字符串初始化 的新实例。 30 | /// 31 | /// 32 | public DynamicXml(string text) 33 | { 34 | var doc = XDocument.Parse(text); 35 | _elements = new List { doc.Root }; 36 | } 37 | 38 | /// 39 | /// 根据 xml 元素对象初始化 的新实例。 40 | /// 41 | /// xml 元素对象。 42 | protected DynamicXml(XElement element) 43 | { 44 | _elements = new List { element }; 45 | } 46 | 47 | /// 48 | /// 根据 xml 元素集合初始化 的新实例。 49 | /// 50 | /// xml 元素集合。 51 | protected DynamicXml(IEnumerable elements) 52 | { 53 | _elements = new List(elements); 54 | } 55 | 56 | #endregion 57 | 58 | #region DynamicObject 成员 59 | 60 | /// 为获取成员值的操作提供实现。从 类派生的类可以重写此方法,以便为诸如获取属性值这样的操作指定动态行为。 61 | /// 提供有关调用了动态操作的对象的信息。binder.Name 属性提供针对其执行动态操作的成员的名称。例如,对于 Console.WriteLine(sampleObject.SampleProperty) 语句(其中 sampleObject 是派生自 类的类的一个实例),binder.Name 将返回“SampleProperty”。binder.IgnoreCase 属性指定成员名称是否区分大小写。 62 | /// 获取操作的结果。例如,如果为某个属性调用该方法,则可以为 指派该属性值。 63 | /// 如果此运算成功,则为 true;否则为 false。如果此方法返回 false,则该语言的运行时联编程序将决定行为。(大多数情况下,将引发运行时异常。) 64 | public override bool TryGetMember(GetMemberBinder binder, out object result) 65 | { 66 | result = null; 67 | if (binder.Name == "Value") 68 | result = _elements[0].Value; 69 | else if (binder.Name == "Count") 70 | result = _elements.Count; 71 | else 72 | { 73 | var attr = _elements[0].Attribute(XName.Get(binder.Name)); 74 | if (attr != null) 75 | result = attr; 76 | else 77 | { 78 | var items = _elements.Descendants(XName.Get(binder.Name)); 79 | if (items == null || items.Count() == 0) return false; 80 | result = new DynamicXml(items); 81 | } 82 | } 83 | return true; 84 | } 85 | 86 | /// 为按索引获取值的操作提供实现。从 类派生的类可以重写此方法,以便为索引操作指定动态行为。 87 | /// 提供有关该操作的信息。 88 | /// 该操作中使用的索引。例如,对于 C# 中的 sampleObject[3] 操作(Visual Basic 中为 sampleObject(3))(其中 sampleObject 派生自 DynamicObject 类), 等于 3。 89 | /// 索引操作的结果。 90 | /// 如果此运算成功,则为 true;否则为 false。如果此方法返回 false,则该语言的运行时联编程序将决定行为。(大多数情况下,将引发运行时异常。) 91 | public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) 92 | { 93 | int ndx = (int)indexes[0]; 94 | result = new DynamicXml(_elements[ndx]); 95 | return true; 96 | } 97 | 98 | #endregion 99 | 100 | #region IEnumerable 成员 101 | 102 | /// 返回一个循环访问集合的枚举器。 103 | /// 可用于循环访问集合的 对象。 104 | public IEnumerator GetEnumerator() 105 | { 106 | foreach (var element in _elements) 107 | yield return new DynamicXml(element); 108 | } 109 | 110 | #endregion 111 | 112 | } 113 | } -------------------------------------------------------------------------------- /test/Common.Logger.Log4Net.Test/Common.Logger.Log4Net.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {4111A247-4A0C-4C11-924A-A69A85E342D7} 8 | Library 9 | Properties 10 | Common.Log4Net.Logger.Test 11 | Common.Log4Net.Logger.Test 12 | v4.5.2 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\..\packages\log4net.2.0.5\lib\net45-full\log4net.dll 35 | True 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll 47 | True 48 | 49 | 50 | ..\..\packages\xunit.assert.2.2.0-beta4-build3444\lib\netstandard1.0\xunit.assert.dll 51 | True 52 | 53 | 54 | ..\..\packages\xunit.extensibility.core.2.2.0-beta4-build3444\lib\net45\xunit.core.dll 55 | True 56 | 57 | 58 | ..\..\packages\xunit.extensibility.execution.2.2.0-beta4-build3444\lib\net45\xunit.execution.desktop.dll 59 | True 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | {d8786051-5c80-49d3-a8af-9711da5cd49e} 70 | Common.Logger.Log4Net 71 | 72 | 73 | {6c3df461-2f2c-4ab9-912f-72de259d311e} 74 | Common 75 | 76 | 77 | 78 | 79 | PreserveNewest 80 | 81 | 82 | 83 | 84 | 91 | -------------------------------------------------------------------------------- /test/Common.Test/Common.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {F3E5778C-7F16-4900-98AB-3686557BBEEE} 8 | Library 9 | Properties 10 | Common.Test 11 | Common.Test 12 | v4.5.2 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | ..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll 43 | True 44 | 45 | 46 | ..\..\packages\xunit.assert.2.1.0\lib\dotnet\xunit.assert.dll 47 | True 48 | 49 | 50 | ..\..\packages\xunit.extensibility.core.2.1.0\lib\dotnet\xunit.core.dll 51 | True 52 | 53 | 54 | ..\..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll 55 | True 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | {6c3df461-2f2c-4ab9-912f-72de259d311e} 82 | Common 83 | 84 | 85 | 86 | 87 | PreserveNewest 88 | 89 | 90 | 91 | 98 | -------------------------------------------------------------------------------- /src/Common/Common.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {6C3DF461-2F2C-4AB9-912F-72DE259D311E} 8 | Library 9 | Properties 10 | Wlitsoft.Framework.Common 11 | Wlitsoft.Framework.Common 12 | v4.5.2 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | bin\Debug\Wlitsoft.Framework.Common.XML 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | bin\Release\Wlitsoft.Framework.Common.XML 33 | 34 | 35 | true 36 | 37 | 38 | Globals\Wlitsoft.Framework.snk 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | Globals\AuthorInfo.cs 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | True 79 | True 80 | Resource.resx 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | ResXFileCodeGenerator 98 | Resource.Designer.cs 99 | 100 | 101 | 102 | 103 | xcopy /y $(ProjectDir)\bin\$(ConfigurationName)\$(TargetName).dll $(SolutionDir)\src\NuGet\$(ProjectName)\lib\net45\ 104 | xcopy /y $(ProjectDir)\bin\$(ConfigurationName)\$(TargetName).xml $(SolutionDir)\src\NuGet\$(ProjectName)\lib\net45\ 105 | 106 | $(SolutionDir)\.nuget\nuget.exe pack $(SolutionDir)\src\NuGet\$(ProjectName)\$(ProjectName).nuspec -OutputDirectory $(SolutionDir)\.nuget\Output 107 | 108 | 115 | -------------------------------------------------------------------------------- /Wlitsoft.Framework.Common.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{9821178D-6AAB-4B69-8816-EDE3FCFC61AB}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{79AAFADC-1FB3-4D1A-97C0-702B703205D1}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "src\Common\Common.csproj", "{6C3DF461-2F2C-4AB9-912F-72DE259D311E}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.Test", "test\Common.Test\Common.Test.csproj", "{F3E5778C-7F16-4900-98AB-3686557BBEEE}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.Logger.Log4Net", "src\Common.Logger.Log4Net\Common.Logger.Log4Net.csproj", "{D8786051-5C80-49D3-A8AF-9711DA5CD49E}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.Logger.Log4Net.Test", "test\Common.Logger.Log4Net.Test\Common.Logger.Log4Net.Test.csproj", "{4111A247-4A0C-4C11-924A-A69A85E342D7}" 17 | EndProject 18 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.Serializer.JsonNet", "src\Common.Serializer.JsonNet\Common.Serializer.JsonNet.csproj", "{B57F3331-A875-40D2-8802-21104E28CC32}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.Serializer.JsonNet.Test", "test\Common.Serializer.JsonNet.Test\Common.Serializer.JsonNet.Test.csproj", "{5A69AA59-1B8A-4FCF-A595-4AD76CE321FC}" 21 | EndProject 22 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{8195F83E-461A-4812-8AAE-2BC2D14461F3}" 23 | EndProject 24 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{C75B2466-5C2C-4859-A57D-45E899B93B01}" 25 | ProjectSection(SolutionItems) = preProject 26 | src\NuGet\Common\Common.nuspec = src\NuGet\Common\Common.nuspec 27 | EndProjectSection 28 | EndProject 29 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common.Logger.Log4Net", "Common.Logger.Log4Net", "{44F94B02-54AC-4B37-B8E2-F68A0EC26E0D}" 30 | ProjectSection(SolutionItems) = preProject 31 | src\NuGet\Common.Logger.Log4Net\Common.Logger.Log4Net.nuspec = src\NuGet\Common.Logger.Log4Net\Common.Logger.Log4Net.nuspec 32 | EndProjectSection 33 | EndProject 34 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common.Serializer.JsonNet", "Common.Serializer.JsonNet", "{637C4F2B-23FC-4C4C-B002-AA4F16C40711}" 35 | ProjectSection(SolutionItems) = preProject 36 | src\NuGet\Common.Serializer.JsonNet\Common.Serializer.JsonNet.nuspec = src\NuGet\Common.Serializer.JsonNet\Common.Serializer.JsonNet.nuspec 37 | EndProjectSection 38 | EndProject 39 | Global 40 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 41 | Debug|Any CPU = Debug|Any CPU 42 | Release|Any CPU = Release|Any CPU 43 | EndGlobalSection 44 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 45 | {6C3DF461-2F2C-4AB9-912F-72DE259D311E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 46 | {6C3DF461-2F2C-4AB9-912F-72DE259D311E}.Debug|Any CPU.Build.0 = Debug|Any CPU 47 | {6C3DF461-2F2C-4AB9-912F-72DE259D311E}.Release|Any CPU.ActiveCfg = Release|Any CPU 48 | {6C3DF461-2F2C-4AB9-912F-72DE259D311E}.Release|Any CPU.Build.0 = Release|Any CPU 49 | {F3E5778C-7F16-4900-98AB-3686557BBEEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 50 | {F3E5778C-7F16-4900-98AB-3686557BBEEE}.Debug|Any CPU.Build.0 = Debug|Any CPU 51 | {F3E5778C-7F16-4900-98AB-3686557BBEEE}.Release|Any CPU.ActiveCfg = Release|Any CPU 52 | {F3E5778C-7F16-4900-98AB-3686557BBEEE}.Release|Any CPU.Build.0 = Release|Any CPU 53 | {D8786051-5C80-49D3-A8AF-9711DA5CD49E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 54 | {D8786051-5C80-49D3-A8AF-9711DA5CD49E}.Debug|Any CPU.Build.0 = Debug|Any CPU 55 | {D8786051-5C80-49D3-A8AF-9711DA5CD49E}.Release|Any CPU.ActiveCfg = Release|Any CPU 56 | {D8786051-5C80-49D3-A8AF-9711DA5CD49E}.Release|Any CPU.Build.0 = Release|Any CPU 57 | {4111A247-4A0C-4C11-924A-A69A85E342D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 58 | {4111A247-4A0C-4C11-924A-A69A85E342D7}.Debug|Any CPU.Build.0 = Debug|Any CPU 59 | {4111A247-4A0C-4C11-924A-A69A85E342D7}.Release|Any CPU.ActiveCfg = Release|Any CPU 60 | {4111A247-4A0C-4C11-924A-A69A85E342D7}.Release|Any CPU.Build.0 = Release|Any CPU 61 | {B57F3331-A875-40D2-8802-21104E28CC32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 62 | {B57F3331-A875-40D2-8802-21104E28CC32}.Debug|Any CPU.Build.0 = Debug|Any CPU 63 | {B57F3331-A875-40D2-8802-21104E28CC32}.Release|Any CPU.ActiveCfg = Release|Any CPU 64 | {B57F3331-A875-40D2-8802-21104E28CC32}.Release|Any CPU.Build.0 = Release|Any CPU 65 | {5A69AA59-1B8A-4FCF-A595-4AD76CE321FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 66 | {5A69AA59-1B8A-4FCF-A595-4AD76CE321FC}.Debug|Any CPU.Build.0 = Debug|Any CPU 67 | {5A69AA59-1B8A-4FCF-A595-4AD76CE321FC}.Release|Any CPU.ActiveCfg = Release|Any CPU 68 | {5A69AA59-1B8A-4FCF-A595-4AD76CE321FC}.Release|Any CPU.Build.0 = Release|Any CPU 69 | EndGlobalSection 70 | GlobalSection(SolutionProperties) = preSolution 71 | HideSolutionNode = FALSE 72 | EndGlobalSection 73 | GlobalSection(NestedProjects) = preSolution 74 | {6C3DF461-2F2C-4AB9-912F-72DE259D311E} = {9821178D-6AAB-4B69-8816-EDE3FCFC61AB} 75 | {F3E5778C-7F16-4900-98AB-3686557BBEEE} = {79AAFADC-1FB3-4D1A-97C0-702B703205D1} 76 | {D8786051-5C80-49D3-A8AF-9711DA5CD49E} = {9821178D-6AAB-4B69-8816-EDE3FCFC61AB} 77 | {4111A247-4A0C-4C11-924A-A69A85E342D7} = {79AAFADC-1FB3-4D1A-97C0-702B703205D1} 78 | {B57F3331-A875-40D2-8802-21104E28CC32} = {9821178D-6AAB-4B69-8816-EDE3FCFC61AB} 79 | {5A69AA59-1B8A-4FCF-A595-4AD76CE321FC} = {79AAFADC-1FB3-4D1A-97C0-702B703205D1} 80 | {8195F83E-461A-4812-8AAE-2BC2D14461F3} = {9821178D-6AAB-4B69-8816-EDE3FCFC61AB} 81 | {C75B2466-5C2C-4859-A57D-45E899B93B01} = {8195F83E-461A-4812-8AAE-2BC2D14461F3} 82 | {44F94B02-54AC-4B37-B8E2-F68A0EC26E0D} = {8195F83E-461A-4812-8AAE-2BC2D14461F3} 83 | {637C4F2B-23FC-4C4C-B002-AA4F16C40711} = {8195F83E-461A-4812-8AAE-2BC2D14461F3} 84 | EndGlobalSection 85 | EndGlobal 86 | -------------------------------------------------------------------------------- /src/Common/Properties/Resource.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | 在枚举项({0})未找到 Description 标记信息。 122 | 123 | 124 | 参数“{0}”不能为空引用(null)。 125 | 126 | 127 | 参数“{0}”不能为空字符串(String.Empty)或空引用(null)参数“{0}”不能为空字符串(String.Empty)或空引用(null)。 128 | 129 | -------------------------------------------------------------------------------- /src/Common/Extension/StringExtension.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 字符串类型扩展方法静态类。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月04日 新建 7 | *********************************************************************************************************************/ 8 | 9 | using System; 10 | using System.Text; 11 | using System.Xml.Linq; 12 | using Wlitsoft.Framework.Common.Core; 13 | using Wlitsoft.Framework.Common.Exception; 14 | using Wlitsoft.Framework.Common.Security; 15 | 16 | namespace Wlitsoft.Framework.Common.Extension 17 | { 18 | /// 19 | /// 字符串类型扩展方法静态类。 20 | /// 21 | public static class StringExtension 22 | { 23 | #region 将 json 字符串转换为指定类型的对象表示形式 24 | 25 | /// 26 | /// 将 json 字符串转换为指定类型的对象表示形式。 27 | /// 28 | /// 要转换成的对象类型。 29 | /// json 字符串。 30 | /// 转换完后的 JSON 对象。 31 | public static T ToJsonObject(this string json) 32 | { 33 | #region 参数校验 34 | 35 | if (string.IsNullOrEmpty(json)) 36 | throw new StringNullOrEmptyException(nameof(json)); 37 | 38 | #endregion 39 | 40 | ISerializer serializer = App.SerializerService.GetJsonSerializer(); 41 | return serializer.Deserialize(json); 42 | } 43 | 44 | #endregion 45 | 46 | #region 将 xml 字符串转换为指定类型的对象表示形式 47 | 48 | /// 49 | /// 将给定 XML 字符串()转换为指定类型的对象表示形式。 50 | /// 51 | /// 要转换成的对象类型。 52 | /// json 字符串。 53 | /// 转换完后的 Xml 对象。 54 | public static T ToXmlObject(this string xml) 55 | { 56 | #region 参数校验 57 | 58 | if (string.IsNullOrEmpty(xml)) 59 | throw new StringNullOrEmptyException(nameof(xml)); 60 | 61 | #endregion 62 | 63 | ISerializer serializer = App.SerializerService.GetXmlSerializer(); 64 | return serializer.Deserialize(xml); 65 | } 66 | 67 | /// 68 | /// 将给定 XML 字符串()转换为对象表示形式。 69 | /// 70 | /// 要转换的 XML 字符串。 71 | /// 要转换成的对象类型。 72 | /// 转换完后的 Xml 对象。 73 | public static object ToXmlObject(this string xml, Type type) 74 | { 75 | #region 参数校验 76 | 77 | if (string.IsNullOrEmpty(xml)) 78 | throw new StringNullOrEmptyException(nameof(xml)); 79 | 80 | if (type == null) 81 | throw new ObjectNullException(nameof(type)); 82 | 83 | #endregion 84 | 85 | ISerializer serializer = App.SerializerService.GetXmlSerializer(); 86 | return serializer.Deserialize(type, xml); 87 | } 88 | 89 | #endregion 90 | 91 | #region 格式化 Xml 字符串 92 | 93 | /// 94 | /// 将给定 XML 字符串()去除格式并返回一个新的 XML 字符串。 95 | /// 96 | /// 要格式化的原始 XML 字符串。 97 | /// 格式化后的 XML 字符串。 98 | public static string FormatXmlString(this string xml) 99 | { 100 | // ReSharper disable once IntroduceOptionalParameters.Global 101 | return FormatXmlString(xml, SaveOptions.DisableFormatting); 102 | } 103 | 104 | /// 105 | /// 根据 提供的选项将给定 XML 字符串()格式化后并返回一个新的 XML 字符串。 106 | /// 107 | /// 要格式化的原始 XML 字符串。 108 | /// 指定序列化选项。 109 | /// 格式化后的 XML 字符串。 110 | public static string FormatXmlString(this string xml, SaveOptions saveOptions) 111 | { 112 | #region 参数校验 113 | 114 | if (string.IsNullOrEmpty(xml)) 115 | throw new StringNullOrEmptyException(nameof(xml)); 116 | 117 | #endregion 118 | 119 | XDocument xDoc = XDocument.Parse(xml); 120 | return xDoc.ToString(saveOptions); 121 | } 122 | 123 | #endregion 124 | 125 | #region 获取大写的 MD5 签名字符串 126 | 127 | /// 128 | /// 将给定的要加密的字符串()使用 utf8 编码方式,获取大写的 MD5 签名字符串。 129 | /// 130 | /// 要加密的字符串。 131 | /// 大写的 MD5 签名字符串。 132 | public static string GetMD5(this string str) 133 | { 134 | return new StringEncrypt(str).GetMD5(); 135 | } 136 | 137 | /// 138 | /// 将给定的要加密的字符串()使用指定编码方式,获取大写的 MD5 签名字符串。 139 | /// 140 | /// 要加密的字符串。 141 | /// 编码方式。 142 | /// 大写的 MD5 签名字符串。 143 | public static string GetMD5(this string str, Encoding encoding) 144 | { 145 | return new StringEncrypt(str, encoding).GetMD5(); 146 | } 147 | 148 | #endregion 149 | 150 | #region 获取 SHA1 签名字符串 151 | 152 | /// 153 | /// 将给定的要加密的字符串()使用 utf8 编码方式,获取 SHA1 签名字符串。 154 | /// 155 | /// 要加密的字符串。 156 | /// 大写的 SHA1 签名字符串。 157 | public static string GetSHA1(this string str) 158 | { 159 | return new StringEncrypt(str).GetSHA1(); 160 | } 161 | 162 | /// 163 | /// 将给定的要加密的字符串()使用指定编码方式,获取 SHA1 签名字符串。 164 | /// 165 | /// 要加密的字符串。 166 | /// 编码方式。 167 | /// 大写的 SHA1 签名字符串。 168 | public static string GetSHA1(this string str, Encoding encoding) 169 | { 170 | return new StringEncrypt(str, encoding).GetSHA1(); 171 | } 172 | 173 | #endregion 174 | 175 | #region 获取一个新的随机字符串 176 | 177 | /// 178 | /// 获取一个新的随机字符串。 179 | /// 180 | /// 随机字符串长度。 181 | /// 获取到的随机字符串。 182 | public static string NewNonceStr(int length) 183 | { 184 | Random r = new Random(); 185 | var sb = new StringBuilder(); 186 | string[] strs = 187 | { 188 | "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", 189 | "v", "w", "x", "y", "z", 190 | "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", 191 | "V", "W", "X", "Y", "Z" 192 | }; 193 | int strsLength = strs.Length; 194 | for (int i = 0; i < length; i++) 195 | { 196 | sb.Append(strs[r.Next(strsLength - 1)]); 197 | } 198 | return sb.ToString(); 199 | } 200 | 201 | #endregion 202 | 203 | } 204 | } 205 | -------------------------------------------------------------------------------- /src/Common/Net/HttpReqeustClient.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * Http 请求客户端。 4 | * 5 | * 变更历史: 6 | * 作者:李亮 时间:2016年11月06日 新建 7 | * 8 | *********************************************************************************************************************/ 9 | 10 | using System; 11 | using System.Collections.Generic; 12 | using System.IO; 13 | using System.Linq; 14 | using System.Net; 15 | using System.Net.Http; 16 | using System.Net.Security; 17 | using System.Security.Cryptography.X509Certificates; 18 | using Wlitsoft.Framework.Common.Exception; 19 | using Wlitsoft.Framework.Common.Extension; 20 | 21 | namespace Wlitsoft.Framework.Common.Net 22 | { 23 | /// 24 | /// Http 请求客户端。 25 | /// 26 | public class HttpReqeustClient 27 | { 28 | #region 公共属性 29 | 30 | /// 31 | /// 获取当前请求使用的 实例。 32 | /// 33 | public HttpClient HttpClient { get; private set; } 34 | 35 | /// 36 | /// 获取包含状态码和数据的 HTTP 相应消息。 37 | /// 38 | public HttpResponseMessage HttpResponseMessage { get; private set; } 39 | 40 | /// 41 | /// 获取Http请求头集合。 42 | /// 43 | public Dictionary Headers { get; } 44 | 45 | /// 46 | /// 获取或设置Cookie集合容器。 47 | /// 48 | public CookieContainer CookieContainer { get; set; } 49 | 50 | /// 51 | /// 获取或设置要使用的安全证书。 52 | /// 53 | public X509Certificate Certificate { get; set; } 54 | 55 | #endregion 56 | 57 | #region 构造方法 58 | 59 | /// 60 | /// 初始化 类的新实例。 61 | /// 62 | public HttpReqeustClient() 63 | { 64 | this.Headers = new Dictionary(); 65 | } 66 | 67 | #endregion 68 | 69 | #region 根据 发送 GET 请求获取响应的文本 70 | 71 | /// 72 | /// 根据 发送 GET 请求获取响应的文本。 73 | /// 74 | /// 要请求的 url 地址。 75 | /// 服务器响应的文本。 76 | public string HttpGetString(string url) 77 | { 78 | this.HttpSend(url, HttpMethod.Get, null); 79 | return this.HttpResponseMessage.GetResultString(); 80 | } 81 | 82 | #endregion 83 | 84 | #region 根据 发送 GET 请求获取响应的二进制数组。 85 | 86 | /// 87 | /// 根据 发送 GET 请求获取响应的二进制数组。 88 | /// 89 | /// 要请求的 url 地址。 90 | /// 服务器响应的二进制数组。 91 | public byte[] HttpGetBytes(string url) 92 | { 93 | this.HttpSend(url, HttpMethod.Get, null); 94 | return this.HttpResponseMessage.GetResultBytes(); 95 | } 96 | 97 | #endregion 98 | 99 | #region 根据 发送 POST 请求获取响应的文本 100 | 101 | /// 102 | /// 根据 发送 POST 请求获取响应的文本。 103 | /// 104 | /// 要请求的 url 地址。 105 | /// 要发送的数据。 106 | /// 服务器响应的文本。 107 | public string HttpPost(string url, Dictionary postData) 108 | { 109 | #region 参数校验 110 | 111 | if (postData == null) 112 | throw new ObjectNullException(nameof(postData)); 113 | 114 | #endregion 115 | 116 | HttpPostDataDictionary dic = new HttpPostDataDictionary(); 117 | foreach (var item in postData) 118 | dic.AddText(item.Key, item.Value); 119 | return this.HttpPost(url, dic); 120 | } 121 | 122 | /// 123 | /// 根据 发送 POST 请求获取响应的文本。 124 | /// 125 | /// 要请求的 url 地址。 126 | /// 要发送的数据。 127 | /// 服务器响应的文本。 128 | public string HttpPost(string url, HttpPostDataDictionary postData) 129 | { 130 | string boundary = string.Format("----{0}", DateTime.Now.Ticks.ToString("x")); 131 | MultipartFormDataContent formDataContent = new MultipartFormDataContent(boundary); 132 | foreach (var item in postData) 133 | { 134 | object value = item.Value.Value; 135 | switch (item.Value.Key) 136 | { 137 | case HttpPostDataType.Text: 138 | formDataContent.Add(new StringContent(value.ToString()), item.Key); 139 | break; 140 | case HttpPostDataType.FilePath: 141 | throw new System.NotImplementedException(); 142 | case HttpPostDataType.FileStream: 143 | FileStream fileStream = (FileStream)value; 144 | formDataContent.Add(new StreamContent(fileStream), item.Key, Path.GetFileName(fileStream.Name)); 145 | break; 146 | } 147 | } 148 | 149 | this.HttpPost(url, formDataContent); 150 | return this.HttpResponseMessage.GetResultString(); 151 | } 152 | 153 | /// 154 | /// 根据 发送 POST 请求获取响应的文本。 155 | /// 156 | /// 要请求的 url 地址。 157 | /// HTTP 实体正文对象。 158 | /// 服务器响应的文本。 159 | public string HttpPost(string url, HttpContent httpContent) 160 | { 161 | this.HttpSend(url, HttpMethod.Post, httpContent); 162 | return this.HttpResponseMessage.GetResultString(); 163 | } 164 | 165 | #endregion 166 | 167 | #region 私有方法 168 | 169 | #region 根据 发送请求获取响应的文本 170 | 171 | /// 172 | /// 根据 发送请求获取响应的文本。 173 | /// 174 | /// 要请求的 url 地址。 175 | /// 请求的方式。 176 | /// HTTP 实体正文对象。 177 | private void HttpSend(string url, HttpMethod httpMethod, HttpContent httpContent) 178 | { 179 | #region 参数校验 180 | 181 | if (string.IsNullOrEmpty(url)) 182 | throw new StringNullOrEmptyException(nameof(url)); 183 | 184 | #endregion 185 | 186 | this.HttpClient = this.CreateHttpClient(); 187 | 188 | if (httpMethod == HttpMethod.Get) 189 | this.HttpResponseMessage = this.HttpClient.GetAsync(url).Result; 190 | if (httpMethod == HttpMethod.Post) 191 | this.HttpResponseMessage = this.HttpClient.PostAsync(url, httpContent).Result; 192 | } 193 | 194 | #endregion 195 | 196 | #endregion 197 | 198 | #region 创建 HttpClient 199 | 200 | /// 201 | /// 创建 对象。 202 | /// 203 | /// 初始化完后的 对象。 204 | private HttpClient CreateHttpClient() 205 | { 206 | WebRequestHandler handler = new WebRequestHandler(); 207 | 208 | if (this.Certificate != null) 209 | { 210 | handler.ClientCertificates.Add(this.Certificate); 211 | 212 | //设置证书校验回掉。 213 | ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => errors == SslPolicyErrors.None; 214 | } 215 | 216 | if (this.CookieContainer != null) 217 | { 218 | handler.UseCookies = true; 219 | handler.CookieContainer = this.CookieContainer; 220 | } 221 | 222 | HttpClient client = new HttpClient(handler); 223 | 224 | #region Http头 225 | 226 | if (this.Headers.Any()) 227 | { 228 | foreach (var item in this.Headers) 229 | { 230 | client.DefaultRequestHeaders.Add(item.Key, item.Value); 231 | } 232 | } 233 | 234 | #endregion 235 | 236 | return client; 237 | } 238 | 239 | #endregion 240 | 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/Common/Serialize/Dynamic/DynamicJson.cs: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************** 2 | * 描述: 3 | * 动态 Json 对象。 4 | * 声明:本代码来源于网络。 5 | * 6 | * 变更历史: 7 | * 作者:李亮 时间:2016年12月23日 新建 8 | *********************************************************************************************************************/ 9 | using System; 10 | using System.Collections; 11 | using System.Collections.Generic; 12 | using System.Diagnostics; 13 | using System.Dynamic; 14 | using System.IO; 15 | using System.Linq; 16 | using System.Reflection; 17 | using System.Runtime.Serialization.Json; 18 | using System.Text; 19 | using System.Xml; 20 | using System.Xml.Linq; 21 | 22 | namespace Wlitsoft.Framework.Common.Serialize.Dynamic 23 | { 24 | /// 25 | /// 动态 Json 对象。 26 | /// 27 | public class DynamicJson : DynamicObject 28 | { 29 | /// 30 | /// Json 类型。 31 | /// 32 | private enum JsonType 33 | { 34 | /// 35 | /// 字符串。 36 | /// 37 | @string, 38 | 39 | /// 40 | /// 数字。 41 | /// 42 | number, 43 | 44 | /// 45 | /// 布尔。 46 | /// 47 | boolean, 48 | 49 | /// 50 | /// 对象。 51 | /// 52 | @object, 53 | 54 | /// 55 | /// 数组。 56 | /// 57 | array, 58 | 59 | /// 60 | /// 空。 61 | /// 62 | @null 63 | } 64 | 65 | // public static methods 66 | 67 | /// from JsonSring to DynamicJson 68 | public static dynamic Parse(string json) 69 | { 70 | return Parse(json, Encoding.Unicode); 71 | } 72 | 73 | /// from JsonSring to DynamicJson 74 | public static dynamic Parse(string json, Encoding encoding) 75 | { 76 | using (var reader = JsonReaderWriterFactory.CreateJsonReader(encoding.GetBytes(json), XmlDictionaryReaderQuotas.Max)) 77 | { 78 | return ToValue(XElement.Load(reader)); 79 | } 80 | } 81 | 82 | /// from JsonSringStream to DynamicJson 83 | public static dynamic Parse(Stream stream) 84 | { 85 | using (var reader = JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max)) 86 | { 87 | return ToValue(XElement.Load(reader)); 88 | } 89 | } 90 | 91 | /// from JsonSringStream to DynamicJson 92 | public static dynamic Parse(Stream stream, Encoding encoding) 93 | { 94 | using (var reader = JsonReaderWriterFactory.CreateJsonReader(stream, encoding, XmlDictionaryReaderQuotas.Max, _ => { })) 95 | { 96 | return ToValue(XElement.Load(reader)); 97 | } 98 | } 99 | 100 | /// create JsonSring from primitive or IEnumerable or Object({public property name:property value}) 101 | public static string Serialize(object obj) 102 | { 103 | return CreateJsonString(new XStreamingElement("root", CreateTypeAttr(GetJsonType(obj)), CreateJsonNode(obj))); 104 | } 105 | 106 | // private static methods 107 | 108 | private static dynamic ToValue(XElement element) 109 | { 110 | var type = (JsonType)Enum.Parse(typeof(JsonType), element.Attribute("type").Value); 111 | switch (type) 112 | { 113 | case JsonType.boolean: 114 | return (bool)element; 115 | case JsonType.number: 116 | return (double)element; 117 | case JsonType.@string: 118 | return (string)element; 119 | case JsonType.@object: 120 | case JsonType.array: 121 | return new DynamicJson(element, type); 122 | case JsonType.@null: 123 | default: 124 | return null; 125 | } 126 | } 127 | 128 | private static JsonType GetJsonType(object obj) 129 | { 130 | if (obj == null) return JsonType.@null; 131 | 132 | switch (Type.GetTypeCode(obj.GetType())) 133 | { 134 | case TypeCode.Boolean: 135 | return JsonType.boolean; 136 | case TypeCode.String: 137 | case TypeCode.Char: 138 | case TypeCode.DateTime: 139 | return JsonType.@string; 140 | case TypeCode.Int16: 141 | case TypeCode.Int32: 142 | case TypeCode.Int64: 143 | case TypeCode.UInt16: 144 | case TypeCode.UInt32: 145 | case TypeCode.UInt64: 146 | case TypeCode.Single: 147 | case TypeCode.Double: 148 | case TypeCode.Decimal: 149 | case TypeCode.SByte: 150 | case TypeCode.Byte: 151 | return JsonType.number; 152 | case TypeCode.Object: 153 | return (obj is IEnumerable) ? JsonType.array : JsonType.@object; 154 | case TypeCode.DBNull: 155 | case TypeCode.Empty: 156 | default: 157 | return JsonType.@null; 158 | } 159 | } 160 | 161 | private static XAttribute CreateTypeAttr(JsonType type) 162 | { 163 | return new XAttribute("type", type.ToString()); 164 | } 165 | 166 | private static object CreateJsonNode(object obj) 167 | { 168 | var type = GetJsonType(obj); 169 | switch (type) 170 | { 171 | case JsonType.@string: 172 | case JsonType.number: 173 | return obj; 174 | case JsonType.boolean: 175 | return obj.ToString().ToLower(); 176 | case JsonType.@object: 177 | return CreateXObject(obj); 178 | case JsonType.array: 179 | return CreateXArray(obj as IEnumerable); 180 | case JsonType.@null: 181 | default: 182 | return null; 183 | } 184 | } 185 | 186 | private static IEnumerable CreateXArray(T obj) where T : IEnumerable 187 | { 188 | return obj.Cast() 189 | .Select(o => new XStreamingElement("item", CreateTypeAttr(GetJsonType(o)), CreateJsonNode(o))); 190 | } 191 | 192 | private static IEnumerable CreateXObject(object obj) 193 | { 194 | return obj.GetType() 195 | .GetProperties(BindingFlags.Public | BindingFlags.Instance) 196 | .Select(pi => new { Name = pi.Name, Value = pi.GetValue(obj, null) }) 197 | .Select(a => new XStreamingElement(a.Name, CreateTypeAttr(GetJsonType(a.Value)), CreateJsonNode(a.Value))); 198 | } 199 | 200 | private static string CreateJsonString(XStreamingElement element) 201 | { 202 | using (var ms = new MemoryStream()) 203 | using (var writer = JsonReaderWriterFactory.CreateJsonWriter(ms, Encoding.Unicode)) 204 | { 205 | element.WriteTo(writer); 206 | writer.Flush(); 207 | return Encoding.Unicode.GetString(ms.ToArray()); 208 | } 209 | } 210 | 211 | // dynamic structure represents JavaScript Object/Array 212 | 213 | readonly XElement xml; 214 | readonly JsonType jsonType; 215 | 216 | /// create blank JSObject 217 | public DynamicJson() 218 | { 219 | xml = new XElement("root", CreateTypeAttr(JsonType.@object)); 220 | jsonType = JsonType.@object; 221 | } 222 | 223 | private DynamicJson(XElement element, JsonType type) 224 | { 225 | Debug.Assert(type == JsonType.array || type == JsonType.@object); 226 | 227 | xml = element; 228 | jsonType = type; 229 | } 230 | 231 | public bool IsObject { get { return jsonType == JsonType.@object; } } 232 | 233 | public bool IsArray { get { return jsonType == JsonType.array; } } 234 | 235 | /// has property or not 236 | public bool IsDefined(string name) 237 | { 238 | return IsObject && (xml.Element(name) != null); 239 | } 240 | 241 | /// has property or not 242 | public bool IsDefined(int index) 243 | { 244 | return IsArray && (xml.Elements().ElementAtOrDefault(index) != null); 245 | } 246 | 247 | /// delete property 248 | public bool Delete(string name) 249 | { 250 | var elem = xml.Element(name); 251 | if (elem != null) 252 | { 253 | elem.Remove(); 254 | return true; 255 | } 256 | else return false; 257 | } 258 | 259 | /// delete property 260 | public bool Delete(int index) 261 | { 262 | var elem = xml.Elements().ElementAtOrDefault(index); 263 | if (elem != null) 264 | { 265 | elem.Remove(); 266 | return true; 267 | } 268 | else return false; 269 | } 270 | 271 | /// mapping to Array or Class by Public PropertyName 272 | public T Deserialize() 273 | { 274 | return (T)Deserialize(typeof(T)); 275 | } 276 | 277 | private object Deserialize(Type type) 278 | { 279 | return (IsArray) ? DeserializeArray(type) : DeserializeObject(type); 280 | } 281 | 282 | private dynamic DeserializeValue(XElement element, Type elementType) 283 | { 284 | var value = ToValue(element); 285 | if (value is DynamicJson) 286 | { 287 | value = ((DynamicJson)value).Deserialize(elementType); 288 | } 289 | return Convert.ChangeType(value, elementType); 290 | } 291 | 292 | private object DeserializeObject(Type targetType) 293 | { 294 | var result = Activator.CreateInstance(targetType); 295 | var dict = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance) 296 | .Where(p => p.CanWrite) 297 | .ToDictionary(pi => pi.Name, pi => pi); 298 | foreach (var item in xml.Elements()) 299 | { 300 | PropertyInfo propertyInfo; 301 | if (!dict.TryGetValue(item.Name.LocalName, out propertyInfo)) continue; 302 | var value = DeserializeValue(item, propertyInfo.PropertyType); 303 | propertyInfo.SetValue(result, value, null); 304 | } 305 | return result; 306 | } 307 | 308 | private object DeserializeArray(Type targetType) 309 | { 310 | if (targetType.IsArray) // Foo[] 311 | { 312 | var elemType = targetType.GetElementType(); 313 | dynamic array = Array.CreateInstance(elemType, xml.Elements().Count()); 314 | var index = 0; 315 | foreach (var item in xml.Elements()) 316 | { 317 | array[index++] = DeserializeValue(item, elemType); 318 | } 319 | return array; 320 | } 321 | else // List 322 | { 323 | var elemType = targetType.GetGenericArguments()[0]; 324 | dynamic list = Activator.CreateInstance(targetType); 325 | foreach (var item in xml.Elements()) 326 | { 327 | list.Add(DeserializeValue(item, elemType)); 328 | } 329 | return list; 330 | } 331 | } 332 | 333 | // Delete 334 | public override bool TryInvoke(InvokeBinder binder, object[] args, out object result) 335 | { 336 | result = (IsArray) 337 | ? Delete((int)args[0]) 338 | : Delete((string)args[0]); 339 | return true; 340 | } 341 | 342 | // IsDefined, if has args then TryGetMember 343 | public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) 344 | { 345 | if (args.Length > 0) 346 | { 347 | result = null; 348 | return false; 349 | } 350 | 351 | result = IsDefined(binder.Name); 352 | return true; 353 | } 354 | 355 | // Deserialize or foreach(IEnumerable) 356 | public override bool TryConvert(ConvertBinder binder, out object result) 357 | { 358 | if (binder.Type == typeof(IEnumerable) || binder.Type == typeof(object[])) 359 | { 360 | var ie = (IsArray) 361 | ? xml.Elements().Select(x => ToValue(x)) 362 | : xml.Elements().Select(x => (dynamic)new KeyValuePair(x.Name.LocalName, ToValue(x))); 363 | result = (binder.Type == typeof(object[])) ? ie.ToArray() : ie; 364 | } 365 | else 366 | { 367 | result = Deserialize(binder.Type); 368 | } 369 | return true; 370 | } 371 | 372 | private bool TryGet(XElement element, out object result) 373 | { 374 | if (element == null) 375 | { 376 | result = null; 377 | return false; 378 | } 379 | 380 | result = ToValue(element); 381 | return true; 382 | } 383 | 384 | public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) 385 | { 386 | return (IsArray) 387 | ? TryGet(xml.Elements().ElementAtOrDefault((int)indexes[0]), out result) 388 | : TryGet(xml.Element((string)indexes[0]), out result); 389 | } 390 | 391 | public override bool TryGetMember(GetMemberBinder binder, out object result) 392 | { 393 | return (IsArray) 394 | ? TryGet(xml.Elements().ElementAtOrDefault(int.Parse(binder.Name)), out result) 395 | : TryGet(xml.Element(binder.Name), out result); 396 | } 397 | 398 | private bool TrySet(string name, object value) 399 | { 400 | var type = GetJsonType(value); 401 | var element = xml.Element(name); 402 | if (element == null) 403 | { 404 | xml.Add(new XElement(name, CreateTypeAttr(type), CreateJsonNode(value))); 405 | } 406 | else 407 | { 408 | element.Attribute("type").Value = type.ToString(); 409 | element.ReplaceNodes(CreateJsonNode(value)); 410 | } 411 | 412 | return true; 413 | } 414 | 415 | private bool TrySet(int index, object value) 416 | { 417 | var type = GetJsonType(value); 418 | var e = xml.Elements().ElementAtOrDefault(index); 419 | if (e == null) 420 | { 421 | xml.Add(new XElement("item", CreateTypeAttr(type), CreateJsonNode(value))); 422 | } 423 | else 424 | { 425 | e.Attribute("type").Value = type.ToString(); 426 | e.ReplaceNodes(CreateJsonNode(value)); 427 | } 428 | 429 | return true; 430 | } 431 | 432 | public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) 433 | { 434 | return (IsArray) 435 | ? TrySet((int)indexes[0], value) 436 | : TrySet((string)indexes[0], value); 437 | } 438 | 439 | public override bool TrySetMember(SetMemberBinder binder, object value) 440 | { 441 | return (IsArray) 442 | ? TrySet(int.Parse(binder.Name), value) 443 | : TrySet(binder.Name, value); 444 | } 445 | 446 | public override IEnumerable GetDynamicMemberNames() 447 | { 448 | return (IsArray) 449 | ? xml.Elements().Select((x, i) => i.ToString()) 450 | : xml.Elements().Select(x => x.Name.LocalName); 451 | } 452 | 453 | /// Serialize to JsonString 454 | public override string ToString() 455 | { 456 | // is can't serialize. replace to 457 | foreach (var elem in xml.Descendants().Where(x => x.Attribute("type").Value == "null")) 458 | { 459 | elem.RemoveNodes(); 460 | } 461 | return CreateJsonString(new XStreamingElement("root", CreateTypeAttr(jsonType), xml.Elements())); 462 | } 463 | } 464 | } --------------------------------------------------------------------------------