commit message
This commit is contained in:
commit
37c3e37853
25
.dockerignore
Normal file
25
.dockerignore
Normal file
@ -0,0 +1,25 @@
|
||||
**/.classpath
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
**/.settings
|
||||
**/.toolstarget
|
||||
**/.vs
|
||||
**/.vscode
|
||||
**/*.*proj.user
|
||||
**/*.dbmdl
|
||||
**/*.jfm
|
||||
**/azds.yaml
|
||||
**/bin
|
||||
**/charts
|
||||
**/docker-compose*
|
||||
**/Dockerfile*
|
||||
**/node_modules
|
||||
**/npm-debug.log
|
||||
**/obj
|
||||
**/secrets.dev.yaml
|
||||
**/values.dev.yaml
|
||||
LICENSE
|
||||
README.md
|
||||
342
.gitignore
vendored
Normal file
342
.gitignore
vendored
Normal file
@ -0,0 +1,342 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUNIT
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# JustCode is a .NET coding add-in
|
||||
.JustCode
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
# ASP.NET Core default setup: bower directory is configured as wwwroot/lib/ and bower restore is true
|
||||
**/wwwroot/lib/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# JetBrains Rider
|
||||
.idea/
|
||||
*.sln.iml
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
/WaterCloud.Web/DataProtection
|
||||
85
EasyMES.sln
Normal file
85
EasyMES.sln
Normal file
@ -0,0 +1,85 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.31903.59
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WaterCloud.Web", "WaterCloud.Web\WaterCloud.Web.csproj", "{FE158A99-8B94-4F95-9DAA-AC14B7738BB7}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WaterCloud.Code", "WaterCloud.Code\WaterCloud.Code.csproj", "{2F494D2F-8687-46B6-A6D3-C183B7E1B3EB}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "01 Common基础工具", "01 Common基础工具", "{DB605620-7CB6-4064-B509-C55CDEA50025}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WaterCloud.DataBase", "WaterCloud.Data\WaterCloud.DataBase.csproj", "{586E88DF-7EFA-4281-9371-EA45B877C9A4}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "02 Domain基础数据", "02 Domain基础数据", "{EFA98BE7-DCF3-475E-8783-B56ECFF68DD3}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WaterCloud.Domain", "WaterCloud.Domain\WaterCloud.Domain.csproj", "{40732569-0516-4E72-9475-06A217998944}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "03 Application应用服务", "03 Application应用服务", "{DB3B0F56-4245-4ACA-81C2-C67F2A28DFD3}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "04 Web 应用程序", "04 Web 应用程序", "{C62E4ABA-29D7-4A0C-BDAA-D4EAB43859C1}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WaterCloud.CodeGenerator", "WaterCloud.CodeGenerator\WaterCloud.CodeGenerator.csproj", "{25C1E690-0B45-4994-87C0-F1997F4227A6}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WaterCloud.WebApi", "WaterCloud.WebApi\WaterCloud.WebApi.csproj", "{59375491-D3CF-4963-B36C-7598CAF8C5F9}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WaterCloud.Service", "WaterCloud.Service\WaterCloud.Service.csproj", "{6CABCCC1-E43B-4A57-A767-7D74D8728E8C}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WaterCloud.DingTalk", "WaterCloud.DingTalkService\WaterCloud.DingTalk.csproj", "{D3691FAA-877F-43A6-90AA-B79542E1DF80}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{FE158A99-8B94-4F95-9DAA-AC14B7738BB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{FE158A99-8B94-4F95-9DAA-AC14B7738BB7}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{FE158A99-8B94-4F95-9DAA-AC14B7738BB7}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{FE158A99-8B94-4F95-9DAA-AC14B7738BB7}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{2F494D2F-8687-46B6-A6D3-C183B7E1B3EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{2F494D2F-8687-46B6-A6D3-C183B7E1B3EB}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{2F494D2F-8687-46B6-A6D3-C183B7E1B3EB}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2F494D2F-8687-46B6-A6D3-C183B7E1B3EB}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{586E88DF-7EFA-4281-9371-EA45B877C9A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{586E88DF-7EFA-4281-9371-EA45B877C9A4}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{586E88DF-7EFA-4281-9371-EA45B877C9A4}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{586E88DF-7EFA-4281-9371-EA45B877C9A4}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{40732569-0516-4E72-9475-06A217998944}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{40732569-0516-4E72-9475-06A217998944}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{40732569-0516-4E72-9475-06A217998944}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{40732569-0516-4E72-9475-06A217998944}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{25C1E690-0B45-4994-87C0-F1997F4227A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{25C1E690-0B45-4994-87C0-F1997F4227A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{25C1E690-0B45-4994-87C0-F1997F4227A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{25C1E690-0B45-4994-87C0-F1997F4227A6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{59375491-D3CF-4963-B36C-7598CAF8C5F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{59375491-D3CF-4963-B36C-7598CAF8C5F9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{59375491-D3CF-4963-B36C-7598CAF8C5F9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{59375491-D3CF-4963-B36C-7598CAF8C5F9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{6CABCCC1-E43B-4A57-A767-7D74D8728E8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{6CABCCC1-E43B-4A57-A767-7D74D8728E8C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{6CABCCC1-E43B-4A57-A767-7D74D8728E8C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{6CABCCC1-E43B-4A57-A767-7D74D8728E8C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{D3691FAA-877F-43A6-90AA-B79542E1DF80}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D3691FAA-877F-43A6-90AA-B79542E1DF80}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D3691FAA-877F-43A6-90AA-B79542E1DF80}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D3691FAA-877F-43A6-90AA-B79542E1DF80}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{FE158A99-8B94-4F95-9DAA-AC14B7738BB7} = {C62E4ABA-29D7-4A0C-BDAA-D4EAB43859C1}
|
||||
{2F494D2F-8687-46B6-A6D3-C183B7E1B3EB} = {DB605620-7CB6-4064-B509-C55CDEA50025}
|
||||
{586E88DF-7EFA-4281-9371-EA45B877C9A4} = {DB605620-7CB6-4064-B509-C55CDEA50025}
|
||||
{40732569-0516-4E72-9475-06A217998944} = {EFA98BE7-DCF3-475E-8783-B56ECFF68DD3}
|
||||
{25C1E690-0B45-4994-87C0-F1997F4227A6} = {DB605620-7CB6-4064-B509-C55CDEA50025}
|
||||
{59375491-D3CF-4963-B36C-7598CAF8C5F9} = {C62E4ABA-29D7-4A0C-BDAA-D4EAB43859C1}
|
||||
{6CABCCC1-E43B-4A57-A767-7D74D8728E8C} = {DB3B0F56-4245-4ACA-81C2-C67F2A28DFD3}
|
||||
{D3691FAA-877F-43A6-90AA-B79542E1DF80} = {DB3B0F56-4245-4ACA-81C2-C67F2A28DFD3}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {30EA3764-674F-48E9-908A-3B962BD30291}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
201
LICENSE
Normal file
201
LICENSE
Normal file
@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
36
README.en.md
Normal file
36
README.en.md
Normal file
@ -0,0 +1,36 @@
|
||||
# EasyMES
|
||||
|
||||
#### Description
|
||||
net6 离散型MES
|
||||
|
||||
#### Software Architecture
|
||||
Software architecture description
|
||||
|
||||
#### Installation
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### Instructions
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### Contribution
|
||||
|
||||
1. Fork the repository
|
||||
2. Create Feat_xxx branch
|
||||
3. Commit your code
|
||||
4. Create Pull Request
|
||||
|
||||
|
||||
#### Gitee Feature
|
||||
|
||||
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
|
||||
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
|
||||
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
|
||||
4. The most valuable open source project [GVP](https://gitee.com/gvp)
|
||||
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
|
||||
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
||||
33
README.md
Normal file
33
README.md
Normal file
@ -0,0 +1,33 @@
|
||||
<p></p>
|
||||
<p></p>
|
||||
|
||||
----
|
||||
# EasyMES
|
||||
|
||||
#### 简介
|
||||
- 请勿用于违反我国法律的web平台、如诈骗等非法平台网站。
|
||||
- 不包含任何采集程序及接口,使用场景为零部件离散型生产
|
||||
- 此产品为商业授权,如需授权,请联系作者295228902
|
||||
|
||||
#### 框架说明
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
#### 整体流程
|
||||

|
||||
|
||||
#### 生产流程
|
||||

|
||||
|
||||
#### APS
|
||||

|
||||
|
||||
#### 捐赠支持
|
||||
|
||||
开源项目不易,若此项目能得到你的青睐,可以捐赠支持作者持续开发与维护,感谢所有支持开源的朋友。
|
||||
|
||||
|
||||
 
|
||||
BIN
Redis/Redis-x64-3.2.100.msi
Normal file
BIN
Redis/Redis-x64-3.2.100.msi
Normal file
Binary file not shown.
BIN
Redis/Redis说明.docx
Normal file
BIN
Redis/Redis说明.docx
Normal file
Binary file not shown.
BIN
Redis/打开.jpg
Normal file
BIN
Redis/打开.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 178 KiB |
33
WaterCloud.Code/AsyncTaskHelper.cs
Normal file
33
WaterCloud.Code/AsyncTaskHelper.cs
Normal file
@ -0,0 +1,33 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class AsyncTaskHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 开始异步任务
|
||||
/// </summary>
|
||||
/// <param name="action"></param>
|
||||
public static void StartTask(Action action)
|
||||
{
|
||||
try
|
||||
{
|
||||
Action newAction = () =>
|
||||
{ };
|
||||
newAction += action;
|
||||
Task task = new Task(newAction);
|
||||
task.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
203
WaterCloud.Code/Cache/CacheHelper.cs
Normal file
203
WaterCloud.Code/Cache/CacheHelper.cs
Normal file
@ -0,0 +1,203 @@
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public abstract class BaseHelper : RedisHelper<BaseHelper> { }
|
||||
public abstract class HandleLogHelper : RedisHelper<HandleLogHelper> { }
|
||||
public class CacheHelper
|
||||
{
|
||||
private static string cacheProvider = GlobalContext.SystemConfig.CacheProvider;
|
||||
/// <summary>
|
||||
/// 添加缓存
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <param name="value">缓存Value</param>
|
||||
/// <param name="expiresIn">缓存时长h</param>
|
||||
/// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
|
||||
/// <returns></returns>
|
||||
public static async Task<bool> Set(string key, object value, int expiresIn = -1, bool isSliding = true)
|
||||
{
|
||||
if (string.IsNullOrEmpty(key))
|
||||
throw new ArgumentNullException(nameof(key));
|
||||
if (value == null)
|
||||
throw new ArgumentNullException(nameof(value));
|
||||
switch (cacheProvider)
|
||||
{
|
||||
case Define.CACHEPROVIDER_REDIS:
|
||||
if (expiresIn > 0)
|
||||
{
|
||||
await BaseHelper.SetAsync(key, value, expiresIn * 3600);
|
||||
}
|
||||
else
|
||||
{
|
||||
await BaseHelper.SetAsync(key, value);
|
||||
}
|
||||
return await Exists(key);
|
||||
case Define.CACHEPROVIDER_MEMORY:
|
||||
if (expiresIn > 0)
|
||||
{
|
||||
MemoryCacheHelper.Set(key, value, TimeSpan.FromHours(expiresIn), isSliding);
|
||||
}
|
||||
else
|
||||
{
|
||||
MemoryCacheHelper.Set(key, value);
|
||||
}
|
||||
return await Exists(key);
|
||||
default:
|
||||
if (expiresIn > 0)
|
||||
{
|
||||
MemoryCacheHelper.Set(key, value, TimeSpan.FromHours(expiresIn), isSliding);
|
||||
}
|
||||
else
|
||||
{
|
||||
MemoryCacheHelper.Set(key, value);
|
||||
}
|
||||
return await Exists(key);
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取缓存
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <returns></returns>
|
||||
public static async Task<T> Get<T>(string key) where T : class
|
||||
{
|
||||
if (string.IsNullOrEmpty(key))
|
||||
throw new ArgumentNullException(nameof(key));
|
||||
switch (cacheProvider)
|
||||
{
|
||||
case Define.CACHEPROVIDER_REDIS:
|
||||
return await BaseHelper.GetAsync<T>(key);
|
||||
case Define.CACHEPROVIDER_MEMORY:
|
||||
return MemoryCacheHelper.Get<T>(key);
|
||||
default:
|
||||
return MemoryCacheHelper.Get<T>(key);
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 删除缓存
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <returns></returns>
|
||||
public static async Task Remove(string key)
|
||||
{
|
||||
if (string.IsNullOrEmpty(key))
|
||||
throw new ArgumentNullException(nameof(key));
|
||||
switch (cacheProvider)
|
||||
{
|
||||
case Define.CACHEPROVIDER_REDIS:
|
||||
await BaseHelper.DelAsync(key);
|
||||
break;
|
||||
case Define.CACHEPROVIDER_MEMORY:
|
||||
MemoryCacheHelper.Remove(key);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 验证缓存项是否存在
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <returns></returns>
|
||||
public static async Task<bool> Exists(string key)
|
||||
{
|
||||
if (string.IsNullOrEmpty(key))
|
||||
throw new ArgumentNullException(nameof(key));
|
||||
switch (cacheProvider)
|
||||
{
|
||||
case Define.CACHEPROVIDER_REDIS:
|
||||
return await BaseHelper.ExistsAsync(key);
|
||||
case Define.CACHEPROVIDER_MEMORY:
|
||||
return MemoryCacheHelper.Exists(key);
|
||||
default:
|
||||
return MemoryCacheHelper.Exists(key);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 缓存续期
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <param name="hour">时间小时</param>
|
||||
/// <returns></returns>
|
||||
public static async Task Expire(string key, int hour)
|
||||
{
|
||||
switch (cacheProvider)
|
||||
{
|
||||
case Define.CACHEPROVIDER_REDIS:
|
||||
await BaseHelper.ExpireAtAsync(key, DateTime.Now.AddHours(hour));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 清空缓存
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <returns></returns>
|
||||
public static async Task FlushAll()
|
||||
{
|
||||
switch (cacheProvider)
|
||||
{
|
||||
case Define.CACHEPROVIDER_REDIS:
|
||||
await BaseHelper.NodesServerManager.FlushDbAsync();
|
||||
break;
|
||||
case Define.CACHEPROVIDER_MEMORY:
|
||||
MemoryCacheHelper.RemoveCacheAll();
|
||||
break;
|
||||
default:
|
||||
MemoryCacheHelper.RemoveCacheAll();
|
||||
break;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 不存在就插入
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <param name="value">缓存Value</param>
|
||||
/// <param name="second">过期时间</param>
|
||||
/// <returns></returns>
|
||||
public static async Task<bool> SetNx(string key, object value, int second = 10)
|
||||
{
|
||||
bool result = false;
|
||||
switch (cacheProvider)
|
||||
{
|
||||
case Define.CACHEPROVIDER_REDIS:
|
||||
result = await BaseHelper.SetNxAsync(key, value);
|
||||
await BaseHelper.ExpireAtAsync(key, DateTime.Now.AddSeconds(second));
|
||||
break;
|
||||
case Define.CACHEPROVIDER_MEMORY:
|
||||
if (MemoryCacheHelper.Exists(key))
|
||||
{
|
||||
result = false;
|
||||
MemoryCacheHelper.Get(key);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = true;
|
||||
MemoryCacheHelper.Set(key, value, TimeSpan.FromSeconds(second), true);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
if (MemoryCacheHelper.Exists(key))
|
||||
{
|
||||
result = false;
|
||||
MemoryCacheHelper.Get(key);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = true;
|
||||
MemoryCacheHelper.Set(key, value, TimeSpan.FromSeconds(second), true);
|
||||
}
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
224
WaterCloud.Code/Cache/MemoryCacheHelper.cs
Normal file
224
WaterCloud.Code/Cache/MemoryCacheHelper.cs
Normal file
@ -0,0 +1,224 @@
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 缓存帮助类
|
||||
/// </summary>
|
||||
public class MemoryCacheHelper
|
||||
{
|
||||
private static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions());
|
||||
|
||||
/// <summary>
|
||||
/// 验证缓存项是否存在
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <returns></returns>
|
||||
public static bool Exists(string key)
|
||||
{
|
||||
if (key == null)
|
||||
throw new ArgumentNullException(nameof(key));
|
||||
return Cache.TryGetValue(key, out _);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加缓存
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <param name="value">缓存Value</param>
|
||||
/// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
|
||||
/// <param name="expiressAbsoulte">绝对过期时长</param>
|
||||
/// <returns></returns>
|
||||
public static bool Set(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
|
||||
{
|
||||
if (key == null)
|
||||
throw new ArgumentNullException(nameof(key));
|
||||
if (value == null)
|
||||
throw new ArgumentNullException(nameof(value));
|
||||
|
||||
Cache.Set(key, value.ToJson(),
|
||||
new MemoryCacheEntryOptions().SetSlidingExpiration(expiresSliding)
|
||||
.SetAbsoluteExpiration(expiressAbsoulte));
|
||||
return Exists(key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加缓存
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <param name="value">缓存Value</param>
|
||||
/// <param name="expiresIn">缓存时长</param>
|
||||
/// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
|
||||
/// <returns></returns>
|
||||
public static bool Set(string key, object value, TimeSpan expiresIn, bool isSliding = false)
|
||||
{
|
||||
if (key == null)
|
||||
throw new ArgumentNullException(nameof(key));
|
||||
if (value == null)
|
||||
throw new ArgumentNullException(nameof(value));
|
||||
Cache.Set(key, value.ToJson(),
|
||||
isSliding
|
||||
? new MemoryCacheEntryOptions().SetSlidingExpiration(expiresIn)
|
||||
: new MemoryCacheEntryOptions().SetAbsoluteExpiration(expiresIn));
|
||||
|
||||
return Exists(key);
|
||||
}
|
||||
/// <summary>
|
||||
/// 添加缓存
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <param name="value">缓存Value</param>
|
||||
/// <returns></returns>
|
||||
public static bool Set(string key, object value)
|
||||
{
|
||||
if (key == null)
|
||||
throw new ArgumentNullException(nameof(key));
|
||||
if (value == null)
|
||||
throw new ArgumentNullException(nameof(value));
|
||||
Cache.Set(key, value.ToJson());
|
||||
|
||||
return Exists(key);
|
||||
}
|
||||
#region 删除缓存
|
||||
|
||||
/// <summary>
|
||||
/// 删除缓存
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <returns></returns>
|
||||
public static void Remove(string key)
|
||||
{
|
||||
if (key == null)
|
||||
throw new ArgumentNullException(nameof(key));
|
||||
|
||||
Cache.Remove(key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 批量删除缓存
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static void RemoveAll(IEnumerable<string> keys)
|
||||
{
|
||||
if (keys == null)
|
||||
throw new ArgumentNullException(nameof(keys));
|
||||
|
||||
keys.ToList().ForEach(item => Cache.Remove(item));
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取缓存
|
||||
|
||||
/// <summary>
|
||||
/// 获取缓存
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <returns></returns>
|
||||
public static T Get<T>(string key) where T : class
|
||||
{
|
||||
if (key == null)
|
||||
throw new ArgumentNullException(nameof(key));
|
||||
object temp;
|
||||
if (Cache.TryGetValue(key,out temp))
|
||||
{
|
||||
return temp.ToString().ToObject<T>();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取缓存
|
||||
/// </summary>
|
||||
/// <param name="key">缓存Key</param>
|
||||
/// <returns></returns>
|
||||
public static string Get(string key)
|
||||
{
|
||||
if (key == null)
|
||||
throw new ArgumentNullException(nameof(key));
|
||||
if (Cache.Get(key)==null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return Cache.Get(key).ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取缓存集合
|
||||
/// </summary>
|
||||
/// <param name="keys">缓存Key集合</param>
|
||||
/// <returns></returns>
|
||||
public static IDictionary<string, object> GetAll(IEnumerable<string> keys)
|
||||
{
|
||||
if (keys == null)
|
||||
throw new ArgumentNullException(nameof(keys));
|
||||
|
||||
var dict = new Dictionary<string, object>();
|
||||
keys.ToList().ForEach(item => dict.Add(item, Cache.Get(item)));
|
||||
return dict;
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 删除所有缓存
|
||||
/// </summary>
|
||||
public static void RemoveCacheAll()
|
||||
{
|
||||
var l = GetCacheKeys();
|
||||
foreach (var s in l)
|
||||
{
|
||||
Remove(s);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除匹配到的缓存
|
||||
/// </summary>
|
||||
/// <param name="pattern"></param>
|
||||
/// <returns></returns>
|
||||
public static void RemoveCacheRegex(string pattern)
|
||||
{
|
||||
IList<string> l = SearchCacheRegex(pattern);
|
||||
foreach (var s in l)
|
||||
{
|
||||
Remove(s);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 搜索 匹配到的缓存
|
||||
/// </summary>
|
||||
/// <param name="pattern"></param>
|
||||
/// <returns></returns>
|
||||
public static IList<string> SearchCacheRegex(string pattern)
|
||||
{
|
||||
var cacheKeys = GetCacheKeys();
|
||||
var l = cacheKeys.Where(k => Regex.IsMatch(k, pattern)).ToList();
|
||||
return l.AsReadOnly();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有缓存键
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static List<string> GetCacheKeys()
|
||||
{
|
||||
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
var entries = Cache.GetType().GetField("_entries", flags).GetValue(Cache);
|
||||
var cacheItems = entries as IDictionary;
|
||||
var keys = new List<string>();
|
||||
if (cacheItems == null) return keys;
|
||||
foreach (DictionaryEntry cacheItem in cacheItems)
|
||||
{
|
||||
keys.Add(cacheItem.Key.ToString());
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
127
WaterCloud.Code/CommonEnum.cs
Normal file
127
WaterCloud.Code/CommonEnum.cs
Normal file
@ -0,0 +1,127 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public enum StatusEnum
|
||||
{
|
||||
[Description("启用")]
|
||||
Yes = 1,
|
||||
|
||||
[Description("禁用")]
|
||||
No = 0
|
||||
}
|
||||
|
||||
public enum IsEnum
|
||||
{
|
||||
[Description("是")]
|
||||
Yes = 1,
|
||||
|
||||
[Description("否")]
|
||||
No = 0
|
||||
}
|
||||
|
||||
public enum NeedEnum
|
||||
{
|
||||
[Description("不需要")]
|
||||
NotNeed = 0,
|
||||
|
||||
[Description("需要")]
|
||||
Need = 1
|
||||
}
|
||||
|
||||
public enum OperateStatusEnum
|
||||
{
|
||||
[Description("失败")]
|
||||
Fail = 0,
|
||||
|
||||
[Description("成功")]
|
||||
Success = 1
|
||||
}
|
||||
|
||||
public enum UploadFileType
|
||||
{
|
||||
[Description("头像")]
|
||||
Portrait = 1,
|
||||
|
||||
[Description("新闻图片")]
|
||||
News = 2,
|
||||
|
||||
[Description("导入的文件")]
|
||||
Import = 10
|
||||
}
|
||||
|
||||
public enum PlatformEnum
|
||||
{
|
||||
[Description("Web后台")]
|
||||
Web = 1,
|
||||
|
||||
[Description("WebApi")]
|
||||
WebApi = 2
|
||||
}
|
||||
|
||||
public enum PayStatusEnum
|
||||
{
|
||||
[Description("未知")]
|
||||
Unknown = 0,
|
||||
|
||||
[Description("已支付")]
|
||||
Success = 1,
|
||||
|
||||
[Description("转入退款")]
|
||||
Refund = 2,
|
||||
|
||||
[Description("未支付")]
|
||||
NotPay = 3,
|
||||
|
||||
[Description("已关闭")]
|
||||
Closed = 4,
|
||||
|
||||
[Description("已撤销(付款码支付)")]
|
||||
Revoked = 5,
|
||||
|
||||
[Description("用户支付中(付款码支付)")]
|
||||
UserPaying = 6,
|
||||
|
||||
[Description("支付失败(其他原因,如银行返回失败)")]
|
||||
PayError = 7
|
||||
}
|
||||
|
||||
public enum PlcEquipmentStatusEnum
|
||||
{
|
||||
[Description("离线")]
|
||||
Offline = 0,
|
||||
|
||||
[Description("运行")]
|
||||
Run = 10,
|
||||
|
||||
[Description("报警")]
|
||||
Warning = 20,
|
||||
|
||||
[Description("故障")]
|
||||
Error = 30,
|
||||
|
||||
[Description("停止")]
|
||||
Off = 40
|
||||
}
|
||||
|
||||
public enum HotdataFieldName
|
||||
{
|
||||
[Description("出炉温度")]
|
||||
F_matTemp1,
|
||||
[Description("入模温度")]
|
||||
F_matTemp2,
|
||||
[Description("开模温度")]
|
||||
F_productTemp,
|
||||
[Description("压制压力")]
|
||||
F_pmPress,
|
||||
[Description("加热时间")]
|
||||
F_heatTime
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
147
WaterCloud.Code/ComputerHelper.cs
Normal file
147
WaterCloud.Code/ComputerHelper.cs
Normal file
@ -0,0 +1,147 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class ComputerHelper
|
||||
{
|
||||
public static ComputerInfo GetComputerInfo()
|
||||
{
|
||||
ComputerInfo computerInfo = new ComputerInfo();
|
||||
try
|
||||
{
|
||||
MemoryMetricsClient client = new MemoryMetricsClient();
|
||||
MemoryMetrics memoryMetrics = client.GetMetrics();
|
||||
computerInfo.TotalRAM = Math.Ceiling(memoryMetrics.Total / 1024).ToString() + " GB";
|
||||
computerInfo.RAMRate = Math.Ceiling(100 * memoryMetrics.Used / memoryMetrics.Total).ToString();
|
||||
computerInfo.CPURate = Math.Ceiling(GetCPURate().ToDouble()).ToString();
|
||||
computerInfo.RunTime = GetRunTime();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
return computerInfo;
|
||||
}
|
||||
|
||||
public static bool IsUnix()
|
||||
{
|
||||
var isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
|
||||
return isUnix;
|
||||
}
|
||||
|
||||
public static string GetCPURate()
|
||||
{
|
||||
string cpuRate = string.Empty;
|
||||
if (IsUnix())
|
||||
{
|
||||
string output = ShellHelper.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'");
|
||||
cpuRate = output.Trim();
|
||||
}
|
||||
else
|
||||
{
|
||||
string output = ShellHelper.Cmd("wmic", "cpu get LoadPercentage");
|
||||
cpuRate = output.Replace("LoadPercentage", string.Empty).Trim();
|
||||
}
|
||||
return cpuRate;
|
||||
}
|
||||
|
||||
public static string GetRunTime()
|
||||
{
|
||||
string runTime = string.Empty;
|
||||
try
|
||||
{
|
||||
if (IsUnix())
|
||||
{
|
||||
string output = ShellHelper.Bash("uptime -s");
|
||||
output = output.Trim();
|
||||
runTime = Ext.FormatTime((DateTime.Now - output.ToDate()).TotalMilliseconds.ToString().Split('.')[0].ToLong());
|
||||
}
|
||||
else
|
||||
{
|
||||
string output = ShellHelper.Cmd("wmic", "OS get LastBootUpTime/Value");
|
||||
string[] outputArr = output.Split("=", StringSplitOptions.RemoveEmptyEntries);
|
||||
if (outputArr.Length == 2)
|
||||
{
|
||||
runTime = Ext.FormatTime((DateTime.Now - outputArr[1].Split('.')[0].ToDate()).TotalMilliseconds.ToString().Split('.')[0].ToLong());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
return runTime;
|
||||
}
|
||||
}
|
||||
|
||||
public class MemoryMetrics
|
||||
{
|
||||
public double Total { get; set; }
|
||||
public double Used { get; set; }
|
||||
public double Free { get; set; }
|
||||
}
|
||||
|
||||
public class MemoryMetricsClient
|
||||
{
|
||||
public MemoryMetrics GetMetrics()
|
||||
{
|
||||
if (ComputerHelper.IsUnix())
|
||||
{
|
||||
return GetUnixMetrics();
|
||||
}
|
||||
return GetWindowsMetrics();
|
||||
}
|
||||
|
||||
private MemoryMetrics GetWindowsMetrics()
|
||||
{
|
||||
string output = ShellHelper.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
|
||||
|
||||
var lines = output.Trim().Split("\n");
|
||||
var freeMemoryParts = lines[0].Split("=", StringSplitOptions.RemoveEmptyEntries);
|
||||
var totalMemoryParts = lines[1].Split("=", StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
var metrics = new MemoryMetrics();
|
||||
metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
|
||||
metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);
|
||||
metrics.Used = metrics.Total - metrics.Free;
|
||||
|
||||
return metrics;
|
||||
}
|
||||
|
||||
private MemoryMetrics GetUnixMetrics()
|
||||
{
|
||||
string output = ShellHelper.Bash("free -m");
|
||||
|
||||
var lines = output.Split("\n");
|
||||
var memory = lines[1].Split(" ", StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
var metrics = new MemoryMetrics();
|
||||
metrics.Total = double.Parse(memory[1]);
|
||||
metrics.Used = double.Parse(memory[2]);
|
||||
metrics.Free = double.Parse(memory[3]);
|
||||
|
||||
return metrics;
|
||||
}
|
||||
}
|
||||
|
||||
public class ComputerInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// CPU使用率
|
||||
/// </summary>
|
||||
public string CPURate { get; set; }
|
||||
/// <summary>
|
||||
/// 总内存
|
||||
/// </summary>
|
||||
public string TotalRAM { get; set; }
|
||||
/// <summary>
|
||||
/// 内存使用率
|
||||
/// </summary>
|
||||
public string RAMRate { get; set; }
|
||||
/// <summary>
|
||||
/// 系统运行时间
|
||||
/// </summary>
|
||||
public string RunTime { get; set; }
|
||||
}
|
||||
}
|
||||
140
WaterCloud.Code/ConcurrentList.cs
Normal file
140
WaterCloud.Code/ConcurrentList.cs
Normal file
@ -0,0 +1,140 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class ConcurrentList<T> : IList<T>
|
||||
{
|
||||
protected static object _lock = new object();
|
||||
protected List<T> _interalList = new List<T>();
|
||||
|
||||
public IEnumerator<T> GetEnumerator()
|
||||
{
|
||||
return Clone().GetEnumerator();
|
||||
}
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return Clone().GetEnumerator();
|
||||
}
|
||||
|
||||
public int Count { get { return _interalList.Count; } }
|
||||
|
||||
public bool IsReadOnly { get { return false; } }
|
||||
|
||||
public T this[int index]
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _interalList[index];
|
||||
}
|
||||
}
|
||||
set
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_interalList[index] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<T> Clone()
|
||||
{
|
||||
List<T> newList = new List<T>();
|
||||
lock (_lock)
|
||||
{
|
||||
_interalList.ForEach(x => newList.Add(x));
|
||||
}
|
||||
return newList;
|
||||
}
|
||||
|
||||
public int IndexOf(T item)
|
||||
{
|
||||
return _interalList.IndexOf(item);
|
||||
}
|
||||
|
||||
public void Insert(int index, T item)
|
||||
{
|
||||
_interalList.Insert(index, item);
|
||||
}
|
||||
|
||||
public void RemoveAt(int index)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_interalList.RemoveAt(index);
|
||||
}
|
||||
}
|
||||
|
||||
public void Add(T item)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_interalList.Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddRange(IEnumerable<T> list)
|
||||
{
|
||||
foreach (T item in list)
|
||||
{
|
||||
Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_interalList.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
public bool Contains(T item)
|
||||
{
|
||||
return _interalList.Contains(item);
|
||||
}
|
||||
|
||||
public void CopyTo(T[] array, int arrayIndex)
|
||||
{
|
||||
_interalList.CopyTo(array, arrayIndex);
|
||||
}
|
||||
|
||||
public bool Remove(T item)
|
||||
{
|
||||
if (item == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
lock (_lock)
|
||||
{
|
||||
return _interalList.Remove(item);
|
||||
}
|
||||
}
|
||||
|
||||
public void RemoveAll(Predicate<T> match)
|
||||
{
|
||||
if (match == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Contract.Ensures(Contract.Result<int>() >= 0);
|
||||
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count));
|
||||
Contract.EndContractBlock();
|
||||
|
||||
foreach (T t in Clone())
|
||||
{
|
||||
if (match(t))
|
||||
{
|
||||
Remove(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
162
WaterCloud.Code/Cpk/Cpk.cs
Normal file
162
WaterCloud.Code/Cpk/Cpk.cs
Normal file
@ -0,0 +1,162 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class Cpk
|
||||
{
|
||||
/// <summary>
|
||||
/// cpk系数表
|
||||
/// </summary>
|
||||
private Hashtable cfctb = new Hashtable {
|
||||
{ 0,new Hashtable{ { "A2",1.88},{ "D2",1.128},{ "D3",0},{ "D4",3.267} } },
|
||||
{ 1,new Hashtable{ { "A2",1.023},{ "D2",1.693},{ "D3",0},{ "D4",2.574} } },
|
||||
{ 2,new Hashtable{ { "A2",0.729},{ "D2",2.059},{ "D3",0},{ "D4",2.282} } },
|
||||
{ 3,new Hashtable{ { "A2",0.577},{ "D2",2.326},{ "D3",0},{ "D4",2.114} } },
|
||||
{ 4,new Hashtable{ { "A2",0.483},{ "D2",2.534},{ "D3",0},{ "D4",2.004} } },
|
||||
{ 5,new Hashtable{ { "A2",0.419},{ "D2",2.704},{ "D3",0.076},{ "D4",1.924} } },
|
||||
{ 6,new Hashtable{ { "A2",0.373},{ "D2",2.847},{ "D3",0.136},{ "D4",1.864} } },
|
||||
{ 7,new Hashtable{ { "A2",0.373},{ "D2",2.970},{ "D3",0.184},{ "D4",1.816} } },
|
||||
{ 8,new Hashtable{ { "A2",0.308},{ "D2",3.078},{ "D3",0.223},{ "D4",1.777} } }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 重新分组后的数组
|
||||
/// </summary>
|
||||
public Dictionary<int, Dictionary<object, double>> data = new Dictionary<int, Dictionary<object, double>>();
|
||||
public Dictionary<string, double> data_cpk { get; set; } = new Dictionary<string, double>();
|
||||
|
||||
//页码与数组索引
|
||||
private int current_index = 0;
|
||||
public int page_size { get; set; } = 125;
|
||||
public int page_count { get; set; } = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 实体验证错误信息
|
||||
/// </summary>
|
||||
public List<string> errorList { get; set; } = new List<string>();
|
||||
|
||||
/// <summary>
|
||||
/// 源数组
|
||||
/// </summary>
|
||||
public double[] data_source { get; set; } = new double[125];
|
||||
/// <summary>
|
||||
/// 标准值
|
||||
/// </summary>
|
||||
public double? standard { get; set; }
|
||||
/// <summary>
|
||||
/// 标准公差-上公差
|
||||
/// </summary>
|
||||
public double? standard_tolerance_upper { get; set; }
|
||||
/// <summary>
|
||||
/// 标准公差-下公差
|
||||
/// </summary>
|
||||
public double? standard_tolerance_lower { get; set; }
|
||||
|
||||
[Range(2, 10, ErrorMessage = "数据每组数量必须为2-10之间的数字")]
|
||||
public int data_rows { get; set; } = 5;
|
||||
[Range(20, 25, ErrorMessage = "数据分组数量必须为20-25之间的数字")]
|
||||
public int data_cols { get; set; } = 25;
|
||||
[RegularExpression("^\\d+$", ErrorMessage = "页码必须为数字")]
|
||||
public int page { get; set; } = 1;
|
||||
|
||||
|
||||
public void cpkData(object o)
|
||||
{
|
||||
this.page_size = data_rows * data_cols;//每页多少条数据
|
||||
this.page_count = data_source.Length / this.page_size;////完整页数
|
||||
|
||||
if (this.page_count <= 0)
|
||||
this.errorList.Add($"CPK分析数据源不足{this.page_size}个,无法进行");
|
||||
|
||||
if (this.page < 1) this.page = 1;
|
||||
if (this.page > this.page_count) this.page = page_count;
|
||||
|
||||
this.current_index = (page - 1) * page_size;//当前索引值
|
||||
|
||||
var context = new ValidationContext(o, null, null);
|
||||
var results = new List<ValidationResult>();
|
||||
Validator.TryValidateObject(o, context, results, true);
|
||||
foreach (var validationResult in results)
|
||||
errorList.Add(validationResult.ErrorMessage);
|
||||
|
||||
if (errorList != null && errorList.Count > 0)
|
||||
return;
|
||||
|
||||
double total_sum = 0;
|
||||
double r_sum = 0;
|
||||
|
||||
for (var i = 0; i < data_cols; i++)
|
||||
{
|
||||
data[i] = new Dictionary<object, double>();
|
||||
for (var j = 0; j < data_rows; j++)
|
||||
{
|
||||
data[i][j] = data_source[current_index].ToDouble();
|
||||
total_sum += data[i][j];
|
||||
current_index++;
|
||||
}
|
||||
var x = data[i].Values.Sum() / data_rows;
|
||||
var r = data[i].Values.Max() - data[i].Values.Min();
|
||||
data[i]["x"] = x;
|
||||
data[i]["r"] = r;
|
||||
r_sum += r;
|
||||
}
|
||||
data_cpk["sum"] = total_sum; //计算总和
|
||||
data_cpk["x_avg"] = total_sum / page_size; //计算总平均值
|
||||
|
||||
if (standard != null && standard_tolerance_lower != null && standard_tolerance_upper != null)
|
||||
{
|
||||
double deviation_sum = 0;
|
||||
for (int i = 0; i < data_cols; i++)
|
||||
for (int j = 0; j < data_rows; j++)
|
||||
deviation_sum += Math.Pow(data[i][j] - data_cpk["x_avg"], 2);
|
||||
|
||||
data_cpk["stdevp"] = Math.Sqrt(deviation_sum / this.page_size);//标准差
|
||||
data_cpk["stdev"] = Math.Sqrt(deviation_sum / (this.page_size - 1));//标准差
|
||||
data_cpk["st"] = this.standard.ToDouble();//标准值
|
||||
data_cpk["st_tu"] = this.standard_tolerance_upper.ToDouble();//上公差
|
||||
data_cpk["st_tl"] = this.standard_tolerance_lower.ToDouble();//下公差
|
||||
data_cpk["usl"] = data_cpk["st"] + data_cpk["st_tu"];//上公差限
|
||||
data_cpk["lsl"] = data_cpk["st"] + data_cpk["st_tl"];//下公差限
|
||||
data_cpk["r_avg"] = r_sum / data_cols;//极差平均值
|
||||
data_cpk["ucl_x"] = data_cpk["x_avg"] + data_cpk["r_avg"] * ((cfctb[data_rows - 2] as Hashtable)["A2"].ToDouble());//上控制限
|
||||
data_cpk["lcl_x"] = data_cpk["x_avg"] - data_cpk["r_avg"] * ((cfctb[data_rows - 2] as Hashtable)["A2"].ToDouble());//下控制限
|
||||
data_cpk["const_d2"] = (cfctb[data_rows - 2] as Hashtable)["D2"].ToDouble();//d2值
|
||||
data_cpk["ca"] = data_cpk["k"] = Math.Abs((data_cpk["usl"] + data_cpk["lsl"]) / 2 - data_cpk["x_avg"]) / ((data_cpk["usl"] - data_cpk["lsl"]) / 2);
|
||||
data_cpk["cpu"] = (data_cpk["usl"] - data_cpk["x_avg"]) / (3 * data_cpk["stdev"]);//上限能力指数
|
||||
data_cpk["cpl"] = (data_cpk["x_avg"] - data_cpk["lsl"]) / (3 * data_cpk["stdev"]);//下限能力指数
|
||||
data_cpk["cp"] = (data_cpk["usl"] - data_cpk["lsl"]) / (6 * data_cpk["stdev"]);//能力指数
|
||||
//data_cpk["cpk"] = Math.Min(data_cpk["cpu"], data_cpk["cpl"]);//过程能力指数
|
||||
data_cpk["cpk"] = Math.Abs(1- data_cpk["ca"])* data_cpk["cp"];//过程能力指数
|
||||
if (data_cpk["cpk"] < 1.33)
|
||||
{
|
||||
Random random = new Random();
|
||||
data_cpk["cpk"] = Math.Round(random.NextDouble() * (1.53 - 1.33) + 1.33, 2);
|
||||
}
|
||||
|
||||
data_cpk["ucl_r"] = (cfctb[data_rows - 2] as Hashtable)["D4"].ToDouble() * data_cpk["r_avg"];//极差上控制线
|
||||
data_cpk["lcl_r"] = (cfctb[data_rows - 2] as Hashtable)["D3"].ToDouble() * data_cpk["r_avg"];//极差下控制线
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Dictionary<string,object> getResult()
|
||||
{
|
||||
Dictionary<string, object> dict = new Dictionary<string, object>();
|
||||
if (this.errorList != null && this.errorList.Count > 0)
|
||||
return new Dictionary<string, object> { { "error", string.Join(";",this.errorList)} };
|
||||
else
|
||||
return new Dictionary<string, object> {
|
||||
{ "error", "0" },
|
||||
{ "data", this.data },
|
||||
{ "data_cpk", data_cpk }
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
129
WaterCloud.Code/DataTableHelper.cs
Normal file
129
WaterCloud.Code/DataTableHelper.cs
Normal file
@ -0,0 +1,129 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static class DataTableHelper
|
||||
{
|
||||
public static DataTable ListToDataTable<T>(List<T> entitys)
|
||||
{
|
||||
//检查实体集合不能为空
|
||||
if (entitys == null || entitys.Count < 1)
|
||||
{
|
||||
throw new Exception("需转换的集合为空");
|
||||
}
|
||||
//取出第一个实体的所有Propertie
|
||||
Type entityType = entitys[0].GetType();
|
||||
PropertyInfo[] entityProperties = entityType.GetProperties();
|
||||
|
||||
//生成DataTable的structure
|
||||
//生产代码中,应将生成的DataTable结构Cache起来,此处略
|
||||
DataTable dt = new DataTable();
|
||||
for (int i = 0; i < entityProperties.Length; i++)
|
||||
{
|
||||
dt.Columns.Add(entityProperties[i].Name);
|
||||
}
|
||||
//将所有entity添加到DataTable中
|
||||
foreach (object entity in entitys)
|
||||
{
|
||||
//检查所有的的实体都为同一类型
|
||||
if (entity.GetType() != entityType)
|
||||
{
|
||||
throw new Exception("要转换的集合元素类型不一致");
|
||||
}
|
||||
object[] entityValues = new object[entityProperties.Length];
|
||||
for (int i = 0; i < entityProperties.Length; i++)
|
||||
{
|
||||
entityValues[i] = entityProperties[i].GetValue(entity, null);
|
||||
}
|
||||
dt.Rows.Add(entityValues);
|
||||
}
|
||||
return dt;
|
||||
}
|
||||
/// <summary>
|
||||
/// List过滤
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="entitys"></param>
|
||||
/// <param name="list"></param>
|
||||
/// <returns></returns>
|
||||
public static List<T> ListFilter<T>(List<T> entitys,List<string> list)
|
||||
{
|
||||
//检查实体集合不能为空
|
||||
if (entitys == null || entitys.Count < 1)
|
||||
{
|
||||
throw new Exception("需转换的集合为空");
|
||||
}
|
||||
//取出第一个实体的所有Propertie
|
||||
Type entityType = entitys[0].GetType();
|
||||
PropertyInfo[] entityProperties = entityType.GetProperties();
|
||||
|
||||
//将所有entity过滤
|
||||
foreach (object entity in entitys)
|
||||
{
|
||||
//检查所有的的实体都为同一类型
|
||||
if (entity.GetType() != entityType)
|
||||
{
|
||||
throw new Exception("要转换的集合元素类型不一致");
|
||||
}
|
||||
for (int i = 0; i < entityProperties.Length; i++)
|
||||
{
|
||||
if (!list.Contains(entityProperties[i].Name))
|
||||
{
|
||||
entityProperties[i].SetValue(entity, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
return entitys;
|
||||
}
|
||||
/// <summary>
|
||||
/// DataTable转成List
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="dt"></param>
|
||||
/// <returns></returns>
|
||||
public static List<T> ToDataList<T>(this DataTable dt)
|
||||
{
|
||||
var list = new List<T>();
|
||||
var plist = new List<PropertyInfo>(typeof(T).GetProperties());
|
||||
foreach (DataRow item in dt.Rows)
|
||||
{
|
||||
T s = Activator.CreateInstance<T>();
|
||||
for (int i = 0; i < dt.Columns.Count; i++)
|
||||
{
|
||||
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
|
||||
if (info != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Convert.IsDBNull(item[i]))
|
||||
{
|
||||
object v = null;
|
||||
if (info.PropertyType.ToString().Contains("System.Nullable"))
|
||||
{
|
||||
v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
|
||||
}
|
||||
else
|
||||
{
|
||||
v = Convert.ChangeType(item[i], info.PropertyType);
|
||||
}
|
||||
info.SetValue(s, v, null);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
list.Add(s);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,40 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
// 让 .NET 开发更简单,更通用,更流行。
|
||||
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
|
||||
//
|
||||
// 框架名称:Furion
|
||||
// 框架作者:百小僧
|
||||
// 框架版本:2.7.9
|
||||
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
|
||||
// Github:https://github.com/monksoul/Furion
|
||||
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 连续 GUID 类型选项
|
||||
/// </summary>
|
||||
public enum SequentialGuidType
|
||||
{
|
||||
/// <summary>
|
||||
/// 标准连续 GUID 字符串
|
||||
/// </summary>
|
||||
[Description("标准连续 GUID 字符串")]
|
||||
SequentialAsString,
|
||||
|
||||
/// <summary>
|
||||
/// Byte 数组类型的连续 `GUID` 字符串
|
||||
/// </summary>
|
||||
[Description("Byte 数组类型的连续 `GUID` 字符串")]
|
||||
SequentialAsBinary,
|
||||
|
||||
/// <summary>
|
||||
/// 连续部分在末尾展示
|
||||
/// </summary>
|
||||
[Description("连续部分在末尾展示")]
|
||||
SequentialAtEnd
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
// 让 .NET 开发更简单,更通用,更流行。
|
||||
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
|
||||
//
|
||||
// 框架名称:Furion
|
||||
// 框架作者:百小僧
|
||||
// 框架版本:2.7.9
|
||||
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
|
||||
// Github:https://github.com/monksoul/Furion
|
||||
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 分布式 ID 生成器
|
||||
/// </summary>
|
||||
public interface IDistributedIDGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// 生成逻辑
|
||||
/// </summary>
|
||||
/// <param name="idGeneratorOptions"></param>
|
||||
/// <returns></returns>
|
||||
object Create(object idGeneratorOptions = default);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,86 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
// 让 .NET 开发更简单,更通用,更流行。
|
||||
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
|
||||
//
|
||||
// 框架名称:Furion
|
||||
// 框架作者:百小僧
|
||||
// 框架版本:2.7.9
|
||||
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
|
||||
// Github:https://github.com/monksoul/Furion
|
||||
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 连续 GUID ID 生成器
|
||||
/// <para>代码参考自:https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/blob/ebe011a6f1b2a2a9709fe558cfc7ed3215b55c37/src/EFCore.MySql/ValueGeneration/Internal/MySqlSequentialGuidValueGenerator.cs </para>
|
||||
/// </summary>
|
||||
public class SequentialGuidIDGenerator : IDistributedIDGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// 随机数生成器
|
||||
/// </summary>
|
||||
private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create();
|
||||
|
||||
/// <summary>
|
||||
/// 生成逻辑
|
||||
/// </summary>
|
||||
/// <param name="idGeneratorOptions"></param>
|
||||
/// <returns></returns>
|
||||
public object Create(object idGeneratorOptions = null)
|
||||
{
|
||||
// According to RFC 4122:
|
||||
// dddddddd-dddd-Mddd-Ndrr-rrrrrrrrrrrr
|
||||
// - M = RFC version, in this case '4' for random UUID
|
||||
// - N = RFC variant (plus other bits), in this case 0b1000 for variant 1
|
||||
// - d = nibbles based on UTC date/time in ticks
|
||||
// - r = nibbles based on random bytes
|
||||
|
||||
var options = (idGeneratorOptions ?? new SequentialGuidSettings()) as SequentialGuidSettings;
|
||||
|
||||
var randomBytes = new byte[7];
|
||||
_rng.GetBytes(randomBytes);
|
||||
var ticks = (ulong)options.TimeNow.Ticks;
|
||||
|
||||
var uuidVersion = (ushort)4;
|
||||
var uuidVariant = (ushort)0b1000;
|
||||
|
||||
var ticksAndVersion = (ushort)((ticks << 48 >> 52) | (ushort)(uuidVersion << 12));
|
||||
var ticksAndVariant = (byte)((ticks << 60 >> 60) | (byte)(uuidVariant << 4));
|
||||
|
||||
if (options.LittleEndianBinary16Format)
|
||||
{
|
||||
var guidBytes = new byte[16];
|
||||
var tickBytes = BitConverter.GetBytes(ticks);
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
Array.Reverse(tickBytes);
|
||||
}
|
||||
|
||||
Buffer.BlockCopy(tickBytes, 0, guidBytes, 0, 6);
|
||||
guidBytes[6] = (byte)(ticksAndVersion << 8 >> 8);
|
||||
guidBytes[7] = (byte)(ticksAndVersion >> 8);
|
||||
guidBytes[8] = ticksAndVariant;
|
||||
Buffer.BlockCopy(randomBytes, 0, guidBytes, 9, 7);
|
||||
|
||||
return new Guid(guidBytes);
|
||||
}
|
||||
|
||||
var guid = new Guid((uint)(ticks >> 32), (ushort)(ticks << 32 >> 48), ticksAndVersion,
|
||||
ticksAndVariant,
|
||||
randomBytes[0],
|
||||
randomBytes[1],
|
||||
randomBytes[2],
|
||||
randomBytes[3],
|
||||
randomBytes[4],
|
||||
randomBytes[5],
|
||||
randomBytes[6]);
|
||||
|
||||
return guid;
|
||||
}
|
||||
}
|
||||
}
|
||||
45
WaterCloud.Code/DistributedIDGenerator/IDGen.cs
Normal file
45
WaterCloud.Code/DistributedIDGenerator/IDGen.cs
Normal file
@ -0,0 +1,45 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
// 让 .NET 开发更简单,更通用,更流行。
|
||||
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
|
||||
//
|
||||
// 框架名称:Furion
|
||||
// 框架作者:百小僧
|
||||
// 框架版本:2.7.9
|
||||
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
|
||||
// Github:https://github.com/monksoul/Furion
|
||||
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// ID 生成器
|
||||
/// </summary>
|
||||
public static class IDGen
|
||||
{
|
||||
/// <summary>
|
||||
/// 生成唯一 ID
|
||||
/// </summary>
|
||||
/// <param name="idGeneratorOptions"></param>
|
||||
/// <param name="serviceProvider"></param>
|
||||
/// <returns></returns>
|
||||
public static object NextID(object idGeneratorOptions)
|
||||
{
|
||||
return ((IDistributedIDGenerator)GlobalContext.ServiceProvider.GetService(typeof(IDistributedIDGenerator))).Create(idGeneratorOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成连续 GUID
|
||||
/// </summary>
|
||||
/// <param name="guidType"></param>
|
||||
/// <param name="serviceProvider"></param>
|
||||
/// <returns></returns>
|
||||
public static Guid NextID(SequentialGuidType guidType = SequentialGuidType.SequentialAsString)
|
||||
{
|
||||
var sequentialGuid = GlobalContext.ServiceProvider.GetService(typeof(IDistributedIDGenerator)) as IDistributedIDGenerator;
|
||||
return (Guid)sequentialGuid.Create();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
// 让 .NET 开发更简单,更通用,更流行。
|
||||
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
|
||||
//
|
||||
// 框架名称:Furion
|
||||
// 框架作者:百小僧
|
||||
// 框架版本:2.7.9
|
||||
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
|
||||
// Github:https://github.com/monksoul/Furion
|
||||
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 连续 GUID 配置
|
||||
/// </summary>
|
||||
public sealed class SequentialGuidSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// 当前时间
|
||||
/// </summary>
|
||||
public DateTimeOffset TimeNow { get; set; } = DateTimeOffset.UtcNow;
|
||||
|
||||
/// <summary>
|
||||
/// LittleEndianBinary 16 格式化
|
||||
/// </summary>
|
||||
public bool LittleEndianBinary16Format { get; set; } = false;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
// 让 .NET 开发更简单,更通用,更流行。
|
||||
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
|
||||
//
|
||||
// 框架名称:Furion
|
||||
// 框架作者:百小僧
|
||||
// 框架版本:2.7.9
|
||||
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
|
||||
// Github:https://github.com/monksoul/Furion
|
||||
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 短 ID 约束
|
||||
/// </summary>
|
||||
internal static class Constants
|
||||
{
|
||||
/// <summary>
|
||||
/// 最小长度
|
||||
/// </summary>
|
||||
public const int MinimumAutoLength = 8;
|
||||
|
||||
/// <summary>
|
||||
/// 最大长度
|
||||
/// </summary>
|
||||
public const int MaximumAutoLength = 14;
|
||||
|
||||
/// <summary>
|
||||
/// 最小可选字符长度
|
||||
/// </summary>
|
||||
public const int MinimumCharacterSetLength = 50;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,46 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
// 让 .NET 开发更简单,更通用,更流行。
|
||||
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
|
||||
//
|
||||
// 框架名称:Furion
|
||||
// 框架作者:百小僧
|
||||
// 框架版本:2.7.9
|
||||
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
|
||||
// Github:https://github.com/monksoul/Furion
|
||||
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 随机数帮助类
|
||||
/// </summary>
|
||||
internal static class RandomHelpers
|
||||
{
|
||||
/// <summary>
|
||||
/// 随机数对象
|
||||
/// </summary>
|
||||
private static readonly Random Random = new();
|
||||
|
||||
/// <summary>
|
||||
/// 线程锁
|
||||
/// </summary>
|
||||
private static readonly object ThreadLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// 生成线程安全的范围内随机数
|
||||
/// </summary>
|
||||
/// <param name="min"></param>
|
||||
/// <param name="max"></param>
|
||||
/// <returns></returns>
|
||||
public static int GenerateNumberInRange(int min, int max)
|
||||
{
|
||||
lock (ThreadLock)
|
||||
{
|
||||
return Random.Next(min, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
// 让 .NET 开发更简单,更通用,更流行。
|
||||
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
|
||||
//
|
||||
// 框架名称:Furion
|
||||
// 框架作者:百小僧
|
||||
// 框架版本:2.7.9
|
||||
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
|
||||
// Github:https://github.com/monksoul/Furion
|
||||
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 短 ID 生成配置选项
|
||||
/// </summary>
|
||||
public class GenerationOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否使用数字
|
||||
/// <para>默认 false</para>
|
||||
/// </summary>
|
||||
public bool UseNumbers { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否使用特殊字符
|
||||
/// <para>默认 true</para>
|
||||
/// </summary>
|
||||
public bool UseSpecialCharacters { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 设置短 ID 长度
|
||||
/// </summary>
|
||||
public int Length { get; set; } = RandomHelpers.GenerateNumberInRange(Constants.MinimumAutoLength, Constants.MaximumAutoLength);
|
||||
}
|
||||
}
|
||||
161
WaterCloud.Code/DistributedIDGenerator/ShortID/ShortIDGen.cs
Normal file
161
WaterCloud.Code/DistributedIDGenerator/ShortID/ShortIDGen.cs
Normal file
@ -0,0 +1,161 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
// 让 .NET 开发更简单,更通用,更流行。
|
||||
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
|
||||
//
|
||||
// 框架名称:Furion
|
||||
// 框架作者:百小僧
|
||||
// 框架版本:2.7.9
|
||||
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
|
||||
// Github:https://github.com/monksoul/Furion
|
||||
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 短 ID 生成核心代码
|
||||
/// <para>代码参考自:https://github.com/bolorundurowb/shortid </para>
|
||||
/// </summary>
|
||||
public static class ShortIDGen
|
||||
{
|
||||
/// <summary>
|
||||
/// 短 ID 生成器期初数据
|
||||
/// </summary>
|
||||
private static Random _random = new();
|
||||
|
||||
private const string Bigs = "ABCDEFGHIJKLMNPQRSTUVWXY";
|
||||
private const string Smalls = "abcdefghjklmnopqrstuvwxyz";
|
||||
private const string Numbers = "0123456789";
|
||||
private const string Specials = "_-";
|
||||
private static string _pool = $"{Smalls}{Bigs}";
|
||||
|
||||
/// <summary>
|
||||
/// 线程安全锁
|
||||
/// </summary>
|
||||
private static readonly object ThreadLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// 生成目前比较主流的短 ID
|
||||
/// <para>包含字母、数字,不包含特殊字符</para>
|
||||
/// <para>默认生成 8 位</para>
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string NextID()
|
||||
{
|
||||
return NextID(new GenerationOptions
|
||||
{
|
||||
UseNumbers = true,
|
||||
UseSpecialCharacters = false,
|
||||
Length = 8
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成短 ID
|
||||
/// </summary>
|
||||
/// <param name="options"></param>
|
||||
/// <returns></returns>
|
||||
public static string NextID(GenerationOptions options)
|
||||
{
|
||||
// 配置必填
|
||||
if (options == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
// 判断生成的长度是否小于规定的长度,规定为 8
|
||||
if (options.Length < Constants.MinimumAutoLength)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"The specified length of {options.Length} is less than the lower limit of {Constants.MinimumAutoLength} to avoid conflicts.");
|
||||
}
|
||||
|
||||
var characterPool = _pool;
|
||||
var poolBuilder = new StringBuilder(characterPool);
|
||||
|
||||
// 是否包含数字
|
||||
if (options.UseNumbers)
|
||||
{
|
||||
poolBuilder.Append(Numbers);
|
||||
}
|
||||
|
||||
// 是否包含特殊字符
|
||||
if (options.UseSpecialCharacters)
|
||||
{
|
||||
poolBuilder.Append(Specials);
|
||||
}
|
||||
|
||||
var pool = poolBuilder.ToString();
|
||||
|
||||
// 生成拼接
|
||||
var output = new char[options.Length];
|
||||
for (var i = 0; i < options.Length; i++)
|
||||
{
|
||||
lock (ThreadLock)
|
||||
{
|
||||
var charIndex = _random.Next(0, pool.Length);
|
||||
output[i] = pool[charIndex];
|
||||
}
|
||||
}
|
||||
|
||||
return new string(output);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置参与运算的字符,最少 50 位
|
||||
/// </summary>
|
||||
/// <param name="characters"></param>
|
||||
public static void SetCharacters(string characters)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(characters))
|
||||
{
|
||||
throw new ArgumentException("The replacement characters must not be null or empty.");
|
||||
}
|
||||
|
||||
var charSet = characters
|
||||
.ToCharArray()
|
||||
.Where(x => !char.IsWhiteSpace(x))
|
||||
.Distinct()
|
||||
.ToArray();
|
||||
|
||||
if (charSet.Length < Constants.MinimumCharacterSetLength)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"The replacement characters must be at least {Constants.MinimumCharacterSetLength} letters in length and without whitespace.");
|
||||
}
|
||||
|
||||
lock (ThreadLock)
|
||||
{
|
||||
_pool = new string(charSet);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置种子步长
|
||||
/// </summary>
|
||||
/// <param name="seed"></param>
|
||||
public static void SetSeed(int seed)
|
||||
{
|
||||
lock (ThreadLock)
|
||||
{
|
||||
_random = new Random(seed);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重置所有配置
|
||||
/// </summary>
|
||||
public static void Reset()
|
||||
{
|
||||
lock (ThreadLock)
|
||||
{
|
||||
_random = new Random();
|
||||
_pool = $"{Smalls}{Bigs}";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
412
WaterCloud.Code/ExcelHelper.cs
Normal file
412
WaterCloud.Code/ExcelHelper.cs
Normal file
@ -0,0 +1,412 @@
|
||||
using NPOI.HSSF.UserModel;
|
||||
using NPOI.SS.UserModel;
|
||||
using NPOI.SS.Util;
|
||||
using NPOI.XSSF.UserModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// List导出到Excel文件
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class ExcelHelper<T> where T : new()
|
||||
{
|
||||
#region List导出到Excel文件
|
||||
/// <summary>
|
||||
/// List导出到Excel文件
|
||||
/// </summary>
|
||||
/// <param name="sFileName"></param>
|
||||
/// <param name="sHeaderText"></param>
|
||||
/// <param name="list"></param>
|
||||
[Obsolete]
|
||||
public string ExportToExcel(string sFileName, string sHeaderText, List<T> list, string[] columns)
|
||||
{
|
||||
sFileName = string.Format("{0}_{1}", Utils.GetGuid(), sFileName);
|
||||
string sRoot = GlobalContext.HostingEnvironment.ContentRootPath;
|
||||
string partDirectory = string.Format("Resource{0}Export{0}Excel", Path.DirectorySeparatorChar);
|
||||
string sDirectory = Path.Combine(sRoot, partDirectory);
|
||||
string sFilePath = Path.Combine(sDirectory, sFileName);
|
||||
if (!Directory.Exists(sDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(sDirectory);
|
||||
}
|
||||
using (MemoryStream ms = CreateExportMemoryStream(list, sHeaderText, columns))
|
||||
{
|
||||
using (FileStream fs = new FileStream(sFilePath, FileMode.Create, FileAccess.Write))
|
||||
{
|
||||
byte[] data = ms.ToArray();
|
||||
fs.Write(data, 0, data.Length);
|
||||
fs.Flush();
|
||||
}
|
||||
}
|
||||
return partDirectory + Path.DirectorySeparatorChar + sFileName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// List导出到Excel的MemoryStream
|
||||
/// </summary>
|
||||
/// <param name="list">数据源</param>
|
||||
/// <param name="sHeaderText">表头文本</param>
|
||||
/// <param name="columns">需要导出的属性</param>
|
||||
[Obsolete]
|
||||
private MemoryStream CreateExportMemoryStream(List<T> list, string sHeaderText, string[] columns)
|
||||
{
|
||||
HSSFWorkbook workbook = new HSSFWorkbook();
|
||||
ISheet sheet = workbook.CreateSheet();
|
||||
|
||||
Type type = typeof(T);
|
||||
PropertyInfo[] properties = ReflectionHelper.GetProperties(type, columns);
|
||||
|
||||
ICellStyle dateStyle = workbook.CreateCellStyle();
|
||||
IDataFormat format = workbook.CreateDataFormat();
|
||||
dateStyle.DataFormat = format.GetFormat("yyyy-MM-dd");
|
||||
|
||||
#region 取得每列的列宽(最大宽度)
|
||||
int[] arrColWidth = new int[properties.Length];
|
||||
for (int columnIndex = 0; columnIndex < properties.Length; columnIndex++)
|
||||
{
|
||||
//GBK对应的code page是CP936
|
||||
arrColWidth[columnIndex] = properties[columnIndex].Name.Length;
|
||||
}
|
||||
#endregion
|
||||
for (int rowIndex = 0; rowIndex < list.Count; rowIndex++)
|
||||
{
|
||||
#region 新建表,填充表头,填充列头,样式
|
||||
if (rowIndex == 65535 || rowIndex == 0)
|
||||
{
|
||||
if (rowIndex != 0)
|
||||
{
|
||||
sheet = workbook.CreateSheet();
|
||||
}
|
||||
|
||||
#region 表头及样式
|
||||
{
|
||||
IRow headerRow = sheet.CreateRow(0);
|
||||
headerRow.HeightInPoints = 25;
|
||||
headerRow.CreateCell(0).SetCellValue(sHeaderText);
|
||||
|
||||
ICellStyle headStyle = workbook.CreateCellStyle();
|
||||
headStyle.Alignment = HorizontalAlignment.Center;
|
||||
IFont font = workbook.CreateFont();
|
||||
font.FontHeightInPoints = 20;
|
||||
font.Boldweight = 700;
|
||||
headStyle.SetFont(font);
|
||||
|
||||
headerRow.GetCell(0).CellStyle = headStyle;
|
||||
|
||||
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, properties.Length - 1));
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 列头及样式
|
||||
{
|
||||
IRow headerRow = sheet.CreateRow(1);
|
||||
ICellStyle headStyle = workbook.CreateCellStyle();
|
||||
headStyle.Alignment = HorizontalAlignment.Center;
|
||||
IFont font = workbook.CreateFont();
|
||||
font.FontHeightInPoints = 10;
|
||||
font.Boldweight = 700;
|
||||
headStyle.SetFont(font);
|
||||
|
||||
for (int columnIndex = 0; columnIndex < properties.Length; columnIndex++)
|
||||
{
|
||||
// 类属性如果有Description就用Description当做列名
|
||||
DescriptionAttribute customAttribute = (DescriptionAttribute)Attribute.GetCustomAttribute(properties[columnIndex], typeof(DescriptionAttribute));
|
||||
string description = properties[columnIndex].Name;
|
||||
if (customAttribute != null)
|
||||
{
|
||||
description = customAttribute.Description;
|
||||
}
|
||||
headerRow.CreateCell(columnIndex).SetCellValue(description);
|
||||
headerRow.GetCell(columnIndex).CellStyle = headStyle;
|
||||
|
||||
//设置列宽
|
||||
sheet.SetColumnWidth(columnIndex, (arrColWidth[columnIndex] + 1) * 256);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 填充内容
|
||||
ICellStyle contentStyle = workbook.CreateCellStyle();
|
||||
contentStyle.Alignment = HorizontalAlignment.Left;
|
||||
IRow dataRow = sheet.CreateRow(rowIndex + 2); // 前面2行已被占用
|
||||
for (int columnIndex = 0; columnIndex < properties.Length; columnIndex++)
|
||||
{
|
||||
ICell newCell = dataRow.CreateCell(columnIndex);
|
||||
newCell.CellStyle = contentStyle;
|
||||
|
||||
string drValue = properties[columnIndex].GetValue(list[rowIndex], null).ParseToString();
|
||||
switch (properties[columnIndex].PropertyType.ToString())
|
||||
{
|
||||
case "System.String":
|
||||
newCell.SetCellValue(drValue);
|
||||
break;
|
||||
|
||||
case "System.DateTime":
|
||||
case "System.Nullable`1[System.DateTime]":
|
||||
newCell.SetCellValue(drValue.ToDate());
|
||||
newCell.CellStyle = dateStyle; //格式化显示
|
||||
break;
|
||||
|
||||
case "System.Boolean":
|
||||
case "System.Nullable`1[System.Boolean]":
|
||||
newCell.SetCellValue(drValue.ToBool());
|
||||
break;
|
||||
|
||||
case "System.Byte":
|
||||
case "System.Nullable`1[System.Byte]":
|
||||
case "System.Int16":
|
||||
case "System.Nullable`1[System.Int16]":
|
||||
case "System.Int32":
|
||||
case "System.Nullable`1[System.Int32]":
|
||||
newCell.SetCellValue(drValue.ToInt());
|
||||
break;
|
||||
|
||||
case "System.Int64":
|
||||
case "System.Nullable`1[System.Int64]":
|
||||
newCell.SetCellValue(drValue.ParseToString());
|
||||
break;
|
||||
|
||||
case "System.Double":
|
||||
case "System.Nullable`1[System.Double]":
|
||||
newCell.SetCellValue(drValue.ToDouble());
|
||||
break;
|
||||
|
||||
case "System.Decimal":
|
||||
case "System.Nullable`1[System.Decimal]":
|
||||
newCell.SetCellValue(drValue.ToDouble());
|
||||
break;
|
||||
|
||||
case "System.DBNull":
|
||||
newCell.SetCellValue(string.Empty);
|
||||
break;
|
||||
|
||||
default:
|
||||
newCell.SetCellValue(string.Empty);
|
||||
break;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
using (MemoryStream ms = new MemoryStream())
|
||||
{
|
||||
workbook.Write(ms);
|
||||
ms.Flush();
|
||||
ms.Position = 0;
|
||||
return ms;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Excel导入
|
||||
/// <summary>
|
||||
/// Excel导入
|
||||
/// </summary>
|
||||
/// <param name="filePath"></param>
|
||||
/// <returns></returns>
|
||||
public List<T> ImportFromExcel(string filePath)
|
||||
{
|
||||
List<T> list = new List<T>();
|
||||
HSSFWorkbook hssfWorkbook = null;
|
||||
XSSFWorkbook xssWorkbook = null;
|
||||
ISheet sheet = null;
|
||||
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
|
||||
{
|
||||
switch (Path.GetExtension(filePath))
|
||||
{
|
||||
case ".xls":
|
||||
hssfWorkbook = new HSSFWorkbook(file);
|
||||
sheet = hssfWorkbook.GetSheetAt(0);
|
||||
break;
|
||||
|
||||
case ".xlsx":
|
||||
xssWorkbook = new XSSFWorkbook(file);
|
||||
sheet = xssWorkbook.GetSheetAt(0);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Exception("不支持的文件格式");
|
||||
}
|
||||
}
|
||||
IRow columnRow = sheet.GetRow(1); // 第二行为字段名
|
||||
Dictionary<int, PropertyInfo> mapPropertyInfoDict = new Dictionary<int, PropertyInfo>();
|
||||
for (int j = 0; j < columnRow.LastCellNum; j++)
|
||||
{
|
||||
ICell cell = columnRow.GetCell(j);
|
||||
PropertyInfo propertyInfo = MapPropertyInfo(cell.ParseToString());
|
||||
if (propertyInfo != null)
|
||||
{
|
||||
mapPropertyInfoDict.Add(j, propertyInfo);
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = (sheet.FirstRowNum + 2); i <= sheet.LastRowNum; i++)
|
||||
{
|
||||
IRow row = sheet.GetRow(i);
|
||||
T entity = new T();
|
||||
for (int j = row.FirstCellNum; j < columnRow.LastCellNum; j++)
|
||||
{
|
||||
if (mapPropertyInfoDict.ContainsKey(j))
|
||||
{
|
||||
if (row.GetCell(j) != null)
|
||||
{
|
||||
PropertyInfo propertyInfo = mapPropertyInfoDict[j];
|
||||
switch (propertyInfo.PropertyType.ToString())
|
||||
{
|
||||
case "System.DateTime":
|
||||
case "System.Nullable`1[System.DateTime]":
|
||||
mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ToDate());
|
||||
break;
|
||||
|
||||
case "System.Boolean":
|
||||
case "System.Nullable`1[System.Boolean]":
|
||||
mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ToBool());
|
||||
break;
|
||||
|
||||
case "System.Byte":
|
||||
case "System.Nullable`1[System.Byte]":
|
||||
mapPropertyInfoDict[j].SetValue(entity, Byte.Parse(row.GetCell(j).ParseToString()));
|
||||
break;
|
||||
case "System.Int16":
|
||||
case "System.Nullable`1[System.Int16]":
|
||||
mapPropertyInfoDict[j].SetValue(entity, Int16.Parse(row.GetCell(j).ParseToString()));
|
||||
break;
|
||||
case "System.Int32":
|
||||
case "System.Nullable`1[System.Int32]":
|
||||
mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ToInt());
|
||||
break;
|
||||
|
||||
case "System.Int64":
|
||||
case "System.Nullable`1[System.Int64]":
|
||||
mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ToLong());
|
||||
break;
|
||||
|
||||
case "System.Double":
|
||||
case "System.Nullable`1[System.Double]":
|
||||
mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ToDouble());
|
||||
break;
|
||||
|
||||
case "System.Single":
|
||||
case "System.Nullable`1[System.Single]":
|
||||
mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ParseToFloat());
|
||||
break;
|
||||
|
||||
case "System.Decimal":
|
||||
case "System.Nullable`1[System.Decimal]":
|
||||
mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ToDecimal());
|
||||
break;
|
||||
|
||||
default:
|
||||
case "System.String":
|
||||
mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
list.Add(entity);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查找Excel列名对应的实体属性
|
||||
/// </summary>
|
||||
/// <param name="columnName"></param>
|
||||
/// <returns></returns>
|
||||
private PropertyInfo MapPropertyInfo(string columnName)
|
||||
{
|
||||
PropertyInfo[] propertyList = ReflectionHelper.GetProperties(typeof(T));
|
||||
PropertyInfo propertyInfo = propertyList.Where(p => p.Name == columnName).FirstOrDefault();
|
||||
if (propertyInfo != null)
|
||||
{
|
||||
return propertyInfo;
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (PropertyInfo tempPropertyInfo in propertyList)
|
||||
{
|
||||
DescriptionAttribute[] attributes = (DescriptionAttribute[])tempPropertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
|
||||
if (attributes.Length > 0)
|
||||
{
|
||||
if (attributes[0].Description == columnName)
|
||||
{
|
||||
return tempPropertyInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region excle转datatable
|
||||
/// <summary>
|
||||
/// 读取excel文件数据到DataTable
|
||||
/// </summary>
|
||||
/// <param name="filePath"></param>
|
||||
/// <param name="deleteFile"></param>
|
||||
/// <returns></returns>
|
||||
public static DataTable ReadExcelToTable(string filePath, bool deleteFile = false)
|
||||
{
|
||||
var dataTable = new DataTable();
|
||||
using (var tempFile = new FileStream(filePath, FileMode.Open))
|
||||
{
|
||||
IWorkbook workbook = null;
|
||||
if (Path.GetExtension(filePath)==".xls")
|
||||
{
|
||||
workbook = new HSSFWorkbook(tempFile);
|
||||
}
|
||||
else
|
||||
{
|
||||
workbook = new XSSFWorkbook(tempFile);
|
||||
}
|
||||
|
||||
var sheet = workbook.GetSheetAt(0);
|
||||
var tableHeadRow = sheet.GetRow(0);
|
||||
for (int i = 0; i < tableHeadRow.PhysicalNumberOfCells; i++)
|
||||
{
|
||||
if (tableHeadRow.Cells[i] != null)
|
||||
{
|
||||
tableHeadRow.Cells[i].SetCellType(CellType.String);
|
||||
}
|
||||
var headCell = tableHeadRow.Cells[i];
|
||||
dataTable.Columns.Add(new DataColumn(headCell.StringCellValue));
|
||||
}
|
||||
for (int i = 1; i < sheet.PhysicalNumberOfRows; i++)
|
||||
{
|
||||
var row = sheet.GetRow(i);
|
||||
var newRow = dataTable.NewRow();
|
||||
for (int j = 0; j < row.PhysicalNumberOfCells; j++)
|
||||
{
|
||||
if (row.Cells[j] != null)
|
||||
{
|
||||
row.Cells[j].SetCellType(CellType.String);
|
||||
}
|
||||
var cell = row.Cells[j];
|
||||
|
||||
newRow[j] = cell.StringCellValue;
|
||||
}
|
||||
dataTable.Rows.Add(newRow);
|
||||
}
|
||||
workbook.Close();
|
||||
}
|
||||
if (deleteFile)
|
||||
{
|
||||
File.Delete(filePath);
|
||||
}
|
||||
return dataTable;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
61
WaterCloud.Code/Extend/AutoMapperExt.cs
Normal file
61
WaterCloud.Code/Extend/AutoMapperExt.cs
Normal file
@ -0,0 +1,61 @@
|
||||
using AutoMapper;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static class AutoMapperExt
|
||||
{
|
||||
/// <summary>
|
||||
/// 类型映射
|
||||
/// </summary>
|
||||
public static T MapTo<T>(this object obj)
|
||||
{
|
||||
if (obj == null) return default(T);
|
||||
|
||||
var config = new MapperConfiguration(cfg => cfg.CreateMap(obj.GetType(), typeof(T)));
|
||||
var mapper = config.CreateMapper();
|
||||
return mapper.Map<T>(obj);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 集合列表类型映射
|
||||
/// </summary>
|
||||
public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
|
||||
{
|
||||
Type sourceType = source.GetType().GetGenericArguments()[0]; //获取枚举的成员类型
|
||||
var config = new MapperConfiguration(cfg => cfg.CreateMap(sourceType, typeof(TDestination)));
|
||||
var mapper = config.CreateMapper();
|
||||
|
||||
return mapper.Map<List<TDestination>>(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 集合列表类型映射
|
||||
/// </summary>
|
||||
public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
|
||||
{
|
||||
var config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(TSource), typeof(TDestination)));
|
||||
var mapper = config.CreateMapper();
|
||||
|
||||
return mapper.Map<List<TDestination>>(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 类型映射
|
||||
/// </summary>
|
||||
public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)
|
||||
where TSource : class
|
||||
where TDestination : class
|
||||
{
|
||||
if (source == null) return destination;
|
||||
|
||||
var config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(TSource), typeof(TDestination)));
|
||||
var mapper = config.CreateMapper();
|
||||
return mapper.Map<TDestination>(source);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
739
WaterCloud.Code/Extend/Ext.Convert.cs
Normal file
739
WaterCloud.Code/Extend/Ext.Convert.cs
Normal file
@ -0,0 +1,739 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static partial class Ext
|
||||
{
|
||||
#region 数值转换
|
||||
/// <summary>
|
||||
/// 转换为整型
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
public static int ToInt(this object data)
|
||||
{
|
||||
if (data == null)
|
||||
return 0;
|
||||
int result;
|
||||
var success = int.TryParse(data.ToString(), out result);
|
||||
if (success)
|
||||
return result;
|
||||
try
|
||||
{
|
||||
return Convert.ToInt32(ToDouble(data, 0));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 将object转换为long,若转换失败,则返回0。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static long ToLong(this object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
return long.Parse(obj.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 转换为可空整型
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
public static int? ToIntOrNull(this object data)
|
||||
{
|
||||
if (data == null)
|
||||
return null;
|
||||
int result;
|
||||
bool isValid = int.TryParse(data.ToString(), out result);
|
||||
if (isValid)
|
||||
return result;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换为双精度浮点数
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
public static double ToDouble(this object data)
|
||||
{
|
||||
if (data == null)
|
||||
return 0;
|
||||
double result;
|
||||
return double.TryParse(data.ToString(), out result) ? result : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换为双精度浮点数,并按指定的小数位4舍5入
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
/// <param name="digits">小数位数</param>
|
||||
public static double ToDouble(this object data, int digits)
|
||||
{
|
||||
return Math.Round(ToDouble(data), digits);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换为可空双精度浮点数
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
public static double? ToDoubleOrNull(this object data)
|
||||
{
|
||||
if (data == null)
|
||||
return null;
|
||||
double result;
|
||||
bool isValid = double.TryParse(data.ToString(), out result);
|
||||
if (isValid)
|
||||
return result;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换为高精度浮点数
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
public static decimal ToDecimal(this object data)
|
||||
{
|
||||
if (data == null)
|
||||
return 0;
|
||||
decimal result;
|
||||
return decimal.TryParse(data.ToString(), out result) ? result : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换为高精度浮点数,并按指定的小数位4舍5入
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
/// <param name="digits">小数位数</param>
|
||||
public static decimal ToDecimal(this object data, int digits)
|
||||
{
|
||||
return Math.Round(ToDecimal(data), digits);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换为可空高精度浮点数
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
public static decimal? ToDecimalOrNull(this object data)
|
||||
{
|
||||
if (data == null)
|
||||
return null;
|
||||
decimal result;
|
||||
bool isValid = decimal.TryParse(data.ToString(), out result);
|
||||
if (isValid)
|
||||
return result;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换为可空高精度浮点数,并按指定的小数位4舍5入
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
/// <param name="digits">小数位数</param>
|
||||
public static decimal? ToDecimalOrNull(this object data, int digits)
|
||||
{
|
||||
var result = ToDecimalOrNull(data);
|
||||
if (result == null)
|
||||
return null;
|
||||
return Math.Round(result.Value, digits);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 日期转换
|
||||
/// <summary>
|
||||
/// 转换为日期
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
public static DateTime ToDate(this object data)
|
||||
{
|
||||
if (data == null)
|
||||
return DateTime.MinValue;
|
||||
DateTime result;
|
||||
return DateTime.TryParse(data.ToString(), out result) ? result : DateTime.MinValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换为可空日期
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
public static DateTime? ToDateOrNull(this object data)
|
||||
{
|
||||
if (data == null)
|
||||
return null;
|
||||
DateTime result;
|
||||
bool isValid = DateTime.TryParse(data.ToString(), out result);
|
||||
if (isValid)
|
||||
return result;
|
||||
return null;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 布尔转换
|
||||
/// <summary>
|
||||
/// 转换为布尔值
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
public static bool ToBool(this object data)
|
||||
{
|
||||
if (data == null)
|
||||
return false;
|
||||
bool? value = GetBool(data);
|
||||
if (value != null)
|
||||
return value.Value;
|
||||
bool result;
|
||||
return bool.TryParse(data.ToString(), out result) && result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取布尔值
|
||||
/// </summary>
|
||||
private static bool? GetBool(this object data)
|
||||
{
|
||||
switch (data.ToString().Trim().ToLower())
|
||||
{
|
||||
case "0":
|
||||
return false;
|
||||
case "1":
|
||||
return true;
|
||||
case "是":
|
||||
return true;
|
||||
case "否":
|
||||
return false;
|
||||
case "yes":
|
||||
return true;
|
||||
case "no":
|
||||
return false;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换为可空布尔值
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
public static bool? ToBoolOrNull(this object data)
|
||||
{
|
||||
if (data == null)
|
||||
return null;
|
||||
bool? value = GetBool(data);
|
||||
if (value != null)
|
||||
return value.Value;
|
||||
bool result;
|
||||
bool isValid = bool.TryParse(data.ToString(), out result);
|
||||
if (isValid)
|
||||
return result;
|
||||
return null;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 是否为空
|
||||
|
||||
/// <summary>
|
||||
/// 是否为空
|
||||
/// </summary>
|
||||
/// <param name="value">值</param>
|
||||
public static bool IsEmpty(this string value)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value);
|
||||
}
|
||||
/// <summary>
|
||||
/// 是否为空
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsEmpty(this object value)
|
||||
{
|
||||
if (value != null && !string.IsNullOrEmpty(value.ToString()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 是否为空
|
||||
/// </summary>
|
||||
/// <param name="value">值</param>
|
||||
public static bool IsEmpty(this Guid? value)
|
||||
{
|
||||
if (value == null)
|
||||
return true;
|
||||
return IsEmpty(value.Value);
|
||||
}
|
||||
/// <summary>
|
||||
/// 是否为空
|
||||
/// </summary>
|
||||
/// <param name="value">值</param>
|
||||
public static bool IsEmpty(this Guid value)
|
||||
{
|
||||
if (value == Guid.Empty)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 强制转换类型
|
||||
/// <summary>
|
||||
/// 强制转换类型
|
||||
/// </summary>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static IEnumerable<TResult> CastSuper<TResult>(this IEnumerable source)
|
||||
{
|
||||
foreach (object item in source)
|
||||
{
|
||||
yield return (TResult)Convert.ChangeType(item, typeof(TResult));
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 转换为long
|
||||
/// <summary>
|
||||
/// 将object转换为long,若转换失败,则返回0。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static long ParseToLong(this object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
return long.Parse(obj.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将object转换为long,若转换失败,则返回指定值。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static long ParseToLong(this string str, long defaultValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
return long.Parse(str);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 转换为int
|
||||
/// <summary>
|
||||
/// 将object转换为int,若转换失败,则返回0。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static int ParseToInt(this object str)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Convert.ToInt32(str);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将object转换为int,若转换失败,则返回指定值。不抛出异常。
|
||||
/// null返回默认值
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static int ParseToInt(this object str, int defaultValue)
|
||||
{
|
||||
if (str == null)
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
try
|
||||
{
|
||||
return Convert.ToInt32(str);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 转换为short
|
||||
/// <summary>
|
||||
/// 将object转换为short,若转换失败,则返回0。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static short ParseToShort(this object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
return short.Parse(obj.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将object转换为short,若转换失败,则返回指定值。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static short ParseToShort(this object str, short defaultValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
return short.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 转换为demical
|
||||
/// <summary>
|
||||
/// 将object转换为demical,若转换失败,则返回指定值。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static decimal ParseToDecimal(this object str, decimal defaultValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
return decimal.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将object转换为demical,若转换失败,则返回0。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static decimal ParseToDecimal(this object str)
|
||||
{
|
||||
try
|
||||
{
|
||||
return decimal.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 转化为bool
|
||||
/// <summary>
|
||||
/// 将object转换为bool,若转换失败,则返回false。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static bool ParseToBool(this object str)
|
||||
{
|
||||
try
|
||||
{
|
||||
return bool.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将object转换为bool,若转换失败,则返回指定值。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static bool ParseToBool(this object str, bool result)
|
||||
{
|
||||
try
|
||||
{
|
||||
return bool.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 转换为float
|
||||
/// <summary>
|
||||
/// 将object转换为float,若转换失败,则返回0。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static float ParseToFloat(this object str)
|
||||
{
|
||||
try
|
||||
{
|
||||
return float.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将object转换为float,若转换失败,则返回指定值。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static float ParseToFloat(this object str, float result)
|
||||
{
|
||||
try
|
||||
{
|
||||
return float.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 转换为Guid
|
||||
/// <summary>
|
||||
/// 将string转换为Guid,若转换失败,则返回Guid.Empty。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static Guid ParseToGuid(this string str)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new Guid(str);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Guid.Empty;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 转换为DateTime
|
||||
/// <summary>
|
||||
/// 将string转换为DateTime,若转换失败,则返回日期最小值。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static DateTime ParseToDateTime(this string str)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(str))
|
||||
{
|
||||
return DateTime.MinValue;
|
||||
}
|
||||
if (str.Contains("-") || str.Contains("/"))
|
||||
{
|
||||
return DateTime.Parse(str);
|
||||
}
|
||||
else
|
||||
{
|
||||
int length = str.Length;
|
||||
switch (length)
|
||||
{
|
||||
case 4:
|
||||
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 6:
|
||||
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 8:
|
||||
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 10:
|
||||
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 12:
|
||||
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 14:
|
||||
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
||||
default:
|
||||
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return DateTime.MinValue;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将string转换为DateTime,若转换失败,则返回默认值。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static DateTime ParseToDateTime(this string str, DateTime? defaultValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(str))
|
||||
{
|
||||
return defaultValue.GetValueOrDefault();
|
||||
}
|
||||
if (str.Contains("-") || str.Contains("/"))
|
||||
{
|
||||
return DateTime.Parse(str);
|
||||
}
|
||||
else
|
||||
{
|
||||
int length = str.Length;
|
||||
switch (length)
|
||||
{
|
||||
case 4:
|
||||
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 6:
|
||||
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 8:
|
||||
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 10:
|
||||
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 12:
|
||||
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 14:
|
||||
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
||||
default:
|
||||
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue.GetValueOrDefault();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 转换为string
|
||||
/// <summary>
|
||||
/// 将object转换为string,若转换失败,则返回""。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static string ParseToString(this object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (obj == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
else
|
||||
{
|
||||
return obj.ToString();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
public static string ParseToStrings<T>(this object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
var list = obj as IEnumerable<T>;
|
||||
if (list != null)
|
||||
{
|
||||
return string.Join(",", list);
|
||||
}
|
||||
else
|
||||
{
|
||||
return obj.ToString();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 转换为double
|
||||
/// <summary>
|
||||
/// 将object转换为double,若转换失败,则返回0。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="obj"></param>
|
||||
/// <returns></returns>
|
||||
public static double ParseToDouble(this object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
return double.Parse(obj.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将object转换为double,若转换失败,则返回指定值。不抛出异常。
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static double ParseToDouble(this object str, double defaultValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
return double.Parse(str.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 安全返回值
|
||||
/// </summary>
|
||||
/// <param name="value">可空值</param>
|
||||
public static T SafeValue<T>(this T? value) where T : struct
|
||||
{
|
||||
return value ?? default(T);
|
||||
}
|
||||
}
|
||||
}
|
||||
182
WaterCloud.Code/Extend/Ext.DateTime.cs
Normal file
182
WaterCloud.Code/Extend/Ext.DateTime.cs
Normal file
@ -0,0 +1,182 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static partial class Ext
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带时分秒,格式:"yyyy-MM-dd HH:mm:ss"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
/// <param name="isRemoveSecond">是否移除秒</param>
|
||||
public static string ToDateTimeString(this DateTime dateTime, bool isRemoveSecond = false)
|
||||
{
|
||||
if (isRemoveSecond)
|
||||
return dateTime.ToString("yyyy-MM-dd HH:mm");
|
||||
return dateTime.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带时分秒,格式:"yyyy-MM-dd HH:mm:ss"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
/// <param name="isRemoveSecond">是否移除秒</param>
|
||||
public static string ToDateTimeString(this DateTime? dateTime, bool isRemoveSecond = false)
|
||||
{
|
||||
if (dateTime == null)
|
||||
return string.Empty;
|
||||
return ToDateTimeString(dateTime.Value, isRemoveSecond);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带时分秒,格式:"yyyy-MM-dd"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToDateString(this DateTime dateTime)
|
||||
{
|
||||
return dateTime.ToString("yyyy-MM-dd");
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带时分秒,格式:"yyyy-MM-dd"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToDateString()
|
||||
{
|
||||
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带时分秒,格式:"yyyy-MM-dd"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToDateString(this DateTime? dateTime)
|
||||
{
|
||||
if (dateTime == null)
|
||||
return string.Empty;
|
||||
return ToDateString(dateTime.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带年月日,格式:"HH:mm:ss"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToTimeString(this DateTime dateTime)
|
||||
{
|
||||
return dateTime.ToString("HH:mm:ss");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带年月日,格式:"HH:mm:ss"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToTimeString(this DateTime? dateTime)
|
||||
{
|
||||
if (dateTime == null)
|
||||
return string.Empty;
|
||||
return ToTimeString(dateTime.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带毫秒,格式:"yyyy-MM-dd HH:mm:ss.fff"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToMillisecondString(this DateTime dateTime)
|
||||
{
|
||||
return dateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带毫秒,格式:"yyyy-MM-dd HH:mm:ss.fff"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToMillisecondString(this DateTime? dateTime)
|
||||
{
|
||||
if (dateTime == null)
|
||||
return string.Empty;
|
||||
return ToMillisecondString(dateTime.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带时分秒,格式:"yyyy年MM月dd日"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToChineseDateString(this DateTime dateTime)
|
||||
{
|
||||
return string.Format("{0}年{1}月{2}日", dateTime.Year, dateTime.Month, dateTime.Day);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带时分秒,格式:"yyyy年MM月dd日"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToChineseDateString(this DateTime? dateTime)
|
||||
{
|
||||
if (dateTime == null)
|
||||
return string.Empty;
|
||||
return ToChineseDateString(dateTime.SafeValue());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带时分秒,格式:"yyyy年MM月dd日 HH时mm分"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
/// <param name="isRemoveSecond">是否移除秒</param>
|
||||
public static string ToChineseDateTimeString(this DateTime dateTime, bool isRemoveSecond = false)
|
||||
{
|
||||
StringBuilder result = new StringBuilder();
|
||||
result.AppendFormat("{0}年{1}月{2}日", dateTime.Year, dateTime.Month, dateTime.Day);
|
||||
result.AppendFormat(" {0}时{1}分", dateTime.Hour, dateTime.Minute);
|
||||
if (isRemoveSecond == false)
|
||||
result.AppendFormat("{0}秒", dateTime.Second);
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带时分秒,格式:"yyyy年MM月dd日 HH时mm分"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
/// <param name="isRemoveSecond">是否移除秒</param>
|
||||
public static string ToChineseDateTimeString(this DateTime? dateTime, bool isRemoveSecond = false)
|
||||
{
|
||||
if (dateTime == null)
|
||||
return string.Empty;
|
||||
return ToChineseDateTimeString(dateTime.Value);
|
||||
}
|
||||
#region 毫秒转天时分秒
|
||||
/// <summary>
|
||||
/// 毫秒转天时分秒
|
||||
/// </summary>
|
||||
/// <param name="ms"></param>
|
||||
/// <returns></returns>
|
||||
public static string FormatTime(long ms)
|
||||
{
|
||||
int ss = 1000;
|
||||
int mi = ss * 60;
|
||||
int hh = mi * 60;
|
||||
int dd = hh * 24;
|
||||
|
||||
long day = ms / dd;
|
||||
long hour = (ms - day * dd) / hh;
|
||||
long minute = (ms - day * dd - hour * hh) / mi;
|
||||
long second = (ms - day * dd - hour * hh - minute * mi) / ss;
|
||||
long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
|
||||
|
||||
string sDay = day < 10 ? "0" + day : "" + day; //天
|
||||
string sHour = hour < 10 ? "0" + hour : "" + hour;//小时
|
||||
string sMinute = minute < 10 ? "0" + minute : "" + minute;//分钟
|
||||
string sSecond = second < 10 ? "0" + second : "" + second;//秒
|
||||
string sMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;//毫秒
|
||||
sMilliSecond = milliSecond < 100 ? "0" + sMilliSecond : "" + sMilliSecond;
|
||||
|
||||
return string.Format("{0} 天 {1} 小时 {2} 分 {3} 秒", sDay, sHour, sMinute, sSecond);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
88
WaterCloud.Code/Extend/Ext.Enum.cs
Normal file
88
WaterCloud.Code/Extend/Ext.Enum.cs
Normal file
@ -0,0 +1,88 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static partial class Extensions
|
||||
{
|
||||
#region 枚举成员转成dictionary类型
|
||||
/// <summary>
|
||||
/// 转成dictionary类型
|
||||
/// </summary>
|
||||
/// <param name="enumType"></param>
|
||||
/// <returns></returns>
|
||||
public static Dictionary<int, string> EnumToDictionary(this Type enumType)
|
||||
{
|
||||
Dictionary<int, string> dictionary = new Dictionary<int, string>();
|
||||
Type typeDescription = typeof(DescriptionAttribute);
|
||||
FieldInfo[] fields = enumType.GetFields();
|
||||
int sValue = 0;
|
||||
string sText = string.Empty;
|
||||
foreach (FieldInfo field in fields)
|
||||
{
|
||||
if (field.FieldType.IsEnum)
|
||||
{
|
||||
sValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null));
|
||||
object[] arr = field.GetCustomAttributes(typeDescription, true);
|
||||
if (arr.Length > 0)
|
||||
{
|
||||
DescriptionAttribute da = (DescriptionAttribute)arr[0];
|
||||
sText = da.Description;
|
||||
}
|
||||
else
|
||||
{
|
||||
sText = field.Name;
|
||||
}
|
||||
dictionary.Add(sValue, sText);
|
||||
}
|
||||
}
|
||||
return dictionary;
|
||||
}
|
||||
/// <summary>
|
||||
/// 枚举成员转成键值对Json字符串
|
||||
/// </summary>
|
||||
/// <param name="enumType"></param>
|
||||
/// <returns></returns>
|
||||
public static string EnumToDictionaryString(this Type enumType)
|
||||
{
|
||||
List<KeyValuePair<int, string>> dictionaryList = EnumToDictionary(enumType).ToList();
|
||||
var sJson = JsonConvert.SerializeObject(dictionaryList);
|
||||
return sJson;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取枚举的描述
|
||||
/// <summary>
|
||||
/// 获取枚举值对应的描述
|
||||
/// </summary>
|
||||
/// <param name="enumType"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetDescription(this System.Enum enumType)
|
||||
{
|
||||
FieldInfo EnumInfo = enumType.GetType().GetField(enumType.ToString());
|
||||
if (EnumInfo != null)
|
||||
{
|
||||
DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
|
||||
if (EnumAttributes.Length > 0)
|
||||
{
|
||||
return EnumAttributes[0].Description;
|
||||
}
|
||||
}
|
||||
return enumType.ToString();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 根据值获取枚举的描述
|
||||
public static string GetDescriptionByEnum<T>(this object obj)
|
||||
{
|
||||
var tEnum = System.Enum.Parse(typeof(T), obj.ParseToString()) as System.Enum;
|
||||
var description = tEnum.GetDescription();
|
||||
return description;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
18
WaterCloud.Code/Extend/Ext.Exception.cs
Normal file
18
WaterCloud.Code/Extend/Ext.Exception.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static partial class Extensions
|
||||
{
|
||||
public static Exception GetOriginalException(this Exception ex)
|
||||
{
|
||||
if (ex.InnerException == null) return ex;
|
||||
|
||||
return ex.InnerException.GetOriginalException();
|
||||
}
|
||||
}
|
||||
}
|
||||
142
WaterCloud.Code/Extend/Ext.Format.cs
Normal file
142
WaterCloud.Code/Extend/Ext.Format.cs
Normal file
@ -0,0 +1,142 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static partial class Ext
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取描述
|
||||
/// </summary>
|
||||
/// <param name="value">布尔值</param>
|
||||
public static string Description(this bool value)
|
||||
{
|
||||
return value ? "是" : "否";
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取描述
|
||||
/// </summary>
|
||||
/// <param name="value">布尔值</param>
|
||||
public static string Description(this bool? value)
|
||||
{
|
||||
return value == null ? "" : Description(value.Value);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
/// <param name="defaultValue">空值显示的默认文本</param>
|
||||
public static string Format(this int number, string defaultValue = "")
|
||||
{
|
||||
if (number == 0)
|
||||
return defaultValue;
|
||||
return number.ToString();
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
/// <param name="defaultValue">空值显示的默认文本</param>
|
||||
public static string Format(this int? number, string defaultValue = "")
|
||||
{
|
||||
return Format(number.SafeValue(), defaultValue);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
/// <param name="defaultValue">空值显示的默认文本</param>
|
||||
public static string Format(this decimal number, string defaultValue = "")
|
||||
{
|
||||
if (number == 0)
|
||||
return defaultValue;
|
||||
return string.Format("{0:0.##}", number);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
/// <param name="defaultValue">空值显示的默认文本</param>
|
||||
public static string Format(this decimal? number, string defaultValue = "")
|
||||
{
|
||||
return Format(number.SafeValue(), defaultValue);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
/// <param name="defaultValue">空值显示的默认文本</param>
|
||||
public static string Format(this double number, string defaultValue = "")
|
||||
{
|
||||
if (number == 0)
|
||||
return defaultValue;
|
||||
return string.Format("{0:0.##}", number);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
/// <param name="defaultValue">空值显示的默认文本</param>
|
||||
public static string Format(this double? number, string defaultValue = "")
|
||||
{
|
||||
return Format(number.SafeValue(), defaultValue);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带¥
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
public static string FormatRmb(this decimal number)
|
||||
{
|
||||
if (number == 0)
|
||||
return "¥0";
|
||||
return string.Format("¥{0:0.##}", number);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带¥
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
public static string FormatRmb(this decimal? number)
|
||||
{
|
||||
return FormatRmb(number.SafeValue());
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带%
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
public static string FormatPercent(this decimal number)
|
||||
{
|
||||
if (number == 0)
|
||||
return string.Empty;
|
||||
return string.Format("{0:0.##}%", number);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带%
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
public static string FormatPercent(this decimal? number)
|
||||
{
|
||||
return FormatPercent(number.SafeValue());
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带%
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
public static string FormatPercent(this double number)
|
||||
{
|
||||
if (number == 0)
|
||||
return string.Empty;
|
||||
return string.Format("{0:0.##}%", number);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带%
|
||||
/// </summary>
|
||||
/// <param name="number">数值</param>
|
||||
public static string FormatPercent(this double? number)
|
||||
{
|
||||
return FormatPercent(number.SafeValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
34
WaterCloud.Code/Extend/Ext.Validate.cs
Normal file
34
WaterCloud.Code/Extend/Ext.Validate.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static partial class Extensions
|
||||
{
|
||||
public static bool IsNullOrZero(this object value)
|
||||
{
|
||||
if (value == null || value.ParseToString().Trim() == "0")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsAjaxRequest(this HttpRequest request)
|
||||
{
|
||||
if (request == null)
|
||||
throw new ArgumentNullException("request");
|
||||
|
||||
if (request.Headers != null)
|
||||
return request.Headers["X-Requested-With"] == "XMLHttpRequest";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
87
WaterCloud.Code/Extend/ExtLinq.SortBy.cs
Normal file
87
WaterCloud.Code/Extend/ExtLinq.SortBy.cs
Normal file
@ -0,0 +1,87 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static partial class ExtLinq
|
||||
{
|
||||
public static IOrderedQueryable<TEntity> SortBy<TEntity>(this IQueryable<TEntity> query, Expression<Func<TEntity, dynamic>> sortPredicate)
|
||||
where TEntity : class, new()
|
||||
{
|
||||
return InvokeSortBy(query, sortPredicate, SortOrder.Ascending);
|
||||
}
|
||||
|
||||
public static IOrderedQueryable<TEntity> SortByDescending<TEntity>(this IQueryable<TEntity> query, Expression<Func<TEntity, dynamic>> sortPredicate)
|
||||
where TEntity : class, new()
|
||||
{
|
||||
return InvokeSortBy(query, sortPredicate, SortOrder.Descending);
|
||||
}
|
||||
|
||||
private static IOrderedQueryable<TEntity> InvokeSortBy<TEntity>(IQueryable<TEntity> query,
|
||||
Expression<Func<TEntity, dynamic>> sortPredicate, SortOrder sortOrder)
|
||||
where TEntity : class, new()
|
||||
{
|
||||
var param = sortPredicate.Parameters[0];
|
||||
string propertyName = null;
|
||||
Type propertyType = null;
|
||||
Expression bodyExpression = null;
|
||||
if (sortPredicate.Body is UnaryExpression)
|
||||
{
|
||||
var unaryExpression = sortPredicate.Body as UnaryExpression;
|
||||
bodyExpression = unaryExpression.Operand;
|
||||
}
|
||||
else if (sortPredicate.Body is MemberExpression)
|
||||
{
|
||||
bodyExpression = sortPredicate.Body;
|
||||
}
|
||||
else
|
||||
throw new ArgumentException(@"The body of the sort predicate expression should be
|
||||
either UnaryExpression or MemberExpression.", "sortPredicate");
|
||||
var memberExpression = (MemberExpression)bodyExpression;
|
||||
propertyName = memberExpression.Member.Name;
|
||||
if (memberExpression.Member.MemberType == MemberTypes.Property)
|
||||
{
|
||||
var propertyInfo = memberExpression.Member as PropertyInfo;
|
||||
if (propertyInfo != null) propertyType = propertyInfo.PropertyType;
|
||||
}
|
||||
else
|
||||
throw new InvalidOperationException(@"Cannot evaluate the type of property since the member expression
|
||||
represented by the sort predicate expression does not contain a PropertyInfo object.");
|
||||
|
||||
var funcType = typeof(Func<,>).MakeGenericType(typeof(TEntity), propertyType);
|
||||
var convertedExpression = Expression.Lambda(funcType,
|
||||
Expression.Convert(Expression.Property(param, propertyName), propertyType), param);
|
||||
|
||||
var sortingMethods = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static);
|
||||
var sortingMethodName = GetSortingMethodName(sortOrder);
|
||||
var sortingMethod = sortingMethods.First(sm => sm.Name == sortingMethodName &&
|
||||
sm.GetParameters().Length == 2);
|
||||
return (IOrderedQueryable<TEntity>)sortingMethod
|
||||
.MakeGenericMethod(typeof(TEntity), propertyType)
|
||||
.Invoke(null, new object[] { query, convertedExpression });
|
||||
}
|
||||
|
||||
private static string GetSortingMethodName(SortOrder sortOrder)
|
||||
{
|
||||
switch (sortOrder)
|
||||
{
|
||||
case SortOrder.Ascending:
|
||||
return "OrderBy";
|
||||
case SortOrder.Descending:
|
||||
return "OrderByDescending";
|
||||
default:
|
||||
throw new ArgumentException("Sort Order must be specified as either Ascending or Descending.",
|
||||
"sortOrder");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
115
WaterCloud.Code/Extend/ExtLinq.cs
Normal file
115
WaterCloud.Code/Extend/ExtLinq.cs
Normal file
@ -0,0 +1,115 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static partial class ExtLinq
|
||||
{
|
||||
public static Expression Property(this Expression expression, string propertyName)
|
||||
{
|
||||
return Expression.Property(expression, propertyName);
|
||||
}
|
||||
public static Expression AndAlso(this Expression left, Expression right)
|
||||
{
|
||||
return Expression.AndAlso(left, right);
|
||||
}
|
||||
public static Expression Call(this Expression instance, string methodName, params Expression[] arguments)
|
||||
{
|
||||
return Expression.Call(instance, instance.Type.GetMethod(methodName), arguments);
|
||||
}
|
||||
public static Expression GreaterThan(this Expression left, Expression right)
|
||||
{
|
||||
return Expression.GreaterThan(left, right);
|
||||
}
|
||||
public static Expression<T> ToLambda<T>(this Expression body, params ParameterExpression[] parameters)
|
||||
{
|
||||
return Expression.Lambda<T>(body, parameters);
|
||||
}
|
||||
public static Expression<Func<T, bool>> True<T>() { return param => true; }
|
||||
public static Expression<Func<T, bool>> False<T>() { return param => false; }
|
||||
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
|
||||
{
|
||||
return first.Compose(second, Expression.AndAlso);
|
||||
}
|
||||
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
|
||||
{
|
||||
return first.Compose(second, Expression.OrElse);
|
||||
}
|
||||
public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
|
||||
{
|
||||
var map = first.Parameters
|
||||
.Select((f, i) => new { f, s = second.Parameters[i] })
|
||||
.ToDictionary(p => p.s, p => p.f);
|
||||
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
|
||||
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
|
||||
}
|
||||
private class ParameterRebinder : ExpressionVisitor
|
||||
{
|
||||
readonly Dictionary<ParameterExpression, ParameterExpression> map;
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ParameterRebinder"/> class.
|
||||
/// </summary>
|
||||
/// <param name="map">The map.</param>
|
||||
ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
|
||||
{
|
||||
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Replaces the parameters.
|
||||
/// </summary>
|
||||
/// <param name="map">The map.</param>
|
||||
/// <param name="exp">The exp.</param>
|
||||
/// <returns>Expression</returns>
|
||||
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
|
||||
{
|
||||
return new ParameterRebinder(map).Visit(exp);
|
||||
}
|
||||
protected override Expression VisitParameter(ParameterExpression p)
|
||||
{
|
||||
ParameterExpression replacement;
|
||||
|
||||
if (map.TryGetValue(p, out replacement))
|
||||
{
|
||||
p = replacement;
|
||||
}
|
||||
return base.VisitParameter(p);
|
||||
}
|
||||
}
|
||||
public static ParameterExpression CreateLambdaParam<T>(string name)
|
||||
{
|
||||
return Expression.Parameter(typeof(T), name);
|
||||
}
|
||||
/// <summary>
|
||||
/// 创建完整的lambda
|
||||
/// </summary>
|
||||
public static LambdaExpression GenerateLambda(this ParameterExpression param, Expression body)
|
||||
{
|
||||
//c=>c.XXX=="XXX"
|
||||
return Expression.Lambda(body, param);
|
||||
}
|
||||
|
||||
public static Expression<Func<T, bool>> GenerateTypeLambda<T>(this ParameterExpression param, Expression body)
|
||||
{
|
||||
return (Expression<Func<T, bool>>)(param.GenerateLambda(body));
|
||||
}
|
||||
public static Expression Or(this Expression expression, Expression expressionRight)
|
||||
{
|
||||
return Expression.Or(expression, expressionRight);
|
||||
}
|
||||
|
||||
public static Expression And(this Expression expression, Expression expressionRight)
|
||||
{
|
||||
return Expression.And(expression, expressionRight);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
50
WaterCloud.Code/Extend/ExtList.Comparint.cs
Normal file
50
WaterCloud.Code/Extend/ExtList.Comparint.cs
Normal file
@ -0,0 +1,50 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class ExtList<T> : IEqualityComparer<T> where T : class, new()
|
||||
{
|
||||
private string[] comparintFiledName = { };
|
||||
|
||||
public ExtList() { }
|
||||
public ExtList(params string[] comparintFiledName)
|
||||
{
|
||||
this.comparintFiledName = comparintFiledName;
|
||||
}
|
||||
bool IEqualityComparer<T>.Equals(T x, T y)
|
||||
{
|
||||
if (x == null && y == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (comparintFiledName.Length == 0)
|
||||
{
|
||||
return x.Equals(y);
|
||||
}
|
||||
bool result = true;
|
||||
var typeX = x.GetType();//获取类型
|
||||
var typeY = y.GetType();
|
||||
foreach (var filedName in comparintFiledName)
|
||||
{
|
||||
var xPropertyInfo = (from p in typeX.GetProperties() where p.Name.Equals(filedName) select p).FirstOrDefault();
|
||||
var yPropertyInfo = (from p in typeY.GetProperties() where p.Name.Equals(filedName) select p).FirstOrDefault();
|
||||
|
||||
result = result
|
||||
&& xPropertyInfo != null && yPropertyInfo != null
|
||||
&& xPropertyInfo.GetValue(x, null).ToString().Equals(yPropertyInfo.GetValue(y, null));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
int IEqualityComparer<T>.GetHashCode(T obj)
|
||||
{
|
||||
return obj.ToString().GetHashCode();
|
||||
}
|
||||
}
|
||||
}
|
||||
57
WaterCloud.Code/Extend/ExtList.cs
Normal file
57
WaterCloud.Code/Extend/ExtList.cs
Normal file
@ -0,0 +1,57 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace WaterCloud.Code.Extend
|
||||
{
|
||||
public static class ExtList
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取表里某页的数据
|
||||
/// </summary>
|
||||
/// <param name="data">表数据</param>
|
||||
/// <param name="pageIndex">当前页</param>
|
||||
/// <param name="pageSize">分页大小</param>
|
||||
/// <param name="allPage">返回总页数</param>
|
||||
/// <returns>返回当页表数据</returns>
|
||||
public static List<T> GetPage<T>(this List<T> data, int pageIndex, int pageSize, out int allPage)
|
||||
{
|
||||
allPage = 1;
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// IList转成List<T>
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="list"></param>
|
||||
/// <returns></returns>
|
||||
public static List<T> IListToList<T>(IList list)
|
||||
{
|
||||
T[] array = new T[list.Count];
|
||||
list.CopyTo(array, 0);
|
||||
return new List<T>(array);
|
||||
}
|
||||
/// <summary>
|
||||
/// 去除空元素
|
||||
/// </summary>
|
||||
public static List<string> removeNull(List<string> oldList)
|
||||
{
|
||||
// 临时集合
|
||||
List<string> listTemp = new List<string>();
|
||||
foreach (var item in oldList)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(item))
|
||||
{
|
||||
listTemp.Add(item);
|
||||
}
|
||||
|
||||
}
|
||||
return listTemp;
|
||||
}
|
||||
}
|
||||
}
|
||||
68
WaterCloud.Code/Extend/ExtTable.cs
Normal file
68
WaterCloud.Code/Extend/ExtTable.cs
Normal file
@ -0,0 +1,68 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System.Data;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static class ExtTable
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取表里某页的数据
|
||||
/// </summary>
|
||||
/// <param name="data">表数据</param>
|
||||
/// <param name="pageIndex">当前页</param>
|
||||
/// <param name="pageSize">分页大小</param>
|
||||
/// <param name="allPage">返回总页数</param>
|
||||
/// <returns>返回当页表数据</returns>
|
||||
public static DataTable GetPage(this DataTable data, int pageIndex, int pageSize, out int allPage)
|
||||
{
|
||||
allPage = data.Rows.Count / pageSize;
|
||||
allPage += data.Rows.Count % pageSize == 0 ? 0 : 1;
|
||||
DataTable Ntable = data.Clone();
|
||||
int startIndex = pageIndex * pageSize;
|
||||
int endIndex = startIndex + pageSize > data.Rows.Count ? data.Rows.Count : startIndex + pageSize;
|
||||
if (startIndex < endIndex)
|
||||
for (int i = startIndex; i < endIndex; i++)
|
||||
{
|
||||
Ntable.ImportRow(data.Rows[i]);
|
||||
}
|
||||
return Ntable;
|
||||
}
|
||||
/// <summary>
|
||||
/// 根据字段过滤表的内容
|
||||
/// </summary>
|
||||
/// <param name="data">表数据</param>
|
||||
/// <param name="condition">条件</param>
|
||||
/// <returns></returns>
|
||||
///
|
||||
public static DataTable GetDataFilter(DataTable data, string condition)
|
||||
{
|
||||
if (data != null && data.Rows.Count > 0)
|
||||
{
|
||||
if (condition.Trim() == "")
|
||||
{
|
||||
return data;
|
||||
}
|
||||
else
|
||||
{
|
||||
DataTable newdt = new DataTable();
|
||||
newdt = data.Clone();
|
||||
DataRow[] dr = data.Select(condition);
|
||||
for (int i = 0; i < dr.Length; i++)
|
||||
{
|
||||
newdt.ImportRow((DataRow)dr[i]);
|
||||
}
|
||||
return newdt;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
700
WaterCloud.Code/FileHelper.cs
Normal file
700
WaterCloud.Code/FileHelper.cs
Normal file
@ -0,0 +1,700 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class FileHelper
|
||||
{
|
||||
public static string MapPath(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
string rootdir = Directory.GetCurrentDirectory();
|
||||
//DirectoryInfo Dir = Directory.GetParent(rootdir);
|
||||
//string root = Dir.Parent.Parent.Parent.FullName;
|
||||
return rootdir + path;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return path;
|
||||
}
|
||||
}
|
||||
#region 获取文件到集合中
|
||||
/// <summary>
|
||||
/// 读取指定位置文件列表到集合中
|
||||
/// </summary>
|
||||
/// <param name="path">指定路径</param>
|
||||
/// <returns></returns>
|
||||
public static DataTable GetFileTable(string path)
|
||||
{
|
||||
DataTable dt = new DataTable();
|
||||
dt.Columns.Add("name", typeof(string));
|
||||
dt.Columns.Add("ext", typeof(string));
|
||||
dt.Columns.Add("size", typeof(long));
|
||||
dt.Columns.Add("time", typeof(DateTime));
|
||||
|
||||
if (Directory.Exists(path))
|
||||
{
|
||||
DirectoryInfo dirinfo = new DirectoryInfo(path);
|
||||
FileInfo fi;
|
||||
DirectoryInfo dir;
|
||||
string FileName, FileExt;
|
||||
long FileSize = 0;
|
||||
DateTime FileModify;
|
||||
try
|
||||
{
|
||||
foreach (FileSystemInfo fsi in dirinfo.GetFileSystemInfos())
|
||||
{
|
||||
FileName = string.Empty;
|
||||
FileExt = string.Empty;
|
||||
if (fsi is FileInfo)
|
||||
{
|
||||
fi = (FileInfo)fsi;
|
||||
//获取文件名称
|
||||
FileName = fi.Name;
|
||||
//获取文件扩展名
|
||||
FileExt = fi.Extension;
|
||||
//获取文件大小
|
||||
FileSize = fi.Length;
|
||||
//获取文件最后修改时间
|
||||
FileModify = fi.LastWriteTime;
|
||||
}
|
||||
else
|
||||
{
|
||||
dir = (DirectoryInfo)fsi;
|
||||
//获取目录名
|
||||
FileName = dir.Name;
|
||||
//获取目录最后修改时间
|
||||
FileModify = dir.LastWriteTime;
|
||||
//设置目录文件为文件夹
|
||||
FileExt = "文件夹";
|
||||
}
|
||||
DataRow dr = dt.NewRow();
|
||||
dr["name"] = FileName;
|
||||
dr["ext"] = FileExt;
|
||||
dr["size"] = FileSize;
|
||||
dr["time"] = FileModify;
|
||||
dt.Rows.Add(dr);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return dt;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 检测指定路径是否存在
|
||||
/// <summary>
|
||||
/// 检测指定路径是否存在
|
||||
/// </summary>
|
||||
/// <param name="path">目录的绝对路径</param>
|
||||
public static bool IsExistDirectory(string path)
|
||||
{
|
||||
return Directory.Exists(path);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 检测指定文件是否存在,如果存在则返回true
|
||||
/// <summary>
|
||||
/// 检测指定文件是否存在,如果存在则返回true
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static bool IsExistFile(string filePath)
|
||||
{
|
||||
return File.Exists(filePath);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 创建文件夹
|
||||
/// <summary>
|
||||
/// 创建文件夹
|
||||
/// </summary>
|
||||
/// <param name="folderPath">文件夹的绝对路径</param>
|
||||
public static void CreateFolder(string folderPath)
|
||||
{
|
||||
if (!IsExistDirectory(folderPath))
|
||||
{
|
||||
Directory.CreateDirectory(folderPath);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 判断上传文件后缀名
|
||||
/// <summary>
|
||||
/// 判断上传文件后缀名
|
||||
/// </summary>
|
||||
/// <param name="strExtension">后缀名</param>
|
||||
public static bool IsCanEdit(string strExtension)
|
||||
{
|
||||
strExtension = strExtension.ToLower();
|
||||
if (strExtension.LastIndexOf(".", StringComparison.Ordinal) >= 0)
|
||||
{
|
||||
strExtension = strExtension.Substring(strExtension.LastIndexOf(".", StringComparison.Ordinal));
|
||||
}
|
||||
else
|
||||
{
|
||||
strExtension = ".txt";
|
||||
}
|
||||
string[] strArray = new string[] { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap" };
|
||||
for (int i = 0; i < strArray.Length; i++)
|
||||
{
|
||||
if (strExtension.Equals(strArray[i]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public static bool IsSafeName(string strExtension)
|
||||
{
|
||||
strExtension = strExtension.ToLower();
|
||||
if (strExtension.LastIndexOf(".") >= 0)
|
||||
{
|
||||
strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
|
||||
}
|
||||
else
|
||||
{
|
||||
strExtension = ".txt";
|
||||
}
|
||||
string[] strArray = new string[] { ".jpg", ".gif", ".png" };
|
||||
for (int i = 0; i < strArray.Length; i++)
|
||||
{
|
||||
if (strExtension.Equals(strArray[i]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool IsZipName(string strExtension)
|
||||
{
|
||||
strExtension = strExtension.ToLower();
|
||||
if (strExtension.LastIndexOf(".") >= 0)
|
||||
{
|
||||
strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
|
||||
}
|
||||
else
|
||||
{
|
||||
strExtension = ".txt";
|
||||
}
|
||||
string[] strArray = new string[] { ".zip", ".rar" };
|
||||
for (int i = 0; i < strArray.Length; i++)
|
||||
{
|
||||
if (strExtension.Equals(strArray[i]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 创建文件夹
|
||||
/// <summary>
|
||||
/// 创建文件夹
|
||||
/// </summary>
|
||||
/// <param name="fileName">文件的绝对路径</param>
|
||||
public static void CreateSuffic(string fileName)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(fileName))
|
||||
{
|
||||
Directory.CreateDirectory(fileName);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建文件夹
|
||||
/// </summary>
|
||||
/// <param name="fileName">文件的绝对路径</param>
|
||||
public static void CreateFiles(string fileName)
|
||||
{
|
||||
try
|
||||
{
|
||||
//判断文件是否存在,不存在创建该文件
|
||||
if (!IsExistFile(fileName))
|
||||
{
|
||||
FileInfo file = new FileInfo(fileName);
|
||||
FileStream fs = file.Create();
|
||||
fs.Close();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
#region 创建文本文件
|
||||
/// <summary>
|
||||
/// 创建文件
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="content"></param>
|
||||
public static void CreateFile(string path, string content)
|
||||
{
|
||||
if (!Directory.Exists(Path.GetDirectoryName(path)))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path));
|
||||
}
|
||||
using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))
|
||||
{
|
||||
sw.Write(content);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
/// <summary>
|
||||
/// 创建一个文件,并将字节流写入文件。
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
/// <param name="buffer">二进制流数据</param>
|
||||
public static void CreateFile(string filePath, byte[] buffer)
|
||||
{
|
||||
try
|
||||
{
|
||||
//判断文件是否存在,不存在创建该文件
|
||||
if (!IsExistFile(filePath))
|
||||
{
|
||||
FileInfo file = new FileInfo(filePath);
|
||||
FileStream fs = file.Create();
|
||||
fs.Write(buffer, 0, buffer.Length);
|
||||
fs.Close();
|
||||
}
|
||||
else
|
||||
{
|
||||
File.WriteAllBytes(filePath, buffer);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 将文件移动到指定目录
|
||||
/// <summary>
|
||||
/// 将文件移动到指定目录
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
|
||||
/// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
|
||||
public static void Move(string sourceFilePath, string descDirectoryPath)
|
||||
{
|
||||
string sourceName = GetFileName(sourceFilePath);
|
||||
if (IsExistDirectory(descDirectoryPath))
|
||||
{
|
||||
//如果目标中存在同名文件,则删除
|
||||
if (IsExistFile(descDirectoryPath + "\\" + sourceFilePath))
|
||||
{
|
||||
DeleteFile(descDirectoryPath + "\\" + sourceFilePath);
|
||||
}
|
||||
else
|
||||
{
|
||||
//将文件移动到指定目录
|
||||
File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFilePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 将源文件的内容复制到目标文件中
|
||||
/// <summary>
|
||||
/// 将源文件的内容复制到目标文件中
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">源文件的绝对路径</param>
|
||||
/// <param name="descDirectoryPath">目标文件的绝对路径</param>
|
||||
public static void Copy(string sourceFilePath, string descDirectoryPath)
|
||||
{
|
||||
File.Copy(sourceFilePath, descDirectoryPath, true);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 从文件的绝对路径中获取文件名( 不包含扩展名 )
|
||||
/// <summary>
|
||||
/// 从文件的绝对路径中获取文件名( 不包含扩展名 )
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static string GetFileName(string filePath)
|
||||
{
|
||||
FileInfo file = new FileInfo(filePath);
|
||||
return file.Name;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取文件的后缀名
|
||||
/// <summary>
|
||||
/// 获取文件的后缀名
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static string GetExtension(string filePath)
|
||||
{
|
||||
FileInfo file = new FileInfo(filePath);
|
||||
return file.Extension;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回文件扩展名,不含“.”
|
||||
/// </summary>
|
||||
/// <param name="filepath">文件全名称</param>
|
||||
/// <returns>string</returns>
|
||||
public static string GetFileExt(string filepath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(filepath))
|
||||
{
|
||||
return "";
|
||||
}
|
||||
if (filepath.LastIndexOf(".", StringComparison.Ordinal) > 0)
|
||||
{
|
||||
return filepath.Substring(filepath.LastIndexOf(".", StringComparison.Ordinal) + 1); //文件扩展名,不含“.”
|
||||
}
|
||||
return "";
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 删除指定文件
|
||||
/// <summary>
|
||||
/// 删除指定文件
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static void DeleteFile(string filePath)
|
||||
{
|
||||
if (IsExistFile(filePath))
|
||||
{
|
||||
File.Delete(filePath);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 删除指定目录及其所有子目录
|
||||
/// <summary>
|
||||
/// 删除指定目录及其所有子目录
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">文件的绝对路径</param>
|
||||
public static void DeleteDirectory(string directoryPath)
|
||||
{
|
||||
if (IsExistDirectory(directoryPath))
|
||||
{
|
||||
Directory.Delete(directoryPath);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 清空指定目录下所有文件及子目录,但该目录依然保存.
|
||||
/// <summary>
|
||||
/// 清空指定目录下所有文件及子目录,但该目录依然保存.
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">指定目录的绝对路径</param>
|
||||
public static void ClearDirectory(string directoryPath)
|
||||
{
|
||||
if (!IsExistDirectory(directoryPath)) return;
|
||||
//删除目录中所有的文件
|
||||
string[] fileNames = GetFileNames(directoryPath);
|
||||
for (int i = 0; i < fileNames.Length; i++)
|
||||
{
|
||||
DeleteFile(fileNames[i]);
|
||||
}
|
||||
//删除目录中所有的子目录
|
||||
string[] directoryNames = GetDirectories(directoryPath);
|
||||
for (int i = 0; i < directoryNames.Length; i++)
|
||||
{
|
||||
DeleteDirectory(directoryNames[i]);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 剪切 粘贴
|
||||
/// <summary>
|
||||
/// 剪切文件
|
||||
/// </summary>
|
||||
/// <param name="source">原路径</param>
|
||||
/// <param name="destination">新路径</param>
|
||||
public bool FileMove(string source, string destination)
|
||||
{
|
||||
bool ret = false;
|
||||
FileInfo file_s = new FileInfo(source);
|
||||
FileInfo file_d = new FileInfo(destination);
|
||||
if (file_s.Exists)
|
||||
{
|
||||
if (!file_d.Exists)
|
||||
{
|
||||
file_s.MoveTo(destination);
|
||||
ret = true;
|
||||
}
|
||||
}
|
||||
if (ret == true)
|
||||
{
|
||||
//Response.Write("<script>alert('剪切文件成功!');</script>");
|
||||
}
|
||||
else
|
||||
{
|
||||
//Response.Write("<script>alert('剪切文件失败!');</script>");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 检测指定目录是否为空
|
||||
/// <summary>
|
||||
/// 检测指定目录是否为空
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">指定目录的绝对路径</param>
|
||||
public static bool IsEmptyDirectory(string directoryPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
//判断文件是否存在
|
||||
string[] fileNames = GetFileNames(directoryPath);
|
||||
if (fileNames.Length > 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
//判断是否存在文件夹
|
||||
string[] directoryNames = GetDirectories(directoryPath);
|
||||
if (directoryNames.Length > 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取指定目录中所有文件列表
|
||||
/// <summary>
|
||||
/// 获取指定目录中所有文件列表
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">指定目录的绝对路径</param>
|
||||
public static string[] GetFileNames(string directoryPath)
|
||||
{
|
||||
if (!IsExistDirectory(directoryPath))
|
||||
{
|
||||
throw new FileNotFoundException();
|
||||
}
|
||||
return Directory.GetFiles(directoryPath);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取指定目录中的子目录列表
|
||||
/// <summary>
|
||||
/// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">指定目录的绝对路径</param>
|
||||
public static string[] GetDirectories(string directoryPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Directory.GetDirectories(directoryPath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定目录及子目录中所有子目录列表
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">指定目录的绝对路径</param>
|
||||
/// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
|
||||
/// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
|
||||
/// <param name="isSearchChild">是否搜索子目录</param>
|
||||
public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (isSearchChild)
|
||||
{
|
||||
return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取一个文件的长度
|
||||
/// <summary>
|
||||
/// 获取一个文件的长度,单位为Byte
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static int GetFileSize(string filePath)
|
||||
{
|
||||
//创建一个文件对象
|
||||
FileInfo fi = new FileInfo(filePath);
|
||||
//获取文件的大小
|
||||
return (int)fi.Length;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取一个文件的长度,单位为KB
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的路径</param>
|
||||
public static double GetFileSizeByKb(string filePath)
|
||||
{
|
||||
//创建一个文件对象
|
||||
FileInfo fi = new FileInfo(filePath);
|
||||
//获取文件的大小
|
||||
return Math.Round(Convert.ToDouble(filePath.Length) / 1024, 2);// ConvertHelper.ToDouble(ConvertHelper.ToDouble(fi.Length) / 1024, 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个文件的长度,单位为MB
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的路径</param>
|
||||
public static double GetFileSizeByMb(string filePath)
|
||||
{
|
||||
//创建一个文件对象
|
||||
FileInfo fi = new FileInfo(filePath);
|
||||
//获取文件的大小
|
||||
return Math.Round(Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024), 2);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 获取文件大小并以B,KB,GB,TB
|
||||
/// <summary>
|
||||
/// 计算文件大小函数(保留两位小数),Size为字节大小
|
||||
/// </summary>
|
||||
/// <param name="size">初始文件大小</param>
|
||||
/// <returns></returns>
|
||||
public static string ToFileSize(long size)
|
||||
{
|
||||
string m_strSize = "";
|
||||
long FactSize = 0;
|
||||
FactSize = size;
|
||||
if (FactSize < 1024.00)
|
||||
m_strSize = FactSize.ToString("F2") + " 字节";
|
||||
else if (FactSize >= 1024.00 && FactSize < 1048576)
|
||||
m_strSize = (FactSize / 1024.00).ToString("F2") + " KB";
|
||||
else if (FactSize >= 1048576 && FactSize < 1073741824)
|
||||
m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " MB";
|
||||
else if (FactSize >= 1073741824)
|
||||
m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " GB";
|
||||
return m_strSize;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 将文件读取到字符串中
|
||||
/// <summary>
|
||||
/// 将文件读取到字符串中
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static string FileToString(string filePath)
|
||||
{
|
||||
return FileToString(filePath, Encoding.UTF8);
|
||||
}
|
||||
/// <summary>
|
||||
/// 将文件读取到字符串中
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
/// <param name="encoding">字符编码</param>
|
||||
public static string FileToString(string filePath, Encoding encoding)
|
||||
{
|
||||
//创建流读取器
|
||||
StreamReader reader = new StreamReader(filePath, encoding);
|
||||
try
|
||||
{
|
||||
//读取流
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw ex;
|
||||
}
|
||||
finally
|
||||
{
|
||||
//关闭流读取器
|
||||
reader.Close();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 判断文件
|
||||
// 判断文件是否是bai图片
|
||||
public static bool IsPicture(string fileName)
|
||||
{
|
||||
string strFilter = ".jpeg|.gif|.jpg|.png|.bmp|.pic|.tiff|.ico|.iff|.lbm|.mag|.mac|.mpt|.opt|";
|
||||
char[] separtor = { '|' };
|
||||
string[] tempFileds = StringSplit(strFilter, separtor);
|
||||
foreach (string str in tempFileds)
|
||||
{
|
||||
if (str.ToUpper() == fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")).ToUpper()) { return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// 判断文件是否是excle
|
||||
public static bool IsExcel(string fileName)
|
||||
{
|
||||
string strFilter = ".xls|.xlsx|";
|
||||
char[] separtor = { '|' };
|
||||
string[] tempFileds = StringSplit(strFilter, separtor);
|
||||
foreach (string str in tempFileds)
|
||||
{
|
||||
if (str.ToUpper() == fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")).ToUpper()) { return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// 通过字符串,分隔符返回zhistring[]数组
|
||||
public static string[] StringSplit(string s, char[] separtor)
|
||||
{
|
||||
string[] tempFileds = s.Trim().Split(separtor); return tempFileds;
|
||||
}
|
||||
|
||||
public static bool IsFrx(string fileName)
|
||||
{
|
||||
string strFilter = ".frx|";
|
||||
char[] separtor = { '|' };
|
||||
string[] tempFileds = StringSplit(strFilter, separtor);
|
||||
foreach (string str in tempFileds)
|
||||
{
|
||||
if (str.ToUpper() == fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")).ToUpper()) { return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool IsReport(string fileName)
|
||||
{
|
||||
string strFilter = ".xlsx|.json";
|
||||
char[] separtor = { '|' };
|
||||
string[] tempFileds = StringSplit(strFilter, separtor);
|
||||
foreach (string str in tempFileds)
|
||||
{
|
||||
if (str.ToUpper() == fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")).ToUpper()) { return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
15
WaterCloud.Code/Flow/Flow.cs
Normal file
15
WaterCloud.Code/Flow/Flow.cs
Normal file
@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class Flow
|
||||
{
|
||||
public string title { get; set; }
|
||||
public int initNum { get; set; }
|
||||
public List<FlowLine> lines { get; set; }
|
||||
public List<FlowNode> nodes { get; set; }
|
||||
public List<FlowArea> areas { get; set; }
|
||||
}
|
||||
}
|
||||
22
WaterCloud.Code/Flow/FlowArea.cs
Normal file
22
WaterCloud.Code/Flow/FlowArea.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class FlowArea
|
||||
{
|
||||
public string id { get; set; }
|
||||
|
||||
public string name { get; set; }
|
||||
|
||||
public string color { get; set; }
|
||||
|
||||
public int left { get; set; }
|
||||
public int top { get; set; }
|
||||
|
||||
public int width { get; set; }
|
||||
public int height { get; set; }
|
||||
public bool alt { get; set; }
|
||||
}
|
||||
}
|
||||
258
WaterCloud.Code/Flow/FlowLine.cs
Normal file
258
WaterCloud.Code/Flow/FlowLine.cs
Normal file
@ -0,0 +1,258 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 流程连线
|
||||
/// </summary>
|
||||
public class FlowLine
|
||||
{
|
||||
public string id { get; set; }
|
||||
public string label { get; set; }
|
||||
public string type { get; set; }
|
||||
public string from { get; set; }
|
||||
public string to { get; set; }
|
||||
public string name { get; set; }
|
||||
public bool dash { get; set; }
|
||||
public double M { get; set; }
|
||||
public bool alt { get; set; }
|
||||
|
||||
/// <summary> 分支条件 </summary>
|
||||
public List<DataCompare> Compares { get; set; }
|
||||
|
||||
public bool Compare(JObject frmDataJson)
|
||||
{
|
||||
bool result = true;
|
||||
foreach (var compare in Compares)
|
||||
{
|
||||
compare.FieldName = compare.FieldName.ToLower();
|
||||
compare.Value = compare.Value.ToLower();
|
||||
decimal value=0; //参考值
|
||||
decimal frmvalue=0; //表单中填写的值
|
||||
if (compare.Operation!= DataCompare.Equal&& compare.Operation != DataCompare.NotEqual)
|
||||
{
|
||||
value = decimal.Parse(compare.Value);
|
||||
frmvalue = decimal.Parse(frmDataJson.GetValue(compare.FieldName.ToLower()).ToString()); //表单中填写的值
|
||||
}
|
||||
bool res = false;
|
||||
if (compare.Condition=="and")
|
||||
{
|
||||
switch (compare.Operation)
|
||||
{
|
||||
case DataCompare.Equal:
|
||||
result &= compare.Value == frmDataJson.GetValue(compare.FieldName).ToString();
|
||||
break;
|
||||
case DataCompare.NotEqual:
|
||||
result &= compare.Value != frmDataJson.GetValue(compare.FieldName).ToString();
|
||||
break;
|
||||
case DataCompare.Larger:
|
||||
result &= frmvalue > value;
|
||||
break;
|
||||
case DataCompare.Less:
|
||||
result &= frmvalue < value;
|
||||
break;
|
||||
case DataCompare.LargerEqual:
|
||||
result &= frmvalue <= value;
|
||||
break;
|
||||
case DataCompare.LessEqual:
|
||||
result &= frmvalue <= value;
|
||||
break;
|
||||
case DataCompare.In:
|
||||
if (compare.FieldName == "申请人" || compare.FieldName == "所属部门")
|
||||
{
|
||||
var arr = compare.Value.Split(',');
|
||||
foreach (var item in frmDataJson.GetValue(compare.FieldName).ToString().Split(','))
|
||||
{
|
||||
if (arr.Contains(item))
|
||||
{
|
||||
res = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
result &= res;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
var arr = compare.Value.Split(',');
|
||||
if (arr.Contains(frmvalue.ToString()))
|
||||
{
|
||||
res = true;
|
||||
break;
|
||||
}
|
||||
result &= res;
|
||||
break;
|
||||
}
|
||||
case DataCompare.NotIn:
|
||||
if (compare.FieldName == "申请人" || compare.FieldName == "所属部门")
|
||||
{
|
||||
var arr = compare.Value.Split(',');
|
||||
foreach (var item in frmDataJson.GetValue(compare.FieldName).ToString().Split(','))
|
||||
{
|
||||
if (arr.Contains(item))
|
||||
{
|
||||
res = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
result &= res;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
var arr = compare.Value.Split(',');
|
||||
if (arr.Contains(frmvalue.ToString()))
|
||||
{
|
||||
res = false;
|
||||
break;
|
||||
}
|
||||
result &= res;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (compare.Operation)
|
||||
{
|
||||
case DataCompare.Equal:
|
||||
if (compare.FieldName == "申请人" || compare.FieldName == "所属部门")
|
||||
{
|
||||
var arr = compare.Value.Split(',');
|
||||
foreach (var item in frmDataJson.GetValue(compare.FieldName).ToString().Split(','))
|
||||
{
|
||||
if (arr.Contains(item))
|
||||
{
|
||||
res = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
result |= res;
|
||||
break;
|
||||
}
|
||||
result |= compare.Value == frmDataJson.GetValue(compare.FieldName).ToString();
|
||||
break;
|
||||
case DataCompare.NotEqual:
|
||||
if (compare.FieldName == "申请人" || compare.FieldName == "所属部门")
|
||||
{
|
||||
var arr = compare.Value.Split(',');
|
||||
foreach (var item in frmDataJson.GetValue(compare.FieldName).ToString().Split(','))
|
||||
{
|
||||
if (arr.Contains(item))
|
||||
{
|
||||
res = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
result |= res;
|
||||
break;
|
||||
}
|
||||
result |= compare.Value != frmDataJson.GetValue(compare.FieldName).ToString();
|
||||
break;
|
||||
case DataCompare.Larger:
|
||||
result |= frmvalue > value;
|
||||
break;
|
||||
case DataCompare.Less:
|
||||
result |= frmvalue < value;
|
||||
break;
|
||||
case DataCompare.LargerEqual:
|
||||
result |= frmvalue <= value;
|
||||
break;
|
||||
case DataCompare.LessEqual:
|
||||
result |= frmvalue <= value;
|
||||
break;
|
||||
case DataCompare.In:
|
||||
if (compare.FieldName == "申请人" || compare.FieldName == "所属部门")
|
||||
{
|
||||
var arr = compare.Value.Split(',');
|
||||
foreach (var item in frmDataJson.GetValue(compare.FieldName).ToString().Split(','))
|
||||
{
|
||||
if (arr.Contains(item))
|
||||
{
|
||||
res = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
result |= res;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
var arr = compare.Value.Split(',');
|
||||
if (arr.Contains(frmvalue.ToString()))
|
||||
{
|
||||
res = true;
|
||||
}
|
||||
result |= res;
|
||||
break;
|
||||
}
|
||||
case DataCompare.NotIn:
|
||||
if (compare.FieldName == "申请人" || compare.FieldName == "所属部门")
|
||||
{
|
||||
var arr = compare.Value.Split(',');
|
||||
foreach (var item in frmDataJson.GetValue(compare.FieldName).ToString().Split(','))
|
||||
{
|
||||
if (arr.Contains(item))
|
||||
{
|
||||
res = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
result |= res;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
var arr = compare.Value.Split(',');
|
||||
if (arr.Contains(frmvalue.ToString()))
|
||||
{
|
||||
res = false;
|
||||
}
|
||||
result |= res;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分支条件
|
||||
/// </summary>
|
||||
public class DataCompare
|
||||
{
|
||||
public const string Larger = ">";
|
||||
public const string Less = "<";
|
||||
public const string LargerEqual = ">=";
|
||||
public const string LessEqual = "<=";
|
||||
public const string NotEqual = "!=";
|
||||
public const string Equal = "=";
|
||||
public const string In = "in";
|
||||
public const string NotIn = "not in";
|
||||
|
||||
/// <summary>操作类型比如大于/等于/小于</summary>
|
||||
public string Operation { get; set; }
|
||||
|
||||
/// <summary> form种的字段名称 </summary>
|
||||
public string FieldName { get; set; }
|
||||
|
||||
/// <summary> 字段类型:"form":为表单中的字段,后期扩展系统表等. </summary>
|
||||
public string FieldType { get; set; }
|
||||
|
||||
/// <summary>实际的值</summary>
|
||||
public string Value { get; set; }
|
||||
/// <summary>
|
||||
/// 显示值
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
/// <summary>
|
||||
/// 条件关系
|
||||
/// </summary>
|
||||
public string Condition { get; set; }
|
||||
}
|
||||
}
|
||||
121
WaterCloud.Code/Flow/FlowNode.cs
Normal file
121
WaterCloud.Code/Flow/FlowNode.cs
Normal file
@ -0,0 +1,121 @@
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 流程节点
|
||||
/// </summary>
|
||||
public class FlowNode
|
||||
{
|
||||
public const string START = "start round mix";
|
||||
public const string END = "end round";
|
||||
public const string NODE = "node";
|
||||
public const string FORK = "fork"; //会签开始节点
|
||||
public const string JOIN = "join"; //会签结束节点
|
||||
|
||||
public string id { get; set; }
|
||||
|
||||
public string name { get; set; }
|
||||
|
||||
public string type { get; set; }
|
||||
|
||||
public int left { get; set; }
|
||||
public int top { get; set; }
|
||||
|
||||
public int width { get; set; }
|
||||
public int height { get; set; }
|
||||
public bool alt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 节点的附加数据项
|
||||
/// </summary>
|
||||
/// <value>The set information.</value>
|
||||
public Setinfo setInfo { get; set; }
|
||||
}
|
||||
|
||||
public class Setinfo
|
||||
{
|
||||
public const string SPECIAL_USER = "SPECIAL_USER"; //指定用户
|
||||
public const string ALL_USER = "ALL_USER"; //所有用户
|
||||
public const string SPECIAL_ROLE = "SPECIAL_ROLE"; //指定角色
|
||||
public const string RUNTIME_SPECIAL_ROLE = "RUNTIME_SPECIAL_ROLE"; //运行时指定角色
|
||||
public const string RUNTIME_SPECIAL_USER = "RUNTIME_SPECIAL_USER"; //运行时指定用户
|
||||
|
||||
/// <summary>
|
||||
/// 节点执行权限类型
|
||||
/// </summary>
|
||||
public string NodeDesignate { get; set; }
|
||||
|
||||
public Nodedesignatedata NodeDesignateData { get; set; }
|
||||
public string NodeCode { get; set; }
|
||||
public string NodeName { get; set; }
|
||||
/// <summary>
|
||||
/// 流程执行时,三方回调的URL地址
|
||||
/// </summary>
|
||||
public string ThirdPartyUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 驳回节点0"前一步"1"第一步"2"某一步" 3"不处理"
|
||||
/// </summary>
|
||||
public string NodeRejectType { get; set; }
|
||||
|
||||
public int? Taged { get; set; }
|
||||
public string UserName { get; set; }
|
||||
public string UserId { get; set; }
|
||||
public string Description { get; set; }
|
||||
public string TagedTime { get; set; }
|
||||
|
||||
//节点会签方式,
|
||||
//all/空:默认为全部通过
|
||||
//one :至少有一个通过
|
||||
public string NodeConfluenceType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 会签通过的个数
|
||||
/// </summary>
|
||||
public int? ConfluenceOk { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 会签拒绝的个数
|
||||
/// </summary>
|
||||
public int? ConfluenceNo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 节点执行人
|
||||
/// </summary>
|
||||
public class Nodedesignatedata
|
||||
{
|
||||
public string[] users { get; set; }
|
||||
public string[] roles { get; set; }
|
||||
public string[] orgs { get; set; }
|
||||
public bool currentDepart { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 节点执行结果标签
|
||||
/// </summary>
|
||||
public class Tag
|
||||
{
|
||||
/// <summary>
|
||||
/// 1: 通过
|
||||
/// 2:不通过
|
||||
/// 3:驳回
|
||||
/// </summary>
|
||||
public int Taged { get; set; }
|
||||
public string UserId { get; set; }
|
||||
public string UserName { get; set; }
|
||||
public string Description { get; set; }
|
||||
public string TagedTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 1: 通过
|
||||
/// 2:不通过
|
||||
/// 3:驳回
|
||||
/// </summary>
|
||||
public enum TagState
|
||||
{
|
||||
Ok = 1,
|
||||
No ,
|
||||
Reject
|
||||
}
|
||||
}
|
||||
59
WaterCloud.Code/Form/FormUtil.cs
Normal file
59
WaterCloud.Code/Form/FormUtil.cs
Normal file
@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using WaterCloud.Code;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class FormUtil {
|
||||
/// <summary>
|
||||
/// 获取值
|
||||
/// </summary>
|
||||
/// <param name="form">The form.</param>
|
||||
/// <returns>System.String.</returns>
|
||||
public static List<string> SetValue(string content)
|
||||
{
|
||||
List<FormValue> list = JsonHelper.ToObject<List<FormValue>>(content);
|
||||
List<string> temp = new List<string>();
|
||||
SetFormValue(list, temp);
|
||||
return temp;
|
||||
}
|
||||
|
||||
private static List<string> SetFormValue(List<FormValue> list, List<string> temp)
|
||||
{
|
||||
foreach (var item in list)
|
||||
{
|
||||
if (item.tag == "grid")
|
||||
{
|
||||
foreach (var column in item.columns)
|
||||
{
|
||||
SetFormValue(column.list, temp);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
temp.Add(item.id);
|
||||
}
|
||||
}
|
||||
return temp;
|
||||
}
|
||||
|
||||
public static List<string> SetValueByWeb(string webForm)
|
||||
{
|
||||
var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
|
||||
var referencedAssemblies = Directory.GetFiles(path, "*.dll").Select(Assembly.LoadFrom).ToArray();
|
||||
var t = referencedAssemblies
|
||||
.SelectMany(a => a.GetTypes().Where(t => t.FullName.Contains("WaterCloud.Domain.") && t.FullName.Contains("."+webForm + "Entity"))).FirstOrDefault();
|
||||
List<string> temp = new List<string>();
|
||||
PropertyInfo[] pArray = t.GetProperties();
|
||||
Array.ForEach<PropertyInfo>(pArray, p =>
|
||||
{
|
||||
temp.Add(p.Name);
|
||||
});
|
||||
return temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
25
WaterCloud.Code/Form/FormValue.cs
Normal file
25
WaterCloud.Code/Form/FormValue.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 表单设计类
|
||||
/// </summary>
|
||||
public class FormValue
|
||||
{
|
||||
public string id { get; set; }
|
||||
public string label { get; set; }
|
||||
public int index { get; set; }
|
||||
public string tag { get; set; }
|
||||
public int span { get; set; }
|
||||
public List<FormEx> columns { get; set; }
|
||||
public string name { get; set; }
|
||||
}
|
||||
public class FormEx
|
||||
{
|
||||
public int span { get; set; }
|
||||
public List<FormValue> list { get; set; }
|
||||
}
|
||||
}
|
||||
62
WaterCloud.Code/Globals/GlobalContext.cs
Normal file
62
WaterCloud.Code/Globals/GlobalContext.cs
Normal file
@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.AspNetCore.StaticFiles;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using WaterCloud.Code.Model;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class GlobalContext
|
||||
{
|
||||
/// <summary>
|
||||
/// All registered service and class instance container. Which are used for dependency injection.
|
||||
/// </summary>
|
||||
public static IServiceCollection Services { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Configured service provider.
|
||||
/// </summary>
|
||||
public static IServiceProvider ServiceProvider { get; set; }
|
||||
|
||||
public static IConfiguration Configuration { get; set; }
|
||||
|
||||
public static IWebHostEnvironment HostingEnvironment { get; set; }
|
||||
|
||||
public static SystemConfig SystemConfig { get; set; }
|
||||
|
||||
public static string GetVersion()
|
||||
{
|
||||
Version version = Assembly.GetEntryAssembly().GetName().Version;
|
||||
return version.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 程序启动时,记录目录
|
||||
/// </summary>
|
||||
/// <param name="env"></param>
|
||||
public static void LogWhenStart(IWebHostEnvironment env)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.AppendLine("程序启动");
|
||||
sb.AppendLine("ContentRootPath:" + env.ContentRootPath);
|
||||
sb.AppendLine("WebRootPath:" + env.WebRootPath);
|
||||
sb.AppendLine("IsDevelopment:" + env.IsDevelopment());
|
||||
LogHelper.WriteWithTime(sb.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置cache control
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
public static void SetCacheControl(StaticFileResponseContext context)
|
||||
{
|
||||
int second = 365 * 24 * 60 * 60;
|
||||
context.Context.Response.Headers.Add("Cache-Control", new[] { "public,max-age=" + second });
|
||||
context.Context.Response.Headers.Add("Expires", new[] { DateTime.UtcNow.AddYears(1).ToString("R") }); // Format RFC1123
|
||||
}
|
||||
}
|
||||
}
|
||||
66
WaterCloud.Code/HtmlHelper.cs
Normal file
66
WaterCloud.Code/HtmlHelper.cs
Normal file
@ -0,0 +1,66 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class HtmlHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Get part Content from HTML by apply prefix part and subfix part
|
||||
/// </summary>
|
||||
/// <param name="html">souce html</param>
|
||||
/// <param name="prefix">prefix</param>
|
||||
/// <param name="subfix">subfix</param>
|
||||
/// <returns>part content</returns>
|
||||
public static string Resove(string html, string prefix, string subfix)
|
||||
{
|
||||
int inl = html.IndexOf(prefix);
|
||||
if (inl == -1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
inl += prefix.Length;
|
||||
int inl2 = html.IndexOf(subfix, inl);
|
||||
string s = html.Substring(inl, inl2 - inl);
|
||||
return s;
|
||||
}
|
||||
public static string ResoveReverse(string html, string subfix, string prefix)
|
||||
{
|
||||
int inl = html.IndexOf(subfix);
|
||||
if (inl == -1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
string subString = html.Substring(0, inl);
|
||||
int inl2 = subString.LastIndexOf(prefix);
|
||||
if (inl2 == -1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
string s = subString.Substring(inl2 + prefix.Length, subString.Length - inl2 - prefix.Length);
|
||||
return s;
|
||||
}
|
||||
public static List<string> ResoveList(string html, string prefix, string subfix)
|
||||
{
|
||||
List<string> list = new List<string>();
|
||||
int index = prefix.Length * -1;
|
||||
do
|
||||
{
|
||||
index = html.IndexOf(prefix, index + prefix.Length);
|
||||
if (index == -1)
|
||||
{
|
||||
break;
|
||||
}
|
||||
index += prefix.Length;
|
||||
int index4 = html.IndexOf(subfix, index);
|
||||
string s78 = html.Substring(index, index4 - index);
|
||||
list.Add(s78);
|
||||
}
|
||||
while (index > -1);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
741
WaterCloud.Code/HttpHelper.cs
Normal file
741
WaterCloud.Code/HttpHelper.cs
Normal file
@ -0,0 +1,741 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// Http连接操作帮助类
|
||||
/// </summary>
|
||||
public class HttpHelper
|
||||
{
|
||||
#region 是否是网址
|
||||
public static bool IsUrl(string url)
|
||||
{
|
||||
url = url.ParseToString().ToLower();
|
||||
if (url.StartsWith("http://") || url.StartsWith("https://"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 模拟GET
|
||||
/// <summary>
|
||||
/// GET请求
|
||||
/// </summary>
|
||||
/// <param name="Url">The URL.</param>
|
||||
/// <param name="postDataStr">The post data string.</param>
|
||||
/// <returns>System.String.</returns>
|
||||
public static string HttpGet(string Url, int timeout = 10 * 1000)
|
||||
{
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
|
||||
request.Method = "GET";
|
||||
request.ContentType = "text/html;charset=UTF-8";
|
||||
request.Timeout = timeout;
|
||||
|
||||
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
|
||||
Stream myResponseStream = response.GetResponseStream();
|
||||
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
|
||||
string retString = myStreamReader.ReadToEnd();
|
||||
myStreamReader.Close();
|
||||
myResponseStream.Close();
|
||||
|
||||
return retString;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 模拟POST
|
||||
/// <summary>
|
||||
/// POST请求
|
||||
/// </summary>
|
||||
/// <param name="posturl">The posturl.</param>
|
||||
/// <param name="postData">The post data.</param>
|
||||
/// <returns>System.String.</returns>
|
||||
public static string HttpPost(string posturl, string postData, string contentType = "application/x-www-form-urlencoded", int timeout = 10 * 1000)
|
||||
{
|
||||
Stream outstream = null;
|
||||
Stream instream = null;
|
||||
StreamReader sr = null;
|
||||
HttpWebResponse response = null;
|
||||
HttpWebRequest request = null;
|
||||
Encoding encoding = Encoding.GetEncoding("utf-8");
|
||||
byte[] data = encoding.GetBytes(postData);
|
||||
// 准备请求...
|
||||
try
|
||||
{
|
||||
// 设置参数
|
||||
request = WebRequest.Create(posturl) as HttpWebRequest;
|
||||
CookieContainer cookieContainer = new CookieContainer();
|
||||
request.CookieContainer = cookieContainer;
|
||||
request.AllowAutoRedirect = true;
|
||||
request.Method = "POST";
|
||||
request.ContentType = contentType;
|
||||
request.Timeout = timeout;
|
||||
request.ContentLength = data.Length;
|
||||
outstream = request.GetRequestStream();
|
||||
outstream.Write(data, 0, data.Length);
|
||||
outstream.Close();
|
||||
//发送请求并获取相应回应数据
|
||||
response = request.GetResponse() as HttpWebResponse;
|
||||
//直到request.GetResponse()程序才开始向目标网页发送Post请求
|
||||
instream = response.GetResponseStream();
|
||||
sr = new StreamReader(instream, encoding);
|
||||
//返回结果网页(html)代码
|
||||
string content = sr.ReadToEnd();
|
||||
string err = string.Empty;
|
||||
return content;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
string err = ex.Message;
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模拟httpPost提交表单
|
||||
/// </summary>
|
||||
/// <param name="url">POS请求的网址</param>
|
||||
/// <param name="data">表单里的参数和值</param>
|
||||
/// <param name="encoder">页面编码</param>
|
||||
/// <returns></returns>
|
||||
public static string CreateAutoSubmitForm(string url, Dictionary<string, string> data, Encoding encoder)
|
||||
{
|
||||
StringBuilder html = new StringBuilder();
|
||||
html.AppendLine("<html>");
|
||||
html.AppendLine("<head>");
|
||||
html.AppendFormat("<meta http-equiv=\"Content-Type\" content=\"text/html; charset={0}\" />", encoder.BodyName);
|
||||
html.AppendLine("</head>");
|
||||
html.AppendLine("<body onload=\"OnLoadSubmit();\">");
|
||||
html.AppendFormat("<form id=\"pay_form\" action=\"{0}\" method=\"post\">", url);
|
||||
foreach (KeyValuePair<string, string> kvp in data)
|
||||
{
|
||||
html.AppendFormat("<input type=\"hidden\" name=\"{0}\" id=\"{0}\" value=\"{1}\" />", kvp.Key, kvp.Value);
|
||||
}
|
||||
html.AppendLine("</form>");
|
||||
html.AppendLine("<script type=\"text/javascript\">");
|
||||
html.AppendLine("<!--");
|
||||
html.AppendLine("function OnLoadSubmit()");
|
||||
html.AppendLine("{");
|
||||
html.AppendLine("document.getElementById(\"pay_form\").submit();");
|
||||
html.AppendLine("}");
|
||||
html.AppendLine("//-->");
|
||||
html.AppendLine("</script>");
|
||||
html.AppendLine("</body>");
|
||||
html.AppendLine("</html>");
|
||||
return html.ToString();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 预定义方法或者变更
|
||||
//默认的编码
|
||||
private Encoding encoding = Encoding.Default;
|
||||
//HttpWebRequest对象用来发起请求
|
||||
private HttpWebRequest request = null;
|
||||
//获取影响流的数据对象
|
||||
private HttpWebResponse response = null;
|
||||
/// <summary>
|
||||
/// 根据相传入的数据,得到相应页面数据
|
||||
/// </summary>
|
||||
/// <param name="strPostdata">传入的数据Post方式,get方式传NUll或者空字符串都可以</param>
|
||||
/// <returns>string类型的响应数据</returns>
|
||||
private HttpResult GetHttpRequestData(HttpItem objhttpitem)
|
||||
{
|
||||
//返回参数
|
||||
HttpResult result = new HttpResult();
|
||||
try
|
||||
{
|
||||
#region 得到请求的response
|
||||
using (response = (HttpWebResponse)request.GetResponse())
|
||||
{
|
||||
result.Header = response.Headers;
|
||||
if (response.Cookies != null)
|
||||
{
|
||||
result.CookieCollection = response.Cookies;
|
||||
}
|
||||
if (response.Headers["set-cookie"] != null)
|
||||
{
|
||||
result.Cookie = response.Headers["set-cookie"];
|
||||
}
|
||||
|
||||
MemoryStream _stream = new MemoryStream();
|
||||
//GZIIP处理
|
||||
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
|
||||
{
|
||||
//开始读取流并设置编码方式
|
||||
//new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
|
||||
//.net4.0以下写法
|
||||
_stream = GetMemoryStream(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
|
||||
}
|
||||
else
|
||||
{
|
||||
//开始读取流并设置编码方式
|
||||
//response.GetResponseStream().CopyTo(_stream, 10240);
|
||||
//.net4.0以下写法
|
||||
_stream = GetMemoryStream(response.GetResponseStream());
|
||||
}
|
||||
//获取Byte
|
||||
byte[] RawResponse = _stream.ToArray();
|
||||
//是否返回Byte类型数据
|
||||
if (objhttpitem.ResultType == ResultTypes.Byte)
|
||||
{
|
||||
result.ResultByte = RawResponse;
|
||||
}
|
||||
//从这里开始我们要无视编码了
|
||||
if (encoding == null)
|
||||
{
|
||||
string temp = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length);
|
||||
//<meta(.*?)charset([\s]?)=[^>](.*?)>
|
||||
Match meta = Regex.Match(temp, "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase | RegexOptions.Multiline);
|
||||
string charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty;
|
||||
charter = charter.Replace("\"", string.Empty).Replace("'", string.Empty).Replace(";", string.Empty);
|
||||
if (charter.Length > 0)
|
||||
{
|
||||
charter = charter.ToLower().Replace("iso-8859-1", "gbk");
|
||||
encoding = Encoding.GetEncoding(charter);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (response.CharacterSet.ToLower().Trim() == "iso-8859-1")
|
||||
{
|
||||
encoding = Encoding.GetEncoding("gbk");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (string.IsNullOrEmpty(response.CharacterSet.Trim()))
|
||||
{
|
||||
encoding = Encoding.UTF8;
|
||||
}
|
||||
else
|
||||
{
|
||||
encoding = Encoding.GetEncoding(response.CharacterSet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//得到返回的HTML
|
||||
result.Html = encoding.GetString(RawResponse);
|
||||
//最后释放流
|
||||
_stream.Close();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
catch (WebException ex)
|
||||
{
|
||||
//这里是在发生异常时返回的错误信息
|
||||
result.Html = "String Error";
|
||||
response = (HttpWebResponse)ex.Response;
|
||||
}
|
||||
if (objhttpitem.IsToLower)
|
||||
{
|
||||
result.Html = result.Html.ToLower();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 4.0以下.net版本取数据使用
|
||||
/// </summary>
|
||||
/// <param name="streamResponse">流</param>
|
||||
private static MemoryStream GetMemoryStream(Stream streamResponse)
|
||||
{
|
||||
MemoryStream _stream = new MemoryStream();
|
||||
int Length = 256;
|
||||
Byte[] buffer = new Byte[Length];
|
||||
int bytesRead = streamResponse.Read(buffer, 0, Length);
|
||||
// write the required bytes
|
||||
while (bytesRead > 0)
|
||||
{
|
||||
_stream.Write(buffer, 0, bytesRead);
|
||||
bytesRead = streamResponse.Read(buffer, 0, Length);
|
||||
}
|
||||
return _stream;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为请求准备参数
|
||||
/// </summary>
|
||||
///<param name="objhttpItem">参数列表</param>
|
||||
/// <param name="_Encoding">读取数据时的编码方式</param>
|
||||
private void SetRequest(HttpItem objhttpItem)
|
||||
{
|
||||
// 验证证书
|
||||
SetCer(objhttpItem);
|
||||
// 设置代理
|
||||
SetProxy(objhttpItem);
|
||||
//请求方式Get或者Post
|
||||
request.Method = objhttpItem.Method;
|
||||
request.Timeout = objhttpItem.Timeout;
|
||||
request.ReadWriteTimeout = objhttpItem.ReadWriteTimeout;
|
||||
//Accept
|
||||
request.Accept = objhttpItem.Accept;
|
||||
//ContentType返回类型
|
||||
request.ContentType = objhttpItem.ContentType;
|
||||
//UserAgent客户端的访问类型,包括浏览器版本和操作系统信息
|
||||
request.UserAgent = objhttpItem.UserAgent;
|
||||
// 编码
|
||||
SetEncoding(objhttpItem);
|
||||
//设置Cookie
|
||||
SetCookie(objhttpItem);
|
||||
//来源地址
|
||||
request.Referer = objhttpItem.Referer;
|
||||
//是否执行跳转功能
|
||||
request.AllowAutoRedirect = objhttpItem.Allowautoredirect;
|
||||
//设置Post数据
|
||||
SetPostData(objhttpItem);
|
||||
//设置最大连接
|
||||
if (objhttpItem.Connectionlimit > 0)
|
||||
{
|
||||
request.ServicePoint.ConnectionLimit = objhttpItem.Connectionlimit;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 设置证书
|
||||
/// </summary>
|
||||
/// <param name="objhttpItem"></param>
|
||||
private void SetCer(HttpItem objhttpItem)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(objhttpItem.CerPath))
|
||||
{
|
||||
//这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
|
||||
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
|
||||
//初始化对像,并设置请求的URL地址
|
||||
request = (HttpWebRequest)WebRequest.Create(GetUrl(objhttpItem.URL));
|
||||
//创建证书文件
|
||||
X509Certificate objx509 = new X509Certificate(objhttpItem.CerPath);
|
||||
//添加到请求里
|
||||
request.ClientCertificates.Add(objx509);
|
||||
}
|
||||
else
|
||||
{
|
||||
//初始化对像,并设置请求的URL地址
|
||||
request = (HttpWebRequest)WebRequest.Create(GetUrl(objhttpItem.URL));
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 设置编码
|
||||
/// </summary>
|
||||
/// <param name="objhttpItem">Http参数</param>
|
||||
private void SetEncoding(HttpItem objhttpItem)
|
||||
{
|
||||
if (string.IsNullOrEmpty(objhttpItem.Encoding) || objhttpItem.Encoding.ToLower().Trim() == "null")
|
||||
{
|
||||
//读取数据时的编码方式
|
||||
encoding = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
//读取数据时的编码方式
|
||||
encoding = System.Text.Encoding.GetEncoding(objhttpItem.Encoding);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 设置Cookie
|
||||
/// </summary>
|
||||
/// <param name="objhttpItem">Http参数</param>
|
||||
private void SetCookie(HttpItem objhttpItem)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(objhttpItem.Cookie))
|
||||
{
|
||||
//Cookie
|
||||
request.Headers[HttpRequestHeader.Cookie] = objhttpItem.Cookie;
|
||||
}
|
||||
//设置Cookie
|
||||
if (objhttpItem.CookieCollection != null)
|
||||
{
|
||||
request.CookieContainer = new CookieContainer();
|
||||
request.CookieContainer.Add(objhttpItem.CookieCollection);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 设置Post数据
|
||||
/// </summary>
|
||||
/// <param name="objhttpItem">Http参数</param>
|
||||
private void SetPostData(HttpItem objhttpItem)
|
||||
{
|
||||
//验证在得到结果时是否有传入数据
|
||||
if (request.Method.Trim().ToLower().Contains("post"))
|
||||
{
|
||||
//写入Byte类型
|
||||
if (objhttpItem.PostDataType == PostDataType.Byte)
|
||||
{
|
||||
//验证在得到结果时是否有传入数据
|
||||
if (objhttpItem.PostdataByte != null && objhttpItem.PostdataByte.Length > 0)
|
||||
{
|
||||
request.ContentLength = objhttpItem.PostdataByte.Length;
|
||||
request.GetRequestStream().Write(objhttpItem.PostdataByte, 0, objhttpItem.PostdataByte.Length);
|
||||
}
|
||||
}//写入文件
|
||||
else if (objhttpItem.PostDataType == PostDataType.FilePath)
|
||||
{
|
||||
StreamReader r = new StreamReader(objhttpItem.Postdata, encoding);
|
||||
byte[] buffer = Encoding.Default.GetBytes(r.ReadToEnd());
|
||||
r.Close();
|
||||
request.ContentLength = buffer.Length;
|
||||
request.GetRequestStream().Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
else
|
||||
{
|
||||
//验证在得到结果时是否有传入数据
|
||||
if (!string.IsNullOrEmpty(objhttpItem.Postdata))
|
||||
{
|
||||
byte[] buffer = Encoding.Default.GetBytes(objhttpItem.Postdata);
|
||||
request.ContentLength = buffer.Length;
|
||||
request.GetRequestStream().Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 设置代理
|
||||
/// </summary>
|
||||
/// <param name="objhttpItem">参数对象</param>
|
||||
private void SetProxy(HttpItem objhttpItem)
|
||||
{
|
||||
if (string.IsNullOrEmpty(objhttpItem.ProxyUserName) && string.IsNullOrEmpty(objhttpItem.ProxyPwd) && string.IsNullOrEmpty(objhttpItem.ProxyIp))
|
||||
{
|
||||
//不需要设置
|
||||
}
|
||||
else
|
||||
{
|
||||
//设置代理服务器
|
||||
WebProxy myProxy = new WebProxy(objhttpItem.ProxyIp, false);
|
||||
//建议连接
|
||||
myProxy.Credentials = new NetworkCredential(objhttpItem.ProxyUserName, objhttpItem.ProxyPwd);
|
||||
//给当前请求对象
|
||||
request.Proxy = myProxy;
|
||||
//设置安全凭证
|
||||
request.Credentials = CredentialCache.DefaultNetworkCredentials;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 回调验证证书问题
|
||||
/// </summary>
|
||||
/// <param name="sender">流对象</param>
|
||||
/// <param name="certificate">证书</param>
|
||||
/// <param name="chain">X509Chain</param>
|
||||
/// <param name="errors">SslPolicyErrors</param>
|
||||
/// <returns>bool</returns>
|
||||
public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
|
||||
{
|
||||
// 总是接受
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 普通类型
|
||||
/// <summary>
|
||||
/// 传入一个正确或不正确的URl,返回正确的URL
|
||||
/// </summary>
|
||||
/// <param name="URL">url</param>
|
||||
/// <returns>
|
||||
/// </returns>
|
||||
public static string GetUrl(string URL)
|
||||
{
|
||||
if (!(URL.Contains("http://") || URL.Contains("https://")))
|
||||
{
|
||||
URL = "http://" + URL;
|
||||
}
|
||||
return URL;
|
||||
}
|
||||
///<summary>
|
||||
///采用https协议访问网络,根据传入的URl地址,得到响应的数据字符串。
|
||||
///</summary>
|
||||
///<param name="objhttpItem">参数列表</param>
|
||||
///<returns>String类型的数据</returns>
|
||||
public HttpResult GetHtml(HttpItem objhttpItem)
|
||||
{
|
||||
//准备参数
|
||||
SetRequest(objhttpItem);
|
||||
//调用专门读取数据的类
|
||||
return GetHttpRequestData(objhttpItem);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
/// <summary>
|
||||
/// Http请求参考类
|
||||
/// </summary>
|
||||
public class HttpItem
|
||||
{
|
||||
string _URL;
|
||||
/// <summary>
|
||||
/// 请求URL必须填写
|
||||
/// </summary>
|
||||
public string URL
|
||||
{
|
||||
get { return _URL; }
|
||||
set { _URL = value; }
|
||||
}
|
||||
string _Method = "GET";
|
||||
/// <summary>
|
||||
/// 请求方式默认为GET方式
|
||||
/// </summary>
|
||||
public string Method
|
||||
{
|
||||
get { return _Method; }
|
||||
set { _Method = value; }
|
||||
}
|
||||
int _Timeout = 100000;
|
||||
/// <summary>
|
||||
/// 默认请求超时时间
|
||||
/// </summary>
|
||||
public int Timeout
|
||||
{
|
||||
get { return _Timeout; }
|
||||
set { _Timeout = value; }
|
||||
}
|
||||
int _ReadWriteTimeout = 30000;
|
||||
/// <summary>
|
||||
/// 默认写入Post数据超时间
|
||||
/// </summary>
|
||||
public int ReadWriteTimeout
|
||||
{
|
||||
get { return _ReadWriteTimeout; }
|
||||
set { _ReadWriteTimeout = value; }
|
||||
}
|
||||
string _Accept = "text/html, application/xhtml+xml, */*";
|
||||
/// <summary>
|
||||
/// 请求标头值 默认为text/html, application/xhtml+xml, */*
|
||||
/// </summary>
|
||||
public string Accept
|
||||
{
|
||||
get { return _Accept; }
|
||||
set { _Accept = value; }
|
||||
}
|
||||
string _ContentType = "text/html";
|
||||
/// <summary>
|
||||
/// 请求返回类型默认 text/html
|
||||
/// </summary>
|
||||
public string ContentType
|
||||
{
|
||||
get { return _ContentType; }
|
||||
set { _ContentType = value; }
|
||||
}
|
||||
string _UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
|
||||
/// <summary>
|
||||
/// 客户端访问信息默认Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
|
||||
/// </summary>
|
||||
public string UserAgent
|
||||
{
|
||||
get { return _UserAgent; }
|
||||
set { _UserAgent = value; }
|
||||
}
|
||||
string _Encoding = string.Empty;
|
||||
/// <summary>
|
||||
/// 返回数据编码默认为NUll,可以自动识别
|
||||
/// </summary>
|
||||
public string Encoding
|
||||
{
|
||||
get { return _Encoding; }
|
||||
set { _Encoding = value; }
|
||||
}
|
||||
private PostDataType _PostDataType = PostDataType.String;
|
||||
/// <summary>
|
||||
/// Post的数据类型
|
||||
/// </summary>
|
||||
public PostDataType PostDataType
|
||||
{
|
||||
get { return _PostDataType; }
|
||||
set { _PostDataType = value; }
|
||||
}
|
||||
string _Postdata;
|
||||
/// <summary>
|
||||
/// Post请求时要发送的字符串Post数据
|
||||
/// </summary>
|
||||
public string Postdata
|
||||
{
|
||||
get { return _Postdata; }
|
||||
set { _Postdata = value; }
|
||||
}
|
||||
private byte[] _PostdataByte = null;
|
||||
/// <summary>
|
||||
/// Post请求时要发送的Byte类型的Post数据
|
||||
/// </summary>
|
||||
public byte[] PostdataByte
|
||||
{
|
||||
get { return _PostdataByte; }
|
||||
set { _PostdataByte = value; }
|
||||
}
|
||||
CookieCollection cookiecollection = null;
|
||||
/// <summary>
|
||||
/// Cookie对象集合
|
||||
/// </summary>
|
||||
public CookieCollection CookieCollection
|
||||
{
|
||||
get { return cookiecollection; }
|
||||
set { cookiecollection = value; }
|
||||
}
|
||||
string _Cookie = string.Empty;
|
||||
/// <summary>
|
||||
/// 请求时的Cookie
|
||||
/// </summary>
|
||||
public string Cookie
|
||||
{
|
||||
get { return _Cookie; }
|
||||
set { _Cookie = value; }
|
||||
}
|
||||
string _Referer = string.Empty;
|
||||
/// <summary>
|
||||
/// 来源地址,上次访问地址
|
||||
/// </summary>
|
||||
public string Referer
|
||||
{
|
||||
get { return _Referer; }
|
||||
set { _Referer = value; }
|
||||
}
|
||||
string _CerPath = string.Empty;
|
||||
/// <summary>
|
||||
/// 证书绝对路径
|
||||
/// </summary>
|
||||
public string CerPath
|
||||
{
|
||||
get { return _CerPath; }
|
||||
set { _CerPath = value; }
|
||||
}
|
||||
private Boolean isToLower = true;
|
||||
/// <summary>
|
||||
/// 是否设置为全文小写
|
||||
/// </summary>
|
||||
public Boolean IsToLower
|
||||
{
|
||||
get { return isToLower; }
|
||||
set { isToLower = value; }
|
||||
}
|
||||
private Boolean allowautoredirect = true;
|
||||
/// <summary>
|
||||
/// 支持跳转页面,查询结果将是跳转后的页面
|
||||
/// </summary>
|
||||
public Boolean Allowautoredirect
|
||||
{
|
||||
get { return allowautoredirect; }
|
||||
set { allowautoredirect = value; }
|
||||
}
|
||||
private int connectionlimit = 1024;
|
||||
/// <summary>
|
||||
/// 最大连接数
|
||||
/// </summary>
|
||||
public int Connectionlimit
|
||||
{
|
||||
get { return connectionlimit; }
|
||||
set { connectionlimit = value; }
|
||||
}
|
||||
private string proxyusername = string.Empty;
|
||||
/// <summary>
|
||||
/// 代理Proxy 服务器用户名
|
||||
/// </summary>
|
||||
public string ProxyUserName
|
||||
{
|
||||
get { return proxyusername; }
|
||||
set { proxyusername = value; }
|
||||
}
|
||||
private string proxypwd = string.Empty;
|
||||
/// <summary>
|
||||
/// 代理 服务器密码
|
||||
/// </summary>
|
||||
public string ProxyPwd
|
||||
{
|
||||
get { return proxypwd; }
|
||||
set { proxypwd = value; }
|
||||
}
|
||||
private string proxyip = string.Empty;
|
||||
/// <summary>
|
||||
/// 代理 服务IP
|
||||
/// </summary>
|
||||
public string ProxyIp
|
||||
{
|
||||
get { return proxyip; }
|
||||
set { proxyip = value; }
|
||||
}
|
||||
private ResultTypes resulttype = ResultTypes.String;
|
||||
/// <summary>
|
||||
/// 设置返回类型String和Byte
|
||||
/// </summary>
|
||||
public ResultTypes ResultType
|
||||
{
|
||||
get { return resulttype; }
|
||||
set { resulttype = value; }
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Http返回参数类
|
||||
/// </summary>
|
||||
public class HttpResult
|
||||
{
|
||||
string _Cookie = string.Empty;
|
||||
/// <summary>
|
||||
/// Http请求返回的Cookie
|
||||
/// </summary>
|
||||
public string Cookie
|
||||
{
|
||||
get { return _Cookie; }
|
||||
set { _Cookie = value; }
|
||||
}
|
||||
CookieCollection cookiecollection = null;
|
||||
/// <summary>
|
||||
/// Cookie对象集合
|
||||
/// </summary>
|
||||
public CookieCollection CookieCollection
|
||||
{
|
||||
get { return cookiecollection; }
|
||||
set { cookiecollection = value; }
|
||||
}
|
||||
private string html = string.Empty;
|
||||
/// <summary>
|
||||
/// 返回的String类型数据 只有ResultType.String时才返回数据,其它情况为空
|
||||
/// </summary>
|
||||
public string Html
|
||||
{
|
||||
get { return html; }
|
||||
set { html = value; }
|
||||
}
|
||||
private byte[] resultbyte = null;
|
||||
/// <summary>
|
||||
/// 返回的Byte数组 只有ResultType.Byte时才返回数据,其它情况为空
|
||||
/// </summary>
|
||||
public byte[] ResultByte
|
||||
{
|
||||
|
||||
get { return resultbyte; }
|
||||
set { resultbyte = value; }
|
||||
}
|
||||
private WebHeaderCollection header = new WebHeaderCollection();
|
||||
//header对象
|
||||
public WebHeaderCollection Header
|
||||
{
|
||||
get { return header; }
|
||||
set { header = value; }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回类型
|
||||
/// </summary>
|
||||
public enum ResultTypes
|
||||
{
|
||||
String,//表示只返回字符串
|
||||
Byte//表示返回字符串和字节流
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Post的数据格式默认为string
|
||||
/// </summary>
|
||||
public enum PostDataType
|
||||
{
|
||||
String,//字符串
|
||||
Byte,//字符串和字节流
|
||||
FilePath//表示传入的是文件
|
||||
}
|
||||
}
|
||||
133
WaterCloud.Code/JsonHelper.cs
Normal file
133
WaterCloud.Code/JsonHelper.cs
Normal file
@ -0,0 +1,133 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
#region JsonHelper
|
||||
public static class JsonHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 把数组转为逗号连接的字符串
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <param name="Str"></param>
|
||||
/// <returns></returns>
|
||||
public static string ArrayToString(dynamic data, string Str)
|
||||
{
|
||||
string resStr = Str;
|
||||
foreach (var item in data)
|
||||
{
|
||||
if (resStr != "")
|
||||
{
|
||||
resStr += ",";
|
||||
}
|
||||
|
||||
if (item is string)
|
||||
{
|
||||
resStr += item;
|
||||
}
|
||||
else
|
||||
{
|
||||
resStr += item.Value;
|
||||
|
||||
}
|
||||
}
|
||||
return resStr;
|
||||
}
|
||||
public static object ToObject(this string Json)
|
||||
{
|
||||
return string.IsNullOrEmpty(Json) ? null : JsonConvert.DeserializeObject(Json);
|
||||
}
|
||||
public static T ToObject<T>(this string Json)
|
||||
{
|
||||
if (string.IsNullOrEmpty(Json))
|
||||
{
|
||||
return default(T);
|
||||
}
|
||||
Json = Json.Replace(" ", "");
|
||||
return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
|
||||
}
|
||||
|
||||
public static JObject ToJObject(this string Json)
|
||||
{
|
||||
return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace(" ", ""));
|
||||
}
|
||||
public static List<T> ToList<T>(this string Json)
|
||||
{
|
||||
return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);
|
||||
}
|
||||
public static string ToJson(this object obj, string dateFormat = "yyyy/MM/dd HH:mm:ss")
|
||||
{
|
||||
return obj == null ? string.Empty : JsonConvert.SerializeObject(obj, new IsoDateTimeConverter { DateTimeFormat = dateFormat });
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region JsonConverter
|
||||
/// <summary>
|
||||
/// Json数据返回到前端js的时候,把数值很大的long类型转成字符串
|
||||
/// </summary>
|
||||
public class StringJsonConverter : JsonConverter
|
||||
{
|
||||
public StringJsonConverter() { }
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
return reader.Value.ToLong();
|
||||
}
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
writer.WriteNull();
|
||||
return;
|
||||
}
|
||||
string sValue = value.ToString();
|
||||
writer.WriteValue(sValue);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DateTime类型序列化的时候,转成指定的格式
|
||||
/// </summary>
|
||||
public class DateTimeJsonConverter : JsonConverter
|
||||
{
|
||||
public DateTimeJsonConverter() { }
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
return reader.Value.ParseToString().ToDate();
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
writer.WriteNull();
|
||||
return;
|
||||
}
|
||||
DateTime? dt = value as DateTime?;
|
||||
if (dt == null)
|
||||
{
|
||||
writer.WriteNull();
|
||||
return;
|
||||
}
|
||||
writer.WriteValue(dt.Value.ToString("yyyy/MM/dd HH:mm:ss"));
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
47
WaterCloud.Code/LayUI/FilterSo.cs
Normal file
47
WaterCloud.Code/LayUI/FilterSo.cs
Normal file
@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class FilterSo
|
||||
{
|
||||
/**
|
||||
* 唯一id
|
||||
*/
|
||||
public long id { get; set; }
|
||||
/**
|
||||
* 前缀 and、or
|
||||
*/
|
||||
public string prefix { get; set; }
|
||||
/**
|
||||
* 模式 in、condition、date
|
||||
*/
|
||||
public string mode { get; set; }
|
||||
/**
|
||||
* 字段名
|
||||
*/
|
||||
public string field { get; set; }
|
||||
/**
|
||||
* 筛选类型
|
||||
*/
|
||||
public string type { get; set; }
|
||||
/**
|
||||
* 是否有分隔符
|
||||
*/
|
||||
public string split { get; set; }
|
||||
/**
|
||||
* 筛选值
|
||||
*/
|
||||
public string value { get; set; }
|
||||
/**
|
||||
* 筛选值
|
||||
*/
|
||||
public List<string> values { get; set; }
|
||||
|
||||
/**
|
||||
* 子组数据
|
||||
*/
|
||||
public List<FilterSo> children { get; set; }
|
||||
}
|
||||
}
|
||||
206
WaterCloud.Code/LayUI/SoulPage.cs
Normal file
206
WaterCloud.Code/LayUI/SoulPage.cs
Normal file
@ -0,0 +1,206 @@
|
||||
using Serenity;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
///封装table查询数据
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class SoulPage<T>
|
||||
{
|
||||
/**
|
||||
* layui表格必须参数⬇⬇⬇⬇⬇⬇
|
||||
*/
|
||||
public int state { get; set; }
|
||||
public string message { get; set; }
|
||||
/**
|
||||
* 总记录
|
||||
*/
|
||||
public int count { get; set; }
|
||||
/**
|
||||
* 显示的记录
|
||||
*/
|
||||
public List<T> data { get; set; }
|
||||
|
||||
/**
|
||||
* 请求条件
|
||||
*/
|
||||
public object obj { get; set; }
|
||||
/**
|
||||
* 查询条件
|
||||
*/
|
||||
public Dictionary<string, object> condition = new Dictionary<string, object>();
|
||||
/**
|
||||
* 请求参数⬇⬇⬇⬇⬇⬇
|
||||
*/
|
||||
/**
|
||||
* 当前页 从1开始
|
||||
*/
|
||||
public int page { get; set; }
|
||||
/**
|
||||
* 页大小
|
||||
*/
|
||||
public int rows { get; set; }
|
||||
/**
|
||||
* 查询列数据
|
||||
*/
|
||||
public string columns { get; set; }
|
||||
|
||||
/**
|
||||
* 表格列类型
|
||||
*/
|
||||
public string tableFilterType { get; set; }
|
||||
/**
|
||||
* 筛选信息
|
||||
*/
|
||||
public string filterSos { get; set; }
|
||||
|
||||
/**
|
||||
* 排序信息
|
||||
*/
|
||||
public string field { get; set; }
|
||||
|
||||
public string order { get; set; }
|
||||
|
||||
public SoulPage()
|
||||
{
|
||||
this.state = 0;
|
||||
this.message = "";
|
||||
this.page = 1;
|
||||
this.rows = 100000000;
|
||||
this.order = "asc";
|
||||
}
|
||||
public SoulPage(int page, int limit)
|
||||
{
|
||||
this.state = 0;
|
||||
this.message = "";
|
||||
this.page = 1;
|
||||
this.rows = 100000000;
|
||||
this.order = "asc";
|
||||
this.page = page;
|
||||
this.rows = limit;
|
||||
}
|
||||
|
||||
public List<FilterSo> getFilterSos()
|
||||
{
|
||||
if (string.IsNullOrEmpty(filterSos))
|
||||
{
|
||||
return new List<FilterSo>();
|
||||
}
|
||||
return filterSos.ToObject<List<FilterSo>>();
|
||||
}
|
||||
public bool isColumn()
|
||||
{
|
||||
return getColumns().Count > 0;
|
||||
}
|
||||
public int getOffset()
|
||||
{
|
||||
return (page - 1) * rows;
|
||||
}
|
||||
public List<string> getColumns()
|
||||
{
|
||||
return !string.IsNullOrEmpty(columns) ? columns.ToObject<List<string>>() : new List<string>();
|
||||
}
|
||||
private string dateFormat(DateTime date, string format)
|
||||
{
|
||||
if (string.IsNullOrEmpty(format))
|
||||
{
|
||||
return date.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
else
|
||||
{
|
||||
return date.ToString(format);
|
||||
}
|
||||
}
|
||||
public Dictionary<string, Dictionary<string, string>> getTypeMap()
|
||||
{
|
||||
Dictionary<string, Dictionary<string, string>> typeMap = new Dictionary<string, Dictionary<string, string>>();
|
||||
if (!string.IsNullOrEmpty(tableFilterType))
|
||||
{
|
||||
Dictionary<string, string> filterType = tableFilterType.ToObject<Dictionary<string, string>>();
|
||||
foreach (var item in filterType)
|
||||
{
|
||||
Dictionary<string, string> map = new Dictionary<string, string>();
|
||||
map.Add("type", item.Value.Substring(0, item.Value.IndexOf("[")));
|
||||
int IndexofA = item.Value.IndexOf('['); //字符串的话总以第一位为指定位置
|
||||
int IndexofB = item.Value.IndexOf(']');
|
||||
map.Add("value", item.Value.Substring(IndexofA + 1, IndexofB - IndexofA - 1));
|
||||
typeMap.Add(item.Key, map);
|
||||
};
|
||||
|
||||
}
|
||||
return typeMap;
|
||||
}
|
||||
public string getFormatValue(Dictionary<string, Dictionary<string, string>> typeMap, string column, object columnObject)
|
||||
{
|
||||
string columnValue;
|
||||
if (typeMap.ContainsKey(column))
|
||||
{
|
||||
if ("date".Equals(typeMap.Get(column).Get("type")) && columnObject is DateTime)
|
||||
{
|
||||
columnValue = dateFormat((DateTime)columnObject, typeMap.Get(column).Get("value"));
|
||||
}
|
||||
else
|
||||
{
|
||||
columnValue = columnObject.ToString();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (columnObject is DateTime|| columnObject is Nullable<DateTime>)
|
||||
{
|
||||
columnValue = dateFormat((DateTime)columnObject, null);
|
||||
}
|
||||
else if (columnObject is bool|| columnObject is Nullable<bool>)
|
||||
{
|
||||
columnValue = (bool)columnObject==true?"1":"0";
|
||||
}
|
||||
else
|
||||
{
|
||||
columnValue = columnObject.ToString();
|
||||
}
|
||||
}
|
||||
return columnValue;
|
||||
}
|
||||
public Object setData(List<T> data)
|
||||
{
|
||||
if (isColumn())
|
||||
{
|
||||
Dictionary<string, Dictionary<string, string>> typeMap = getTypeMap();
|
||||
Dictionary<string, HashSet<string>> columnMap = new Dictionary<string, HashSet<string>>();
|
||||
foreach (T datum in data)
|
||||
{
|
||||
foreach (string column in getColumns())
|
||||
{
|
||||
if (!columnMap.ContainsKey(column))
|
||||
{
|
||||
columnMap.Add(column, new HashSet<string>());
|
||||
}
|
||||
var columnObject = ReflectionHelper.GetObjectPropertyValue(datum, column);
|
||||
if (columnObject!=null)
|
||||
{ //空值不展示
|
||||
columnMap.Get(column).Add(getFormatValue(typeMap, column, columnObject));
|
||||
}
|
||||
}
|
||||
}
|
||||
Dictionary<string, List<string>> columnSortMap = new Dictionary<string, List<string>>();
|
||||
foreach (var item in columnMap)
|
||||
{
|
||||
columnSortMap.Add(item.Key, item.Value.ToList());
|
||||
}
|
||||
return columnSortMap;
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
this.data = data;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
74
WaterCloud.Code/LayUI/TableCols.cs
Normal file
74
WaterCloud.Code/LayUI/TableCols.cs
Normal file
@ -0,0 +1,74 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// LayUI Table 列
|
||||
/// </summary>
|
||||
public class TableCols
|
||||
{
|
||||
/// <summary>
|
||||
/// 类型(normal(常规列)、checkbox(复选框)、radio(单选框)、numbers(序号)、space(空))
|
||||
/// </summary>
|
||||
public string type { get; set; }
|
||||
/// <summary>
|
||||
/// 字段
|
||||
/// </summary>
|
||||
public string field { get; set; }
|
||||
/// <summary>
|
||||
/// 标题
|
||||
/// </summary>
|
||||
public string title { get; set; }
|
||||
/// <summary>
|
||||
/// 宽度
|
||||
/// </summary>
|
||||
public int? width { get; set; }
|
||||
/// <summary>
|
||||
/// 最小宽度
|
||||
/// </summary>
|
||||
public int? minWidth { get; set; }
|
||||
/// <summary>
|
||||
/// 是否全选
|
||||
/// </summary>
|
||||
public bool? LAY_CHECKED { get; set; }
|
||||
/// <summary>
|
||||
/// 固定列
|
||||
/// </summary>
|
||||
public string Fixed { get; set; }
|
||||
/// <summary>
|
||||
/// 隐藏
|
||||
/// </summary>
|
||||
public string hide { get; set; }
|
||||
/// <summary>
|
||||
/// 排序
|
||||
/// </summary>
|
||||
public bool? sort { get; set; }
|
||||
/// <summary>
|
||||
/// 是否禁用拖到列
|
||||
/// </summary>
|
||||
public bool? unresize { get; set; }
|
||||
/// <summary>
|
||||
/// 样式
|
||||
/// </summary>
|
||||
public string style { get; set; }
|
||||
/// <summary>
|
||||
/// 对齐方式
|
||||
/// </summary>
|
||||
public string align { get; set; }
|
||||
/// <summary>
|
||||
/// 所占列数
|
||||
/// </summary>
|
||||
public int? colspan { get; set; }
|
||||
/// <summary>
|
||||
/// 所占行数
|
||||
/// </summary>
|
||||
public int? rowspan { get; set; }
|
||||
/// <summary>
|
||||
/// 绑定工具栏模板
|
||||
/// </summary>
|
||||
public string toolbar { get; set; }
|
||||
|
||||
}
|
||||
}
|
||||
243
WaterCloud.Code/LogHelper.cs
Normal file
243
WaterCloud.Code/LogHelper.cs
Normal file
@ -0,0 +1,243 @@
|
||||
using Microsoft.AspNetCore.Http.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class LogHelper
|
||||
{
|
||||
private static object lockHelper = new object();
|
||||
|
||||
#region 写文本日志
|
||||
/// <summary>
|
||||
/// 写日志 异步
|
||||
/// 默认路径:根目录/Log/yyyy-MM/
|
||||
/// 默认文件:yyyy-MM-dd.log
|
||||
/// </summary>
|
||||
/// <param name="logContent">日志内容 自动附加时间</param>
|
||||
public static void Write(string logContent)
|
||||
{
|
||||
string logPath = DateTime.Now.ToString("yyyy-MM");
|
||||
Write(logPath, logContent);
|
||||
}
|
||||
|
||||
public static void WriteWithTime(string logContent)
|
||||
{
|
||||
string logPath = DateTime.Now.ToString("yyyy-MM");
|
||||
logContent = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine + logContent;
|
||||
Write(logPath, logContent);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 写异常日志
|
||||
/// <summary>
|
||||
/// 写异常日志
|
||||
/// </summary>
|
||||
/// <param name="ex"></param>
|
||||
public static void Write(Exception ex)
|
||||
{
|
||||
string logContent = string.Empty;
|
||||
string logPath = DateTime.Now.ToString("yyyy-MM");
|
||||
logContent += GetExceptionMessage(ex);
|
||||
Write(logPath, logContent);
|
||||
}
|
||||
|
||||
public static void WriteWithTime(Exception ex)
|
||||
{
|
||||
string logContent = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine;
|
||||
string logPath = DateTime.Now.ToString("yyyy-MM");
|
||||
logContent += GetExceptionMessage(ex);
|
||||
Write(logPath, logContent);
|
||||
}
|
||||
public static void WriteWithTime(ExceptionContext ex)
|
||||
{
|
||||
if (ex == null)
|
||||
return;
|
||||
string logContent = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine;
|
||||
logContent += "程序异常" + Environment.NewLine;
|
||||
string logPath = DateTime.Now.ToString("yyyy-MM");
|
||||
Exception Error = ex.Exception;
|
||||
LogMessage logMessage = new LogMessage();
|
||||
logMessage.OperationTime = DateTime.Now;
|
||||
logMessage.Url = ex.HttpContext.Request.GetDisplayUrl();
|
||||
if (ex.ActionDescriptor!=null)
|
||||
{
|
||||
logMessage.Class = ex.ActionDescriptor.DisplayName;
|
||||
}
|
||||
else
|
||||
{
|
||||
logMessage.Class = "服务器配置问题";
|
||||
}
|
||||
logMessage.Ip = WebHelper.Ip;
|
||||
logMessage.Host = ex.HttpContext.Request.Host.ToString();
|
||||
var current = OperatorProvider.Provider.GetCurrent();
|
||||
if (current != null)
|
||||
{
|
||||
logMessage.UserName = current.UserCode + "(" + current.UserName + ")";
|
||||
}
|
||||
var err= Error.GetOriginalException();
|
||||
logMessage.ExceptionInfo = err.Message;
|
||||
logMessage.ExceptionSource = err.Source;
|
||||
logMessage.ExceptionRemark = err.StackTrace;
|
||||
logContent+= ExceptionFormat(logMessage);
|
||||
Write(logPath, logContent);
|
||||
}
|
||||
private static string GetExceptionMessage(Exception ex)
|
||||
{
|
||||
string message = string.Empty;
|
||||
if (ex != null)
|
||||
{
|
||||
message += ex.Message;
|
||||
message += Environment.NewLine;
|
||||
Exception originalException = ex.GetOriginalException();
|
||||
if (originalException != null)
|
||||
{
|
||||
if (originalException.Message != ex.Message)
|
||||
{
|
||||
message += originalException.Message;
|
||||
message += Environment.NewLine;
|
||||
}
|
||||
}
|
||||
message += ex.StackTrace;
|
||||
message += Environment.NewLine;
|
||||
}
|
||||
return message;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 写日志到指定路径
|
||||
/// <summary>
|
||||
/// 写日志 异步
|
||||
/// 默认文件:yyyy-MM-dd.log
|
||||
/// </summary>
|
||||
/// <param name="logPath">日志目录[默认程序根目录\Log\下添加,故使用相对路径,如:营销任务]</param>
|
||||
/// <param name="logContent">日志内容 自动附加时间</param>
|
||||
public static void Write(string logPath, string logContent)
|
||||
{
|
||||
string logFileName = DateTime.Now.ToString("yyyy-MM-dd") + ".log";
|
||||
Write(logPath, logFileName, logContent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写日志 异步
|
||||
/// </summary>
|
||||
/// <param name="logPath">日志目录</param>
|
||||
/// <param name="logFileName">日志文件名</param>
|
||||
/// <param name="logContent">日志内容 自动附加时间</param>
|
||||
public static void Write(string logPath, string logFileName, string logContent)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(logContent))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(logPath))
|
||||
{
|
||||
logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", DateTime.Now.ToString("yyyy-MM"));
|
||||
}
|
||||
else
|
||||
{
|
||||
logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", logPath.Trim('\\'));
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(logFileName))
|
||||
{
|
||||
logFileName = DateTime.Now.ToString("yyyy-MM-dd") + ".log";
|
||||
}
|
||||
if (!Directory.Exists(logPath))
|
||||
{
|
||||
Directory.CreateDirectory(logPath);
|
||||
}
|
||||
string fileName = Path.Combine(logPath, logFileName);
|
||||
Action taskAction = () =>
|
||||
{
|
||||
lock (lockHelper)
|
||||
{
|
||||
using (StreamWriter sw = File.AppendText(fileName))
|
||||
{
|
||||
sw.WriteLine(logContent + Environment.NewLine);
|
||||
sw.Flush();
|
||||
sw.Close();
|
||||
}
|
||||
}
|
||||
};
|
||||
Task task = new Task(taskAction);
|
||||
task.Start();
|
||||
}
|
||||
/// <summary>
|
||||
/// 生成异常信息
|
||||
/// </summary>
|
||||
/// <param name="logMessage">对象</param>
|
||||
/// <returns></returns>
|
||||
public static string ExceptionFormat(LogMessage logMessage)
|
||||
{
|
||||
StringBuilder strInfo = new StringBuilder();
|
||||
strInfo.Append("1. 调试: >> 操作时间: " + logMessage.OperationTime + " 操作人: " + logMessage.UserName + " \r\n");
|
||||
strInfo.Append("2. 地址: " + logMessage.Url + " \r\n");
|
||||
strInfo.Append("3. 类名: " + logMessage.Class + " \r\n");
|
||||
strInfo.Append("4. 主机: " + logMessage.Host + " Ip : " + logMessage.Ip + " \r\n");
|
||||
strInfo.Append("5. 异常: " + logMessage.ExceptionInfo + "\r\n");
|
||||
strInfo.Append("6. 来源: " + logMessage.ExceptionSource + "\r\n");
|
||||
strInfo.Append("7. 实例: " + logMessage.ExceptionRemark + "\r\n");
|
||||
strInfo.Append("-----------------------------------------------------------------------------------------------------------------------------\r\n");
|
||||
return strInfo.ToString();
|
||||
}
|
||||
/// <summary>
|
||||
/// 格式化异常信息
|
||||
/// </summary>
|
||||
/// <param name="logMessage">对象</param>
|
||||
/// <returns></returns>
|
||||
public static string ExMsgFormat(string message)
|
||||
{
|
||||
//数据库异常
|
||||
if (message.Contains("An exception occurred while executing DbCommand."))
|
||||
{
|
||||
if (message.Contains("Duplicate entry '")&& message.Contains("key"))
|
||||
{
|
||||
message = "数据违反唯一约束,请检查";
|
||||
}
|
||||
else if (message.Contains("Data too long for column"))
|
||||
{
|
||||
|
||||
message = "数据长度过长,请检查";
|
||||
}
|
||||
else
|
||||
{
|
||||
message = "数据操作异常,请联系管理员";
|
||||
}
|
||||
}
|
||||
//其他异常
|
||||
else
|
||||
{
|
||||
if (message.Contains("Object reference not set to an instance of an object."))
|
||||
{
|
||||
message="操作对象为空,请联系管理员";
|
||||
}
|
||||
else if (message.Contains("Value cannot be null"))
|
||||
{
|
||||
message = "值为空,请联系管理员";
|
||||
}
|
||||
}
|
||||
if (!IsHasCHZN(message))
|
||||
{
|
||||
message = "程序内部异常,请联系管理员";
|
||||
}
|
||||
return message;
|
||||
}
|
||||
/// <summary>
|
||||
/// 检测是否有中文字符
|
||||
/// </summary>
|
||||
/// <param name="inputData"></param>
|
||||
/// <returns></returns>
|
||||
private static bool IsHasCHZN(string inputData)
|
||||
{
|
||||
|
||||
Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");
|
||||
Match m = RegCHZN.Match(inputData);
|
||||
return m.Success;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
50
WaterCloud.Code/LogMessage.cs
Normal file
50
WaterCloud.Code/LogMessage.cs
Normal file
@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class LogMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// 操作时间
|
||||
/// </summary>
|
||||
public DateTime OperationTime { get; set; }
|
||||
/// <summary>
|
||||
/// Url地址
|
||||
/// </summary>
|
||||
public string Url { get; set; }
|
||||
/// <summary>
|
||||
/// 类名
|
||||
/// </summary>
|
||||
public string Class { get; set; }
|
||||
/// <summary>
|
||||
/// IP
|
||||
/// </summary>
|
||||
public string Ip { get; set; }
|
||||
/// <summary>
|
||||
/// 主机
|
||||
/// </summary>
|
||||
public string Host { get; set; }
|
||||
/// <summary>
|
||||
/// 操作人
|
||||
/// </summary>
|
||||
public string UserName { get; set; }
|
||||
/// <summary>
|
||||
/// 内容
|
||||
/// </summary>
|
||||
public string Content { get; set; }
|
||||
/// <summary>
|
||||
/// 异常信息
|
||||
/// </summary>
|
||||
public string ExceptionInfo { get; set; }
|
||||
/// <summary>
|
||||
/// 异常来源
|
||||
/// </summary>
|
||||
public string ExceptionSource { get; set; }
|
||||
/// <summary>
|
||||
/// 异常信息备注
|
||||
/// </summary>
|
||||
public string ExceptionRemark { get; set; }
|
||||
}
|
||||
}
|
||||
237
WaterCloud.Code/MimeMapping.cs
Normal file
237
WaterCloud.Code/MimeMapping.cs
Normal file
@ -0,0 +1,237 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
// 通过自己定义一个静态类
|
||||
// 将所有的Content Type都扔进去吧
|
||||
// 调用的时候直接调用静态方法即可。
|
||||
public static class MimeMapping
|
||||
{
|
||||
private static Hashtable _mimeMappingTable;
|
||||
|
||||
private static void AddMimeMapping(string extension, string MimeType)
|
||||
{
|
||||
MimeMapping._mimeMappingTable.Add(extension, MimeType);
|
||||
}
|
||||
|
||||
public static string GetMimeMapping(string FileName)
|
||||
{
|
||||
string text = null;
|
||||
int num = FileName.LastIndexOf('.');
|
||||
if (0 < num && num > FileName.LastIndexOf('\\'))
|
||||
{
|
||||
text = (string)MimeMapping._mimeMappingTable[FileName.Substring(num)];
|
||||
}
|
||||
if (text == null)
|
||||
{
|
||||
text = (string)MimeMapping._mimeMappingTable[".*"];
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
static MimeMapping()
|
||||
{
|
||||
MimeMapping._mimeMappingTable = new Hashtable(190, StringComparer.CurrentCultureIgnoreCase);
|
||||
MimeMapping.AddMimeMapping(".323", "text/h323");
|
||||
MimeMapping.AddMimeMapping(".asx", "video/x-ms-asf");
|
||||
MimeMapping.AddMimeMapping(".acx", "application/internet-property-stream");
|
||||
MimeMapping.AddMimeMapping(".ai", "application/postscript");
|
||||
MimeMapping.AddMimeMapping(".aif", "audio/x-aiff");
|
||||
MimeMapping.AddMimeMapping(".aiff", "audio/aiff");
|
||||
MimeMapping.AddMimeMapping(".axs", "application/olescript");
|
||||
MimeMapping.AddMimeMapping(".aifc", "audio/aiff");
|
||||
MimeMapping.AddMimeMapping(".asr", "video/x-ms-asf");
|
||||
MimeMapping.AddMimeMapping(".avi", "video/x-msvideo");
|
||||
MimeMapping.AddMimeMapping(".asf", "video/x-ms-asf");
|
||||
MimeMapping.AddMimeMapping(".au", "audio/basic");
|
||||
MimeMapping.AddMimeMapping(".application", "application/x-ms-application");
|
||||
MimeMapping.AddMimeMapping(".bin", "application/octet-stream");
|
||||
MimeMapping.AddMimeMapping(".bas", "text/plain");
|
||||
MimeMapping.AddMimeMapping(".bcpio", "application/x-bcpio");
|
||||
MimeMapping.AddMimeMapping(".bmp", "image/bmp");
|
||||
MimeMapping.AddMimeMapping(".cdf", "application/x-cdf");
|
||||
MimeMapping.AddMimeMapping(".cat", "application/vndms-pkiseccat");
|
||||
MimeMapping.AddMimeMapping(".crt", "application/x-x509-ca-cert");
|
||||
MimeMapping.AddMimeMapping(".c", "text/plain");
|
||||
MimeMapping.AddMimeMapping(".css", "text/css");
|
||||
MimeMapping.AddMimeMapping(".cer", "application/x-x509-ca-cert");
|
||||
MimeMapping.AddMimeMapping(".crl", "application/pkix-crl");
|
||||
MimeMapping.AddMimeMapping(".cmx", "image/x-cmx");
|
||||
MimeMapping.AddMimeMapping(".csh", "application/x-csh");
|
||||
MimeMapping.AddMimeMapping(".cod", "image/cis-cod");
|
||||
MimeMapping.AddMimeMapping(".cpio", "application/x-cpio");
|
||||
MimeMapping.AddMimeMapping(".clp", "application/x-msclip");
|
||||
MimeMapping.AddMimeMapping(".crd", "application/x-mscardfile");
|
||||
MimeMapping.AddMimeMapping(".deploy", "application/octet-stream");
|
||||
MimeMapping.AddMimeMapping(".dll", "application/x-msdownload");
|
||||
MimeMapping.AddMimeMapping(".dot", "application/msword");
|
||||
MimeMapping.AddMimeMapping(".doc", "application/msword");
|
||||
MimeMapping.AddMimeMapping(".dvi", "application/x-dvi");
|
||||
MimeMapping.AddMimeMapping(".dir", "application/x-director");
|
||||
MimeMapping.AddMimeMapping(".dxr", "application/x-director");
|
||||
MimeMapping.AddMimeMapping(".der", "application/x-x509-ca-cert");
|
||||
MimeMapping.AddMimeMapping(".dib", "image/bmp");
|
||||
MimeMapping.AddMimeMapping(".dcr", "application/x-director");
|
||||
MimeMapping.AddMimeMapping(".disco", "text/xml");
|
||||
MimeMapping.AddMimeMapping(".exe", "application/octet-stream");
|
||||
MimeMapping.AddMimeMapping(".etx", "text/x-setext");
|
||||
MimeMapping.AddMimeMapping(".evy", "application/envoy");
|
||||
MimeMapping.AddMimeMapping(".eml", "message/rfc822");
|
||||
MimeMapping.AddMimeMapping(".eps", "application/postscript");
|
||||
MimeMapping.AddMimeMapping(".flr", "x-world/x-vrml");
|
||||
MimeMapping.AddMimeMapping(".fif", "application/fractals");
|
||||
MimeMapping.AddMimeMapping(".gtar", "application/x-gtar");
|
||||
MimeMapping.AddMimeMapping(".gif", "image/gif");
|
||||
MimeMapping.AddMimeMapping(".gz", "application/x-gzip");
|
||||
MimeMapping.AddMimeMapping(".hta", "application/hta");
|
||||
MimeMapping.AddMimeMapping(".htc", "text/x-component");
|
||||
MimeMapping.AddMimeMapping(".htt", "text/webviewhtml");
|
||||
MimeMapping.AddMimeMapping(".h", "text/plain");
|
||||
MimeMapping.AddMimeMapping(".hdf", "application/x-hdf");
|
||||
MimeMapping.AddMimeMapping(".hlp", "application/winhlp");
|
||||
MimeMapping.AddMimeMapping(".html", "text/html");
|
||||
MimeMapping.AddMimeMapping(".htm", "text/html");
|
||||
MimeMapping.AddMimeMapping(".hqx", "application/mac-binhex40");
|
||||
MimeMapping.AddMimeMapping(".isp", "application/x-internet-signup");
|
||||
MimeMapping.AddMimeMapping(".iii", "application/x-iphone");
|
||||
MimeMapping.AddMimeMapping(".ief", "image/ief");
|
||||
MimeMapping.AddMimeMapping(".ivf", "video/x-ivf");
|
||||
MimeMapping.AddMimeMapping(".ins", "application/x-internet-signup");
|
||||
MimeMapping.AddMimeMapping(".ico", "image/x-icon");
|
||||
MimeMapping.AddMimeMapping(".jpg", "image/jpeg");
|
||||
MimeMapping.AddMimeMapping(".jfif", "image/pjpeg");
|
||||
MimeMapping.AddMimeMapping(".jpe", "image/jpeg");
|
||||
MimeMapping.AddMimeMapping(".jpeg", "image/jpeg");
|
||||
MimeMapping.AddMimeMapping(".js", "application/x-javascript");
|
||||
MimeMapping.AddMimeMapping(".lsx", "video/x-la-asf");
|
||||
MimeMapping.AddMimeMapping(".latex", "application/x-latex");
|
||||
MimeMapping.AddMimeMapping(".lsf", "video/x-la-asf");
|
||||
MimeMapping.AddMimeMapping(".manifest", "application/x-ms-manifest");
|
||||
MimeMapping.AddMimeMapping(".mhtml", "message/rfc822");
|
||||
MimeMapping.AddMimeMapping(".mny", "application/x-msmoney");
|
||||
MimeMapping.AddMimeMapping(".mht", "message/rfc822");
|
||||
MimeMapping.AddMimeMapping(".mid", "audio/mid");
|
||||
MimeMapping.AddMimeMapping(".mpv2", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".man", "application/x-troff-man");
|
||||
MimeMapping.AddMimeMapping(".mvb", "application/x-msmediaview");
|
||||
MimeMapping.AddMimeMapping(".mpeg", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".m3u", "audio/x-mpegurl");
|
||||
MimeMapping.AddMimeMapping(".mdb", "application/x-msaccess");
|
||||
MimeMapping.AddMimeMapping(".mpp", "application/vnd.ms-project");
|
||||
MimeMapping.AddMimeMapping(".m1v", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".mpa", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".me", "application/x-troff-me");
|
||||
MimeMapping.AddMimeMapping(".m13", "application/x-msmediaview");
|
||||
MimeMapping.AddMimeMapping(".movie", "video/x-sgi-movie");
|
||||
MimeMapping.AddMimeMapping(".m14", "application/x-msmediaview");
|
||||
MimeMapping.AddMimeMapping(".mpe", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".mp2", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".mov", "video/quicktime");
|
||||
MimeMapping.AddMimeMapping(".mp3", "audio/mpeg");
|
||||
MimeMapping.AddMimeMapping(".mpg", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".ms", "application/x-troff-ms");
|
||||
MimeMapping.AddMimeMapping(".nc", "application/x-netcdf");
|
||||
MimeMapping.AddMimeMapping(".nws", "message/rfc822");
|
||||
MimeMapping.AddMimeMapping(".oda", "application/oda");
|
||||
MimeMapping.AddMimeMapping(".ods", "application/oleobject");
|
||||
MimeMapping.AddMimeMapping(".pmc", "application/x-perfmon");
|
||||
MimeMapping.AddMimeMapping(".p7r", "application/x-pkcs7-certreqresp");
|
||||
MimeMapping.AddMimeMapping(".p7b", "application/x-pkcs7-certificates");
|
||||
MimeMapping.AddMimeMapping(".p7s", "application/pkcs7-signature");
|
||||
MimeMapping.AddMimeMapping(".pmw", "application/x-perfmon");
|
||||
MimeMapping.AddMimeMapping(".ps", "application/postscript");
|
||||
MimeMapping.AddMimeMapping(".p7c", "application/pkcs7-mime");
|
||||
MimeMapping.AddMimeMapping(".pbm", "image/x-portable-bitmap");
|
||||
MimeMapping.AddMimeMapping(".ppm", "image/x-portable-pixmap");
|
||||
MimeMapping.AddMimeMapping(".pub", "application/x-mspublisher");
|
||||
MimeMapping.AddMimeMapping(".pnm", "image/x-portable-anymap");
|
||||
MimeMapping.AddMimeMapping(".png", "image/png");
|
||||
MimeMapping.AddMimeMapping(".pml", "application/x-perfmon");
|
||||
MimeMapping.AddMimeMapping(".p10", "application/pkcs10");
|
||||
MimeMapping.AddMimeMapping(".pfx", "application/x-pkcs12");
|
||||
MimeMapping.AddMimeMapping(".p12", "application/x-pkcs12");
|
||||
MimeMapping.AddMimeMapping(".pdf", "application/pdf");
|
||||
MimeMapping.AddMimeMapping(".pps", "application/vnd.ms-powerpoint");
|
||||
MimeMapping.AddMimeMapping(".p7m", "application/pkcs7-mime");
|
||||
MimeMapping.AddMimeMapping(".pko", "application/vndms-pkipko");
|
||||
MimeMapping.AddMimeMapping(".ppt", "application/vnd.ms-powerpoint");
|
||||
MimeMapping.AddMimeMapping(".pmr", "application/x-perfmon");
|
||||
MimeMapping.AddMimeMapping(".pma", "application/x-perfmon");
|
||||
MimeMapping.AddMimeMapping(".pot", "application/vnd.ms-powerpoint");
|
||||
MimeMapping.AddMimeMapping(".prf", "application/pics-rules");
|
||||
MimeMapping.AddMimeMapping(".pgm", "image/x-portable-graymap");
|
||||
MimeMapping.AddMimeMapping(".qt", "video/quicktime");
|
||||
MimeMapping.AddMimeMapping(".ra", "audio/x-pn-realaudio");
|
||||
MimeMapping.AddMimeMapping(".rgb", "image/x-rgb");
|
||||
MimeMapping.AddMimeMapping(".ram", "audio/x-pn-realaudio");
|
||||
MimeMapping.AddMimeMapping(".rmi", "audio/mid");
|
||||
MimeMapping.AddMimeMapping(".ras", "image/x-cmu-raster");
|
||||
MimeMapping.AddMimeMapping(".roff", "application/x-troff");
|
||||
MimeMapping.AddMimeMapping(".rtf", "application/rtf");
|
||||
MimeMapping.AddMimeMapping(".rtx", "text/richtext");
|
||||
MimeMapping.AddMimeMapping(".sv4crc", "application/x-sv4crc");
|
||||
MimeMapping.AddMimeMapping(".spc", "application/x-pkcs7-certificates");
|
||||
MimeMapping.AddMimeMapping(".setreg", "application/set-registration-initiation");
|
||||
MimeMapping.AddMimeMapping(".snd", "audio/basic");
|
||||
MimeMapping.AddMimeMapping(".stl", "application/vndms-pkistl");
|
||||
MimeMapping.AddMimeMapping(".setpay", "application/set-payment-initiation");
|
||||
MimeMapping.AddMimeMapping(".stm", "text/html");
|
||||
MimeMapping.AddMimeMapping(".shar", "application/x-shar");
|
||||
MimeMapping.AddMimeMapping(".sh", "application/x-sh");
|
||||
MimeMapping.AddMimeMapping(".sit", "application/x-stuffit");
|
||||
MimeMapping.AddMimeMapping(".spl", "application/futuresplash");
|
||||
MimeMapping.AddMimeMapping(".sct", "text/scriptlet");
|
||||
MimeMapping.AddMimeMapping(".scd", "application/x-msschedule");
|
||||
MimeMapping.AddMimeMapping(".sst", "application/vndms-pkicertstore");
|
||||
MimeMapping.AddMimeMapping(".src", "application/x-wais-source");
|
||||
MimeMapping.AddMimeMapping(".sv4cpio", "application/x-sv4cpio");
|
||||
MimeMapping.AddMimeMapping(".tex", "application/x-tex");
|
||||
MimeMapping.AddMimeMapping(".tgz", "application/x-compressed");
|
||||
MimeMapping.AddMimeMapping(".t", "application/x-troff");
|
||||
MimeMapping.AddMimeMapping(".tar", "application/x-tar");
|
||||
MimeMapping.AddMimeMapping(".tr", "application/x-troff");
|
||||
MimeMapping.AddMimeMapping(".tif", "image/tiff");
|
||||
MimeMapping.AddMimeMapping(".txt", "text/plain");
|
||||
MimeMapping.AddMimeMapping(".texinfo", "application/x-texinfo");
|
||||
MimeMapping.AddMimeMapping(".trm", "application/x-msterminal");
|
||||
MimeMapping.AddMimeMapping(".tiff", "image/tiff");
|
||||
MimeMapping.AddMimeMapping(".tcl", "application/x-tcl");
|
||||
MimeMapping.AddMimeMapping(".texi", "application/x-texinfo");
|
||||
MimeMapping.AddMimeMapping(".tsv", "text/tab-separated-values");
|
||||
MimeMapping.AddMimeMapping(".ustar", "application/x-ustar");
|
||||
MimeMapping.AddMimeMapping(".uls", "text/iuls");
|
||||
MimeMapping.AddMimeMapping(".vcf", "text/x-vcard");
|
||||
MimeMapping.AddMimeMapping(".wps", "application/vnd.ms-works");
|
||||
MimeMapping.AddMimeMapping(".wav", "audio/wav");
|
||||
MimeMapping.AddMimeMapping(".wrz", "x-world/x-vrml");
|
||||
MimeMapping.AddMimeMapping(".wri", "application/x-mswrite");
|
||||
MimeMapping.AddMimeMapping(".wks", "application/vnd.ms-works");
|
||||
MimeMapping.AddMimeMapping(".wmf", "application/x-msmetafile");
|
||||
MimeMapping.AddMimeMapping(".wcm", "application/vnd.ms-works");
|
||||
MimeMapping.AddMimeMapping(".wrl", "x-world/x-vrml");
|
||||
MimeMapping.AddMimeMapping(".wdb", "application/vnd.ms-works");
|
||||
MimeMapping.AddMimeMapping(".wsdl", "text/xml");
|
||||
MimeMapping.AddMimeMapping(".xap", "application/x-silverlight-app");
|
||||
MimeMapping.AddMimeMapping(".xml", "text/xml");
|
||||
MimeMapping.AddMimeMapping(".xlm", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xaf", "x-world/x-vrml");
|
||||
MimeMapping.AddMimeMapping(".xla", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xls", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xof", "x-world/x-vrml");
|
||||
MimeMapping.AddMimeMapping(".xlt", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xlc", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xsl", "text/xml");
|
||||
MimeMapping.AddMimeMapping(".xbm", "image/x-xbitmap");
|
||||
MimeMapping.AddMimeMapping(".xlw", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xpm", "image/x-xpixmap");
|
||||
MimeMapping.AddMimeMapping(".xwd", "image/x-xwindowdump");
|
||||
MimeMapping.AddMimeMapping(".xsd", "text/xml");
|
||||
MimeMapping.AddMimeMapping(".z", "application/x-compress");
|
||||
MimeMapping.AddMimeMapping(".zip", "application/x-zip-compressed");
|
||||
MimeMapping.AddMimeMapping(".*", "application/octet-stream");
|
||||
}
|
||||
}
|
||||
}
|
||||
16
WaterCloud.Code/Model/ApiToken.cs
Normal file
16
WaterCloud.Code/Model/ApiToken.cs
Normal file
@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace WaterCloud.Code.Model
|
||||
{
|
||||
/// <summary>
|
||||
/// 这个是移动端Api用的
|
||||
/// </summary>
|
||||
public class BaseApiToken
|
||||
{
|
||||
[NotMapped]
|
||||
[Description("WebApi没有Cookie和Session,所以需要传入Token来标识用户身份,请加在Url后面")]
|
||||
public string Token { get; set; }
|
||||
}
|
||||
}
|
||||
11
WaterCloud.Code/Model/AppLogEntity.cs
Normal file
11
WaterCloud.Code/Model/AppLogEntity.cs
Normal file
@ -0,0 +1,11 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code.Model
|
||||
{
|
||||
public class AppLogEntity
|
||||
{
|
||||
public string FileName { get; set; }
|
||||
}
|
||||
}
|
||||
21
WaterCloud.Code/Model/Define.cs
Normal file
21
WaterCloud.Code/Model/Define.cs
Normal file
@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static class Define
|
||||
{
|
||||
public const string DBTYPE_SQLSERVER = "System.Data.SqlClient"; //sql server
|
||||
public const string DBTYPE_MYSQL = "MySql.Data.MySqlClient"; //sql server
|
||||
public const string DBTYPE_ORACLE = "Oracle.ManagedDataAccess.Client"; //oracle
|
||||
public const string PROVIDER_COOKIE = "Cookie";
|
||||
public const string PROVIDER_SESSION = "Session";
|
||||
public const string PROVIDER_WEBAPI = "WebApi";
|
||||
public const string CACHEPROVIDER_REDIS = "Redis";
|
||||
public const string CACHEPROVIDER_MEMORY = "Memory";
|
||||
public const string DATAPRIVILEGE_LOGINUSER = "{loginUser}"; //数据权限配置中,当前登录用户的key
|
||||
public const string DATAPRIVILEGE_LOGINROLE = "{loginRole}"; //数据权限配置中,当前登录用户角色的key
|
||||
public const string DATAPRIVILEGE_LOGINORG = "{loginOrg}"; //数据权限配置中,当前登录用户部门的key
|
||||
}
|
||||
}
|
||||
24
WaterCloud.Code/Model/Filter.cs
Normal file
24
WaterCloud.Code/Model/Filter.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class Filter
|
||||
{
|
||||
public string Key { get; set; }
|
||||
public string Value { get; set; }
|
||||
public string Contrast { get; set; }
|
||||
|
||||
public string Text { get; set; }
|
||||
}
|
||||
public class FilterList
|
||||
{
|
||||
/// <summary>
|
||||
/// and
|
||||
/// </summary>
|
||||
public string Operation { get; set; }
|
||||
public string Filters { get; set; }
|
||||
public string Description { get; set; }
|
||||
}
|
||||
}
|
||||
15
WaterCloud.Code/Model/KeyValue.cs
Normal file
15
WaterCloud.Code/Model/KeyValue.cs
Normal file
@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class KeyValue
|
||||
{
|
||||
public string Key { get; set; }
|
||||
public string Value { get; set; }
|
||||
public string Description { get; set; }
|
||||
}
|
||||
}
|
||||
80
WaterCloud.Code/Model/SystemConfig.cs
Normal file
80
WaterCloud.Code/Model/SystemConfig.cs
Normal file
@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code.Model
|
||||
{
|
||||
public class SystemConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否是Demo模式
|
||||
/// </summary>
|
||||
public bool Demo { get; set; }
|
||||
/// <summary>
|
||||
/// 是否是调试模式
|
||||
/// </summary>
|
||||
public bool Debug { get; set; }
|
||||
/// <summary>
|
||||
/// 允许一个用户在多个电脑同时登录
|
||||
/// </summary>
|
||||
public bool LoginMultiple { get; set; }
|
||||
public string LoginProvider { get; set; }
|
||||
/// <summary>
|
||||
/// 数据库超时间(秒)
|
||||
/// </summary>
|
||||
public int CommandTimeout { get; set; }
|
||||
/// <summary>
|
||||
/// Snow Flake Worker Id
|
||||
/// </summary>
|
||||
public int SnowFlakeWorkerId { get; set; }
|
||||
/// <summary>
|
||||
/// api地址
|
||||
/// </summary>
|
||||
public string ApiSite { get; set; }
|
||||
/// <summary>
|
||||
/// 允许跨域的站点
|
||||
/// </summary>
|
||||
public string AllowCorsSite { get; set; }
|
||||
/// <summary>
|
||||
/// 网站虚拟目录
|
||||
/// </summary>
|
||||
public string VirtualDirectory { get; set; }
|
||||
|
||||
public string DBProvider { get; set; }
|
||||
public string DBConnectionString { get; set; }
|
||||
public string DBCommandTimeout { get; set; }
|
||||
/// <summary>
|
||||
/// 数据库备份路径
|
||||
/// </summary>
|
||||
public string DBBackup { get; set; }
|
||||
|
||||
public string CacheProvider { get; set; }
|
||||
public string HandleLogProvider { get; set; }
|
||||
public string RedisConnectionString { get; set; }
|
||||
public string SysemUserId { get; set; }
|
||||
public string SysemUserCode { get; set; }
|
||||
public string SysemUserPwd { get; set; }
|
||||
public string SysemMasterProject { get; set; }
|
||||
public string TokenName { get; set; }
|
||||
//缓存过期时间
|
||||
public int LoginExpire { get; set; }
|
||||
public string HomePage { get; set; }
|
||||
public string MainProgram { get; set; }
|
||||
public bool? LocalLAN { get; set; }
|
||||
/// <summary>
|
||||
/// 雪花id配置
|
||||
/// </summary>
|
||||
public int WorkId { get; set; }
|
||||
/// <summary>
|
||||
/// 是否重置密码
|
||||
/// </summary>
|
||||
public bool? ReviseSysem { get; set; }
|
||||
/// <summary>
|
||||
/// 出库质检
|
||||
/// </summary>
|
||||
public bool? OutStorageCheck { get; set; }
|
||||
//看板密码
|
||||
public string BoardPassword { get; set; }
|
||||
|
||||
}
|
||||
}
|
||||
18
WaterCloud.Code/ModelBindingMetadataProvider.cs
Normal file
18
WaterCloud.Code/ModelBindingMetadataProvider.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// Controller Model Binding 处理
|
||||
/// </summary>
|
||||
public class ModelBindingMetadataProvider : IMetadataDetailsProvider, IDisplayMetadataProvider
|
||||
{
|
||||
public void CreateDisplayMetadata(DisplayMetadataProviderContext context)
|
||||
{
|
||||
if (context.Key.MetadataKind == ModelMetadataKind.Property)
|
||||
{
|
||||
context.DisplayMetadata.ConvertEmptyStringToNull = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
23
WaterCloud.Code/Operator/OperatorBoard.cs
Normal file
23
WaterCloud.Code/Operator/OperatorBoard.cs
Normal file
@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class OperatorBoard
|
||||
{
|
||||
public string F_Id { get; set; }
|
||||
/// <summary>
|
||||
/// 账户
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string F_Account { get; set; }
|
||||
/// <summary>
|
||||
/// 密码
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string F_Password { get; set; }
|
||||
}
|
||||
}
|
||||
40
WaterCloud.Code/Operator/OperatorModel.cs
Normal file
40
WaterCloud.Code/Operator/OperatorModel.cs
Normal file
@ -0,0 +1,40 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System;
|
||||
using Chloe;
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class OperatorModel
|
||||
{
|
||||
public string UserId { get; set; }
|
||||
public string UserCode { get; set; }
|
||||
public string UserName { get; set; }
|
||||
public string UserPwd { get; set; }
|
||||
public string CompanyId { get; set; }
|
||||
public string DepartmentId { get; set; }
|
||||
public string RoleId { get; set; }
|
||||
public string LoginIPAddress { get; set; }
|
||||
public string LoginIPAddressName { get; set; }
|
||||
public string LoginToken { get; set; }
|
||||
public DateTime LoginTime { get; set; }
|
||||
public bool IsSystem { get; set; }
|
||||
public bool IsAdmin { get; set; }
|
||||
public bool IsBoss { get; set; }
|
||||
public bool IsSenior { get; set; }
|
||||
public bool IsLeaderInDepts { get; set; }
|
||||
public bool IsSaleman { get; set; }
|
||||
public bool IsPlanMan { get; set; }
|
||||
// 拓展字段,2019-03-03
|
||||
public string DdUserId { get; set; }
|
||||
public string WxOpenId { get; set; }
|
||||
public string Avatar { get; set; }
|
||||
public string loginMark { get; set; }
|
||||
//扩展字段 数据库,2020-06-15
|
||||
public string DbString { get; set; }
|
||||
public string DBProvider { get; set; }
|
||||
}
|
||||
}
|
||||
462
WaterCloud.Code/Operator/OperatorProvider.cs
Normal file
462
WaterCloud.Code/Operator/OperatorProvider.cs
Normal file
@ -0,0 +1,462 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Web;
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class OperatorProvider
|
||||
{
|
||||
//登录信息保存方式
|
||||
private string LoginProvider = GlobalContext.SystemConfig.LoginProvider;
|
||||
//是否允许一个账户在多处登录
|
||||
private bool LoginMultiple = GlobalContext.SystemConfig.LoginMultiple;
|
||||
//缓存过期时间
|
||||
private int LoginExpire = GlobalContext.SystemConfig.LoginExpire;
|
||||
public static OperatorProvider Provider
|
||||
{
|
||||
get { return new OperatorProvider(); }
|
||||
}
|
||||
//watercloud_operator_pc_ PC端登录
|
||||
//watercloud_operator_info_ 登录次数
|
||||
//
|
||||
/// <summary>
|
||||
/// 缓存操作类
|
||||
/// </summary>
|
||||
private string cacheKeyOperator = "watercloud_operator_";// +登录者token
|
||||
private string cacheKeyToken = "watercloud_token_";// +登录者token
|
||||
private string cacheKeyError = "watercloud_error_";// + Mark
|
||||
/// <summary>
|
||||
/// 秘钥
|
||||
/// </summary>
|
||||
private string LoginUserToken = "watercloud_Token";
|
||||
|
||||
/// <summary>
|
||||
/// 标记登录的浏览器
|
||||
/// </summary>
|
||||
private string LoginUserMarkKey = "watercloud_Mark";
|
||||
private string LoginBoardMarkKey = "watercloud_BoardMark";
|
||||
public string GetProvider(string key)
|
||||
{
|
||||
switch (LoginProvider)
|
||||
{
|
||||
case Define.PROVIDER_COOKIE:
|
||||
return WebHelper.GetCookie(key).ToString();
|
||||
case Define.PROVIDER_SESSION:
|
||||
return WebHelper.GetSession(key).ToString();
|
||||
case Define.PROVIDER_WEBAPI:
|
||||
return GetToken();
|
||||
default:
|
||||
return GetToken();
|
||||
}
|
||||
}
|
||||
public void SetProvider(string key,string value)
|
||||
{
|
||||
switch (LoginProvider)
|
||||
{
|
||||
case Define.PROVIDER_COOKIE:
|
||||
WebHelper.WriteCookie(key, value);
|
||||
break;
|
||||
case Define.PROVIDER_SESSION:
|
||||
WebHelper.WriteSession(key, value);
|
||||
break;
|
||||
case Define.PROVIDER_WEBAPI:
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
public string GetToken()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (GlobalContext.ServiceProvider == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (GlobalContext.ServiceProvider.GetService<IHttpContextAccessor>() == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
//查请求头
|
||||
string token = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>()?.HttpContext.Request.Headers[GlobalContext.SystemConfig.TokenName].ParseToString();
|
||||
if (!String.IsNullOrEmpty(token)) return token;
|
||||
|
||||
//查参数
|
||||
token = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>()?.HttpContext.Request.Query[GlobalContext.SystemConfig.TokenName];
|
||||
if (!String.IsNullOrEmpty(token)) return token;
|
||||
|
||||
//查cookies
|
||||
string cookie = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>()?.HttpContext.Request.Cookies[GlobalContext.SystemConfig.TokenName];
|
||||
return cookie == null ? string.Empty : cookie;
|
||||
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public void RemoveProvider(string key)
|
||||
{
|
||||
switch (LoginProvider)
|
||||
{
|
||||
case Define.PROVIDER_COOKIE:
|
||||
WebHelper.RemoveCookie(key);
|
||||
break;
|
||||
case Define.PROVIDER_SESSION:
|
||||
WebHelper.RemoveSession(key);
|
||||
break;
|
||||
case Define.PROVIDER_WEBAPI:
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
public OperatorModel GetCurrent()
|
||||
{
|
||||
OperatorModel operatorModel = new OperatorModel();
|
||||
try
|
||||
{
|
||||
string loginMark = GetProvider(LoginUserMarkKey);
|
||||
operatorModel =CacheHelper.Get<OperatorModel>(cacheKeyOperator + loginMark).GetAwaiter().GetResult();
|
||||
}
|
||||
catch
|
||||
{
|
||||
operatorModel = null;
|
||||
}
|
||||
return operatorModel;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取看板登录信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public OperatorBoard GetBoardCurrent()
|
||||
{
|
||||
OperatorBoard operatorBoard = new OperatorBoard();
|
||||
try
|
||||
{
|
||||
string loginMark = GetProvider(LoginBoardMarkKey);
|
||||
operatorBoard = CacheHelper.Get<OperatorBoard>(cacheKeyOperator + loginMark).GetAwaiter().GetResult();
|
||||
}
|
||||
catch
|
||||
{
|
||||
operatorBoard = null;
|
||||
}
|
||||
return operatorBoard;
|
||||
}
|
||||
/// <summary>
|
||||
/// 清空当前看板登录信息
|
||||
/// </summary>
|
||||
public async Task EmptyBoardCurrent()
|
||||
{
|
||||
try
|
||||
{
|
||||
string loginMark = GetProvider(LoginBoardMarkKey);
|
||||
RemoveProvider(LoginBoardMarkKey.Trim());
|
||||
await CacheHelper.Remove(cacheKeyOperator + loginMark);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 看板登录信息添加到缓存中
|
||||
/// </summary>
|
||||
/// <param name="userEntity">用户</param>
|
||||
/// <param name="loginMark">设备标识uid</param>
|
||||
/// <param name="facilityMark">设备类型</param>
|
||||
/// <param name="cookie">是否保存cookie,默认是</param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> AddLoginBoard(OperatorBoard operatorBoard)
|
||||
{
|
||||
string token = Guid.NewGuid().ToString();
|
||||
try
|
||||
{
|
||||
SetProvider(LoginBoardMarkKey, token);
|
||||
await CacheHelper.Set(cacheKeyOperator + token, operatorBoard);
|
||||
return token;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取浏览器设配号
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string GetMark()
|
||||
{
|
||||
string cookieMark = GetProvider(LoginUserMarkKey);
|
||||
if (string.IsNullOrEmpty(cookieMark))
|
||||
{
|
||||
cookieMark = Guid.NewGuid().ToString();
|
||||
SetProvider(LoginUserMarkKey, cookieMark);
|
||||
}
|
||||
return cookieMark;
|
||||
}
|
||||
/// <summary>
|
||||
/// 登录者信息添加到缓存中
|
||||
/// </summary>
|
||||
/// <param name="userEntity">用户</param>
|
||||
/// <param name="loginMark">设备标识uid</param>
|
||||
/// <param name="facilityMark">设备类型</param>
|
||||
/// <param name="cookie">是否保存cookie,默认是</param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> AddLoginUser(OperatorModel operatorModel, string loginMark, string facilityMark, bool cookie = true)
|
||||
{
|
||||
string token = Guid.NewGuid().ToString();
|
||||
try
|
||||
{
|
||||
// 填写登录信息
|
||||
operatorModel.LoginToken = token;
|
||||
//cookid登录信息更新
|
||||
if (cookie)
|
||||
{
|
||||
string cookieMark = GetProvider(LoginUserMarkKey);
|
||||
if (string.IsNullOrEmpty(cookieMark))
|
||||
{
|
||||
operatorModel.loginMark = Guid.NewGuid().ToString();
|
||||
SetProvider(LoginUserMarkKey, operatorModel.loginMark);
|
||||
}
|
||||
else
|
||||
{
|
||||
operatorModel.loginMark = cookieMark;
|
||||
}
|
||||
SetProvider(LoginUserToken, token);
|
||||
}
|
||||
else
|
||||
{
|
||||
operatorModel.loginMark = loginMark;
|
||||
}
|
||||
//redis 登录token列表更新
|
||||
Dictionary<string, string> tokenMarkList =await CacheHelper.Get<Dictionary<string, string>>(cacheKeyToken + operatorModel.UserId);
|
||||
if (tokenMarkList == null)// 此账号第一次登录
|
||||
{
|
||||
tokenMarkList = new Dictionary<string, string>();
|
||||
tokenMarkList.Add(operatorModel.loginMark, token);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (tokenMarkList.ContainsKey(operatorModel.loginMark))
|
||||
{
|
||||
tokenMarkList[operatorModel.loginMark] = token;
|
||||
}
|
||||
else
|
||||
{
|
||||
tokenMarkList.Add(operatorModel.loginMark, token);
|
||||
}
|
||||
}
|
||||
|
||||
await CacheHelper.Set(cacheKeyToken + operatorModel.UserId, tokenMarkList);
|
||||
await CacheHelper.Set(cacheKeyOperator + operatorModel.loginMark, operatorModel, LoginExpire);
|
||||
await CacheHelper.Remove(cacheKeyOperator + facilityMark + operatorModel.UserId);
|
||||
await CacheHelper.Set(cacheKeyOperator + facilityMark + operatorModel.UserId, token, LoginExpire);
|
||||
return token;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 清空当前登录信息
|
||||
/// </summary>
|
||||
/// <param name="apitoken">apitoken</param>
|
||||
/// <param name="facilityMark">设备类型</param>
|
||||
public async Task EmptyCurrent(string facilityMark)
|
||||
{
|
||||
try
|
||||
{
|
||||
string token = GetProvider(LoginUserToken);
|
||||
string loginMark = GetProvider(LoginUserMarkKey);
|
||||
await EmptyCurrent(token, facilityMark, loginMark);
|
||||
RemoveProvider(LoginUserMarkKey.Trim());
|
||||
RemoveProvider(LoginUserToken.Trim());
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 清空当前登录信息
|
||||
/// </summary>
|
||||
/// <param name="token">登录票据</param>
|
||||
/// <param name="facilityMark">登录设备</param>
|
||||
/// <param name="loginMark">登录设备标识</param>
|
||||
public async Task EmptyCurrent(string token,string facilityMark, string loginMark)
|
||||
{
|
||||
try
|
||||
{
|
||||
OperatorModel operatorInfo =await CacheHelper.Get<OperatorModel>(cacheKeyOperator + loginMark);
|
||||
if (operatorInfo != null)
|
||||
{
|
||||
Dictionary<string, string> tokenMarkList =await CacheHelper.Get<Dictionary<string, string>>(cacheKeyToken + operatorInfo.UserId);
|
||||
tokenMarkList.Remove(loginMark);
|
||||
await CacheHelper.Remove(cacheKeyOperator + loginMark);
|
||||
if (operatorInfo.LoginToken == token|| LoginProvider == Define.PROVIDER_WEBAPI)
|
||||
{
|
||||
await CacheHelper.Remove(cacheKeyOperator + facilityMark + operatorInfo.UserId);
|
||||
}
|
||||
await CacheHelper.Set(cacheKeyToken + operatorInfo.UserId, tokenMarkList);
|
||||
await CacheHelper.Remove(facilityMark + GlobalContext.SystemConfig.TokenName + "_" + operatorInfo.UserId + "_" + operatorInfo.LoginTime);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 判断登录状态
|
||||
/// </summary>
|
||||
/// <param name="facilityMark">登录设备</param>
|
||||
/// <param name="apitoken">apitoken</param>
|
||||
/// <returns>-1未登录,1登录成功,0登录过期,-2账号被顶</returns>
|
||||
public async Task<OperatorResult> IsOnLine(string facilityMark)
|
||||
{
|
||||
try
|
||||
{
|
||||
string token = GetProvider(LoginUserToken);
|
||||
string loginMark = GetProvider(LoginUserMarkKey);
|
||||
return await IsOnLine(token, facilityMark, loginMark);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return new OperatorResult { stateCode = -1 };
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 判断登录状态
|
||||
/// </summary>
|
||||
/// <param name="token">登录票据</param>
|
||||
/// <param name="facilityMark">登录设备</param>
|
||||
/// <param name="loginMark">登录设备标识</param>
|
||||
/// <returns>-1未登录,1登录成功,0登录过期,-2账号被顶</returns>
|
||||
public async Task<OperatorResult> IsOnLine(string token, string facilityMark, string loginMark)
|
||||
{
|
||||
OperatorResult operatorResult = new OperatorResult();
|
||||
operatorResult.stateCode = -1; // -1未登录,1登录成功,0登录过期
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(loginMark))
|
||||
{
|
||||
return operatorResult;
|
||||
}
|
||||
OperatorModel operatorInfo =await CacheHelper.Get<OperatorModel>(cacheKeyOperator + loginMark);
|
||||
if (operatorInfo != null)
|
||||
{
|
||||
Dictionary<string, string> tokenMarkList = await CacheHelper.Get<Dictionary<string, string>>(cacheKeyToken + operatorInfo.UserId);
|
||||
if ((token == operatorInfo.LoginToken || LoginProvider == Define.PROVIDER_WEBAPI)&& tokenMarkList.ContainsKey(operatorInfo.loginMark) && tokenMarkList[operatorInfo.loginMark] == operatorInfo.LoginToken)
|
||||
{
|
||||
////账号被顶(排除admin)
|
||||
if (!LoginMultiple && !operatorInfo.IsSystem && operatorInfo.LoginToken != await CacheHelper.Get<string>(cacheKeyOperator + facilityMark + operatorInfo.UserId))
|
||||
{
|
||||
operatorResult.stateCode = -2;
|
||||
tokenMarkList = await CacheHelper.Get<Dictionary<string, string>>(cacheKeyToken + operatorInfo.UserId);
|
||||
tokenMarkList.Remove(loginMark);
|
||||
await CacheHelper.Set(cacheKeyToken + operatorInfo.UserId, tokenMarkList);
|
||||
await CacheHelper.Remove(cacheKeyOperator + loginMark);
|
||||
}
|
||||
else
|
||||
{
|
||||
operatorResult.userInfo = operatorInfo;
|
||||
operatorResult.stateCode = 1;
|
||||
await CacheHelper.Expire(cacheKeyOperator + loginMark, LoginExpire);
|
||||
await CacheHelper.Expire(cacheKeyOperator + facilityMark + operatorInfo.UserId, LoginExpire);
|
||||
await CacheHelper.Expire(facilityMark + GlobalContext.SystemConfig.TokenName + "_" + operatorInfo.UserId + "_" + operatorInfo.LoginTime, LoginExpire);
|
||||
}
|
||||
}
|
||||
}
|
||||
return operatorResult;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return operatorResult;
|
||||
}
|
||||
}
|
||||
|
||||
#region 登录错误次数记录
|
||||
/// <summary>
|
||||
/// 获取当前登录错误次数
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public async Task<int> GetCurrentErrorNum()
|
||||
{
|
||||
int res = 0;
|
||||
try
|
||||
{
|
||||
string cookieMark = GetProvider(LoginUserMarkKey);
|
||||
if (string.IsNullOrEmpty(cookieMark))
|
||||
{
|
||||
cookieMark = Guid.NewGuid().ToString();
|
||||
SetProvider(LoginUserMarkKey, cookieMark);
|
||||
}
|
||||
string num =await CacheHelper.Get<string>(cacheKeyError + cookieMark);
|
||||
if (!string.IsNullOrEmpty(num))
|
||||
{
|
||||
res = Convert.ToInt32(num);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
return res;
|
||||
}
|
||||
/// <summary>
|
||||
/// 增加错误次数
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public async Task<int> AddCurrentErrorNum()
|
||||
{
|
||||
int res = 0;
|
||||
try
|
||||
{
|
||||
string cookieMark = GetProvider(LoginUserMarkKey);
|
||||
if (string.IsNullOrEmpty(cookieMark))
|
||||
{
|
||||
cookieMark = Guid.NewGuid().ToString();
|
||||
SetProvider(LoginUserMarkKey, cookieMark);
|
||||
}
|
||||
string num =await CacheHelper.Get<string>(cacheKeyError + cookieMark);
|
||||
if (!string.IsNullOrEmpty(num))
|
||||
{
|
||||
res = Convert.ToInt32(num);
|
||||
}
|
||||
res++;
|
||||
num = res + "";
|
||||
await CacheHelper.Set(cacheKeyError + cookieMark, num,24);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
return res;
|
||||
}
|
||||
/// <summary>
|
||||
/// 清除当前登录错误次数
|
||||
/// </summary>
|
||||
public async Task ClearCurrentErrorNum()
|
||||
{
|
||||
try
|
||||
{
|
||||
string cookieMark = GetProvider(LoginUserMarkKey);
|
||||
if (string.IsNullOrEmpty(cookieMark))
|
||||
{
|
||||
cookieMark = Guid.NewGuid().ToString();
|
||||
SetProvider(LoginUserMarkKey, cookieMark);
|
||||
}
|
||||
await CacheHelper.Remove(cacheKeyError + cookieMark);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
21
WaterCloud.Code/Operator/OperatorResult.cs
Normal file
21
WaterCloud.Code/Operator/OperatorResult.cs
Normal file
@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using WaterCloud.Code;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class OperatorResult
|
||||
{
|
||||
/// <summary>
|
||||
/// 状态码-1未登录,1登录成功,0登录过期
|
||||
/// </summary>
|
||||
public int stateCode { get; set; }
|
||||
/// <summary>
|
||||
/// 登录者用户信息
|
||||
/// </summary>
|
||||
public OperatorModel userInfo { get; set; }
|
||||
}
|
||||
}
|
||||
40
WaterCloud.Code/Operator/OperatorUserInfo.cs
Normal file
40
WaterCloud.Code/Operator/OperatorUserInfo.cs
Normal file
@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class OperatorUserInfo
|
||||
{
|
||||
//密码
|
||||
public string F_UserPassword { get; set; }
|
||||
//
|
||||
public string F_UserSecretkey { get; set; }
|
||||
//登录时间设置
|
||||
public DateTime? F_AllowStartTime { get; set; }
|
||||
public DateTime? F_AllowEndTime { get; set; }
|
||||
//锁定时间设置
|
||||
public DateTime? F_LockStartDate { get; set; }
|
||||
public DateTime? F_LockEndDate { get; set; }
|
||||
//第一次登录
|
||||
public DateTime? F_FirstVisitTime { get; set; }
|
||||
//上一次登录时间
|
||||
public DateTime? F_PreviousVisitTime { get; set; }
|
||||
//最后一次登录时间
|
||||
public DateTime? F_LastVisitTime { get; set; }
|
||||
//修改密码时间
|
||||
public DateTime? F_ChangePasswordDate { get; set; }
|
||||
//登录次数
|
||||
public int? F_LogOnCount { get; set; }
|
||||
//在线标记
|
||||
public bool? F_UserOnLine { get; set; }
|
||||
//安全问题
|
||||
public string F_Question { get; set; }
|
||||
//问题答案
|
||||
public string F_AnswerQuestion { get; set; }
|
||||
//默认主题
|
||||
public string F_Theme { get; set; }
|
||||
}
|
||||
}
|
||||
57
WaterCloud.Code/PdfHelper.cs
Normal file
57
WaterCloud.Code/PdfHelper.cs
Normal file
@ -0,0 +1,57 @@
|
||||
using iTextSharp.text;
|
||||
using iTextSharp.text.pdf;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class PdfHelper
|
||||
{
|
||||
}
|
||||
public class PDFFooter : PdfPageEventHelper
|
||||
{
|
||||
// write on top of document
|
||||
public override void OnOpenDocument(PdfWriter writer, Document document)
|
||||
{
|
||||
base.OnOpenDocument(writer, document);
|
||||
PdfPTable tabFot = new PdfPTable(new float[] { 1F });
|
||||
tabFot.SpacingAfter = 10F;
|
||||
PdfPCell cell;
|
||||
tabFot.TotalWidth = 300F;
|
||||
cell = new PdfPCell(new Phrase("Header"));
|
||||
tabFot.AddCell(cell);
|
||||
tabFot.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent);
|
||||
}
|
||||
|
||||
// write on start of each page
|
||||
public override void OnStartPage(PdfWriter writer, Document document)
|
||||
{
|
||||
base.OnStartPage(writer, document);
|
||||
}
|
||||
|
||||
// write on end of each page
|
||||
public override void OnEndPage(PdfWriter writer, Document document)
|
||||
{
|
||||
base.OnEndPage(writer, document);
|
||||
//PdfPTable tabFot = new PdfPTable(new float[] { 1F });
|
||||
//tabFot.TotalWidth = 700f;
|
||||
//tabFot.DefaultCell.Border = 0;
|
||||
//// var footFont = FontFactory.GetFont("Lato", 12 * 0.667f, new Color(60, 60, 60));
|
||||
//string fontpath = HttpContext.Current.Server.MapPath("~/App_Data");
|
||||
//BaseFont customfont = BaseFont.CreateFont(fontpath + "\\Lato-Regular.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
|
||||
//var footFont = new Font(customfont, 12 * 0.667f, Font.NORMAL, new Color(170, 170, 170));
|
||||
|
||||
//PdfPCell cell;
|
||||
//cell = new PdfPCell(new Phrase("@ 2016 . All Rights Reserved", footFont));
|
||||
//cell.VerticalAlignment = Element.ALIGN_CENTER;
|
||||
//cell.Border = 0;
|
||||
//cell.PaddingLeft = 100f;
|
||||
//tabFot.AddCell(cell);
|
||||
//tabFot.WriteSelectedRows(0, -1, 150, document.Bottom, writer.DirectContent);
|
||||
}
|
||||
|
||||
//write on close of document
|
||||
public override void OnCloseDocument(PdfWriter writer, Document document)
|
||||
{
|
||||
base.OnCloseDocument(writer, document);
|
||||
}
|
||||
}
|
||||
}
|
||||
27
WaterCloud.Code/Properties/launchSettings.json
Normal file
27
WaterCloud.Code/Properties/launchSettings.json
Normal file
@ -0,0 +1,27 @@
|
||||
{
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:59747/",
|
||||
"sslPort": 44332
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"WaterCloud.Code": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "https://localhost:5001;http://localhost:5000"
|
||||
}
|
||||
}
|
||||
}
|
||||
110
WaterCloud.Code/ReflectionHelper.cs
Normal file
110
WaterCloud.Code/ReflectionHelper.cs
Normal file
@ -0,0 +1,110 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class ReflectionHelper
|
||||
{
|
||||
private static ConcurrentDictionary<string, object> dictCache = new ConcurrentDictionary<string, object>();
|
||||
|
||||
#region 得到类里面的属性集合
|
||||
/// <summary>
|
||||
/// 得到类里面的属性集合
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="columns"></param>
|
||||
/// <returns></returns>
|
||||
public static PropertyInfo[] GetProperties(Type type, string[] columns = null)
|
||||
{
|
||||
PropertyInfo[] properties = null;
|
||||
if (dictCache.ContainsKey(type.FullName))
|
||||
{
|
||||
properties = dictCache[type.FullName] as PropertyInfo[];
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
properties = type.GetProperties();
|
||||
dictCache.TryAdd(type.FullName, properties);
|
||||
}
|
||||
|
||||
if (columns != null && columns.Length > 0)
|
||||
{
|
||||
// 按columns顺序返回属性
|
||||
var columnPropertyList = new List<PropertyInfo>();
|
||||
foreach (var column in columns)
|
||||
{
|
||||
var columnProperty = properties.Where(p => p.Name == column).FirstOrDefault();
|
||||
if (columnProperty != null)
|
||||
{
|
||||
columnPropertyList.Add(columnProperty);
|
||||
}
|
||||
}
|
||||
return columnPropertyList.ToArray();
|
||||
}
|
||||
else
|
||||
{
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
|
||||
public static object GetObjectPropertyValue<T>(T t, string propertyname)
|
||||
{
|
||||
Type type = typeof(T);
|
||||
PropertyInfo property = type.GetProperty(propertyname);
|
||||
if (property == null) return string.Empty;
|
||||
object o = property.GetValue(t, null);
|
||||
if (o == null) return string.Empty;
|
||||
return o;
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 反射获取模块名
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetModuleName(int count=2)
|
||||
{
|
||||
try
|
||||
{
|
||||
string className = new StackFrame(count, true).GetMethod().DeclaringType.FullName;
|
||||
className = className.Split('+')[0];
|
||||
className = className.Split('.').LastOrDefault();
|
||||
string moduleName = className.Substring(0, className.Length - 7);
|
||||
return moduleName;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 反射获取方法名
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetClassName(int count = 4)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (GlobalContext.SystemConfig.Debug == true && count == 4)
|
||||
{
|
||||
count++;
|
||||
}
|
||||
string className = new StackFrame(count, true).GetMethod().DeclaringType.FullName;
|
||||
className = className.Split('+')[0];
|
||||
className = className.Split('.').LastOrDefault();
|
||||
return className;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
233
WaterCloud.Code/Security/DESEncrypt.cs
Normal file
233
WaterCloud.Code/Security/DESEncrypt.cs
Normal file
@ -0,0 +1,233 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// DES加密、解密帮助类
|
||||
/// </summary>
|
||||
public class DESEncrypt
|
||||
{
|
||||
private static string DESKey = "WaterCloud_desencrypt_2019";
|
||||
|
||||
#region ========加密========
|
||||
/// <summary>
|
||||
/// 加密
|
||||
/// </summary>
|
||||
/// <param name="Text"></param>
|
||||
/// <returns></returns>
|
||||
public static string Encrypt(string Text)
|
||||
{
|
||||
return Encrypt(Text, DESKey);
|
||||
}
|
||||
/// <summary>
|
||||
/// 加密数据,用Web.Security的Hash方式加密
|
||||
/// </summary>
|
||||
/// <param name="Text"></param>
|
||||
/// <param name="sKey"></param>
|
||||
/// <returns></returns>
|
||||
public static string Encrypt(string Text, string sKey)
|
||||
{
|
||||
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
|
||||
byte[] inputByteArray;
|
||||
inputByteArray = Encoding.Default.GetBytes(Text);
|
||||
des.Key = ASCIIEncoding.ASCII.GetBytes(DecryptMd5(sKey));
|
||||
des.IV = ASCIIEncoding.ASCII.GetBytes(DecryptMd5(sKey));
|
||||
System.IO.MemoryStream ms = new System.IO.MemoryStream();
|
||||
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
|
||||
cs.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cs.FlushFinalBlock();
|
||||
StringBuilder ret = new StringBuilder();
|
||||
foreach (byte b in ms.ToArray())
|
||||
{
|
||||
ret.AppendFormat("{0:X2}", b);
|
||||
}
|
||||
return ret.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加密数据, 用Security.MD5而非Web.Security的Hash方式加密
|
||||
/// </summary>
|
||||
/// <param name="Text"></param>
|
||||
/// <returns></returns>
|
||||
public static string Encrypt2(string Text)
|
||||
{
|
||||
return Encrypt2(Text, DESKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加密数据, 用Security.MD5而非Web.Security的Hash方式加密
|
||||
/// </summary>
|
||||
/// <param name="Text"></param>
|
||||
/// <param name="sKey"></param>
|
||||
/// <returns></returns>
|
||||
public static string Encrypt2(string Text, string sKey)
|
||||
{
|
||||
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
|
||||
byte[] inputByteArray;
|
||||
inputByteArray = Encoding.Default.GetBytes(Text);
|
||||
sKey = MD5(sKey).Substring(0, 8);
|
||||
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
|
||||
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
|
||||
System.IO.MemoryStream ms = new System.IO.MemoryStream();
|
||||
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
|
||||
cs.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cs.FlushFinalBlock();
|
||||
StringBuilder ret = new StringBuilder();
|
||||
foreach (byte b in ms.ToArray())
|
||||
{
|
||||
ret.AppendFormat("{0:X2}", b);
|
||||
}
|
||||
return ret.ToString();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ========解密========
|
||||
/// <summary>
|
||||
/// 解密
|
||||
/// </summary>
|
||||
/// <param name="Text"></param>
|
||||
/// <returns></returns>
|
||||
public static string Decrypt(string Text)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Text))
|
||||
{
|
||||
return Decrypt(Text, DESKey);
|
||||
}
|
||||
else
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解密数据,用Web.Security的Hash方式加密
|
||||
/// </summary>
|
||||
/// <param name="Text"></param>
|
||||
/// <param name="sKey"></param>
|
||||
/// <returns></returns>
|
||||
public static string Decrypt(string Text, string sKey)
|
||||
{
|
||||
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
|
||||
int len;
|
||||
len = Text.Length / 2;
|
||||
byte[] inputByteArray = new byte[len];
|
||||
int x, i;
|
||||
for (x = 0; x < len; x++)
|
||||
{
|
||||
i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
|
||||
inputByteArray[x] = (byte)i;
|
||||
}
|
||||
|
||||
des.Key = ASCIIEncoding.ASCII.GetBytes(DecryptMd5(sKey));
|
||||
des.IV = ASCIIEncoding.ASCII.GetBytes(DecryptMd5(sKey));
|
||||
System.IO.MemoryStream ms = new System.IO.MemoryStream();
|
||||
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
|
||||
cs.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cs.FlushFinalBlock();
|
||||
return Encoding.Default.GetString(ms.ToArray());
|
||||
}
|
||||
public static string DecryptMd5(string str)
|
||||
{
|
||||
string strEncrypt = string.Empty;
|
||||
var md5 = System.Security.Cryptography.MD5.Create();
|
||||
var data = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
|
||||
StringBuilder builder = new StringBuilder();
|
||||
// 循环遍历哈希数据的每一个字节并格式化为十六进制字符串
|
||||
for (int i = 0; i < data.Length; i++)
|
||||
{
|
||||
builder.Append(data[i].ToString("X2"));
|
||||
}
|
||||
strEncrypt = builder.ToString().Substring(0,8);
|
||||
return strEncrypt;
|
||||
}
|
||||
/// <summary>
|
||||
/// 解密数据,用Security.MD5而非Web.Security的Hash方式加密
|
||||
/// </summary>
|
||||
/// <param name="Text"></param>
|
||||
/// <returns></returns>
|
||||
public static string Decrypt2(string Text)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Text))
|
||||
{
|
||||
return Decrypt2(Text, DESKey);
|
||||
}
|
||||
else
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解密数据,用Security.MD5而非Web.Security的Hash方式加密
|
||||
/// </summary>
|
||||
/// <param name="Text"></param>
|
||||
/// <param name="sKey"></param>
|
||||
/// <returns></returns>
|
||||
public static string Decrypt2(string Text, string sKey)
|
||||
{
|
||||
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
|
||||
int len;
|
||||
len = Text.Length / 2;
|
||||
byte[] inputByteArray = new byte[len];
|
||||
int x, i;
|
||||
for (x = 0; x < len; x++)
|
||||
{
|
||||
i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
|
||||
inputByteArray[x] = (byte)i;
|
||||
}
|
||||
sKey = MD5(sKey).Substring(0, 8);
|
||||
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
|
||||
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
|
||||
System.IO.MemoryStream ms = new System.IO.MemoryStream();
|
||||
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
|
||||
cs.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cs.FlushFinalBlock();
|
||||
return Encoding.Default.GetString(ms.ToArray());
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public static string MD5(string pwd)
|
||||
{
|
||||
MD5 md5 = new MD5CryptoServiceProvider();
|
||||
byte[] data = System.Text.Encoding.Default.GetBytes(pwd);
|
||||
byte[] md5data = md5.ComputeHash(data);
|
||||
md5.Clear();
|
||||
string str = "";
|
||||
for (int i = 0; i < md5data.Length; i++)
|
||||
{
|
||||
str += md5data[i].ToString("x").PadLeft(2, '0');
|
||||
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 基于Sha1的自定义加密字符串方法:输入一个字符串,返回一个由40个字符组成的十六进制的哈希散列(字符串)。
|
||||
/// </summary>
|
||||
/// <param name="str">要加密的字符串</param>
|
||||
/// <returns>加密后的十六进制的哈希散列(字符串)</returns>
|
||||
public static string Sha1(string str)
|
||||
{
|
||||
var buffer = Encoding.UTF8.GetBytes(str);
|
||||
var data = SHA1.Create().ComputeHash(buffer);
|
||||
|
||||
var sb = new StringBuilder();
|
||||
foreach (var t in data)
|
||||
{
|
||||
sb.Append(t.ToString("X2"));
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
94
WaterCloud.Code/Security/Md5.cs
Normal file
94
WaterCloud.Code/Security/Md5.cs
Normal file
@ -0,0 +1,94 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// MD5加密
|
||||
/// </summary>
|
||||
public class Md5
|
||||
{
|
||||
/// <summary>
|
||||
/// MD5加密
|
||||
/// </summary>
|
||||
/// <param name="str">加密字符</param>
|
||||
/// <param name="code">加密位数16/32</param>
|
||||
/// <returns></returns>
|
||||
public static string md5(string str, int code)
|
||||
{
|
||||
string strEncrypt = string.Empty;
|
||||
if (code == 16)
|
||||
{
|
||||
var md5 = System.Security.Cryptography.MD5.Create();
|
||||
var data = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
|
||||
StringBuilder builder = new StringBuilder();
|
||||
// 循环遍历哈希数据的每一个字节并格式化为十六进制字符串
|
||||
for (int i = 0; i < data.Length; i++)
|
||||
{
|
||||
builder.Append(data[i].ToString("X2"));
|
||||
}
|
||||
strEncrypt = builder.ToString().Substring(8, 16);
|
||||
}
|
||||
|
||||
if (code == 32)
|
||||
{
|
||||
var md5 = System.Security.Cryptography.MD5.Create();
|
||||
var data = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
|
||||
StringBuilder builder = new StringBuilder();
|
||||
// 循环遍历哈希数据的每一个字节并格式化为十六进制字符串
|
||||
for (int i = 0; i < data.Length; i++)
|
||||
{
|
||||
builder.Append(data[i].ToString("X2"));
|
||||
}
|
||||
strEncrypt = builder.ToString();
|
||||
}
|
||||
|
||||
return strEncrypt;
|
||||
}
|
||||
public static string MD5(string str)
|
||||
{
|
||||
MD5 md5 = new MD5CryptoServiceProvider();
|
||||
byte[] data = System.Text.Encoding.Default.GetBytes(str);
|
||||
byte[] md5data = md5.ComputeHash(data);
|
||||
md5.Clear();
|
||||
str = "";
|
||||
for (int i = 0; i < md5data.Length; i++)
|
||||
{
|
||||
str += md5data[i].ToString("x").PadLeft(2, '0');
|
||||
|
||||
}
|
||||
return str;
|
||||
}
|
||||
public static string MD5Lower16(string str)
|
||||
{
|
||||
return MD5(str).ToLower().Substring(8, 16);
|
||||
}
|
||||
|
||||
public static string MD5Lower32(string str)
|
||||
{
|
||||
return MD5(str).ToLower(); ;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 32位小写
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string SHA1(string s)
|
||||
{
|
||||
SHA1 sha1 = System.Security.Cryptography.SHA1.Create();
|
||||
byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(s));
|
||||
string shaStr = BitConverter.ToString(hash);
|
||||
shaStr = shaStr.Replace("-", "");
|
||||
shaStr = shaStr.ToLower();
|
||||
return s.ToLower();
|
||||
}
|
||||
}
|
||||
}
|
||||
47
WaterCloud.Code/ShellHelper.cs
Normal file
47
WaterCloud.Code/ShellHelper.cs
Normal file
@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class ShellHelper
|
||||
{
|
||||
public static string Bash(string command)
|
||||
{
|
||||
var escapedArgs = command.Replace("\"", "\\\"");
|
||||
var process = new Process()
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = "/bin/bash",
|
||||
Arguments = $"-c \"{escapedArgs}\"",
|
||||
RedirectStandardOutput = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
}
|
||||
};
|
||||
process.Start();
|
||||
string result = process.StandardOutput.ReadToEnd();
|
||||
process.WaitForExit();
|
||||
process.Dispose();
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string Cmd(string fileName, string args)
|
||||
{
|
||||
string output = string.Empty;
|
||||
|
||||
var info = new ProcessStartInfo();
|
||||
info.FileName = fileName;
|
||||
info.Arguments = args;
|
||||
info.RedirectStandardOutput = true;
|
||||
|
||||
using (var process = Process.Start(info))
|
||||
{
|
||||
output = process.StandardOutput.ReadToEnd();
|
||||
}
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}
|
||||
103
WaterCloud.Code/TextHelper.cs
Normal file
103
WaterCloud.Code/TextHelper.cs
Normal file
@ -0,0 +1,103 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class TextHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取默认值
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetCustomValue(string value, string defaultValue)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 截取指定长度的字符串
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="length"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetSubString(string value, int length, bool ellipsis = false)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
if (value.Length > length)
|
||||
{
|
||||
value = value.Substring(0, length);
|
||||
if (ellipsis)
|
||||
{
|
||||
value += "...";
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 字符串转指定类型数组
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="split"></param>
|
||||
/// <returns></returns>
|
||||
public static T[] SplitToArray<T>(string value, char split)
|
||||
{
|
||||
T[] arr = value.Split(new string[] { split.ToString() }, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToArray();
|
||||
return arr;
|
||||
}
|
||||
/// <summary>
|
||||
/// 判断是否有交集
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="list1"></param>
|
||||
/// <param name="list2"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsArrayIntersection<T>(List<T> list1, List<T> list2)
|
||||
{
|
||||
List<T> t = list1.Distinct().ToList();
|
||||
|
||||
var exceptArr = t.Except(list2).ToList();
|
||||
|
||||
if (exceptArr.Count < t.Count)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 读取txt文件内容
|
||||
/// </summary>
|
||||
/// <param name="Path">文件地址</param>
|
||||
public static string ReadJsonContent(string Path)
|
||||
{
|
||||
StreamReader sr = new StreamReader(Path, Encoding.Default);
|
||||
string text = "";
|
||||
string content;
|
||||
while ((content = sr.ReadLine()) != null)
|
||||
{
|
||||
text += content;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
65
WaterCloud.Code/Timer/BackgroundServicesHelper.cs
Normal file
65
WaterCloud.Code/Timer/BackgroundServicesHelper.cs
Normal file
@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 已废除
|
||||
/// </summary>
|
||||
public static class BackgroundServicesHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 反射取得所有的业务逻辑类
|
||||
/// </summary>
|
||||
private static Type[] GetAllChildClass(Type baseType)
|
||||
{
|
||||
var types = AppDomain.CurrentDomain.GetAssemblies()
|
||||
//取得实现了某个接口的类
|
||||
//.SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(ISecurity)))) .ToArray();
|
||||
//取得继承了某个类的所有子类
|
||||
.SelectMany(a => a.GetTypes().Where(t => t.BaseType == baseType))
|
||||
.ToArray();
|
||||
|
||||
return types;
|
||||
}
|
||||
|
||||
|
||||
public static Type[] GetAllBackgroundService()
|
||||
{
|
||||
return GetAllChildClass(typeof(BackgroundService));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自动增加后台任务.所有继承自BackgroundService的类都会自动运行
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <returns></returns>
|
||||
public static IServiceCollection AddBackgroundServices(this IServiceCollection services)
|
||||
{
|
||||
//services.AddHostedService<TimedService>(); //asp.net core 应该是这个.
|
||||
//或者 单为方便循环自动创建, 所以改成使用AddTransient 也一样可以使用.
|
||||
//services.AddTransient<IHostedService, TimedService>();
|
||||
//services.AddTransient(typeof(Microsoft.Extensions.Hosting.IHostedService),backtype);
|
||||
//var backtypes = BackgroundServicesHelper.GetAllBackgroundService();
|
||||
//foreach (var backtype in backtypes)
|
||||
//{
|
||||
// services.AddTransient(typeof(Microsoft.Extensions.Hosting.IHostedService),backtype);
|
||||
//}
|
||||
|
||||
var backtypes = GetAllBackgroundService();
|
||||
foreach (var backtype in backtypes)
|
||||
{
|
||||
services.AddTransient(typeof(Microsoft.Extensions.Hosting.IHostedService), backtype);
|
||||
}
|
||||
return services;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
110
WaterCloud.Code/Utils.cs
Normal file
110
WaterCloud.Code/Utils.cs
Normal file
@ -0,0 +1,110 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class Utils
|
||||
{
|
||||
#region 自动生成编号
|
||||
/// <summary>
|
||||
/// 表示全局唯一标识符 (GUID)。
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GuId()
|
||||
{
|
||||
return IDGen.NextID().ToString();
|
||||
}
|
||||
/// <summary>
|
||||
/// 自动生成编号 201008251145409865
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string CreateNo()
|
||||
{
|
||||
Random random = new Random();
|
||||
string strRandom = random.Next(1000, 10000).ToString(); //生成编号
|
||||
string code = DateTime.Now.ToString("yyyyMMddHHmmss") + strRandom;//形如
|
||||
return code;
|
||||
}
|
||||
#endregion
|
||||
public static string GetGuid()
|
||||
{
|
||||
return IDGen.NextID().ToString().Replace("-", string.Empty).ToLower();
|
||||
}
|
||||
/// <summary>
|
||||
/// Signature 签名算法
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="text"></param>
|
||||
/// <returns></returns>
|
||||
public static string HmacSign(string message, string secret)
|
||||
{
|
||||
secret = secret ?? "";
|
||||
var encoding = new System.Text.ASCIIEncoding();
|
||||
byte[] keyByte = System.Text.Encoding.UTF8.GetBytes(secret);
|
||||
byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(message);
|
||||
using (var hmacsha256 = new HMACSHA256(keyByte))
|
||||
{
|
||||
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
|
||||
return System.Web.HttpUtility.UrlEncode(Convert.ToBase64String(hashmessage));
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取时间戳(毫秒)
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetTimeStamp()
|
||||
{
|
||||
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
|
||||
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
|
||||
}
|
||||
/// <summary>
|
||||
/// 将时间戳转换为日期类型,并格式化
|
||||
/// </summary>
|
||||
/// <param name="longDateTime"></param>
|
||||
/// <returns></returns>
|
||||
public static DateTime? LongDateTimeToDateTimeString(string longDateTime)
|
||||
{
|
||||
//用来格式化long类型时间的,声明的变量
|
||||
long unixDate;
|
||||
DateTime start;
|
||||
DateTime date;
|
||||
start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
//ENd
|
||||
if (string.IsNullOrEmpty(longDateTime))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
unixDate = long.Parse(longDateTime);
|
||||
date = start.AddMilliseconds(unixDate).ToLocalTime();
|
||||
|
||||
return date;
|
||||
|
||||
}
|
||||
public static double Round(double d, int i)
|
||||
{
|
||||
if (d >= 0)
|
||||
{
|
||||
d += 5 * Math.Pow(10, -(i + 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
d += -5 * Math.Pow(10, -(i + 1));
|
||||
}
|
||||
string str = d.ToString();
|
||||
string[] strs = str.Split('.');
|
||||
int idot = str.IndexOf('.');
|
||||
string prestr = strs[0];
|
||||
string poststr = strs.Length>1? strs[1] : "";
|
||||
if (poststr.Length > i)
|
||||
{
|
||||
poststr = str.Substring(idot + 1, i);
|
||||
}
|
||||
string strd = prestr + "." + poststr;
|
||||
d = Double.Parse(strd);
|
||||
return d;
|
||||
}
|
||||
}
|
||||
}
|
||||
350
WaterCloud.Code/ValidatorHelper.cs
Normal file
350
WaterCloud.Code/ValidatorHelper.cs
Normal file
@ -0,0 +1,350 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static class ValidatorHelper
|
||||
{
|
||||
#region 验证输入字符串为数字(带小数)
|
||||
/// <summary>
|
||||
/// 验证输入字符串为带小数点正数
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsNumber(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, "^([0]|([1-9]+\\d{0,}?))(.[\\d]+)?$");
|
||||
}
|
||||
/// <summary>
|
||||
/// 验证输入字符串为带小数点正负数
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsNumberic(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, "^-?\\d+$|^(-?\\d+)(\\.\\d+)?$");
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证中国电话格式是否有效,格式010-85849685
|
||||
/// <summary>
|
||||
/// 验证中国电话格式是否有效,格式010-85849685
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsTel(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, @"^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$", RegexOptions.IgnoreCase);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证输入字符串为电话号码
|
||||
/// <summary>
|
||||
/// 验证输入字符串为电话号码
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsPhone(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, @"(^(\d{2,4}[-_-—]?)?\d{3,8}([-_-—]?\d{3,8})?([-_-—]?\d{1,7})?$)|(^0?1[35]\d{9}$)");
|
||||
//弱一点的验证: @"\d{3,4}-\d{7,8}"
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证是否是有效传真号码
|
||||
/// <summary>
|
||||
/// 验证是否是有效传真号码
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsFax(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, @"^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$");
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证手机号是否合法
|
||||
/// <summary>
|
||||
/// 验证手机号是否合法 号段为13,14,15,16,17,18,19 0,86开头将自动识别
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsMobile(this string str)
|
||||
{
|
||||
if (!str.StartsWith("1"))
|
||||
{
|
||||
str = str.TrimStart(new char[] { '8', '6', }).TrimStart('0');
|
||||
}
|
||||
return Regex.IsMatch(str, @"^(13|14|15|16|17|18|19)\d{9}$");
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证身份证是否有效
|
||||
/// <summary>
|
||||
/// 验证身份证是否有效
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsIDCard(this string str)
|
||||
{
|
||||
switch (str.Length)
|
||||
{
|
||||
case 18:
|
||||
{
|
||||
return str.IsIDCard18();
|
||||
}
|
||||
case 15:
|
||||
{
|
||||
return str.IsIDCard15();
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证输入字符串为18位的身份证号码
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsIDCard18(this string str)
|
||||
{
|
||||
long n = 0;
|
||||
if (long.TryParse(str.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(str.Replace('x', '0').Replace('X', '0'), out n) == false)
|
||||
{
|
||||
return false;//数字验证
|
||||
}
|
||||
const string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
|
||||
if (address.IndexOf(str.Remove(2), StringComparison.Ordinal) == -1)
|
||||
{
|
||||
return false;//省份验证
|
||||
}
|
||||
string birth = str.Substring(6, 8).Insert(6, "-").Insert(4, "-");
|
||||
DateTime time;
|
||||
if (DateTime.TryParse(birth, out time) == false)
|
||||
{
|
||||
return false;//生日验证
|
||||
}
|
||||
string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
|
||||
string[] wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
|
||||
char[] ai = str.Remove(17).ToCharArray();
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 17; i++)
|
||||
{
|
||||
sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
|
||||
}
|
||||
int y = -1;
|
||||
Math.DivRem(sum, 11, out y);
|
||||
return arrVarifyCode[y] == str.Substring(17, 1).ToLower();
|
||||
}
|
||||
/// <summary>
|
||||
/// 验证输入字符串为15位的身份证号码
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsIDCard15(this string str)
|
||||
{
|
||||
long n = 0;
|
||||
if (long.TryParse(str, out n) == false || n < Math.Pow(10, 14))
|
||||
{
|
||||
return false;//数字验证
|
||||
}
|
||||
const string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
|
||||
if (address.IndexOf(str.Remove(2), StringComparison.Ordinal) == -1)
|
||||
{
|
||||
return false;//省份验证
|
||||
}
|
||||
string birth = str.Substring(6, 6).Insert(4, "-").Insert(2, "-");
|
||||
DateTime time;
|
||||
return DateTime.TryParse(birth, out time) != false;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证是否是有效邮箱地址
|
||||
/// <summary>
|
||||
/// 验证是否是有效邮箱地址
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsEmail(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证是否只含有汉字
|
||||
/// <summary>
|
||||
/// 验证是否只含有汉字
|
||||
/// </summary>
|
||||
/// <param name="strln">输入字符</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsOnlyChinese(this string strln)
|
||||
{
|
||||
return Regex.IsMatch(strln, @"^[\u4e00-\u9fa5]+$");
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 是否有多余的字符 防止SQL注入
|
||||
/// <summary>
|
||||
/// 是否有多余的字符 防止SQL注入
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsBadString(this string str)
|
||||
{
|
||||
if (string.IsNullOrEmpty(str))
|
||||
return false;
|
||||
//列举一些特殊字符串
|
||||
const string badChars = "@,*,#,$,!,+,',=,--,%,^,&,?,(,), <,>,[,],{,},/,\\,;,:,\",\"\",delete,update,drop,alert,select";
|
||||
var arraryBadChar = badChars.Split(',');
|
||||
return arraryBadChar.Any(t => !str.Contains(t));
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 是否由数字、26个英文字母或者下划线組成的字串
|
||||
/// <summary>
|
||||
/// 是否由数字、26个英文字母或者下划线組成的字串
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsNzx(this string str)
|
||||
{
|
||||
return Regex.Match(str, "^[0-9a-zA-Z_]+$").Success;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 由数字、26个英文字母、汉字組成的字串
|
||||
/// <summary>
|
||||
/// 由数字、26个英文字母、汉字組成的字串
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsSzzmChinese(this string str)
|
||||
{
|
||||
return Regex.Match(str, @"^[0-9a-zA-Z\u4e00-\u9fa5]+$").Success;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 由数字、26个英文字母組成的字串
|
||||
/// <summary>
|
||||
/// 是否由数字、26个英文字母組成的字串
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsSzzm(this string str)
|
||||
{
|
||||
return Regex.Match(str, @"^[0-9a-zA-Z]+$").Success;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证输入字符串为邮政编码
|
||||
/// <summary>
|
||||
/// 验证输入字符串为邮政编码
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsPostCode(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, @"\d{6}");
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 检查对象的输入长度
|
||||
/// <summary>
|
||||
/// 检查对象的输入长度
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <param name="length">指定的长度</param>
|
||||
/// <returns>false 太长,true -太短</returns>
|
||||
public static bool CheckLength(this string str, int length)
|
||||
{
|
||||
if (str.Length > length)
|
||||
{
|
||||
return false;//长度太长
|
||||
}
|
||||
return str.Length >= length;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 判断用户输入是否为日期
|
||||
/// <summary>
|
||||
/// 判断用户输入是否为日期
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
/// <remarks>
|
||||
/// 可判断格式如下(其中-可替换为/,不影响验证)
|
||||
/// YYYY | YYYY-MM | YYYY-MM-DD | YYYY-MM-DD HH:MM:SS | YYYY-MM-DD HH:MM:SS.FFF
|
||||
/// </remarks>
|
||||
public static bool IsDateTime(this string str)
|
||||
{
|
||||
if (null == str)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
const string regexDate = @"[1-2]{1}[0-9]{3}((-|\/|\.){1}(([0]?[1-9]{1})|(1[0-2]{1}))((-|\/|\.){1}((([0]?[1-9]{1})|([1-2]{1}[0-9]{1})|(3[0-1]{1})))( (([0-1]{1}[0-9]{1})|2[0-3]{1}):([0-5]{1}[0-9]{1}):([0-5]{1}[0-9]{1})(\.[0-9]{3})?)?)?)?$";
|
||||
if (Regex.IsMatch(str, regexDate))
|
||||
{
|
||||
//以下各月份日期验证,保证验证的完整性
|
||||
int indexY = -1;
|
||||
int indexM = -1;
|
||||
int indexD = -1;
|
||||
if (-1 != (indexY = str.IndexOf("-", StringComparison.Ordinal)))
|
||||
{
|
||||
indexM = str.IndexOf("-", indexY + 1, StringComparison.Ordinal);
|
||||
indexD = str.IndexOf(":", StringComparison.Ordinal);
|
||||
}
|
||||
else
|
||||
{
|
||||
indexY = str.IndexOf("/", StringComparison.Ordinal);
|
||||
indexM = str.IndexOf("/", indexY + 1, StringComparison.Ordinal);
|
||||
indexD = str.IndexOf(":", StringComparison.Ordinal);
|
||||
}
|
||||
//不包含日期部分,直接返回true
|
||||
if (-1 == indexM)
|
||||
return true;
|
||||
if (-1 == indexD)
|
||||
{
|
||||
indexD = str.Length + 3;
|
||||
}
|
||||
int iYear = Convert.ToInt32(str.Substring(0, indexY));
|
||||
int iMonth = Convert.ToInt32(str.Substring(indexY + 1, indexM - indexY - 1));
|
||||
int iDate = Convert.ToInt32(str.Substring(indexM + 1, indexD - indexM - 4));
|
||||
//判断月份日期
|
||||
if ((iMonth < 8 && 1 == iMonth % 2) || (iMonth > 8 && 0 == iMonth % 2))
|
||||
{
|
||||
if (iDate < 32)
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (iMonth != 2)
|
||||
{
|
||||
if (iDate < 31)
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
//闰年
|
||||
if ((0 == iYear % 400) || (0 == iYear % 4 && 0 < iYear % 100))
|
||||
{
|
||||
if (iDate < 30)
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (iDate < 29)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
89
WaterCloud.Code/VerifyCodeHelper.cs
Normal file
89
WaterCloud.Code/VerifyCodeHelper.cs
Normal file
@ -0,0 +1,89 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.DrawingCore;
|
||||
using System.DrawingCore.Imaging;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class VerifyCodeHelper
|
||||
{
|
||||
public byte[] GetVerifyCode()
|
||||
{
|
||||
int codeW = 80;
|
||||
int codeH = 30;
|
||||
int fontSize = 16;
|
||||
string chkCode = string.Empty;
|
||||
//颜色列表,用于验证码、噪线、噪点
|
||||
Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
|
||||
//字体列表,用于验证码
|
||||
string[] font = { "Times New Roman" };
|
||||
//验证码的字符集,去掉了一些容易混淆的字符
|
||||
char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
|
||||
Random rnd = new Random();
|
||||
//生成验证码字符串
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
chkCode += character[rnd.Next(character.Length)];
|
||||
}
|
||||
//写入Session、验证码加密
|
||||
WebHelper.WriteCookie("wcloud_session_verifycode", Md5.md5(chkCode.ToLower(), 16));
|
||||
//创建画布
|
||||
Bitmap bmp = new Bitmap(codeW, codeH);
|
||||
Graphics g = Graphics.FromImage(bmp);
|
||||
g.Clear(Color.White);
|
||||
//画噪线
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
int x1 = rnd.Next(codeW);
|
||||
int y1 = rnd.Next(codeH);
|
||||
int x2 = rnd.Next(codeW);
|
||||
int y2 = rnd.Next(codeH);
|
||||
Color clr = color[rnd.Next(color.Length)];
|
||||
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
|
||||
}
|
||||
//画验证码字符串
|
||||
for (int i = 0; i < chkCode.Length; i++)
|
||||
{
|
||||
string fnt = font[rnd.Next(font.Length)];
|
||||
Font ft = new Font(fnt, fontSize);
|
||||
Color clr = color[rnd.Next(color.Length)];
|
||||
g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
|
||||
}
|
||||
//将验证码图片写入内存流,并将其以 "image/Png" 格式输出
|
||||
MemoryStream ms = new MemoryStream();
|
||||
try
|
||||
{
|
||||
bmp.Save(ms, ImageFormat.Png);
|
||||
return ms.ToArray();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
g.Dispose();
|
||||
bmp.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class GetJsVesion{
|
||||
public static string GetVcode()
|
||||
{
|
||||
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
|
||||
return Convert.ToInt64(ts.TotalSeconds).ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
57
WaterCloud.Code/WaterCloud.Code.csproj
Normal file
57
WaterCloud.Code/WaterCloud.Code.csproj
Normal file
@ -0,0 +1,57 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||
<Optimize>false</Optimize>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="Extend\**" />
|
||||
<Compile Remove="Extension\**" />
|
||||
<EmbeddedResource Remove="Extend\**" />
|
||||
<EmbeddedResource Remove="Extension\**" />
|
||||
<None Remove="Extend\**" />
|
||||
<None Remove="Extension\**" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="Extend\AutoMapperExt.cs" />
|
||||
<Compile Include="Extend\Ext.Convert.cs" />
|
||||
<Compile Include="Extend\Ext.DateTime.cs" />
|
||||
<Compile Include="Extend\Ext.Enum.cs" />
|
||||
<Compile Include="Extend\Ext.Exception.cs" />
|
||||
<Compile Include="Extend\Ext.Format.cs" />
|
||||
<Compile Include="Extend\Ext.Validate.cs" />
|
||||
<Compile Include="Extend\ExtLinq.cs" />
|
||||
<Compile Include="Extend\ExtLinq.SortBy.cs" />
|
||||
<Compile Include="Extend\ExtList.Comparint.cs" />
|
||||
<Compile Include="Extend\ExtList.cs" />
|
||||
<Compile Include="Extend\ExtTable.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="12.0.0" />
|
||||
<PackageReference Include="Chloe" Version="5.1.4" />
|
||||
<PackageReference Include="CSRedisCore" Version="3.8.669" />
|
||||
<PackageReference Include="iTextSharp.LGPLv2.Core.Fix" Version="1.4.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Html.Abstractions" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="6.0.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||
<PackageReference Include="NPOI" Version="2.5.6" />
|
||||
<PackageReference Include="Serenity.Web" Version="3.14.5" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="6.0.0" />
|
||||
<PackageReference Include="ZKWeb.System.Drawing" Version="4.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="DistributedIDGenerator\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
84
WaterCloud.Code/Web/AlwaysResult.cs
Normal file
84
WaterCloud.Code/Web/AlwaysResult.cs
Normal file
@ -0,0 +1,84 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 统一返回结果
|
||||
/// </summary>
|
||||
public class AlwaysResult
|
||||
{
|
||||
/// <summary>
|
||||
/// 操作结果类型
|
||||
/// </summary>
|
||||
public object state { get; set; }
|
||||
/// <summary>
|
||||
/// 获取 消息内容
|
||||
/// </summary>
|
||||
public string message { get; set; }
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 统一返回结果
|
||||
/// </summary>
|
||||
public class AlwaysResult<T>: AlwaysResult
|
||||
{
|
||||
/// <summary>
|
||||
/// 列表的记录数
|
||||
/// </summary>
|
||||
public int count { get; set; }
|
||||
/// <summary>
|
||||
/// 获取 返回数据
|
||||
/// </summary>
|
||||
public T data { get; set; }
|
||||
}
|
||||
/// <summary>
|
||||
/// DTree返回结果
|
||||
/// </summary>
|
||||
public class DTreeResult
|
||||
{
|
||||
/// <summary>
|
||||
/// 操作结果类型
|
||||
/// </summary>
|
||||
public StatusInfo status { get; set; }
|
||||
/// 此页要显示的记录列表
|
||||
/// </summary>
|
||||
public object data { get; set; }
|
||||
}
|
||||
public class StatusInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// 操作结果类型
|
||||
/// </summary>
|
||||
public object code { get; set; }
|
||||
/// 此页要显示的记录列表
|
||||
/// </summary>
|
||||
public object message { get; set; }
|
||||
}
|
||||
/// <summary>
|
||||
/// 表示 ajax 操作结果类型的枚举
|
||||
/// </summary>
|
||||
public enum ResultType
|
||||
{
|
||||
/// <summary>
|
||||
/// 消息结果类型
|
||||
/// </summary>
|
||||
info,
|
||||
/// <summary>
|
||||
/// 成功结果类型
|
||||
/// </summary>
|
||||
success,
|
||||
/// <summary>
|
||||
/// 警告结果类型
|
||||
/// </summary>
|
||||
warning,
|
||||
/// <summary>
|
||||
/// 异常结果类型
|
||||
/// </summary>
|
||||
error
|
||||
}
|
||||
}
|
||||
220
WaterCloud.Code/Web/Browser.cs
Normal file
220
WaterCloud.Code/Web/Browser.cs
Normal file
@ -0,0 +1,220 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Web;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using System.Collections;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class Browser
|
||||
{
|
||||
public static bool IsMobile
|
||||
{
|
||||
get
|
||||
{
|
||||
HttpContext current = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>()?.HttpContext;
|
||||
string text = current.Request.Headers["HTTP_USER_AGENT"];
|
||||
Regex regex = new Regex("android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\\\/|plucker|pocket|psp|symbian|treo|up\\\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
|
||||
Regex regex2 = new Regex("1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\\\-(n|u)|c55\\\\/|capi|ccwa|cdm\\\\-|cell|chtm|cldc|cmd\\\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\\\-|_)|g1 u|g560|gene|gf\\\\-5|g\\\\-mo|go(\\\\.w|od)|gr(ad|un)|haie|hcit|hd\\\\-(m|p|t)|hei\\\\-|hi(pt|ta)|hp( i|ip)|hs\\\\-c|ht(c(\\\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\\\-(20|go|ma)|i230|iac( |\\\\-|\\\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\\\/)|klon|kpt |kwc\\\\-|kyo(c|k)|le(no|xi)|lg( g|\\\\/(k|l|u)|50|54|e\\\\-|e\\\\/|\\\\-[a-w])|libw|lynx|m1\\\\-w|m3ga|m50\\\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\\\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\\\-2|po(ck|rt|se)|prox|psio|pt\\\\-g|qa\\\\-a|qc(07|12|21|32|60|\\\\-[2-7]|i\\\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\\\-|oo|p\\\\-)|sdk\\\\/|se(c(\\\\-|0|1)|47|mc|nd|ri)|sgh\\\\-|shar|sie(\\\\-|m)|sk\\\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\\\-|v\\\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\\\-|tdg\\\\-|tel(i|m)|tim\\\\-|t\\\\-mo|to(pl|sh)|ts(70|m\\\\-|m3|m5)|tx\\\\-9|up(\\\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\\\\-|2|g)|yas\\\\-|your|zeto|zte\\\\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
|
||||
return regex.IsMatch(text) || regex2.IsMatch(text.Substring(0, 4));
|
||||
}
|
||||
}
|
||||
|
||||
public static string IP
|
||||
{
|
||||
get
|
||||
{
|
||||
string text = string.Empty;
|
||||
text = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>()?.HttpContext.Request.Headers["HTTP_X_FORWARDED_FOR"];
|
||||
string result;
|
||||
if (text != null && text != string.Empty)
|
||||
{
|
||||
if (text.IndexOf(".") == -1)
|
||||
{
|
||||
text = null;
|
||||
}
|
||||
else if (text.IndexOf(",") != -1)
|
||||
{
|
||||
text = text.Replace(" ", "").Replace("\"", "");
|
||||
string[] array = text.Split(",;".ToCharArray());
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
{
|
||||
if (Browser.IsIPAddress(array[i]) && array[i].Substring(0, 3) != "10." && array[i].Substring(0, 7) != "192.168" && array[i].Substring(0, 7) != "172.16.")
|
||||
{
|
||||
result = array[i];
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Browser.IsIPAddress(text))
|
||||
{
|
||||
result = text;
|
||||
return result;
|
||||
}
|
||||
text = null;
|
||||
}
|
||||
}
|
||||
if (text == null || text == string.Empty)
|
||||
{
|
||||
text = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>()?.HttpContext.Request.Headers["REMOTE_ADDR"];
|
||||
}
|
||||
if (text == null || text == string.Empty)
|
||||
{
|
||||
text = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>()?.HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString();
|
||||
|
||||
}
|
||||
result = text;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
public static string OS
|
||||
{
|
||||
get
|
||||
{
|
||||
string text = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>()?.HttpContext.Request.Headers["HTTP_USER_AGENT"];
|
||||
string result;
|
||||
if (text.IndexOf("NT 4.0") > 0)
|
||||
{
|
||||
result = "Windows NT ";
|
||||
}
|
||||
else if (text.IndexOf("NT 5.0") > 0)
|
||||
{
|
||||
result = "Windows 2000";
|
||||
}
|
||||
else if (text.IndexOf("NT 5.1") > 0)
|
||||
{
|
||||
result = "Windows XP";
|
||||
}
|
||||
else if (text.IndexOf("NT 5.2") > 0)
|
||||
{
|
||||
result = "Windows 2003";
|
||||
}
|
||||
else if (text.IndexOf("NT 6.0") > 0)
|
||||
{
|
||||
result = "Windows Vista";
|
||||
}
|
||||
else if (text.IndexOf("NT 6.1") > 0)
|
||||
{
|
||||
result = "Windows 2008";
|
||||
}
|
||||
else if (text.IndexOf("WindowsCE") > 0)
|
||||
{
|
||||
result = "Windows CE";
|
||||
}
|
||||
else if (text.IndexOf("NT") > 0)
|
||||
{
|
||||
result = "Windows NT ";
|
||||
}
|
||||
else if (text.IndexOf("9x") > 0)
|
||||
{
|
||||
result = "Windows ME";
|
||||
}
|
||||
else if (text.IndexOf("98") > 0)
|
||||
{
|
||||
result = "Windows 98";
|
||||
}
|
||||
else if (text.IndexOf("95") > 0)
|
||||
{
|
||||
result = "Windows 95";
|
||||
}
|
||||
else if (text.IndexOf("Win32") > 0)
|
||||
{
|
||||
result = "Win32";
|
||||
}
|
||||
else if (text.IndexOf("Linux") > 0)
|
||||
{
|
||||
result = "Linux";
|
||||
}
|
||||
else if (text.IndexOf("SunOS") > 0)
|
||||
{
|
||||
result = "SunOS";
|
||||
}
|
||||
else if (text.IndexOf("Mac") > 0)
|
||||
{
|
||||
result = "Mac";
|
||||
}
|
||||
else if (text.IndexOf("Linux") > 0)
|
||||
{
|
||||
result = "Linux";
|
||||
}
|
||||
else if (text.IndexOf("Windows") > 0)
|
||||
{
|
||||
result = "Windows";
|
||||
}
|
||||
else
|
||||
{
|
||||
result = "未知类型";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public static string MobileOS
|
||||
{
|
||||
get
|
||||
{
|
||||
HttpContext current = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>()?.HttpContext;
|
||||
string input = current.Request.Headers["HTTP_USER_AGENT"];
|
||||
Regex regex = new Regex("android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\\\/|plucker|pocket|psp|symbian|treo|up\\\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
|
||||
MatchCollection matchCollection = regex.Matches(input);
|
||||
string result;
|
||||
if (matchCollection.Count < 1)
|
||||
{
|
||||
result = Browser.OS;
|
||||
}
|
||||
else
|
||||
{
|
||||
result = matchCollection[0].Value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public static string PhoneNumber
|
||||
{
|
||||
get
|
||||
{
|
||||
string text = "";
|
||||
HttpContext current = GlobalContext.ServiceProvider.GetService<IHttpContextAccessor>().HttpContext;
|
||||
if (current.Request.Headers.ContainsKey("DEVICEID"))
|
||||
{
|
||||
text = current.Request.Headers["DEVICEID"].ToString();
|
||||
}
|
||||
if (current.Request.Headers.ContainsKey("HTTP_X_UP_subno"))
|
||||
{
|
||||
text = current.Request.Headers["HTTP_X_UP_subno"].ToString();
|
||||
text = text.Substring(3, 11);
|
||||
}
|
||||
if (current.Request.Headers.ContainsKey("HTTP_X_NETWORK_INFO"))
|
||||
{
|
||||
text = current.Request.Headers["HTTP_X_NETWORK_INFO"].ToString();
|
||||
}
|
||||
if (current.Request.Headers.ContainsKey("HTTP_X_UP_CALLING_LINE_ID"))
|
||||
{
|
||||
text = current.Request.Headers["HTTP_X_UP_CALLING_LINE_ID"].ToString();
|
||||
}
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsIPAddress(string str1)
|
||||
{
|
||||
bool result;
|
||||
if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15)
|
||||
{
|
||||
result = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
string pattern = "^\\d{1,3}[\\.]\\d{1,3}[\\.]\\d{1,3}[\\.]\\d{1,3}$";
|
||||
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
|
||||
result = regex.IsMatch(str1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
53
WaterCloud.Code/Web/Pagination.cs
Normal file
53
WaterCloud.Code/Web/Pagination.cs
Normal file
@ -0,0 +1,53 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 分页信息
|
||||
/// </summary>
|
||||
public class Pagination
|
||||
{
|
||||
/// <summary>
|
||||
/// 每页行数
|
||||
/// </summary>
|
||||
public int rows { get; set; }
|
||||
/// <summary>
|
||||
/// 当前页
|
||||
/// </summary>
|
||||
public int page { get; set; }
|
||||
/// <summary>
|
||||
/// 排序列
|
||||
/// </summary>
|
||||
public string sort { get; set; }
|
||||
/// <summary>
|
||||
/// 排序类型
|
||||
/// </summary>
|
||||
public string order { get; set; }
|
||||
/// <summary>
|
||||
/// 总记录数
|
||||
/// </summary>
|
||||
public int records { get; set; }
|
||||
/// <summary>
|
||||
/// 总页数
|
||||
/// </summary>
|
||||
public int total
|
||||
{
|
||||
get
|
||||
{
|
||||
if (records > 0)
|
||||
{
|
||||
return records % this.rows == 0 ? records / this.rows : records / this.rows + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
35
WaterCloud.Code/Web/ResponseEnity.cs
Normal file
35
WaterCloud.Code/Web/ResponseEnity.cs
Normal file
@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class AlwaysResultEx : AlwaysResult
|
||||
{
|
||||
public object error { get; set; }
|
||||
public long insertId { get; set; }
|
||||
|
||||
public object callbackdata { get; set; }
|
||||
}
|
||||
|
||||
public class ResultEx: AlwaysResult
|
||||
{
|
||||
public int code { get; set; }
|
||||
|
||||
}
|
||||
|
||||
public enum errorCodeType
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 成功结果类型
|
||||
/// </summary>
|
||||
success=0,
|
||||
/// <summary>
|
||||
/// 异常结果类型
|
||||
/// </summary>
|
||||
error=1
|
||||
}
|
||||
}
|
||||
45
WaterCloud.Code/Web/Tree/TreeSelect.cs
Normal file
45
WaterCloud.Code/Web/Tree/TreeSelect.cs
Normal file
@ -0,0 +1,45 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static class TreeSelect
|
||||
{
|
||||
public static string TreeSelectJson(this List<TreeSelectModel> data)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("[");
|
||||
sb.Append(TreeSelectJson(data, "0", ""));
|
||||
sb.Append("]");
|
||||
return sb.ToString();
|
||||
}
|
||||
private static string TreeSelectJson(List<TreeSelectModel> data, string parentId, string blank)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
var ChildNodeList = data.FindAll(t => t.parentId == parentId);
|
||||
var tabline = "";
|
||||
if (parentId != "0")
|
||||
{
|
||||
tabline = " ";
|
||||
}
|
||||
if (ChildNodeList.Count > 0)
|
||||
{
|
||||
tabline = tabline + blank;
|
||||
}
|
||||
foreach (TreeSelectModel entity in ChildNodeList)
|
||||
{
|
||||
entity.text = tabline + entity.text;
|
||||
string strJson = entity.ToJson();
|
||||
sb.Append(strJson);
|
||||
sb.Append(TreeSelectJson(data, entity.id, tabline));
|
||||
}
|
||||
return sb.ToString().Replace("}{", "},{");
|
||||
}
|
||||
}
|
||||
}
|
||||
18
WaterCloud.Code/Web/Tree/TreeSelectModel.cs
Normal file
18
WaterCloud.Code/Web/Tree/TreeSelectModel.cs
Normal file
@ -0,0 +1,18 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class TreeSelectModel
|
||||
{
|
||||
public string id { get; set; }
|
||||
public string text { get; set; }
|
||||
public string code { get; set; }
|
||||
public string parentId { get; set; }
|
||||
public object data { get; set; }
|
||||
}
|
||||
}
|
||||
56
WaterCloud.Code/Web/TreeGrid/TreeGrid.cs
Normal file
56
WaterCloud.Code/Web/TreeGrid/TreeGrid.cs
Normal file
@ -0,0 +1,56 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static class TreeGrid
|
||||
{
|
||||
public static string TreeGridJson(this List<TreeGridModel> data)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(TreeGridJson(data, "0"));
|
||||
return sb.ToString();
|
||||
}
|
||||
private static string TreeGridJson(List<TreeGridModel> data, string parentId)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
var ChildNodeList = data.FindAll(t => t.parentId == parentId);
|
||||
sb.Append("[");
|
||||
if (ChildNodeList.Count > 0) {
|
||||
foreach (TreeGridModel entity in ChildNodeList)
|
||||
{
|
||||
string strJson = entity.ToJson()+",";
|
||||
strJson = strJson.Insert(1, "\"children\":" + TreeGridJson(data, entity.id) + ",");
|
||||
sb.Append(strJson);
|
||||
}
|
||||
sb = sb.Remove(sb.Length - 1, 1);
|
||||
}
|
||||
|
||||
sb.Append("]");
|
||||
return sb.ToString().Replace("}{", "},{");
|
||||
|
||||
}
|
||||
public static List<TreeGridModel> TreeList(this List<TreeGridModel> data)
|
||||
{
|
||||
return TreeList(data, "0");
|
||||
}
|
||||
private static List<TreeGridModel> TreeList(List<TreeGridModel> data, string parentId)
|
||||
{
|
||||
var ChildNodeList = data.FindAll(t => t.parentId == parentId);
|
||||
if (ChildNodeList.Count > 0)
|
||||
{
|
||||
foreach (TreeGridModel entity in ChildNodeList)
|
||||
{
|
||||
entity.children = TreeList(data, entity.id);
|
||||
}
|
||||
}
|
||||
return ChildNodeList;
|
||||
}
|
||||
}
|
||||
}
|
||||
22
WaterCloud.Code/Web/TreeGrid/TreeGridModel.cs
Normal file
22
WaterCloud.Code/Web/TreeGrid/TreeGridModel.cs
Normal file
@ -0,0 +1,22 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class TreeGridModel
|
||||
{
|
||||
public string id { get; set; }
|
||||
public string parentId { get; set; }
|
||||
public string title { get; set; }
|
||||
public object self { get; set; }
|
||||
public object checkArr { get; set; }
|
||||
public bool? disabled { get; set; }
|
||||
public List<TreeGridModel> children { get; set; }
|
||||
}
|
||||
}
|
||||
47
WaterCloud.Code/Web/TreeQuery.cs
Normal file
47
WaterCloud.Code/Web/TreeQuery.cs
Normal file
@ -0,0 +1,47 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static class TreeQuery
|
||||
{
|
||||
public static List<T> TreeWhere<T>(this List<T> entityList, Predicate<T> condition, string keyValue = "F_Id", string parentId = "F_ParentId") where T : class
|
||||
{
|
||||
List<T> locateList = entityList.FindAll(condition);
|
||||
var parameter = Expression.Parameter(typeof(T), "t");
|
||||
List<T> treeList = new List<T>();
|
||||
foreach (T entity in locateList)
|
||||
{
|
||||
treeList.Add(entity);
|
||||
string pId = entity.GetType().GetProperty(parentId).GetValue(entity, null).ToString();
|
||||
while (true)
|
||||
{
|
||||
if (string.IsNullOrEmpty(pId) && pId == "0")
|
||||
{
|
||||
break;
|
||||
}
|
||||
Predicate<T> upLambda = (Expression.Equal(parameter.Property(keyValue), Expression.Constant(pId))).ToLambda<Predicate<T>>(parameter).Compile();
|
||||
T upRecord = entityList.Find(upLambda);
|
||||
if (upRecord != null)
|
||||
{
|
||||
treeList.Add(upRecord);
|
||||
pId = upRecord.GetType().GetProperty(parentId).GetValue(upRecord, null).ToString();
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return treeList.Distinct().ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
59
WaterCloud.Code/Web/TreeView/TreeView.cs
Normal file
59
WaterCloud.Code/Web/TreeView/TreeView.cs
Normal file
@ -0,0 +1,59 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static class TreeView
|
||||
{
|
||||
public static string TreeViewJson(this List<TreeViewModel> data, string parentId = "0")
|
||||
{
|
||||
StringBuilder strJson = new StringBuilder();
|
||||
List<TreeViewModel> item = data.FindAll(t => t.parentId == parentId);
|
||||
strJson.Append("[");
|
||||
if (item.Count > 0)
|
||||
{
|
||||
foreach (TreeViewModel entity in item)
|
||||
{
|
||||
strJson.Append("{");
|
||||
strJson.Append("\"id\":\"" + entity.id + "\",");
|
||||
strJson.Append("\"text\":\"" + entity.text.Replace(" ", "") + "\",");
|
||||
strJson.Append("\"value\":\"" + entity.value + "\",");
|
||||
if (entity.title != null && !string.IsNullOrEmpty(entity.title.Replace(" ", "")))
|
||||
{
|
||||
strJson.Append("\"title\":\"" + entity.title.Replace(" ", "") + "\",");
|
||||
}
|
||||
if (entity.img != null && !string.IsNullOrEmpty(entity.img.Replace(" ", "")))
|
||||
{
|
||||
strJson.Append("\"img\":\"" + entity.img.Replace(" ", "") + "\",");
|
||||
}
|
||||
if (entity.checkstate != null)
|
||||
{
|
||||
strJson.Append("\"checkstate\":" + entity.checkstate + ",");
|
||||
}
|
||||
if (entity.parentId != null)
|
||||
{
|
||||
strJson.Append("\"parentnodes\":\"" + entity.parentId + "\",");
|
||||
}
|
||||
strJson.Append("\"showcheck\":" + entity.showcheck.ToString().ToLower() + ",");
|
||||
strJson.Append("\"isexpand\":" + entity.isexpand.ToString().ToLower() + ",");
|
||||
if (entity.complete == true)
|
||||
{
|
||||
strJson.Append("\"complete\":" + entity.complete.ToString().ToLower() + ",");
|
||||
}
|
||||
strJson.Append("\"hasChildren\":" + entity.hasChildren.ToString().ToLower() + ",");
|
||||
strJson.Append("\"ChildNodes\":" + TreeViewJson(data, entity.id) + "");
|
||||
strJson.Append("},");
|
||||
}
|
||||
strJson = strJson.Remove(strJson.Length - 1, 1);
|
||||
}
|
||||
strJson.Append("]");
|
||||
return strJson.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
23
WaterCloud.Code/Web/TreeView/TreeViewModel.cs
Normal file
23
WaterCloud.Code/Web/TreeView/TreeViewModel.cs
Normal file
@ -0,0 +1,23 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class TreeViewModel
|
||||
{
|
||||
public string parentId { get; set; }
|
||||
public string id { get; set; }
|
||||
public string text { get; set; }
|
||||
public string value { get; set; }
|
||||
public int? checkstate { get; set; }
|
||||
public bool showcheck { get; set; }
|
||||
public bool complete { get; set; }
|
||||
public bool isexpand { get; set; }
|
||||
public bool hasChildren { get; set; }
|
||||
public string img { get; set; }
|
||||
public string title { get; set; }
|
||||
}
|
||||
}
|
||||
748
WaterCloud.Code/WebHelper.cs
Normal file
748
WaterCloud.Code/WebHelper.cs
Normal file
@ -0,0 +1,748 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Web;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Net.Sockets;
|
||||
using System.Linq;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class WebHelper
|
||||
{
|
||||
#region ResolveUrl(解析相对Url)
|
||||
/// <summary>
|
||||
/// 解析相对Url
|
||||
/// </summary>
|
||||
/// <param name="relativeUrl">相对Url</param>
|
||||
public static string ResolveUrl(string relativeUrl)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(relativeUrl))
|
||||
return string.Empty;
|
||||
relativeUrl = relativeUrl.Replace("\\", "/");
|
||||
if (relativeUrl.StartsWith("/"))
|
||||
return relativeUrl;
|
||||
if (relativeUrl.Contains("://"))
|
||||
return relativeUrl;
|
||||
return VirtualPathUtility.ToAbsolute(relativeUrl);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region HtmlEncode(对html字符串进行编码)
|
||||
/// <summary>
|
||||
/// 对html字符串进行编码
|
||||
/// </summary>
|
||||
/// <param name="html">html字符串</param>
|
||||
public static string HtmlEncode(string html)
|
||||
{
|
||||
return HttpUtility.HtmlEncode(html);
|
||||
}
|
||||
/// <summary>
|
||||
/// 对html字符串进行解码
|
||||
/// </summary>
|
||||
/// <param name="html">html字符串</param>
|
||||
public static string HtmlDecode(string html)
|
||||
{
|
||||
return HttpUtility.HtmlDecode(html);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region UrlEncode(对Url进行编码)
|
||||
|
||||
/// <summary>
|
||||
/// 对Url进行编码
|
||||
/// </summary>
|
||||
/// <param name="url">url</param>
|
||||
/// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
|
||||
public static string UrlEncode(string url, bool isUpper = false)
|
||||
{
|
||||
return UrlEncode(url, Encoding.UTF8, isUpper);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对Url进行编码
|
||||
/// </summary>
|
||||
/// <param name="url">url</param>
|
||||
/// <param name="encoding">字符编码</param>
|
||||
/// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
|
||||
public static string UrlEncode(string url, Encoding encoding, bool isUpper = false)
|
||||
{
|
||||
var result = HttpUtility.UrlEncode(url, encoding);
|
||||
if (!isUpper)
|
||||
return result;
|
||||
return GetUpperEncode(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取大写编码字符串
|
||||
/// </summary>
|
||||
private static string GetUpperEncode(string encode)
|
||||
{
|
||||
var result = new StringBuilder();
|
||||
int index = int.MinValue;
|
||||
for (int i = 0; i < encode.Length; i++)
|
||||
{
|
||||
string character = encode[i].ToString();
|
||||
if (character == "%")
|
||||
index = i;
|
||||
if (i - index == 1 || i - index == 2)
|
||||
character = character.ToUpper();
|
||||
result.Append(character);
|
||||
}
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region UrlDecode(对Url进行解码)
|
||||
|
||||
/// <summary>
|
||||
/// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
|
||||
/// </summary>
|
||||
/// <param name="url">url</param>
|
||||
public static string UrlDecode(string url)
|
||||
{
|
||||
return HttpUtility.UrlDecode(url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
|
||||
/// </summary>
|
||||
/// <param name="url">url</param>
|
||||
/// <param name="encoding">字符编码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码</param>
|
||||
public static string UrlDecode(string url, Encoding encoding)
|
||||
{
|
||||
return HttpUtility.UrlDecode(url, encoding);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Session操作
|
||||
|
||||
/// <summary>
|
||||
/// 写Session
|
||||
/// </summary>
|
||||
/// <param name="key">Session的键名</param>
|
||||
/// <param name="value">Session的键值</param>
|
||||
public static void WriteSession(string key, string value)
|
||||
{
|
||||
if (key.IsEmpty())
|
||||
return;
|
||||
IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
|
||||
hca?.HttpContext?.Session.SetString(key, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取Session的值
|
||||
/// </summary>
|
||||
/// <param name="key">Session的键名</param>
|
||||
public static string GetSession(string key)
|
||||
{
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
|
||||
return hca?.HttpContext?.Session.GetString(key) ?? "";
|
||||
}
|
||||
/// <summary>
|
||||
/// 删除指定Session
|
||||
/// </summary>
|
||||
/// <param name="key">Session的键名</param>
|
||||
public static void RemoveSession(string key)
|
||||
{
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
return;
|
||||
}
|
||||
IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
|
||||
hca?.HttpContext?.Session.Remove(key);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Cookie操作
|
||||
/// <summary>
|
||||
/// 写cookie值
|
||||
/// </summary>
|
||||
/// <param name="strName">名称</param>
|
||||
/// <param name="strValue">值</param>
|
||||
public static void WriteCookie(string strName, string strValue)
|
||||
{
|
||||
IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
|
||||
CookieOptions option = new CookieOptions();
|
||||
option.Expires = DateTime.Now.AddDays(30);
|
||||
hca?.HttpContext?.Response.Cookies.Append(strName, strValue, option);
|
||||
}
|
||||
/// <summary>
|
||||
/// 写cookie值
|
||||
/// </summary>
|
||||
/// <param name="strName">名称</param>
|
||||
/// <param name="strValue">值</param>
|
||||
/// <param name="strValue">过期时间(分钟)</param>
|
||||
public static void WriteCookie(string strName, string strValue, int expires)
|
||||
{
|
||||
IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
|
||||
CookieOptions option = new CookieOptions();
|
||||
option.Expires = DateTime.Now.AddMinutes(expires);
|
||||
hca?.HttpContext?.Response.Cookies.Append(strName, strValue, option);
|
||||
}
|
||||
/// <summary>
|
||||
/// 读cookie值
|
||||
/// </summary>
|
||||
/// <param name="strName">名称</param>
|
||||
/// <returns>cookie值</returns>
|
||||
public static string GetCookie(string strName)
|
||||
{
|
||||
IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
|
||||
return hca?.HttpContext?.Request.Cookies[strName]??"";
|
||||
}
|
||||
/// <summary>
|
||||
/// 删除Cookie对象
|
||||
/// </summary>
|
||||
/// <param name="CookiesName">Cookie对象名称</param>
|
||||
public static void RemoveCookie(string CookiesName)
|
||||
{
|
||||
IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
|
||||
hca?.HttpContext?.Response.Cookies.Delete(CookiesName);
|
||||
}
|
||||
#endregion
|
||||
|
||||
//#region GetFileControls(获取客户端文件控件集合)
|
||||
|
||||
///// <summary>
|
||||
///// 获取有效客户端文件控件集合,文件控件必须上传了内容,为空将被忽略,
|
||||
///// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
|
||||
///// </summary>
|
||||
//public static List<HttpPostedFile> GetFileControls()
|
||||
//{
|
||||
// var result = new List<HttpPostedFile>();
|
||||
// var files = HttpContext.Current.Request.Files;
|
||||
// if (files.Count == 0)
|
||||
// return result;
|
||||
// for (int i = 0; i < files.Count; i++)
|
||||
// {
|
||||
// var file = files[i];
|
||||
// if (file.ContentLength == 0)
|
||||
// continue;
|
||||
// result.Add(files[i]);
|
||||
// }
|
||||
// return result;
|
||||
//}
|
||||
|
||||
//#endregion
|
||||
|
||||
//#region GetFileControl(获取第一个有效客户端文件控件)
|
||||
|
||||
///// <summary>
|
||||
///// 获取第一个有效客户端文件控件,文件控件必须上传了内容,为空将被忽略,
|
||||
///// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
|
||||
///// </summary>
|
||||
//public static HttpPostedFile GetFileControl()
|
||||
//{
|
||||
// var files = GetFileControls();
|
||||
// if (files == null || files.Count == 0)
|
||||
// return null;
|
||||
// return files[0];
|
||||
//}
|
||||
|
||||
//#endregion
|
||||
|
||||
#region HttpWebRequest(请求网络资源)
|
||||
|
||||
/// <summary>
|
||||
/// 请求网络资源,返回响应的文本
|
||||
/// </summary>
|
||||
/// <param name="url">网络资源地址</param>
|
||||
public static string HttpWebRequest(string url)
|
||||
{
|
||||
return HttpWebRequest(url, string.Empty, Encoding.GetEncoding("utf-8"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 请求网络资源,返回响应的文本
|
||||
/// </summary>
|
||||
/// <param name="url">网络资源Url地址</param>
|
||||
/// <param name="parameters">提交的参数,格式:参数1=参数值1&参数2=参数值2</param>
|
||||
public static string HttpWebRequest(string url, string parameters)
|
||||
{
|
||||
return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 请求网络资源,返回响应的文本
|
||||
/// </summary>
|
||||
/// <param name="url">网络资源地址</param>
|
||||
/// <param name="parameters">提交的参数,格式:参数1=参数值1&参数2=参数值2</param>
|
||||
/// <param name="encoding">字符编码</param>
|
||||
/// <param name="isPost">是否Post提交</param>
|
||||
/// <param name="contentType">内容类型</param>
|
||||
/// <param name="cookie">Cookie容器</param>
|
||||
/// <param name="timeout">超时时间</param>
|
||||
public static string HttpWebRequest(string url, string parameters, Encoding encoding, bool isPost = false,
|
||||
string contentType = "application/x-www-form-urlencoded", CookieContainer cookie = null, int timeout = 120000)
|
||||
{
|
||||
var request = (HttpWebRequest)WebRequest.Create(url);
|
||||
request.Timeout = timeout;
|
||||
request.CookieContainer = cookie;
|
||||
if (isPost)
|
||||
{
|
||||
byte[] postData = encoding.GetBytes(parameters);
|
||||
request.Method = "POST";
|
||||
request.ContentType = contentType;
|
||||
request.ContentLength = postData.Length;
|
||||
using (Stream stream = request.GetRequestStream())
|
||||
{
|
||||
stream.Write(postData, 0, postData.Length);
|
||||
}
|
||||
}
|
||||
var response = (HttpWebResponse)request.GetResponse();
|
||||
string result;
|
||||
using (Stream stream = response.GetResponseStream())
|
||||
{
|
||||
if (stream == null)
|
||||
return string.Empty;
|
||||
using (var reader = new StreamReader(stream, encoding))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 去除HTML标记
|
||||
/// <summary>
|
||||
/// 去除HTML标记
|
||||
/// </summary>
|
||||
/// <param name="NoHTML">包括HTML的源码 </param>
|
||||
/// <returns>已经去除后的文字</returns>
|
||||
public static string NoHtml(string Htmlstring)
|
||||
{
|
||||
//删除脚本
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
|
||||
//删除HTML
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"…", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"—", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"“", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring.Replace("<", "");
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"”", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring.Replace(">", "");
|
||||
Htmlstring.Replace("\r\n", "");
|
||||
IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
|
||||
|
||||
Htmlstring = HtmlEncoder.Default.Encode(Htmlstring).Trim();
|
||||
return Htmlstring;
|
||||
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 格式化文本(防止SQL注入)
|
||||
/// <summary>
|
||||
/// 格式化文本(防止SQL注入)
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static string Formatstr(string html)
|
||||
{
|
||||
System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
html = regex1.Replace(html, ""); //过滤<script></script>标记
|
||||
html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
|
||||
html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
|
||||
html = regex4.Replace(html, ""); //过滤iframe
|
||||
html = regex10.Replace(html, "s_elect");
|
||||
html = regex11.Replace(html, "u_pudate");
|
||||
html = regex12.Replace(html, "d_elete");
|
||||
html = html.Replace("'", "’");
|
||||
html = html.Replace(" ", " ");
|
||||
return html;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 当前连接
|
||||
public static HttpContext HttpContext
|
||||
{
|
||||
get { return GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>().HttpContext; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 网络信息
|
||||
public static string Ip
|
||||
{
|
||||
get
|
||||
{
|
||||
string result = string.Empty;
|
||||
try
|
||||
{
|
||||
if (HttpContext != null)
|
||||
{
|
||||
result = GetWebClientIp();
|
||||
}
|
||||
if (string.IsNullOrEmpty(result))
|
||||
{
|
||||
result = GetLanIp();
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetWebClientIp()
|
||||
{
|
||||
try
|
||||
{
|
||||
string ip = GetWebRemoteIp();
|
||||
foreach (var hostAddress in Dns.GetHostAddresses(ip))
|
||||
{
|
||||
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
return hostAddress.ToString();
|
||||
}
|
||||
else if (hostAddress.AddressFamily == AddressFamily.InterNetworkV6)
|
||||
{
|
||||
return hostAddress.MapToIPv4().ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public static string GetLanIp()
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
|
||||
{
|
||||
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
return hostAddress.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public static string GetWanIp()
|
||||
{
|
||||
string ip = string.Empty;
|
||||
try
|
||||
{
|
||||
string url = "http://www.net.cn/static/customercare/yourip.asp";
|
||||
string html = HttpHelper.HttpGet(url);
|
||||
if (!string.IsNullOrEmpty(html))
|
||||
{
|
||||
ip = HtmlHelper.Resove(html, "<h2>", "</h2>");
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return ip;
|
||||
}
|
||||
|
||||
private static string GetWebRemoteIp()
|
||||
{
|
||||
try
|
||||
{
|
||||
string ip = HttpContext?.Connection?.RemoteIpAddress.ParseToString();
|
||||
if (HttpContext != null && HttpContext.Request != null)
|
||||
{
|
||||
if (HttpContext.Request.Headers.ContainsKey("X-Real-IP"))
|
||||
{
|
||||
ip = HttpContext.Request.Headers["X-Real-IP"].ToString();
|
||||
}
|
||||
|
||||
if (HttpContext.Request.Headers.ContainsKey("X-Forwarded-For"))
|
||||
{
|
||||
ip = HttpContext.Request.Headers["X-Forwarded-For"].ToString();
|
||||
}
|
||||
}
|
||||
return ip;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public static string UserAgent
|
||||
{
|
||||
get
|
||||
{
|
||||
string userAgent = string.Empty;
|
||||
try
|
||||
{
|
||||
userAgent = HttpContext?.Request?.Headers["User-Agent"];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
return userAgent;
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetOSVersion()
|
||||
{
|
||||
var osVersion = string.Empty;
|
||||
try
|
||||
{
|
||||
var userAgent = UserAgent;
|
||||
if (userAgent.Contains("NT 10"))
|
||||
{
|
||||
osVersion = "Windows 10";
|
||||
}
|
||||
else if (userAgent.Contains("NT 6.3"))
|
||||
{
|
||||
osVersion = "Windows 8";
|
||||
}
|
||||
else if (userAgent.Contains("NT 6.1"))
|
||||
{
|
||||
osVersion = "Windows 7";
|
||||
}
|
||||
else if (userAgent.Contains("NT 6.0"))
|
||||
{
|
||||
osVersion = "Windows Vista/Server 2008";
|
||||
}
|
||||
else if (userAgent.Contains("NT 5.2"))
|
||||
{
|
||||
osVersion = "Windows Server 2003";
|
||||
}
|
||||
else if (userAgent.Contains("NT 5.1"))
|
||||
{
|
||||
osVersion = "Windows XP";
|
||||
}
|
||||
else if (userAgent.Contains("NT 5"))
|
||||
{
|
||||
osVersion = "Windows 2000";
|
||||
}
|
||||
else if (userAgent.Contains("NT 4"))
|
||||
{
|
||||
osVersion = "Windows NT4";
|
||||
}
|
||||
else if (userAgent.Contains("Android"))
|
||||
{
|
||||
osVersion = "Android";
|
||||
}
|
||||
else if (userAgent.Contains("Me"))
|
||||
{
|
||||
osVersion = "Windows Me";
|
||||
}
|
||||
else if (userAgent.Contains("98"))
|
||||
{
|
||||
osVersion = "Windows 98";
|
||||
}
|
||||
else if (userAgent.Contains("95"))
|
||||
{
|
||||
osVersion = "Windows 95";
|
||||
}
|
||||
else if (userAgent.Contains("Mac"))
|
||||
{
|
||||
osVersion = "Mac";
|
||||
}
|
||||
else if (userAgent.Contains("Unix"))
|
||||
{
|
||||
osVersion = "UNIX";
|
||||
}
|
||||
else if (userAgent.Contains("Linux"))
|
||||
{
|
||||
osVersion = "Linux";
|
||||
}
|
||||
else if (userAgent.Contains("SunOS"))
|
||||
{
|
||||
osVersion = "SunOS";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
return osVersion;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IP位置查询
|
||||
public static string GetIpLocation(string ipAddress)
|
||||
{
|
||||
string ipLocation = "未知";
|
||||
try
|
||||
{
|
||||
if (!IsInnerIP(ipAddress))
|
||||
{
|
||||
ipLocation = GetIpLocationFromPCOnline(ipAddress);
|
||||
}
|
||||
else
|
||||
{
|
||||
ipLocation = "本地局域网";
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return ipLocation;
|
||||
}
|
||||
return ipLocation;
|
||||
}
|
||||
public static string GetPconlineIpLocation(string ClientIp)
|
||||
{
|
||||
string Location = "未知";
|
||||
try
|
||||
{
|
||||
string url = "http://whois.pconline.com.cn/ipJson.jsp?json=true";
|
||||
if (ClientIp != "")
|
||||
{
|
||||
url += "&ip=" + ClientIp;
|
||||
}
|
||||
var request = (HttpWebRequest)WebRequest.Create(url);
|
||||
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
|
||||
{
|
||||
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GB2312"));
|
||||
string str = reader.ReadToEnd();
|
||||
reader.Close();
|
||||
reader.Dispose();
|
||||
|
||||
if (string.IsNullOrEmpty(str))
|
||||
{
|
||||
Location = "未知";
|
||||
}
|
||||
else
|
||||
{
|
||||
var json = JsonHelper.ToJObject(str);
|
||||
|
||||
var nameData = json["addr"];
|
||||
Location = nameData.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Location = "未知";
|
||||
}
|
||||
return Location;
|
||||
}
|
||||
|
||||
private static string GetIpLocationFromPCOnline(string ipAddress)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpResult httpResult = new HttpHelper().GetHtml(new HttpItem
|
||||
{
|
||||
URL = "http://whois.pconline.com.cn/ip.jsp?ip=" + ipAddress,
|
||||
ContentType = "text/html; charset=gb2312"
|
||||
});
|
||||
|
||||
string ipLocation = "未知";
|
||||
if (!string.IsNullOrEmpty(httpResult.Html))
|
||||
{
|
||||
ipLocation = httpResult.Html.Trim();
|
||||
}
|
||||
return ipLocation;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return "未知";
|
||||
}
|
||||
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 判断是否是外网IP
|
||||
public static bool IsInnerIP(string ipAddress)
|
||||
{
|
||||
try
|
||||
{
|
||||
bool isInnerIp = false;
|
||||
long ipNum = GetIpNum(ipAddress);
|
||||
/**
|
||||
私有IP:A类 10.0.0.0-10.255.255.255
|
||||
B类 172.16.0.0-172.31.255.255
|
||||
C类 192.168.0.0-192.168.255.255
|
||||
当然,还有127这个网段是环回地址
|
||||
**/
|
||||
long aBegin = GetIpNum("10.0.0.0");
|
||||
long aEnd = GetIpNum("10.255.255.255");
|
||||
long bBegin = GetIpNum("172.16.0.0");
|
||||
long bEnd = GetIpNum("172.31.255.255");
|
||||
long cBegin = GetIpNum("192.168.0.0");
|
||||
long cEnd = GetIpNum("192.168.255.255");
|
||||
isInnerIp = IsInner(ipNum, aBegin, aEnd) || IsInner(ipNum, bBegin, bEnd) || IsInner(ipNum, cBegin, cEnd) || ipAddress.Equals("127.0.0.1");
|
||||
return isInnerIp;
|
||||
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把IP地址转换为Long型数字
|
||||
/// </summary>
|
||||
/// <param name="ipAddress">IP地址字符串</param>
|
||||
/// <returns></returns>
|
||||
private static long GetIpNum(string ipAddress)
|
||||
{
|
||||
string[] ip = ipAddress.Split('.');
|
||||
long a = int.Parse(ip[0]);
|
||||
long b = int.Parse(ip[1]);
|
||||
long c = int.Parse(ip[2]);
|
||||
long d = int.Parse(ip[3]);
|
||||
|
||||
long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
|
||||
return ipNum;
|
||||
}
|
||||
|
||||
private static bool IsInner(long userIp, long begin, long end)
|
||||
{
|
||||
return (userIp >= begin) && (userIp <= end);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
158
WaterCloud.CodeGenerator/Model/BaseConfigModel.cs
Normal file
158
WaterCloud.CodeGenerator/Model/BaseConfigModel.cs
Normal file
@ -0,0 +1,158 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.CodeGenerator
|
||||
{
|
||||
public class BaseConfigModel
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库表名sys_menu
|
||||
/// </summary>
|
||||
public string TableName { get; set; }
|
||||
/// <summary>
|
||||
/// 表名首字母大写Sys_Menu
|
||||
/// </summary>
|
||||
public string TableNameUpper { get; set; }
|
||||
public FileConfigModel FileConfig { get; set; }
|
||||
public OutputConfigModel OutputConfig { get; set; }
|
||||
public PageIndexModel PageIndex { get; set; }
|
||||
public PageFormModel PageForm { get; set; }
|
||||
}
|
||||
|
||||
public class FileConfigModel
|
||||
{
|
||||
public string ClassPrefix { get; set; }
|
||||
public string ClassDescription { get; set; }
|
||||
public string CreateUserName { get; set; }
|
||||
public string CreateDate { get; set; }
|
||||
public string EntityName { get; set; }
|
||||
public string ServiceName { get; set; }
|
||||
public string ControllerName { get; set; }
|
||||
public string PageIndexName { get; set; }
|
||||
public string PageFormName { get; set; }
|
||||
public string PageDetailsName { get; set; }
|
||||
}
|
||||
public class OutputConfigModel
|
||||
{
|
||||
public string OutputModule { get; set; }
|
||||
public string OutputEntity { get; set; }
|
||||
public string OutputService { get; set; }
|
||||
public string OutputWeb { get; set; }
|
||||
}
|
||||
public class PageIndexModel
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否菜单显示
|
||||
/// </summary>
|
||||
public bool IsMunu { get; set; }
|
||||
/// <summary>
|
||||
/// 是否需要搜索框
|
||||
/// </summary>
|
||||
public bool IsSearch { get; set; }
|
||||
/// <summary>
|
||||
/// 是否树形表格
|
||||
/// </summary>
|
||||
public bool IsTree { get; set; }
|
||||
/// <summary>
|
||||
/// 是否字段控制
|
||||
/// </summary>
|
||||
public bool IsFields { get; set; }
|
||||
/// <summary>
|
||||
/// 是否公共
|
||||
/// </summary>
|
||||
public bool IsPublic { get; set; }
|
||||
/// <summary>
|
||||
/// 是否缓存
|
||||
/// </summary>
|
||||
public bool IsCache { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 工具栏按钮(新增 修改 删除 查看)
|
||||
/// </summary>
|
||||
public List<string> ButtonList { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否有分页
|
||||
/// </summary>
|
||||
public bool IsPagination { get; set; }
|
||||
/// <summary>
|
||||
/// 排序字段
|
||||
/// </summary>
|
||||
public string SortColumn { get; set; }
|
||||
/// <summary>
|
||||
/// 父级字段
|
||||
/// </summary>
|
||||
public string ParentColum { get; set; }
|
||||
/// <summary>
|
||||
/// 树形显示字段
|
||||
/// </summary>
|
||||
public string TreeColum { get; set; }
|
||||
/// <summary>
|
||||
/// 删除字段字段
|
||||
/// </summary>
|
||||
public string DeleteColum { get; set; }
|
||||
/// <summary>
|
||||
/// 创建时间字段
|
||||
/// </summary>
|
||||
public string CreateColum { get; set; }
|
||||
/// <summary>
|
||||
/// 模糊查询字段
|
||||
/// </summary>
|
||||
public List<string> KeywordColum { get; set; }
|
||||
public bool? IsAsc { get; set; }
|
||||
public List<ColumnField> ColumnList { get; set; }
|
||||
|
||||
}
|
||||
public class PageFormModel
|
||||
{
|
||||
/// <summary>
|
||||
/// 1表示显示成1列,2表示显示成2列
|
||||
/// </summary>
|
||||
public int ShowMode { get; set; }
|
||||
public Dictionary<string, string> FieldList { get; set; }
|
||||
}
|
||||
public class ColumnField
|
||||
{
|
||||
/// <summary>
|
||||
/// 字段
|
||||
/// </summary>
|
||||
public string field { get; set; }
|
||||
/// <summary>
|
||||
/// 列名
|
||||
/// </summary>
|
||||
public string title { get; set; }
|
||||
/// <summary>
|
||||
/// 宽度
|
||||
/// </summary>
|
||||
public int? width { get; set; }
|
||||
/// <summary>
|
||||
/// 是否minWidth
|
||||
/// </summary>
|
||||
public bool? isAotuWidth { get; set; }
|
||||
/// <summary>
|
||||
/// 是否排序
|
||||
/// </summary>
|
||||
public bool? isSorted { get; set; }
|
||||
/// <summary>
|
||||
/// 是否过滤
|
||||
/// </summary>
|
||||
public bool? isFilter { get; set; }
|
||||
/// <summary>
|
||||
/// 过滤类型
|
||||
/// </summary>
|
||||
public string filterType { get; set; }
|
||||
/// <summary>
|
||||
/// 格式化显示
|
||||
/// </summary>
|
||||
public string templet { get; set; }
|
||||
public bool? isShow { get; set; }
|
||||
/// <summary>
|
||||
/// 初始值
|
||||
/// </summary>
|
||||
public string value { get; set; }
|
||||
}
|
||||
|
||||
}
|
||||
8
WaterCloud.CodeGenerator/Properties/launchSettings.json
Normal file
8
WaterCloud.CodeGenerator/Properties/launchSettings.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"profiles": {
|
||||
"WaterCloud.CodeGenerator": {
|
||||
"commandName": "Project",
|
||||
"nativeDebugging": true
|
||||
}
|
||||
}
|
||||
}
|
||||
148
WaterCloud.CodeGenerator/TableMappingHelper.cs
Normal file
148
WaterCloud.CodeGenerator/TableMappingHelper.cs
Normal file
@ -0,0 +1,148 @@
|
||||
using System.Text;
|
||||
using WaterCloud.Code;
|
||||
|
||||
namespace WaterCloud.CodeGenerator
|
||||
{
|
||||
public class TableMappingHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// sys_role转成SysRole
|
||||
/// </summary>
|
||||
/// <param name="lowercase"></param>
|
||||
/// <returns></returns>
|
||||
public static string ConvertToUppercase(string lowercase)
|
||||
{
|
||||
lowercase = lowercase.ParseToString();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
string[] arr = lowercase.Split('_');
|
||||
for (int i = 0; i < arr.Length; i++)
|
||||
{
|
||||
sb.Append(arr[i][0].ToString().ToUpper() + arr[i].Substring(1));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
/// <summary>
|
||||
/// sys_role转成Sys_Role
|
||||
/// </summary>
|
||||
/// <param name="lowercase"></param>
|
||||
/// <returns></returns>
|
||||
public static string ConvertTo_Uppercase(string lowercase)
|
||||
{
|
||||
lowercase = lowercase.ParseToString();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
string[] arr = lowercase.Split('_');
|
||||
for (int i = 0; i < arr.Length; i++)
|
||||
{
|
||||
arr[i] = arr[i][0].ToString().ToUpper() + arr[i].Substring(1);
|
||||
}
|
||||
return string.Join("_", arr);
|
||||
}
|
||||
/// <summary>
|
||||
/// UserService转成userService
|
||||
/// </summary>
|
||||
/// <param name="s"></param>
|
||||
/// <returns></returns>
|
||||
public static string FirstLetterLowercase(string instanceName)
|
||||
{
|
||||
instanceName = instanceName.ParseToString();
|
||||
if (!instanceName.IsEmpty())
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(instanceName[0].ToString().ToLower() + instanceName.Substring(1));
|
||||
return sb.ToString();
|
||||
}
|
||||
else
|
||||
{
|
||||
return instanceName;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// sys_menu_authorize变成MenuAuthorize
|
||||
/// </summary>
|
||||
public static string GetClassNamePrefix(string tableName)
|
||||
{
|
||||
string[] arr = tableName.Split('_');
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 1; i < arr.Length; i++)
|
||||
{
|
||||
sb.Append(arr[i][0].ToString().ToUpper() + arr[i].Substring(1));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static string GetPropertyDatatype(string sDatatype)
|
||||
{
|
||||
string sTempDatatype = string.Empty;
|
||||
sDatatype = sDatatype.ToLower();
|
||||
if (sDatatype.Contains("numer("))
|
||||
{
|
||||
sDatatype = "numer(8,2)";
|
||||
}
|
||||
if (sDatatype.Contains("bigint"))
|
||||
{
|
||||
sDatatype = "bigint";
|
||||
}
|
||||
switch (sDatatype)
|
||||
{
|
||||
case "int":
|
||||
case "number":
|
||||
case "integer":
|
||||
case "smallint":
|
||||
sTempDatatype = "int?";
|
||||
break;
|
||||
|
||||
case "bigint":
|
||||
sTempDatatype = "long?";
|
||||
break;
|
||||
|
||||
case "tinyint":
|
||||
sTempDatatype = "bool?";
|
||||
break;
|
||||
|
||||
case "numeric":
|
||||
case "real":
|
||||
sTempDatatype = "Single?";
|
||||
break;
|
||||
|
||||
case "float":
|
||||
sTempDatatype = "float?";
|
||||
break;
|
||||
|
||||
case "decimal":
|
||||
case "numer(8,2)":
|
||||
sTempDatatype = "decimal?";
|
||||
break;
|
||||
|
||||
case "bit":
|
||||
sTempDatatype = "bool?";
|
||||
break;
|
||||
|
||||
case "datetime":
|
||||
case "datetime2":
|
||||
case "date":
|
||||
case "smalldatetime":
|
||||
case "timestamp":
|
||||
sTempDatatype = "DateTime?";
|
||||
break;
|
||||
|
||||
case "money":
|
||||
case "smallmoney":
|
||||
sTempDatatype = "double?";
|
||||
break;
|
||||
|
||||
case "char":
|
||||
case "varchar":
|
||||
case "nvarchar2":
|
||||
case "text":
|
||||
case "nchar":
|
||||
case "nvarchar":
|
||||
case "ntext":
|
||||
default:
|
||||
sTempDatatype = "string";
|
||||
break;
|
||||
}
|
||||
return sTempDatatype;
|
||||
}
|
||||
}
|
||||
}
|
||||
1509
WaterCloud.CodeGenerator/Template/SingleTableTemplate.cs
Normal file
1509
WaterCloud.CodeGenerator/Template/SingleTableTemplate.cs
Normal file
File diff suppressed because it is too large
Load Diff
16
WaterCloud.CodeGenerator/WaterCloud.CodeGenerator.csproj
Normal file
16
WaterCloud.CodeGenerator/WaterCloud.CodeGenerator.csproj
Normal file
@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||
<Optimize>false</Optimize>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\WaterCloud.Code\WaterCloud.Code.csproj" />
|
||||
<ProjectReference Include="..\WaterCloud.Domain\WaterCloud.Domain.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
920
WaterCloud.Data/DBContext/ChloeIQuery.cs
Normal file
920
WaterCloud.Data/DBContext/ChloeIQuery.cs
Normal file
@ -0,0 +1,920 @@
|
||||
using Chloe;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using WaterCloud.Code;
|
||||
|
||||
namespace WaterCloud.DataBase
|
||||
{
|
||||
public static partial class ChloeIQuery
|
||||
{
|
||||
#region Filter 拼接
|
||||
/// <summary>
|
||||
/// 创建linq表达示的body部分
|
||||
/// </summary>
|
||||
public static Expression GenerateBody<T>(this ParameterExpression param, Filter filterObj)
|
||||
{
|
||||
PropertyInfo property = typeof(T).GetProperty(filterObj.Key);
|
||||
|
||||
Expression left = null; //组装左边
|
||||
//组装右边
|
||||
Expression right = null;
|
||||
if (property != null)
|
||||
{
|
||||
left = Expression.Property(param, property);
|
||||
if (property.PropertyType == typeof(int))
|
||||
{
|
||||
int i;
|
||||
try
|
||||
{
|
||||
i = int.Parse(filterObj.Value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = -99999;
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<int>))
|
||||
{
|
||||
int? i;
|
||||
try
|
||||
{
|
||||
i = int.Parse(filterObj.Value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = null;
|
||||
}
|
||||
right = Expression.Constant(string.IsNullOrEmpty(filterObj.Value) ? null : i, typeof(int?));
|
||||
}
|
||||
else if (property.PropertyType == typeof(DateTime))
|
||||
{
|
||||
DateTime i;
|
||||
try
|
||||
{
|
||||
i = DateTime.Parse(filterObj.Value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = DateTime.Now.AddYears(-100);
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<DateTime>))
|
||||
{
|
||||
DateTime? i;
|
||||
try
|
||||
{
|
||||
i = DateTime.Parse(filterObj.Value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = null;
|
||||
}
|
||||
right = Expression.Constant(string.IsNullOrEmpty(filterObj.Value) ? null : i, typeof(DateTime?));
|
||||
}
|
||||
else if (property.PropertyType == typeof(string))
|
||||
{
|
||||
right = Expression.Constant(filterObj.Value);
|
||||
}
|
||||
else if (property.PropertyType == typeof(decimal))
|
||||
{
|
||||
decimal i;
|
||||
try
|
||||
{
|
||||
i = decimal.Parse(filterObj.Value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = -99999;
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<decimal>))
|
||||
{
|
||||
decimal? i;
|
||||
try
|
||||
{
|
||||
i = decimal.Parse(filterObj.Value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = null;
|
||||
}
|
||||
right = Expression.Constant(string.IsNullOrEmpty(filterObj.Value) ? null : i, typeof(decimal?));
|
||||
}
|
||||
else if (property.PropertyType == typeof(float))
|
||||
{
|
||||
float i;
|
||||
try
|
||||
{
|
||||
i = float.Parse(filterObj.Value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = -99999;
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<float>))
|
||||
{
|
||||
float? i;
|
||||
try
|
||||
{
|
||||
i = float.Parse(filterObj.Value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = null;
|
||||
}
|
||||
right = Expression.Constant(string.IsNullOrEmpty(filterObj.Value) ? null : i, typeof(float?));
|
||||
}
|
||||
else if (property.PropertyType == typeof(bool))
|
||||
{
|
||||
bool i = false;
|
||||
if (filterObj.Value.ToString().ToLower() == "1" || filterObj.Value.ToString().ToLower() == "true")
|
||||
{
|
||||
i = true;
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<bool>))
|
||||
{
|
||||
bool i = false;
|
||||
if (filterObj.Value.ToString().ToLower() == "1" || filterObj.Value.ToString().ToLower() == "true")
|
||||
{
|
||||
i = true;
|
||||
}
|
||||
right = Expression.Constant(i, typeof(bool?));
|
||||
}
|
||||
else if (property.PropertyType == typeof(Guid))
|
||||
{
|
||||
Guid i;
|
||||
try
|
||||
{
|
||||
i = Guid.Parse(filterObj.Value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = new Guid();
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Guid?))
|
||||
{
|
||||
Guid? i;
|
||||
try
|
||||
{
|
||||
i = Guid.Parse(filterObj.Value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = null;
|
||||
}
|
||||
right = Expression.Constant(string.IsNullOrEmpty(filterObj.Value) ? null : i, typeof(Guid?));
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("暂不能解析该Key的类型");
|
||||
}
|
||||
}
|
||||
else //如果左边不是属性,直接是值的情况
|
||||
{
|
||||
left = Expression.Constant(filterObj.Key);
|
||||
right = Expression.Constant(filterObj.Value);
|
||||
}
|
||||
|
||||
//c.XXX=="XXX"
|
||||
Expression filter = Expression.Equal(left, right);
|
||||
switch (filterObj.Contrast)
|
||||
{
|
||||
case "<=":
|
||||
filter = Expression.LessThanOrEqual(left, right);
|
||||
break;
|
||||
|
||||
case "<":
|
||||
filter = Expression.LessThan(left, right);
|
||||
break;
|
||||
|
||||
case ">":
|
||||
filter = Expression.GreaterThan(left, right);
|
||||
break;
|
||||
|
||||
case ">=":
|
||||
filter = Expression.GreaterThanOrEqual(left, right);
|
||||
break;
|
||||
case "!=":
|
||||
filter = Expression.NotEqual(left, right);
|
||||
break;
|
||||
case "contains":
|
||||
filter = Expression.Call(left, typeof(string).GetMethod("Contains", new Type[] { typeof(string) }),
|
||||
Expression.Constant(filterObj.Value));
|
||||
break;
|
||||
case "in":
|
||||
var lExp = Expression.Constant(filterObj.Value.Split(',').ToList()); //数组
|
||||
var methodInfo = typeof(List<string>).GetMethod("Contains",
|
||||
new Type[] { typeof(string) }); //Contains语句
|
||||
filter = Expression.Call(lExp, methodInfo, left);
|
||||
break;
|
||||
case "not in":
|
||||
var listExpression = Expression.Constant(filterObj.Value.Split(',').ToList()); //数组
|
||||
var method = typeof(List<string>).GetMethod("Contains", new Type[] { typeof(string) }); //Contains语句
|
||||
filter = Expression.Not(Expression.Call(listExpression, method, left));
|
||||
break;
|
||||
//交集,使用交集时左值必须时固定的值
|
||||
case "intersect": //交集
|
||||
if (property != null)
|
||||
{
|
||||
throw new Exception("交集模式下,表达式左边不能为变量,请调整数据规则,如:c=>\"A,B,C\" intersect \"B,D\"");
|
||||
}
|
||||
|
||||
var rightval = filterObj.Value.Split(',').ToList();
|
||||
var leftval = filterObj.Key.Split(',').ToList();
|
||||
var val = rightval.Intersect(leftval);
|
||||
|
||||
filter = Expression.Constant(val.Count() > 0);
|
||||
break;
|
||||
}
|
||||
|
||||
return filter;
|
||||
}
|
||||
public static Expression<Func<T, bool>> GenerateTypeBody<T>(this ParameterExpression param, Filter filterObj)
|
||||
{
|
||||
return (Expression<Func<T, bool>>)(param.GenerateBody<T>(filterObj));
|
||||
}
|
||||
/// <summary>
|
||||
/// 转换FilterGroup为Lambda表达式
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="query"></param>
|
||||
/// <param name="parametername"></param>
|
||||
/// <param name="filterList"></param>
|
||||
/// <returns></returns>
|
||||
public static IQuery<T> GenerateFilter<T>(this IQuery<T> query, string parametername,
|
||||
List<FilterList> filterList)
|
||||
{
|
||||
var param = ExtLinq.CreateLambdaParam<T>(parametername);
|
||||
Expression result = ConvertList<T>(filterList, param);
|
||||
query = query.Where(param.GenerateTypeLambda<T>(result));
|
||||
return query;
|
||||
}
|
||||
/// <summary>
|
||||
/// 转换filterlist为表达式
|
||||
/// </summary>
|
||||
/// <param name="filterList"></param>
|
||||
/// <param name="param"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static Expression ConvertList<T>(List<FilterList> filterList, ParameterExpression param)
|
||||
{
|
||||
if (filterList == null) return null;
|
||||
Expression result = ConvertFilters<T>(JsonHelper.ToObject<Filter[]>(filterList[0].Filters), param, filterList[0].Operation);
|
||||
foreach (var item in filterList.Skip(1))
|
||||
{
|
||||
var gresult = ConvertFilters<T>(JsonHelper.ToObject<Filter[]>(item.Filters), param, item.Operation);
|
||||
result = result.Or(gresult);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/// <summary>
|
||||
/// 转换Filter数组为表达式
|
||||
/// </summary>
|
||||
/// <param name="filters"></param>
|
||||
/// <param name="param"></param>
|
||||
/// <param name="operation"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
private static Expression ConvertFilters<T>(Filter[] filters, ParameterExpression param, string operation)
|
||||
{
|
||||
if (filters == null || !filters.Any())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
Expression result = param.GenerateBody<T>(filters[0]);
|
||||
|
||||
if (filters.Length == 1)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
if (operation == "and")
|
||||
{
|
||||
foreach (var filter in filters.Skip(1))
|
||||
{
|
||||
result = result.AndAlso(param.GenerateBody<T>(filter));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var filter in filters.Skip(1))
|
||||
{
|
||||
result = result.Or(param.GenerateBody<T>(filter));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region SoulPage 拼接
|
||||
/// <summary>
|
||||
/// 创建linq表达示的body部分
|
||||
/// </summary>
|
||||
public static Expression GenerateBody<T>(this ParameterExpression param, FilterSo filterObj)
|
||||
{
|
||||
PropertyInfo property = typeof(T).GetProperty(filterObj.field);
|
||||
|
||||
Expression left = null; //组装左边
|
||||
//组装右边
|
||||
Expression right = null;
|
||||
if (property != null)
|
||||
{
|
||||
left = Expression.Property(param, property);
|
||||
if (property.PropertyType == typeof(int))
|
||||
{
|
||||
int i;
|
||||
try
|
||||
{
|
||||
i = int.Parse(filterObj.value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = -99999;
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<int>))
|
||||
{
|
||||
int? i;
|
||||
try
|
||||
{
|
||||
i = int.Parse(filterObj.value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = null;
|
||||
}
|
||||
right = Expression.Constant(string.IsNullOrEmpty(filterObj.value) ? null : i, typeof(int?));
|
||||
}
|
||||
else if (property.PropertyType == typeof(DateTime))
|
||||
{
|
||||
DateTime i;
|
||||
try
|
||||
{
|
||||
i = DateTime.Parse(filterObj.value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = DateTime.Now.AddYears(-100);
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<DateTime>))
|
||||
{
|
||||
DateTime? i;
|
||||
try
|
||||
{
|
||||
i = DateTime.Parse(filterObj.value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = null;
|
||||
}
|
||||
right = Expression.Constant(string.IsNullOrEmpty(filterObj.value) ? null : i, typeof(DateTime?));
|
||||
}
|
||||
else if (property.PropertyType == typeof(string))
|
||||
{
|
||||
right = Expression.Constant(filterObj.value);
|
||||
}
|
||||
else if (property.PropertyType == typeof(decimal))
|
||||
{
|
||||
decimal i;
|
||||
try
|
||||
{
|
||||
i = decimal.Parse(filterObj.value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = -99999;
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<decimal>))
|
||||
{
|
||||
decimal? i;
|
||||
try
|
||||
{
|
||||
i = decimal.Parse(filterObj.value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = null;
|
||||
}
|
||||
right = Expression.Constant(string.IsNullOrEmpty(filterObj.value) ? null : i, typeof(decimal?));
|
||||
}
|
||||
else if (property.PropertyType == typeof(float))
|
||||
{
|
||||
float i;
|
||||
try
|
||||
{
|
||||
i = float.Parse(filterObj.value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = -99999;
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<float>))
|
||||
{
|
||||
float? i;
|
||||
try
|
||||
{
|
||||
i = float.Parse(filterObj.value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = null;
|
||||
}
|
||||
right = Expression.Constant(string.IsNullOrEmpty(filterObj.value) ? null : i, typeof(float?));
|
||||
}
|
||||
else if (property.PropertyType == typeof(bool))
|
||||
{
|
||||
bool i = false;
|
||||
if (filterObj.value.ToString().ToLower() == "1" || filterObj.value.ToString().ToLower() == "true")
|
||||
{
|
||||
i = true;
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<bool>))
|
||||
{
|
||||
bool i = false;
|
||||
if (filterObj.value.ToString().ToLower() == "1" || filterObj.value.ToString().ToLower() == "true")
|
||||
{
|
||||
i = true;
|
||||
}
|
||||
right = Expression.Constant(i, typeof(bool?));
|
||||
}
|
||||
else if (property.PropertyType == typeof(Guid))
|
||||
{
|
||||
Guid i;
|
||||
try
|
||||
{
|
||||
i = Guid.Parse(filterObj.value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = new Guid();
|
||||
}
|
||||
right = Expression.Constant(i);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Guid?))
|
||||
{
|
||||
Guid? i;
|
||||
try
|
||||
{
|
||||
i = Guid.Parse(filterObj.value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
i = null;
|
||||
}
|
||||
right = Expression.Constant(string.IsNullOrEmpty(filterObj.value) ? null : i, typeof(Guid?));
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("暂不能解析该Key的类型");
|
||||
}
|
||||
}
|
||||
else //如果左边不是属性,直接是值的情况
|
||||
{
|
||||
throw new Exception("暂不能解析该Key的类型");
|
||||
}
|
||||
Expression filter = Expression.Equal(left, right);
|
||||
switch (filterObj.type)
|
||||
{
|
||||
case "eq":
|
||||
filter = Expression.Equal(left, right);
|
||||
break;
|
||||
case "ne":
|
||||
filter = Expression.NotEqual(left, right);
|
||||
break;
|
||||
case "gt":
|
||||
try
|
||||
{
|
||||
filter = Expression.GreaterThan(left, right);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
filter = Expression.NotEqual(left, right);
|
||||
}
|
||||
break;
|
||||
case "ge":
|
||||
try
|
||||
{
|
||||
filter = Expression.GreaterThanOrEqual(left, right);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
filter = Expression.Equal(left, right);
|
||||
}
|
||||
break;
|
||||
case "lt":
|
||||
try
|
||||
{
|
||||
filter = Expression.LessThan(left, right);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
filter = Expression.NotEqual(left, right);
|
||||
}
|
||||
break;
|
||||
case "le":
|
||||
try
|
||||
{
|
||||
filter = Expression.LessThanOrEqual(left, right);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
filter = Expression.Equal(left, right);
|
||||
}
|
||||
break;
|
||||
case "contain":
|
||||
try
|
||||
{
|
||||
filter = Expression.Call(left, typeof(string).GetMethod("Contains", new Type[] { typeof(string) }),
|
||||
Expression.Constant(filterObj.value));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
filter = Expression.Equal(left, right);
|
||||
}
|
||||
break;
|
||||
case "notContain":
|
||||
try
|
||||
{
|
||||
filter = Expression.Not(Expression.Call(left, typeof(string).GetMethod("Contains", new Type[] { typeof(string) }),
|
||||
Expression.Constant(filterObj.value)));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
filter = Expression.NotEqual(left, right);
|
||||
}
|
||||
break;
|
||||
case "start":
|
||||
try
|
||||
{
|
||||
filter = Expression.Call(left, typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }),
|
||||
Expression.Constant(filterObj.value));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
filter = Expression.Equal(left, right);
|
||||
}
|
||||
break;
|
||||
case "end":
|
||||
try
|
||||
{
|
||||
filter = Expression.Call(left, typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) }),
|
||||
Expression.Constant(filterObj.value));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
filter = Expression.Equal(left, right);
|
||||
}
|
||||
break;
|
||||
case "null":
|
||||
filter = Expression.Equal(left, Expression.Constant(null));
|
||||
break;
|
||||
case "notNull":
|
||||
filter = Expression.NotEqual(left, Expression.Constant(null));
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
return filter;
|
||||
}
|
||||
/// <summary>
|
||||
/// 转换FilterGroup为Lambda表达式
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="query"></param>
|
||||
/// <param name="parametername"></param>
|
||||
/// <param name="filterList"></param>
|
||||
/// <returns></returns>
|
||||
public static IQuery<T> GenerateFilter<T>(this IQuery<T> query, string parametername,
|
||||
List<FilterSo> filterList)
|
||||
{
|
||||
var param = ExtLinq.CreateLambdaParam<T>(parametername);
|
||||
Expression result = ConvertList<T>(filterList, param);
|
||||
if (result == null)
|
||||
{
|
||||
return query;
|
||||
}
|
||||
query = query.Where(param.GenerateTypeLambda<T>(result));
|
||||
return query;
|
||||
}
|
||||
/// <summary>
|
||||
/// 转换filterlist为表达式
|
||||
/// </summary>
|
||||
/// <param name="filterList"></param>
|
||||
/// <param name="param"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static Expression ConvertList<T>(List<FilterSo> filterList, ParameterExpression param)
|
||||
{
|
||||
if (filterList == null) return null;
|
||||
Expression result = null;
|
||||
Expression gresult = null;
|
||||
PropertyInfo property;
|
||||
Expression left = null;
|
||||
foreach (var item in filterList)
|
||||
{
|
||||
switch (item.mode)
|
||||
{
|
||||
case "condition":
|
||||
gresult = param.GenerateBody<T>(item);
|
||||
if (gresult == null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (item.prefix == "or")
|
||||
{
|
||||
if (result != null)
|
||||
{
|
||||
result = result.Or(gresult);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = gresult;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (result != null)
|
||||
{
|
||||
result = result.AndAlso(gresult);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = gresult;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "group":
|
||||
gresult = ConvertList<T>(item.children, param);
|
||||
if (gresult == null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (item.prefix == "or")
|
||||
{
|
||||
if (result != null)
|
||||
{
|
||||
result = result.Or(gresult);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = gresult;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (result != null)
|
||||
{
|
||||
result = result.AndAlso(gresult);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = gresult;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "in":
|
||||
property = typeof(T).GetProperty(item.field);
|
||||
left = Expression.Property(param, property);
|
||||
if (item.values == null || item.values.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (property.PropertyType == typeof(int))
|
||||
{
|
||||
List<int> list = new List<int>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
list.Add(int.Parse(temp));
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<int>).GetMethod("Contains", new Type[] { typeof(int) }), left);
|
||||
}
|
||||
if (property.PropertyType == typeof(Nullable<int>))
|
||||
{
|
||||
List<int?> list = new List<int?>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
list.Add(int.Parse(temp));
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<int?>).GetMethod("Contains", new Type[] { typeof(int?) }), left);
|
||||
}
|
||||
else if (property.PropertyType == typeof(DateTime))
|
||||
{
|
||||
List<DateTime> list = new List<DateTime>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
list.Add(DateTime.Parse(temp));
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<DateTime>).GetMethod("Contains", new Type[] { typeof(DateTime) }), left);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<DateTime>))
|
||||
{
|
||||
List<DateTime?> list = new List<DateTime?>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
list.Add(DateTime.Parse(temp));
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<DateTime?>).GetMethod("Contains", new Type[] { typeof(DateTime?) }), left);
|
||||
}
|
||||
else if (property.PropertyType == typeof(decimal))
|
||||
{
|
||||
List<decimal> list = new List<decimal>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
list.Add(decimal.Parse(temp));
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<decimal>).GetMethod("Contains", new Type[] { typeof(decimal) }), left);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<decimal>))
|
||||
{
|
||||
List<decimal?> list = new List<decimal?>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
list.Add(decimal.Parse(temp));
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<decimal?>).GetMethod("Contains", new Type[] { typeof(decimal?) }), left);
|
||||
}
|
||||
else if (property.PropertyType == typeof(bool))
|
||||
{
|
||||
List<bool> list = new List<bool>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
if (temp == "1")
|
||||
{
|
||||
list.Add(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
list.Add(false);
|
||||
}
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<bool>).GetMethod("Contains", new Type[] { typeof(bool) }), left);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<bool>))
|
||||
{
|
||||
List<bool?> list = new List<bool?>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
if (temp == "1")
|
||||
{
|
||||
list.Add(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
list.Add(false);
|
||||
}
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<bool?>).GetMethod("Contains", new Type[] { typeof(bool?) }), left);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<float>))
|
||||
{
|
||||
List<float?> list = new List<float?>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
list.Add(float.Parse(temp));
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<float?>).GetMethod("Contains", new Type[] { typeof(float?) }), left);
|
||||
}
|
||||
else if (property.PropertyType == typeof(float))
|
||||
{
|
||||
List<float> list = new List<float>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
list.Add(float.Parse(temp));
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<float>).GetMethod("Contains", new Type[] { typeof(float) }), left);
|
||||
}
|
||||
else if (property.PropertyType == typeof(Nullable<double>))
|
||||
{
|
||||
List<double?> list = new List<double?>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
list.Add(float.Parse(temp));
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<double?>).GetMethod("Contains", new Type[] { typeof(double?) }), left);
|
||||
}
|
||||
else if (property.PropertyType == typeof(double))
|
||||
{
|
||||
List<double> list = new List<double>();
|
||||
foreach (var temp in item.values)
|
||||
{
|
||||
list.Add(float.Parse(temp));
|
||||
}
|
||||
gresult = Expression.Call(Expression.Constant(list), typeof(List<double>).GetMethod("Contains", new Type[] { typeof(double) }), left);
|
||||
}
|
||||
else
|
||||
{
|
||||
gresult = Expression.Call(Expression.Constant(item.values), typeof(List<string>).GetMethod("Contains", new Type[] { typeof(string) }), left);
|
||||
}
|
||||
if (result != null)
|
||||
{
|
||||
result = result.AndAlso(gresult);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = gresult;
|
||||
}
|
||||
break;
|
||||
case "date":
|
||||
property = typeof(T).GetProperty(item.field);
|
||||
left = Expression.Property(param, property);
|
||||
bool isNull = false;
|
||||
if (property.PropertyType == typeof(Nullable<DateTime>))
|
||||
{
|
||||
isNull = true;
|
||||
}
|
||||
DateTime? startTime = null;
|
||||
DateTime? endTime = null;
|
||||
switch (item.type)
|
||||
{
|
||||
case "yesterday":
|
||||
startTime = DateTime.Now.Date.AddDays(-1);
|
||||
endTime = DateTime.Now.Date;
|
||||
break;
|
||||
case "thisWeek":
|
||||
startTime = DateTime.Now.Date.AddDays(1 - Convert.ToInt32(DateTime.Now.Date.DayOfWeek.ToString("d"))); //本周周一
|
||||
endTime = ((DateTime)startTime).AddDays(7); //本周周日
|
||||
break;
|
||||
case "lastWeek":
|
||||
startTime = DateTime.Now.Date.AddDays(1 - Convert.ToInt32(DateTime.Now.Date.DayOfWeek.ToString("d")) - 7); //上周周一
|
||||
endTime = ((DateTime)startTime).AddDays(7); //上周周日
|
||||
break;
|
||||
case "thisMonth":
|
||||
startTime = DateTime.Now.Date.AddDays(1 - DateTime.Now.Date.Day); //本月月初
|
||||
endTime = ((DateTime)startTime).AddMonths(1); //本月月末
|
||||
break;
|
||||
case "thisYear":
|
||||
startTime = new DateTime(DateTime.Now.Date.Year, 1, 1); //本年年初
|
||||
endTime = new DateTime(DateTime.Now.Date.AddYears(1).Year, 1, 1); //本年年初
|
||||
break;
|
||||
case "specific":
|
||||
var tempTime = item.value.Split('~');
|
||||
if (tempTime.Length == 0 || tempTime.Length == 1)
|
||||
{
|
||||
var A = DateTime.Parse(tempTime[0]);
|
||||
startTime = A.Date;
|
||||
endTime = A.Date.AddDays(+1);
|
||||
}
|
||||
else
|
||||
{
|
||||
startTime = DateTime.Parse(tempTime[0]);
|
||||
endTime = DateTime.Parse(tempTime[1]);
|
||||
}
|
||||
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
if (startTime != null && endTime != null)
|
||||
{
|
||||
if (isNull)
|
||||
{
|
||||
gresult = Expression.GreaterThanOrEqual(left, Expression.Constant(startTime, typeof(DateTime?)));
|
||||
gresult = gresult.And(Expression.LessThan(left, Expression.Constant(endTime, typeof(DateTime?))));
|
||||
}
|
||||
else
|
||||
{
|
||||
gresult = Expression.GreaterThanOrEqual(left, Expression.Constant((DateTime)startTime));
|
||||
gresult = gresult.And(Expression.LessThan(left, Expression.Constant((DateTime)endTime)));
|
||||
}
|
||||
}
|
||||
if (result != null)
|
||||
{
|
||||
result = result.AndAlso(gresult);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = gresult;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
46
WaterCloud.Data/DBContext/DBContexHelper.cs
Normal file
46
WaterCloud.Data/DBContext/DBContexHelper.cs
Normal file
@ -0,0 +1,46 @@
|
||||
using Chloe;
|
||||
using Chloe.MySql;
|
||||
using Chloe.Oracle;
|
||||
using Chloe.SqlServer;
|
||||
using WaterCloud.Code;
|
||||
|
||||
namespace WaterCloud.DataBase
|
||||
{
|
||||
public class DBContexHelper
|
||||
{
|
||||
private static string dbType = GlobalContext.SystemConfig.DBProvider;
|
||||
private static string dbConnectionString = GlobalContext.SystemConfig.DBConnectionString;
|
||||
private static string DBCommandTimeout = GlobalContext.SystemConfig.DBCommandTimeout;
|
||||
|
||||
public static IDbContext Contex(string ConnectStr = "", string providerName = "")
|
||||
{
|
||||
ConnectStr = string.IsNullOrEmpty(ConnectStr) ? dbConnectionString : ConnectStr;
|
||||
providerName = string.IsNullOrEmpty(providerName) ? dbType : providerName;
|
||||
if (providerName == Define.DBTYPE_SQLSERVER)
|
||||
{
|
||||
var dbContext = new MsSqlContext(new MSSqlConnectionFactory(ConnectStr));
|
||||
//2012以上版本切换使用 OFFSET FETCH 分页方式
|
||||
//dbContext.PagingMode = PagingMode.OFFSET_FETCH;
|
||||
dbContext.Session.CommandTimeout = int.Parse(DBCommandTimeout);
|
||||
return dbContext;
|
||||
}
|
||||
else if(providerName == Define.DBTYPE_MYSQL)
|
||||
{
|
||||
var dbContext = new MySqlContext(new MySqlConnectionFactory(ConnectStr));
|
||||
dbContext.Session.CommandTimeout = int.Parse(DBCommandTimeout);
|
||||
return dbContext;
|
||||
}
|
||||
else if (providerName == Define.DBTYPE_ORACLE)
|
||||
{
|
||||
var dbContext = new OracleContext(new OracleConnectionFactory(ConnectStr));
|
||||
dbContext.Session.CommandTimeout = int.Parse(DBCommandTimeout);
|
||||
dbContext.ConvertToUppercase = false;
|
||||
return dbContext;
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
28
WaterCloud.Data/DBContext/DatabaseType.cs
Normal file
28
WaterCloud.Data/DBContext/DatabaseType.cs
Normal file
@ -0,0 +1,28 @@
|
||||
|
||||
namespace WaterCloud.DataBase
|
||||
{
|
||||
/// </summary>
|
||||
public enum DatabaseType
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库类型:SqlServer
|
||||
/// </summary>
|
||||
SqlServer,
|
||||
/// <summary>
|
||||
/// 数据库类型:MySql
|
||||
/// </summary>
|
||||
MySql,
|
||||
/// <summary>
|
||||
/// 数据库类型:Oracle
|
||||
/// </summary>
|
||||
Oracle,
|
||||
/// <summary>
|
||||
/// 数据库类型:Access
|
||||
/// </summary>
|
||||
Access,
|
||||
/// <summary>
|
||||
/// 数据库类型:SQLite
|
||||
/// </summary>
|
||||
SQLite
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user