Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
P
performance
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
zry
performance
Commits
641fea6f
Commit
641fea6f
authored
Mar 01, 2019
by
zry
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
run
parent
fd2e4918
Hide whitespace changes
Inline
Side-by-side
Showing
25 changed files
with
757 additions
and
16 deletions
+757
-16
performance/Performance.Api/Controllers/AccountController.cs
+28
-0
performance/Performance.Api/Controllers/NotFoundController.cs
+19
-0
performance/Performance.Api/Filters/ActionsFilter.cs
+38
-0
performance/Performance.Api/Filters/ExceptionsFilter.cs
+29
-0
performance/Performance.Api/Performance.Api.csproj
+12
-0
performance/Performance.Api/Startup.cs
+43
-7
performance/Performance.Api/nlog.config
+4
-3
performance/Performance.DtoModels/ApiRequest.cs
+5
-3
performance/Performance.DtoModels/ApiResponse.cs
+60
-0
performance/Performance.DtoModels/AppSettings/AppConnection.cs
+3
-0
performance/Performance.DtoModels/AutoMapper/AutoMapperConfigs.cs
+19
-0
performance/Performance.DtoModels/Performance.DtoModels.csproj
+9
-0
performance/Performance.DtoModels/Request/LoginRequest.cs
+40
-0
performance/Performance.DtoModels/Response/LoginResponse.cs
+16
-0
performance/Performance.DtoModels/ResponseType.cs
+16
-0
performance/Performance.EntityModels/Performance.EntityModels.csproj
+10
-0
performance/Performance.EntityModels/T4Template/Entity.cs
+2
-0
performance/Performance.EntityModels/T4Template/Entity.tt
+67
-0
performance/Performance.EntityModels/T4Template/MultipleOutputHelper.cs
+2
-0
performance/Performance.EntityModels/T4Template/MultipleOutputHelper.tt
+189
-0
performance/Performance.Infrastructure/JsonHelper.cs
+95
-0
performance/Performance.Infrastructure/JsonSettings.cs
+0
-0
performance/Performance.Infrastructure/Performance.Infrastructure.csproj
+6
-0
performance/Performance.Services/PerformanceServiceExtensions.cs
+21
-2
performance/Performance.Services/UserService.cs
+24
-1
No files found.
performance/Performance.Api/Controllers/AccountController.cs
0 → 100644
View file @
641fea6f
using
Microsoft.AspNetCore.Mvc
;
using
Newtonsoft.Json.Linq
;
using
Performance.DtoModels
;
using
Performance.Infrastructure
;
using
Performance.Services
;
using
System
;
using
System.Collections.Generic
;
using
System.Linq
;
using
System.Threading.Tasks
;
namespace
Performance.Api.Controllers
{
[
Route
(
"api/[controller]/[action]"
)]
public
class
AccountController
:
Controller
{
UserService
_userService
;
public
AccountController
(
UserService
userService
)
{
_userService
=
userService
;
}
[
HttpPost
]
public
ApiResponse
<
LoginResponse
>
Login
([
FromBody
]
LoginRequest
request
)
{
return
_userService
.
Login
(
request
);
}
}
}
performance/Performance.Api/Controllers/NotFoundController.cs
0 → 100644
View file @
641fea6f
using
Microsoft.AspNetCore.Mvc
;
using
Performance.DtoModels
;
using
System
;
using
System.Collections.Generic
;
using
System.Linq
;
using
System.Threading.Tasks
;
namespace
Performance.Api.Controllers
{
[
ApiController
]
public
class
NotFoundController
:
ControllerBase
{
[
Route
(
"error/404"
)]
public
ActionResult
<
ApiResponse
>
Get
()
{
return
new
ApiResponse
(
ResponseType
.
NotFound
,
"not found"
);
}
}
}
performance/Performance.Api/Filters/ActionsFilter.cs
0 → 100644
View file @
641fea6f
using
Microsoft.AspNetCore.Mvc
;
using
Microsoft.AspNetCore.Mvc.Filters
;
using
Microsoft.Extensions.Logging
;
using
Performance.DtoModels
;
using
System
;
using
System.Collections.Generic
;
using
System.Linq
;
using
System.Threading.Tasks
;
namespace
Performance.Api
{
public
class
ActionsFilter
:
IAsyncActionFilter
{
private
readonly
ILoggerFactory
factory
;
public
ActionsFilter
(
ILoggerFactory
factory
)
{
this
.
factory
=
factory
;
}
public
async
Task
OnActionExecutionAsync
(
ActionExecutingContext
context
,
ActionExecutionDelegate
next
)
{
var
logger
=
factory
.
CreateLogger
<
ActionsFilter
>();
logger
.
LogWarning
(
$"action filter is executing new ,context.modelstate:
{
context
.
ModelState
.
IsValid
}
"
);
if
(!
context
.
ModelState
.
IsValid
)
{
string
errorMessage
=
string
.
Join
(
","
,
context
.
ModelState
.
Values
.
Select
(
t
=>
t
?.
Errors
?.
FirstOrDefault
()?.
ErrorMessage
));
var
response
=
new
ApiResponse
(
ResponseType
.
ParameterError
,
"参数错误"
,
errorMessage
);
context
.
Result
=
new
ObjectResult
(
response
);
return
;
}
var
executedContext
=
await
next
();
logger
.
LogWarning
(
$"action filter is executed now,executedContext controller:
{
executedContext
.
Controller
.
ToString
()}
"
);
}
}
}
performance/Performance.Api/Filters/ExceptionsFilter.cs
0 → 100644
View file @
641fea6f
using
Microsoft.AspNetCore.Mvc
;
using
Microsoft.AspNetCore.Mvc.Filters
;
using
Microsoft.Extensions.Logging
;
using
Performance.DtoModels
;
using
System
;
using
System.Collections.Generic
;
using
System.Linq
;
using
System.Threading.Tasks
;
namespace
Performance.Api
{
public
class
ExceptionsFilter
:
IAsyncExceptionFilter
{
private
readonly
ILoggerFactory
loggerFactory
;
public
ExceptionsFilter
(
ILoggerFactory
loggerFactory
)
{
this
.
loggerFactory
=
loggerFactory
;
}
public
Task
OnExceptionAsync
(
ExceptionContext
context
)
{
var
logger
=
loggerFactory
.
CreateLogger
<
ExceptionsFilter
>();
logger
.
LogError
(
$"接口异常:
{
context
.
Exception
.
Message
}
"
);
var
response
=
new
ApiResponse
(
ResponseType
.
Error
,
"接口异常"
,
context
.
Exception
.
Message
);
context
.
Result
=
new
ObjectResult
(
response
);
return
Task
.
CompletedTask
;
}
}
}
performance/Performance.Api/Performance.Api.csproj
View file @
641fea6f
...
...
@@ -6,6 +6,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="8.0.0" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="6.0.0" />
<PackageReference Include="FluentValidation.AspNetCore" Version="8.1.3" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
...
...
@@ -22,4 +25,13 @@
<ProjectReference Include="..\Performance.Services\Performance.Services.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Content>
<Content Update="nlog.config">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
performance/Performance.Api/Startup.cs
View file @
641fea6f
using
Microsoft.AspNetCore.Builder
;
using
AutoMapper
;
using
FluentValidation
;
using
FluentValidation.AspNetCore
;
using
Microsoft.AspNetCore.Builder
;
using
Microsoft.AspNetCore.Hosting
;
using
Microsoft.AspNetCore.Mvc
;
using
Microsoft.AspNetCore.Mvc.Filters
;
using
Microsoft.EntityFrameworkCore
;
using
Microsoft.Extensions.Configuration
;
using
Microsoft.Extensions.DependencyInjection
;
...
...
@@ -9,7 +13,9 @@
using
NLog
;
using
NLog.Extensions.Logging
;
using
NLog.Web
;
using
Performance.DtoModels
;
using
Performance.DtoModels.AppSettings
;
using
Performance.DtoModels.AutoMapper
;
using
Performance.EntityModels
;
using
Performance.Infrastructure
;
using
Performance.Repository
;
...
...
@@ -18,6 +24,10 @@
using
System.Collections.Generic
;
using
System.Globalization
;
using
System.Linq
;
using
System.Net.Http
;
using
System.Reflection
;
using
System.Text
;
using
System.Threading
;
using
System.Threading.Tasks
;
namespace
Performance.Api
...
...
@@ -34,7 +44,13 @@ public Startup(IConfiguration configuration)
// This method gets called by the runtime. Use this method to add services to the container.
public
void
ConfigureServices
(
IServiceCollection
services
)
{
services
.
AddMvc
()
Encoding
.
RegisterProvider
(
CodePagesEncodingProvider
.
Instance
);
services
.
AddMvc
(
option
=>
{
option
.
Filters
.
Add
<
ActionsFilter
>();
option
.
Filters
.
Add
<
ExceptionsFilter
>();
})
.
SetCompatibilityVersion
(
CompatibilityVersion
.
Version_2_1
)
.
AddJsonOptions
(
json
=>
{
...
...
@@ -46,15 +62,32 @@ public void ConfigureServices(IServiceCollection services)
json
.
SerializerSettings
.
DateTimeZoneHandling
=
Newtonsoft
.
Json
.
DateTimeZoneHandling
.
Utc
;
json
.
SerializerSettings
.
Culture
=
new
CultureInfo
(
"it-IT"
);
json
.
SerializerSettings
.
ReferenceLoopHandling
=
Newtonsoft
.
Json
.
ReferenceLoopHandling
.
Ignore
;
})
.
AddFluentValidation
(
fv
=>
{
//禁用其他以使FluentValidation是唯一执行的验证库
fv
.
RunDefaultMvcValidationAfterFluentValidationExecutes
=
false
;
var
assembly
=
Assembly
.
Load
(
"Performance.DtoModels"
);
var
types
=
ReflectionHelper
.
GetInstances
<
IValidator
>(
assembly
);
foreach
(
var
type
in
types
)
{
fv
.
RegisterValidatorsFromAssemblyContaining
(
type
.
GetType
());
}
});
services
.
AddPerformanceService
();
services
.
Configure
<
AppConnection
>(
Configuration
.
GetSection
(
"AppConnection"
));
services
.
AddAutoMapper
(
mapper
=>
{
Mapper
.
Initialize
(
cfg
=>
cfg
.
AddProfile
<
AutoMapperConfigs
>());
});
services
.
AddPerformanceService
()
.
AddPerformanceRepoitory
()
.
Configure
<
AppConnection
>(
Configuration
.
GetSection
(
"AppConnection"
));
services
.
AddOptions
<
AppConnection
>(
"AppConnection"
);
var
connection
=
services
.
BuildServiceProvider
().
GetService
<
IOptions
<
AppConnection
>>();
services
.
AddDbContext
<
PerformanceDbContext
>(
options
=>
{
options
.
UseMySQL
(
connection
.
Value
.
PerformanceConnectionString
);
...
...
@@ -70,7 +103,10 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
{
app
.
UseDeveloperExceptionPage
();
}
else
{
app
.
UseStatusCodePagesWithReExecute
(
"/error/{0}"
);
}
app
.
UseMvc
();
}
}
...
...
performance/Performance.Api/nlog.config
View file @
641fea6f
...
...
@@ -26,7 +26,7 @@
layout
=
"日志记录时间:${longdate}${newline}日志级别:${uppercase:${level}}${newline}日志来源:${logger}${newline}日志信息:${message}${newline}错误信息:${exception:format=tostring}${newline}url: ${aspnet-request-url}${newline}action: ${aspnet-mvc-action}${newline}==============================================================${newline}"
/>
<!--
write
log
to
mongodb
-->
<
target
xsi
:
type
=
"Mongo"
<
!--<
target
xsi
:
type
=
"Mongo"
name
=
"mongo"
databaseName
=
"nlog"
collectionName
=
"Logs"
connectionString
=
"mongodb://172.31.216.37:27017/nlog"
...
...
@@ -39,7 +39,7 @@
<
property
name
=
"Url"
layout
=
"${aspnet-request-url}"
/>
<
property
name
=
"Action"
layout
=
"${aspnet-mvc-action}"
/>
<
property
name
=
"UserName"
layout
=
"${windows-identity}"
/>
</
target
>
</
target
>
-->
</
targets
>
...
...
@@ -54,6 +54,6 @@
<
logger
name
=
"*"
minlevel
=
"Trace"
writeTo
=
"ownFile-web"
/>
<!--
Add
logs
to
mongodb
-->
<
logger
name
=
"*"
minlevel
=
"Trace"
writeTo
=
"mongo"
/
>
<
!--<
logger
name
=
"*"
minlevel
=
"Trace"
writeTo
=
"mongo"
/>--
>
</
rules
>
</
nlog
>
\ No newline at end of file
performance/Performance.DtoModels/Ap
pSettings/IAppSetting
.cs
→
performance/Performance.DtoModels/Ap
iRequest
.cs
View file @
641fea6f
using
System
;
using
Microsoft.AspNetCore.Mvc.ModelBinding
;
using
System
;
using
System.Collections.Generic
;
using
System.Linq
;
using
System.Text
;
namespace
Performance.DtoModels
.AppSettings
namespace
Performance.DtoModels
{
public
interface
IAppSetting
public
class
ApiRequest
{
}
}
performance/Performance.DtoModels/ApiResponse.cs
0 → 100644
View file @
641fea6f
using
System
;
using
System.Collections.Generic
;
using
System.Text
;
namespace
Performance.DtoModels
{
public
class
ApiResponse
<
TEntity
>
where
TEntity
:
class
,
new
()
{
public
ResponseType
State
{
get
;
set
;
}
/// <summary>
/// 消息内容。
/// </summary>
public
string
Message
{
get
;
set
;
}
/// <summary>
/// 返回数据。
/// </summary>
public
TEntity
Data
{
get
;
set
;
}
public
ApiResponse
()
:
this
(
ResponseType
.
Fail
,
""
,
null
)
{
}
public
ApiResponse
(
ResponseType
type
)
:
this
(
type
,
""
,
null
)
{
}
public
ApiResponse
(
ResponseType
type
,
string
message
)
:
this
(
type
,
message
,
null
)
{
}
public
ApiResponse
(
ResponseType
type
,
string
message
,
TEntity
entity
)
{
State
=
ResponseType
.
Fail
;
Message
=
message
;
Data
=
entity
;
}
}
public
class
ApiResponse
:
ApiResponse
<
Object
>
{
public
ApiResponse
()
{
}
public
ApiResponse
(
ResponseType
type
)
:
base
(
type
)
{
}
public
ApiResponse
(
ResponseType
type
,
string
message
)
:
base
(
type
,
message
)
{
}
public
ApiResponse
(
ResponseType
type
,
string
message
,
object
entity
)
:
base
(
type
,
message
,
entity
)
{
}
}
}
performance/Performance.DtoModels/AppSettings/AppConnection.cs
View file @
641fea6f
...
...
@@ -4,6 +4,9 @@
namespace
Performance.DtoModels.AppSettings
{
/// <summary>
/// 数据库连接字符串
/// </summary>
public
class
AppConnection
{
public
string
PerformanceConnectionString
{
get
;
set
;
}
...
...
performance/Performance.DtoModels/AutoMapper/AutoMapperConfigs.cs
0 → 100644
View file @
641fea6f
using
AutoMapper
;
using
Performance.EntityModels
;
using
System
;
using
System.Collections.Generic
;
using
System.Text
;
namespace
Performance.DtoModels.AutoMapper
{
public
class
AutoMapperConfigs
:
Profile
{
public
AutoMapperConfigs
()
{
CreateMap
<
LoginResponse
,
Sys_User
>()
.
ForMember
(
dest
=>
dest
.
ID
,
opt
=>
opt
.
MapFrom
(
src
=>
src
.
UserID
));
CreateMap
<
Sys_User
,
LoginResponse
>()
.
ForMember
(
dest
=>
dest
.
UserID
,
opt
=>
opt
.
MapFrom
(
src
=>
src
.
ID
));
}
}
}
performance/Performance.DtoModels/Performance.DtoModels.csproj
View file @
641fea6f
...
...
@@ -4,4 +4,13 @@
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="8.0.0" />
<PackageReference Include="FluentValidation.AspNetCore" Version="8.1.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.EntityModels\Performance.EntityModels.csproj" />
</ItemGroup>
</Project>
performance/Performance.DtoModels/Request/LoginRequest.cs
0 → 100644
View file @
641fea6f
using
FluentValidation
;
using
System
;
using
System.Collections.Generic
;
using
System.Text
;
namespace
Performance.DtoModels
{
/// <summary>
/// 登录请求
/// </summary>
public
class
LoginRequest
:
ApiRequest
{
/// <summary>
/// 登录类型 1 手机号登录 2 账号登录
/// </summary>
public
int
LoginType
{
get
;
set
;
}
public
string
Account
{
get
;
set
;
}
public
string
Password
{
get
;
set
;
}
}
public
class
LoginRequestValidator
:
AbstractValidator
<
LoginRequest
>
{
public
LoginRequestValidator
()
{
RuleFor
(
x
=>
x
.
LoginType
)
.
InclusiveBetween
(
1
,
2
)
.
WithMessage
(
"LoginType超出范围"
);
RuleFor
(
x
=>
x
.
Account
)
.
NotNull
()
.
Length
(
1
,
200
)
.
WithMessage
(
"Account参数错误"
);
RuleFor
(
x
=>
x
.
Password
)
.
NotNull
()
.
Length
(
1
,
200
)
.
WithMessage
(
"Password参数错误"
);
}
}
}
performance/Performance.DtoModels/Response/LoginResponse.cs
0 → 100644
View file @
641fea6f
using
System
;
using
System.Collections.Generic
;
using
System.Text
;
namespace
Performance.DtoModels
{
public
class
LoginResponse
{
public
int
UserID
{
get
;
set
;
}
public
string
RealName
{
get
;
set
;
}
public
string
Login
{
get
;
set
;
}
public
string
Mail
{
get
;
set
;
}
public
string
Mobile
{
get
;
set
;
}
public
int
States
{
get
;
set
;
}
}
}
performance/Performance.DtoModels/ResponseType.cs
0 → 100644
View file @
641fea6f
using
System
;
using
System.Collections.Generic
;
using
System.Text
;
namespace
Performance.DtoModels
{
public
enum
ResponseType
{
OK
=
1
,
Fail
=
2
,
Error
=
3
,
TokenError
=
4
,
NotFound
=
5
,
ParameterError
=
6
,
}
}
performance/Performance.EntityModels/Performance.EntityModels.csproj
View file @
641fea6f
...
...
@@ -5,6 +5,12 @@
</PropertyGroup>
<ItemGroup>
<Compile Remove="T4Template\**" />
<EmbeddedResource Remove="T4Template\**" />
<None Remove="T4Template\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.0">
<PrivateAssets>all</PrivateAssets>
...
...
@@ -13,4 +19,8 @@
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>
</Project>
performance/Performance.EntityModels/T4Template/Entity.cs
0 → 100644
View file @
641fea6f
ErrorGeneratingOutput
\ No newline at end of file
performance/Performance.EntityModels/T4Template/Entity.tt
0 → 100644
View file @
641fea6f
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.xml" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="$(TargetDir)\MySql.Data.dll" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="MySql.Data.MySqlClient" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
// 导入MultipleOutputHelper.ttinclude文件
<#@ include file=".\MultipleOutputHelper.tt" #>
<#
string connectionString= "server=qq;database=db;uid=sa;pwd=sa;";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
string selectQuery ="SET FMTONLY ON; select * from @tableName; SET FMTONLY OFF;";
SqlCommand command = new SqlCommand(selectQuery,conn);
SqlDataAdapter ad = new SqlDataAdapter(command);
System.Data.DataSet ds = new DataSet();
var manager = Manager.Create(Host, GenerationEnvironment);
System.Data.DataTable schema = conn.GetSchema("Tables");
foreach(System.Data.DataRow row in schema.Rows)
{
ds.Tables.Clear();
string tb_name= row["TABLE_NAME"].ToString();
command.CommandText = selectQuery.Replace("@tableName",row["TABLE_NAME"].ToString());
ad.FillSchema(ds, SchemaType.Mapped,tb_name);
manager.StartNewFile(tb_name+".cs");#>
using FluentData;
using System;
using System.Collections.Generic;
namespace My.Model
{
/// <summary>
/// 实体-<#=tb_name#>
/// </summary>
public partial class <#=tb_name#>
{
<#
PushIndent(" ");
foreach (DataColumn dc in ds.Tables[0].Columns)
{
WriteLine("public " + dc.DataType.Name+ (dc.AllowDBNull && dc.DataType.Name.ToLower() != "string" ? "? ": " ") + dc.ColumnName + " { get; set; }");
}
PopIndent();
#>
}
}
<#
manager.EndBlock();
}
conn.Close();
manager.Process(true);
#>
\ No newline at end of file
performance/Performance.EntityModels/T4Template/MultipleOutputHelper.cs
0 → 100644
View file @
641fea6f
\ No newline at end of file
performance/Performance.EntityModels/T4Template/MultipleOutputHelper.tt
0 → 100644
View file @
641fea6f
<#@ assembly name="System.Core"#>
<#@ assembly name="System.Data.Linq"#>
<#@ assembly name="EnvDTE"#>
<#@ assembly name="System.Xml"#>
<#@ assembly name="System.Xml.Linq"#>
<#@ import namespace="System.Collections.Generic"#>
<#@ import namespace="System.IO"#>
<#@ import namespace="System.Text"#>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating"#>
<#+
// https://raw.github.com/damieng/DamienGKit
// http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited
// Manager class records the various blocks so it can split them up
class Manager
{
private class Block
{
public String Name;
public int Start, Length;
public bool IncludeInDefault;
}
private Block currentBlock;
private readonly List<Block> files = new List<Block>();
private readonly Block footer = new Block();
private readonly Block header = new Block();
private readonly ITextTemplatingEngineHost host;
private readonly StringBuilder template;
protected readonly List<String> generatedFileNames = new List<String>();
public static Manager Create(ITextTemplatingEngineHost host, StringBuilder template)
{
return (host is IServiceProvider) ? new VSManager(host, template) : new Manager(host, template);
}
public void StartNewFile(String name)
{
if (name == null)
throw new ArgumentNullException("name");
CurrentBlock = new Block { Name = name };
}
public void StartFooter(bool includeInDefault = true)
{
CurrentBlock = footer;
footer.IncludeInDefault = includeInDefault;
}
public void StartHeader(bool includeInDefault = true)
{
CurrentBlock = header;
header.IncludeInDefault = includeInDefault;
}
public void EndBlock()
{
if (CurrentBlock == null)
return;
CurrentBlock.Length = template.Length - CurrentBlock.Start;
if (CurrentBlock != header && CurrentBlock != footer)
files.Add(CurrentBlock);
currentBlock = null;
}
public virtual void Process(bool split, bool sync = true)
{
if (split) {
EndBlock();
String headerText = template.ToString(header.Start, header.Length);
String footerText = template.ToString(footer.Start, footer.Length);
String outputPath = Path.GetDirectoryName(host.TemplateFile);
files.Reverse();
if (!footer.IncludeInDefault)
template.Remove(footer.Start, footer.Length);
foreach(Block block in files) {
String fileName = Path.Combine(outputPath, block.Name);
String content = headerText + template.ToString(block.Start, block.Length) + footerText;
generatedFileNames.Add(fileName);
CreateFile(fileName, content);
template.Remove(block.Start, block.Length);
}
if (!header.IncludeInDefault)
template.Remove(header.Start, header.Length);
}
}
protected virtual void CreateFile(String fileName, String content) {
if (IsFileContentDifferent(fileName, content))
File.WriteAllText(fileName, content);
}
public virtual String GetCustomToolNamespace(String fileName) {
return null;
}
public virtual String DefaultProjectNamespace {
get { return null; }
}
protected bool IsFileContentDifferent(String fileName, String newContent) {
return !(File.Exists(fileName) && File.ReadAllText(fileName) == newContent);
}
private Manager(ITextTemplatingEngineHost host, StringBuilder template) {
this.host = host;
this.template = template;
}
private Block CurrentBlock {
get { return currentBlock; }
set {
if (CurrentBlock != null)
EndBlock();
if (value != null)
value.Start = template.Length;
currentBlock = value;
}
}
private class VSManager: Manager {
private readonly EnvDTE.ProjectItem templateProjectItem;
private readonly EnvDTE.DTE dte;
private readonly Action<String> checkOutAction;
private readonly Action<List<String>> projectSyncAction;
public override String DefaultProjectNamespace {
get {
return templateProjectItem.ContainingProject.Properties.Item("DefaultNamespace").Value.ToString();
}
}
public override String GetCustomToolNamespace(string fileName) {
return dte.Solution.FindProjectItem(fileName).Properties.Item("CustomToolNamespace").Value.ToString();
}
public override void Process(bool split, bool sync) {
if (templateProjectItem.ProjectItems == null)
return;
base.Process(split, sync);
if (sync)
projectSyncAction(generatedFileNames);
}
protected override void CreateFile(String fileName, String content) {
if (IsFileContentDifferent(fileName, content)) {
CheckoutFileIfRequired(fileName);
File.WriteAllText(fileName, content);
}
}
internal VSManager(ITextTemplatingEngineHost host, StringBuilder template)
: base(host, template) {
var hostServiceProvider = (IServiceProvider)host;
if (hostServiceProvider == null)
throw new ArgumentNullException("Could not obtain IServiceProvider");
dte = (EnvDTE.DTE) hostServiceProvider.GetService(typeof(EnvDTE.DTE));
if (dte == null)
throw new ArgumentNullException("Could not obtain DTE from host");
templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile);
checkOutAction = fileName => dte.SourceControl.CheckOutItem(fileName);
projectSyncAction = keepFileNames => ProjectSync(templateProjectItem, keepFileNames);
}
private static void ProjectSync(EnvDTE.ProjectItem templateProjectItem, List<String> keepFileNames) {
var keepFileNameSet = new HashSet<String>(keepFileNames);
var projectFiles = new Dictionary<String, EnvDTE.ProjectItem>();
var originalFilePrefix = Path.GetFileNameWithoutExtension(templateProjectItem.FileNames[0]) + ".";
foreach (EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems)
projectFiles.Add(projectItem.FileNames[0], projectItem);
// Remove unused items from the project
foreach (var pair in projectFiles)
if (!keepFileNames.Contains(pair.Key) && !(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalFilePrefix))
pair.Value.Delete();
// Add missing files to the project
foreach(String fileName in keepFileNameSet)
if (!projectFiles.ContainsKey(fileName))
templateProjectItem.ProjectItems.AddFromFile(fileName);
}
private void CheckoutFileIfRequired(String fileName) {
var sc = dte.SourceControl;
if (sc != null && sc.IsItemUnderSCC(fileName) && !sc.IsItemCheckedOut(fileName))
checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, null, null));
}
}
} #>
\ No newline at end of file
performance/Performance.Infrastructure/JsonHelper.cs
0 → 100644
View file @
641fea6f
using
Newtonsoft.Json
;
using
Newtonsoft.Json.Converters
;
using
Newtonsoft.Json.Linq
;
using
System
;
using
System.Collections.Generic
;
using
System.Text
;
namespace
Performance.Infrastructure
{
public
static
class
JsonHelper
{
private
static
JsonSerializerSettings
_jsonSettings
;
static
JsonHelper
()
{
IsoDateTimeConverter
datetimeConverter
=
new
IsoDateTimeConverterContent
{
DateTimeFormat
=
"yyyy-MM-dd HH:mm:ss"
};
_jsonSettings
=
new
JsonSerializerSettings
{
MissingMemberHandling
=
MissingMemberHandling
.
Ignore
,
NullValueHandling
=
NullValueHandling
.
Ignore
,
ReferenceLoopHandling
=
ReferenceLoopHandling
.
Ignore
};
_jsonSettings
.
Converters
.
Add
(
datetimeConverter
);
_jsonSettings
.
ContractResolver
=
new
LowercaseContractResolver
();
}
/// <summary>
/// 将指定的对象序列化成 JSON 数据。
/// </summary>
/// <param name="obj">要序列化的对象。</param>
/// <returns></returns>
public
static
string
Serialize
(
object
@object
)
{
if
(
null
==
@object
)
return
null
;
return
JsonConvert
.
SerializeObject
(
@object
,
Formatting
.
None
,
_jsonSettings
);
}
/// <summary>
/// 将指定的 JSON 数据反序列化成指定对象。
/// </summary>
/// <typeparam name="T">对象类型。</typeparam>
/// <param name="json">JSON 数据。</param>
/// <returns></returns>
public
static
T
Deserialize
<
T
>(
string
json
)
{
if
(
string
.
IsNullOrEmpty
(
json
))
return
default
(
T
);
return
JsonConvert
.
DeserializeObject
<
T
>(
json
,
_jsonSettings
);
}
/// <summary>
/// 将转换后的Key全部设置为小写
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public
static
SortedDictionary
<
string
,
object
>
Deserialize
(
string
json
)
{
return
Deserialize
<
SortedDictionary
<
string
,
object
>>(
json
);
}
/// <summary>
/// 将转换后的Key全部设置为小写
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public
static
SortedDictionary
<
string
,
object
>
DeserializeLower
(
JObject
json
)
{
return
DeserializeLower
(
json
.
ToString
());
}
/// <summary>
/// 将转换后的Key全部设置为小写
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public
static
SortedDictionary
<
string
,
object
>
DeserializeLower
(
string
json
)
{
var
obj
=
Deserialize
<
SortedDictionary
<
string
,
object
>>(
json
);
SortedDictionary
<
string
,
object
>
nobj
=
new
SortedDictionary
<
string
,
object
>();
foreach
(
var
item
in
obj
)
{
nobj
[
item
.
Key
.
ToLower
()]
=
item
.
Value
;
}
obj
.
Clear
();
obj
=
null
;
return
nobj
;
}
}
}
performance/Performance.Infrastructure/JsonSe
rializer
.cs
→
performance/Performance.Infrastructure/JsonSe
ttings
.cs
View file @
641fea6f
File moved
performance/Performance.Infrastructure/Performance.Infrastructure.csproj
View file @
641fea6f
...
...
@@ -8,4 +8,10 @@
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Mvc.Abstractions">
<HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.abstractions\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Abstractions.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
performance/Performance.Services/PerformanceServiceExtensions.cs
View file @
641fea6f
using
Microsoft.Extensions.DependencyInjection
;
using
Microsoft.Extensions.Configuration
;
using
Microsoft.Extensions.DependencyInjection
;
using
Microsoft.Extensions.Options
;
using
Performance.DtoModels.AppSettings
;
using
Performance.Infrastructure
;
using
Performance.Repository
;
using
System
;
...
...
@@ -9,8 +12,16 @@
namespace
Performance.Services
{
/// <summary>
/// DI扩展
/// </summary>
public
static
class
PerformanceServiceExtensions
{
/// <summary>
/// 自动注入Service
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public
static
IServiceCollection
AddPerformanceService
(
this
IServiceCollection
services
)
{
var
types
=
ReflectionHelper
.
GetClassType
<
IAutoInjection
>(
Assembly
.
GetExecutingAssembly
());
...
...
@@ -18,13 +29,21 @@ public static IServiceCollection AddPerformanceService(this IServiceCollection s
{
services
.
AddScoped
(
type
);
}
return
services
;
}
/// <summary>
/// 自动注入Repository
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public
static
IServiceCollection
AddPerformanceRepoitory
(
this
IServiceCollection
services
)
{
var
repository
=
typeof
(
PerforRepository
<>).
Assembly
.
GetTypes
().
Where
(
t
=>
t
.
IsClass
&&
!
t
.
IsAbstract
);
foreach
(
var
type
in
repository
)
{
services
.
AddScoped
(
type
);
}
return
services
;
}
}
...
...
performance/Performance.Services/UserService.cs
View file @
641fea6f
using
Performance.EntityModels
;
using
AutoMapper
;
using
Newtonsoft.Json.Linq
;
using
Performance.DtoModels
;
using
Performance.EntityModels
;
using
Performance.Repository
;
using
System
;
using
System.Collections.Generic
;
using
System.Linq
;
using
System.Text
;
using
System.Threading.Tasks
;
namespace
Performance.Services
{
...
...
@@ -19,5 +23,24 @@ public List<Sys_User> GetUser()
{
return
_userRepository
.
GetEntities
().
ToList
();
}
public
ApiResponse
<
LoginResponse
>
Login
(
LoginRequest
request
)
{
if
(
request
.
LoginType
==
1
)
{
var
user
=
_userRepository
.
GetEntity
(
t
=>
t
.
Mobile
==
request
.
Account
);
}
else
if
(
request
.
LoginType
==
2
)
{
var
user
=
_userRepository
.
GetEntity
(
t
=>
t
.
Login
==
request
.
Account
);
if
(
user
!=
null
&&
user
.
Password
==
request
.
Password
)
{
var
data
=
Mapper
.
Map
<
LoginResponse
>(
user
);
return
new
ApiResponse
<
LoginResponse
>(
ResponseType
.
OK
,
"登录成功"
,
data
);
}
}
return
new
ApiResponse
<
LoginResponse
>();
}
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment