Skip to content

Commit

Permalink
以XML格式从config配置文件读取连接字符串
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Jun 21, 2018
1 parent 48e278c commit 6000a47
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 128 deletions.
29 changes: 15 additions & 14 deletions Test/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using NewLife.Caching;
using NewLife.Log;
using NewLife.Net;
Expand Down Expand Up @@ -39,7 +40,7 @@ private static void Main(String[] args)
try
{
#endif
Test1();
Test2();
#if !DEBUG
}
catch (Exception ex)
Expand Down Expand Up @@ -111,20 +112,20 @@ static void Test1()

static void Test2()
{
using (var mmf = MemoryMappedFile.CreateFromFile("mmf.db", FileMode.OpenOrCreate, "mmf", 1 << 10))
var file = "web.config".GetFullPath();
if (!File.Exists(file)) file = "{0}.config".F(AppDomain.CurrentDomain.FriendlyName).GetFullPath();

// 读取配置文件
var doc = new XmlDocument();
doc.Load(file);
var nodes = doc.SelectNodes("/configuration/connectionStrings/add");
foreach (XmlNode item in nodes)
{
var ms = mmf.CreateViewStream(8, 64);
var str = ms.ReadArray().ToStr();
XTrace.WriteLine(str);

str = "学无先后达者为师 " + DateTime.Now;
ms.Position = 0;
ms.WriteArray(str.GetBytes());
//ms.Flush();

//ms.Position = 0;
//str = ms.ReadArray().ToStr();
//Console.WriteLine(str);
var name = item.Attributes["name"]?.Value;
var connstr = item.Attributes["connectionString"]?.Value;
var provider = item.Attributes["providerName"]?.Value;

Console.WriteLine($"name={name} connstr={connstr} provider={provider}");
}
}

Expand Down
10 changes: 4 additions & 6 deletions TestST/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ static void Main(String[] args)

var sw = Stopwatch.StartNew();

Test3();
Test2();

sw.Stop();
Console.WriteLine("OK! {0:n0}ms", sw.ElapsedMilliseconds);
Expand Down Expand Up @@ -49,12 +49,10 @@ private static void Svr_Received(Object sender, ReceivedEventArgs e)

static void Test2()
{
var css = new ConfigurationBuilder()
.AddXmlFile("TestST.dll.config")
.Build().GetSection("connectionStrings").GetSection("add");
foreach (var item in css.GetChildren())
var cs = DAL.ConnStrs;
foreach (var item in cs)
{
Console.WriteLine("{0} {1} {2} {3}", item.Key, item["name"], item["connectionString"], item["providerName"]);
Console.WriteLine("{0}={1}", item.Key, item.Value);
}
}

Expand Down
93 changes: 18 additions & 75 deletions XCode/DataAccessLayer/DAL.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using NewLife;
using NewLife.Log;
using NewLife.Reflection;
using XCode.Code;
#if __CORE__
using Microsoft.Extensions.Configuration;
#endif

namespace XCode.DataAccessLayer
{
Expand Down Expand Up @@ -122,95 +119,41 @@ public static Dictionary<String, String> ConnStrs
lock (_connTypes)
{
if (_connStrs != null) return _connStrs;
var cs = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase);

#if !__CORE__
// 读取配置文件
var css = ConfigurationManager.ConnectionStrings;
if (css != null && css.Count > 0)
{
foreach (ConnectionStringSettings set in css)
{
var name = set.Name;
var connstr = set.ConnectionString;
var provider = set.ProviderName;
if (connstr.IsNullOrWhiteSpace()) continue;
if (name.EqualIgnoreCase("LocalSqlServer", "LocalMySqlServer")) continue;

var type = DbFactory.GetProviderType(connstr, provider);
if (type == null) XTrace.WriteLine("无法识别{0}的提供者{1}!", name, provider);
var cs = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase);

cs.Add(name, set.ConnectionString);
_connTypes.Add(name, type);
}
}
_connStrs = cs;
#else
var file = "web.config".GetFullPath();
if (!File.Exists(file)) file = "{0}.exe.config".F(AppDomain.CurrentDomain.FriendlyName).GetFullPath();
if (!File.Exists(file)) file = "{0}.dll.config".F(AppDomain.CurrentDomain.FriendlyName).GetFullPath();
var fname = AppDomain.CurrentDomain.FriendlyName;
if (!File.Exists(file)) file = "{0}.config".F(fname).GetFullPath();
if (!File.Exists(file)) file = "{0}.exe.config".F(fname).GetFullPath();
if (!File.Exists(file)) file = "{0}.dll.config".F(fname).GetFullPath();

if (File.Exists(file))
{
// 读取配置文件
var css = new ConfigurationBuilder()
.AddXmlFile(file)
.Build().GetSection("connectionStrings")?.GetSection("add");
if (css != null)
var doc = new XmlDocument();
doc.Load(file);
var nodes = doc.SelectNodes("/configuration/connectionStrings/add");
if (nodes != null)
{
foreach (var item in css.GetChildren())
foreach (XmlNode item in nodes)
{
var name = item["name"];
var constr = item["connectionString"];
var provider = item["providerName"];
if (constr.IsNullOrWhiteSpace()) continue;
if (name.EqualIgnoreCase("LocalSqlServer", "LocalMySqlServer")) continue;

var type = DbFactory.GetProviderType(constr, provider);
if (type == null) XTrace.WriteLine("无法识别{0}的提供者{1}!", name, provider);
var name = item.Attributes["name"]?.Value;
var connstr = item.Attributes["connectionString"]?.Value;
var provider = item.Attributes["providerName"]?.Value;

cs.Add(name, constr);
_connTypes.Add(name, type);
}
}
}

//var settings = "appsettings.json".GetFullPath();
//if (File.Exists(settings))

//根据当前程序执行目录而不是当前dll/exe所在目录来获取appsettings.json文件,避免将appsettings.json的操作改成复制到输出目录
var css2 = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile("appsettings.Development.json", true, true)
.Build()
.GetSection("connectionStrings");
{
// 读取配置文件

//var css2 = new ConfigurationBuilder().AddJsonFile(settings).Build().GetSection("connectionStrings");
// var css2 = new ConfigurationBuilder()
//.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
//.Build().GetSection("connectionStrings");
if (css2 != null)
{
foreach (var item in css2.GetChildren())
{
var name = item.Path.Substring(item.Path.IndexOf(":") + 1);
var constr = item["connectionString"];
var provider = item["providerName"];
if (name.IsNullOrEmpty() || connstr.IsNullOrWhiteSpace()) continue;
if (name.EqualIgnoreCase("LocalSqlServer", "LocalMySqlServer")) continue;

var type = DbFactory.GetProviderType(constr, provider);
var type = DbFactory.GetProviderType(connstr, provider);
if (type == null) XTrace.WriteLine("无法识别{0}的提供者{1}!", name, provider);

cs.Add(name, constr);
cs.Add(name, connstr);
_connTypes.Add(name, type);
}

}
}
_connStrs = cs;
#endif
}
return _connStrs;
}
Expand Down
5 changes: 0 additions & 5 deletions XCode/XCode.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,10 @@
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Data" />
<Reference Include="System.Management" />
<Reference Include="System.Security" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.XML" />
</ItemGroup>
<ItemGroup>
Expand Down
5 changes: 0 additions & 5 deletions XCode/XCode40.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,10 @@
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Data" />
<Reference Include="System.Management" />
<Reference Include="System.Security" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.XML" />
</ItemGroup>
<ItemGroup Condition="'$(Configuration)|$(Platform)' == 'Net4Debug|AnyCPU'">
Expand Down
10 changes: 3 additions & 7 deletions XCodeST/XCodeST.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>XCode</AssemblyName>
<RootNamespace>XCode</RootNamespace>
<AssemblyTitle>大数据中间件</AssemblyTitle>
<Description>分布式大数据中间件</Description>
<AssemblyTitle>数据中间件</AssemblyTitle>
<Description>数据中间件、MySQL、SQLite、SqlServer、Oracle</Description>
<Company>新生命开发团队</Company>
<Copyright>©2002-2018 新生命开发团队 http://www.NewLifeX.com</Copyright>
<Copyright>©2002-2018 新生命开发团队</Copyright>
<FileVersion>9.8.2018.0605</FileVersion>
<AssemblyVersion>9.8.*</AssemblyVersion>
<!--是否确定版本,false以支持*-->
Expand Down Expand Up @@ -211,10 +211,6 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Xml" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="2.1.0" />
<PackageReference Include="System.Data.Common" Version="4.3.0" />
</ItemGroup>

Expand Down
32 changes: 16 additions & 16 deletions XCodeST/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,37 +11,37 @@
"providerName": "Sqlite"
},
"MySql": {
"connectionStrin": "Server=.;Port=3306;Database=mysql;Uid=root;Pwd=;",
"providerNam": "MySql.Data.MySqlClient"
"connectionString": "Server=.;Port=3306;Database=mysql;Uid=root;Pwd=;",
"providerName": "MySql.Data.MySqlClient"
},
"MSSQL": {
"connectionStrin": "Server=.;User ID=sa;Password=sa;Database=Test;datapath=~\\App_Data",
"providerNam": "System.Data.SqlClient"
"connectionString": "Server=.;User ID=sa;Password=sa;Database=Test;datapath=~\\App_Data",
"providerName": "System.Data.SqlClient"
},
"Oracle": {
"connectionStrin": "Data Source=Tcp://127.0.0.1/ORC;User ID=sys;Password=admin;Owner=mis",
"providerNam": "System.Data.OracleClient"
"connectionString": "Data Source=Tcp://127.0.0.1/ORC;User ID=sys;Password=admin;Owner=mis",
"providerName": "System.Data.OracleClient"
},
"PostgreSQL": {
"connectionStrin": "Server=.;Database=master;Uid=root;Pwd=root;",
"providerNam": "PostgreSQL.Data.PostgreSQLClient"
"connectionString": "Server=.;Database=master;Uid=root;Pwd=root;",
"providerName": "PostgreSQL.Data.PostgreSQLClient"
},
"MSSQL2": {
"connectionStrin": "Server=.;Integrated Security=SSPI;Database=Test",
"providerNam": "System.Data.SqlClient"
"connectionString": "Server=.;Integrated Security=SSPI;Database=Test",
"providerName": "System.Data.SqlClient"
},
"Oracle2": {
"connectionStrin": "Data Source=orc;User ID=sys;Password=admin;",
"providerNam": "System.Data.OracleClient"
"connectionString": "Data Source=orc;User ID=sys;Password=admin;",
"providerName": "System.Data.OracleClient"
},
//OLE DB Services=-1±íʾ´ò¿ªÁ¬½Ó³Ø
"Access": {
"connectionStrin": "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=~\\App_Data\\Test.mdb;Persist Security Info=False;OLE DB Services=-1",
"providerNam": "Access"
"connectionString": "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=~\\App_Data\\Test.mdb;Persist Security Info=False;OLE DB Services=-1",
"providerName": "Access"
},
"SqlCe": {
"connectionStrin": "Data Source=test.sdf;",
"providerNam": "SqlCe"
"connectionString": "Data Source=test.sdf;",
"providerName": "SqlCe"
}
}
}

0 comments on commit 6000a47

Please sign in to comment.