diff --git a/.gitignore b/.gitignore index 3ddda332d..d9cef967a 100644 --- a/.gitignore +++ b/.gitignore @@ -195,6 +195,7 @@ ClientBin/ *.pfx *.publishsettings node_modules/ +!/node_modules/swagger-ui-dist/ orleans.codegen.cs # Since there are multiple workflows, uncomment next line to ignore bower_components @@ -262,3 +263,9 @@ paket-files/ __pycache__/ *.pyc +/src/Surging.Core/Surging.Core.CPlatform/CPlatformResource.en-US.resources +api/ +_site/ + +/src/Surging.ApiGateway +/src/Surging.Services/Surging.Services.Server/Dockerfile diff --git a/samples/README.md b/FETCH_HEAD similarity index 100% rename from samples/README.md rename to FETCH_HEAD diff --git a/README.EN.md b/README.EN.md index de4072624..95fc52d7d 100644 --- a/README.EN.md +++ b/README.EN.md @@ -4,7 +4,11 @@ # surging is a distributed micro service framework that provides high-performance RPC remote service calls, using Zookeeper, Consul as the registration center for surging services, integrating hash, random, polling as a load balancing algorithm, RPC integration using the netty framework, Using asynchronous transmission.
-Start configuration: +### Architecture: + +架构图 + +### Start configuration:
diff --git a/README.md b/README.md index 5574e670b..719aca3a9 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # surging                     [English](https://github.com/dotnetcore/surging/blob/master/README.EN.md) [![Member project of .NET Core Community](https://img.shields.io/badge/member%20project%20of-NCC-9e20c9.svg)](https://github.com/dotnetcore) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://mit-license.org/) -### surging 是一个分布式微服务框架,提供高性能RPC远程服务调用,采用Zookeeper、Consul作为surging服务的注册中心,集成了哈希,随机,轮询,压力最小优先作为负载均衡的算法,RPC集成采用的是netty框架,采用异步传输。 +### surging 是一个分布式微服务框架,提供高性能RPC远程服务调用,采用Zookeeper、Consul作为surging服务的注册中心,集成了哈希,随机,轮询,压力最小优先作为负载均衡的算法,RPC可以选择采用netty或thrift框架,采用异步非阻塞传输。
@@ -18,6 +18,11 @@ ### 微服务定义 微服务应该是可以自由组合拆分,对于每个业务都是独立的,针对于业务模块的 CRUD 可以注册为服务,而每个服务都是高度自治的,从开发,部署都是独立,而每个服务只做单一功能,利用领域驱动设计去更好的拆分成粒度更小的模块 +### 微服务边界 +微服务是针对业务的松耦合,也是粒度最小的功能业务模块,针对于行业解决方案,集成相应的service host,而针对于业务需要一些中间件来辅助,比如缓存中间件,eventbus中间件(消息中间件),数据储存中间件,而各个服务又可以互相通过rpc进行可靠性通信。 + +引擎是微服务的容器,而docker 是服务引擎的容器,而利用k8s或rancher可以针对docker集群化管理,可以服务编排弹性扩容,熟知工具,让工具物尽其用。 + ### 能做什么 1.简化的服务调用,通过服务规则的指定,就可以做到服务之间的远程调用,无需其它方式的侵入 @@ -39,9 +44,13 @@ docker hub : docker pull serviceengine/surging:版本号 nuget:Install-Package surging -Version 版本号 -### surging模块功能 +### 架构图 + +架构图 -surging模块功能 +### 调用链 + +链路图 ### 配置: @@ -262,11 +271,18 @@ Task.FromResult(new Surging.IModuleServices.Common.Models.UserModel .AddClientIntercepted(typeof(CacheProviderInterceptor)) ``` +## 捐赠明细 + +surging 接受来自社区的捐赠,所有款项将通过 [捐赠明细表](Statement-of-Income-and-Expense.md) 进行公示,接受社区监督。 + IDE:Visual Studio 2017 15.5,vscode
框架:.NET core 2.1
QQ群:615562965 -* [Demo](https://github.com/billyang/SurgingDemo) * [文档](http://docs.dotnet-china.org/surging/) * [简单示例](https://github.com/dotnetcore/surging/blob/master/docs/docs.en/INDEX.md) + +## 谁在使用 + + diff --git a/Statement-of-Income-and-Expense.md b/Statement-of-Income-and-Expense.md new file mode 100644 index 000000000..2090bfa09 --- /dev/null +++ b/Statement-of-Income-and-Expense.md @@ -0,0 +1,64 @@ +# 收支明细表 + +说明:为保证surging财务公开透明,决定将每一笔捐赠和支出记录于本表,资金由 [fanly](https://github.com/fanliang11) 托管,并且受社区人员监督用于surging的生态发展 + + +## 汇总 + +截止到 2018 年 12 月 28 日: ++ 共获得捐赠 `49` 笔计 `8679.06` 元人民币 ++ 暂无支出项 + +## 明细 + +| 序号 | 捐赠人 | 时间 | 金额 | 说明 | 留言 | 类型 | +|------------|:------------:|-------------|--------------------|-------------------|--------------------|-----| +| 1 | Murphy | 2018-12-19 | 100 | Murphy 个人捐赠 | 这家伙很懒 |获赠 | +| 2 | 宗国 | 2018-12-19 | 20 | 宗国 个人捐赠 | 这家伙很懒 |获赠 | +| 3 | 紫能 | 2018-12-19 | 50 | 紫能 个人捐赠 | 这家伙很懒 |获赠 | +| 4 | Damon | 2018-12-19 | 18.8 | Damon 个人捐赠 | 支持一下 |获赠 | +| 5 | 悉路 | 2018-12-19 | 10 | 悉路 个人捐赠 | 感谢作者的付出,希望能完善文档 |获赠 | +| 6 | jiang | 2018-12-19 | 16.66 | jiang 个人捐赠 | 这家伙很懒 |获赠 | +| 7 | 伯锰 z.l | 2018-12-19 | 20 | 伯锰 z.l 个人捐赠 | 期待1.0 |获赠 | +| 8 | 匿名 | 2018-12-19 | 5000 | 匿名个人捐赠 | 这家伙很懒 |获赠 | +| 9 | 爱吃牛排的牛仔 | 2018-12-19 | 66.66 | 爱吃牛排的牛仔个人捐赠 | 这家伙很懒 |获赠 | +| 10 | siyue | 2018-12-20 | 50 | siyue个人捐赠 | 这家伙很懒 |获赠 | +| 11 | 学飞 | 2018-12-20 | 200 | 学飞个人捐赠 | 还在学习,期待surging越来越好 |获赠 | +| 12 | 昵称bai | 2018-12-21 | 10 | 昵称bai个人捐赠 | 这家伙很懒 |获赠 | +| 13 | 半碗的彩霞 | 2018-12-21 | 10 | 半碗的彩霞个人捐赠 | 这家伙很懒 |获赠 | +| 14 | 虎牙 | 2018-12-21 | 1000 | 虎牙个人捐赠 | 这家伙很懒 |获赠 | +| 15 | 寸草无心 | 2018-12-21 | 100 | 寸草无心个人捐赠 | 关注surging已有大半年了 默默支持 |获赠 | +| 16 | 洋 | 2018-12-24 | 1 | 洋个人捐赠 | dotnetty支持websocket了 |获赠 | +| 17 | 高文 | 2018-12-24 | 10 | 高文个人捐赠 | 庆祝1.0 |获赠 | +| 18 | 培根 | 2018-12-24 | 36 | 培根个人捐赠 | 捐赠一杯咖啡 |获赠 | +| 19 | gesneriana | 2018-12-24 | 26 | gesneriana个人捐赠 | 这家伙很懒 |获赠 | +| 20 | 学军 | 2018-12-27 | 100 | 学军个人捐赠 | 这家伙很懒 |获赠 | +| 21 | 高立哲 | 2018-12-27 | 30 | 高立哲个人捐赠 | 这家伙很懒 |获赠 | +| 22 | 俊文 | 2018-12-27 | 10 | 俊文个人捐赠 | 这家伙很懒 |获赠 | +| 23 | 根堂 | 2018-12-28 | 100 | 根堂个人捐赠 | 这家伙很懒 |获赠 | +| 24 | 东周 | 2018-12-28 | 5 | 东周个人捐赠 | 辛苦 |获赠 | +| 25 | 纯 | 2018-12-28 | 20 | 纯个人捐赠 | 这家伙很懒 |获赠 | +| 26 | 夏志行 | 2018-12-28 | 88 | 夏志行个人捐赠 | 这家伙很懒 |获赠 | +| 27 | 勇 | 2018-12-28 | 88.88 | 勇个人捐赠 | 这家伙很懒 |获赠 | +| 28 | 启旺 | 2018-12-28 | 10 | 勇个人捐赠 | 这家伙很懒 |获赠 | +| 29 | 雯昌 | 2018-12-28 | 20 | 雯昌个人捐赠 | 支持surging |获赠 | +| 30 | 宏伟 | 2018-12-28 | 500 | 宏伟个人捐赠 | 这家伙很懒 |获赠 | +| 31 | 伟 | 2018-12-28 | 20 | 伟个人捐赠 | 这家伙很懒 |获赠 | +| 32 | 建 | 2018-12-28 | 10 |建个人捐赠 | 希望大佬搞好文档,在下尽点微薄之力 |获赠 | +| 33 | 林 | 2018-12-29 | 30 |林个人捐赠 | 这家伙很懒 |获赠 | +| 34 | 俊强 | 2018-12-29 | 100 | 俊强个人捐赠 | 这家伙很懒 |获赠 | +| 35 | 彪 | 2018-01-02 | 10 | 彪个人捐赠 | 支持一下surging |获赠 | +| 36 | 忠全 | 2018-01-02 | 200 | 忠全个人捐赠 | 学习一下 |获赠 | +| 37 | 思恒 | 2018-01-03 | 10 | 思恒个人捐赠 | 这家伙很懒 |获赠 | +| 38 | 松波 | 2018-01-04 | 100 | 松波个人捐赠 | 出精品 |获赠 | +| 39 | 先鸿 | 2019-01-05 | 30 | 先鸿个人捐赠 | 加油 |获赠 | +| 40 | 杨坚 | 2019-01-08 | 100 | 杨坚个人捐赠 | 加油,希望surging能形成自己的社区 |获赠 | +| 41 | 济良 | 2019-01-09 | 10 | 济良个人捐赠 | 这家伙很懒 |获赠 | +| 42 | 祥 | 2019-01-11 | 36 | 祥个人捐赠 | 支持大佬,希望.net社区越来越好 |获赠 | +| 43 | 文斌 | 2019-01-14 | 50 | 文斌个人捐赠 | 读书也要交学费,买书起码花点钱 |获赠 | +| 44 | 笋 | 2019-01-25 | 30 | 笋个人捐赠 | 支持一下 |获赠 | +| 45 | Leo | 2019-01-30 | 100 | Leo个人捐赠 | 支持surging |获赠 | +| 46 | 文丽 | 2019-02-01 | 20 | 文丽 | 这家伙很懒 |获赠 | +| 47 | 卫东 | 2019-02-13 | 16 | 卫东 | 这家伙很懒 |获赠 | +| 48 | 安平 | 2019-02-15 | 30 | 安平 | 支持surging,感谢作者付出. |获赠 | +| 49 | MyDAL | 2019-02-19 | 6.66 | MyDAL | 支持国人自己的轮子. |获赠 | diff --git a/docfx.json b/docfx.json new file mode 100644 index 000000000..b436d8477 --- /dev/null +++ b/docfx.json @@ -0,0 +1,83 @@ +{ + "metadata": [ + ], + "build": { + "content": [ + { + "files": [ + "docs/**.md", + "docs/**/toc.yml", + "toc.yml", + "*.md" + ] + } + ], + "resource": [ + { + "files": [ + "**/images/**" + ] + } + ], + "overwrite": [ + { + "files": [ + "apidoc/**.md" + ], + "exclude": [ + "obj/**", + "_site/**" + ] + } + ], + "dest": "_site", + "globalMetadataFiles": [], + "fileMetadataFiles": [], + "template": [ + "default" + ], + "postProcessors": [], + "markdownEngineName": "markdig", + "noLangKeyword": false, + "keepFileLink": false, + "cleanupCacheHistory": false, + "disableGitFeatures": false + } +// "pdf": { +// "content": [ +// { +// "files": [ +// "docs/**.md", +// "docs/**/toc.yml", +// "toc.yml", +// "*.md" +// ] +// } +// ], +// "resource": [ +// { +// "files": [ +// "**/images/**" +// ], +// "exclude": [ +// "**/bin/**", +// "**/obj/**", +// "_site_pdf/**" +// ] +// } +// ], +// "overwrite": [ +// { +// "files": [ +// "apidoc/**.md" +// ], +// "exclude": [ +// "**/bin/**", +// "**/obj/**", +// "_site_pdf/**" +// ] +// } +// ], +// "dest": "_site_pdf" +// } +} \ No newline at end of file diff --git a/docs/Architecture.png b/docs/Architecture.png new file mode 100644 index 000000000..af1d6e577 Binary files /dev/null and b/docs/Architecture.png differ diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md new file mode 100644 index 000000000..581bdf7eb --- /dev/null +++ b/docs/CONTRIBUTING.md @@ -0,0 +1,45 @@ +# Surging文档贡献指南 + +## docfx的安装与使用 +### 1. 打开`powershell`,使用如下命令安装[Chocolatey](https://chocolatey.org/install) +```shell +Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1')) +``` + +### 2. 安装`docfx`工具 +```shell +choco install docfx -y +``` +> **Notes** +> - 安装完`docfx`之后需要重启`powershell`,才会有`docfx`命令 + +### 3. `docfx`的使用 +```shell +# 构建文档 +docfx build + +# 构建文档同时本地预览 +docfx build -s + +# 本地预览文档 +docfx serve +``` +> **Notes** +> - 更多关于`docfx`工具使用教程的请[参考](https://dotnet.github.io/docfx/tutorial/docfx.exe_user_manual.html) + +## 如何成为开发者文档贡献者 +我们欢迎所有有能力的开发者为surging社区做出自己的贡献,为surging的发展贡献自己的力量。您可以通过qq群或是issues向作者申请成为文档作者。我们会将文档的贡献者显示在开发者文档相关页面,对所有做出贡献的开发者表示感谢。 + +## 编写开发者文档 + +### 1. 新增文档目录 +在[`./docs/toc.yml`](./toc.yml)新增文档目录,并在首页[`./docs/index.md`](./index.md)中创建相关的链接。 + +### 2. 编写开发者文档 +使用`markdown`编写开发者文档,将文档存放到相关模块的目录下。关于文档写作规范请[参考](https://github.com/ruanyf/document-style-guide)。 + +### 3. 提交并发起PR +发起pr后,经作者审核通过,将会合并到主分支。 + +## 投稿 +欢迎开发者向社区投稿关于surging或是微服务相关的博客,您可以选择同时发表到其他平台,但是必须是原创的。请将相关的博文存放在`./docs/blogs`目录下,并向社区提交`PR`。 diff --git a/docs/blogs/index.md b/docs/blogs/index.md new file mode 100644 index 000000000..2e88b4546 --- /dev/null +++ b/docs/blogs/index.md @@ -0,0 +1,3 @@ +# Surging相关博文 + +## 欢迎投稿 \ No newline at end of file diff --git a/docs/call-chain.png b/docs/call-chain.png new file mode 100644 index 000000000..aeb496f01 Binary files /dev/null and b/docs/call-chain.png differ diff --git a/docs/docs.cn/INDEX.md b/docs/docs.cn/INDEX.md index b9adf8f4e..14d681c63 100644 --- a/docs/docs.cn/INDEX.md +++ b/docs/docs.cn/INDEX.md @@ -1,3 +1,40 @@ -surging is a high-performance microservice framework based on the .NET core language,It was created by an individual and designed for use in the cloud, -Then add to dotnetcore +# surging的介绍               +``` + 作者:fanly 校对:fanly +``` + +什么是Surging + + surging 是微服务引擎,提供了轻量级,高性能,模块化的RPC请求管道,服务引擎支持http、TCP、WS、Mqtt、UDP、DNS协议,采用了Zookeeper、Consul作为注册中心,集成了哈希,随机,轮询,压力最小优先作为负载均衡的算法,内置了服务治理用来保证可靠性RPC通信 + +使用surging你可以: + + * 构建Web应用程序,微服务和api网关 + * 微服务可以部署在docker。可以使用k8s、rancher服务编排弹性扩容 + * 提供了多协议支持 + * 支持负载平衡分流压力 + * 基于.NET Core的跨平台可以在Windows,macOS和Linux上运行;也可以移植到其他操作系统。 + * 简化的服务调用,通过服务规则的指定,就可以做到服务之间的远程调用,无需其它方式的侵入 + * 服务自动注册与发现,不需要配置服务提供方地址,注册中心基于ServiceId 或者RoutePath查询服务提供者的地址和元数据,并且能够平滑添加或删除服务提供者。 + * 软负载均衡及容错机制,通过surging内部负载算法和容错规则的设定,从而达到内部调用的负载和容错 + * 分布式缓存中间件:通过哈希一致性算法来实现负载,并且有健康检查能够平滑的把不健康的服务从列表中删除 + * 事件总线:通过对于事件总线的适配可以实现发布订阅交互模式 + * 容器化持续集成与持续交付 :通过构建一体化Devops平台,实现项目的自动化构建、部署、测试和发布,从而提高生产环境的可靠性、稳定性、弹性和安全性。 + * 业务模块化驱动引擎,通过加载指定业务模块,能够更加灵活、高效的部署不同版本的业务功能模块 + +基于surging微服务的开发人员提供以下好处: + + * 统一构建微服务。 + * 内置依赖注入,您可以自由组合依赖组件。 + * 内置服务注册中心。 + * 内置网关可以统一外部访问和管理。 + * 轻量级,高性能,模块化的RPC请求管道。 + * 能够在您自己的进程中托管IIS或自托管。 + * 可以在.NET Core上运行,能够在Windows,macOS和Linux上构建和运行 + * 简化繁琐的维护。 + * 基于github平台的开源。 + * 支持负载平衡分流压力。 + * 支持多协议服务主机。 + * 内置服务化治理。 + * 支持引用、Nuget Install Package、扫描三种方式来加载组件和业务模块 diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 000000000..fff2a2778 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,62 @@ +# 关于开发者文档 + +## 文档简介 + +## 目录 +- [概述](quick-start/index.md) +- - [surging 简介]() +- - [版本更新]() +- [教程]() +- - [服务主机如何构建]() +- - - [依赖注入服务]() +- - - [配置日志组件]() +- - - [如何设置成服务提供者]() +- - - [启动配置]() +- - - [配置文件构建]() +- - [协议主机构建]() +- - - [构建TCP协议服务主机]() +- - - [构建MQTT协议服务主机]() +- - - [构建WS协议服务主机]() +- - - [构建UDP协议服务主机]() +- - - [构建Http协议服务主机]() +- - - [构建Dns协议服务主机]() +- - [如何构建微服务]() +- - - [微服务规则]() +- - - [配置routepath]() +- - - [配置ServiceMetadata]() +- - - [服务拦截器配置]() +- - - [配置依赖注入]() +- - - [如何配置和读取配置项]() +- - [服务注册发现和服务治理]() +- - - [consul的注册与发现]() +- - - [zookeeper的注册与发现]() +- - - [服务路由的负载均衡]() +- - - [容错策略]() +- - - [服务熔断]() +- - [引擎核心组件]() +- - - [配置使用Swagger组件]() +- - - [配置ProtoBuffer、MessagePack或Json.net组件编解码消息]() +- - - [配置Log4net日志组件]() +- - - [配置NLog日志组件]() +- - - [配置Stage关卡组件]() +- - - [配置扩展SystemModule组件]() +- - - [配置扩展BusinessModule组件]() +- - - [配置扩展EnginePartModule组件]() +- - - [配置扩展KestrelHttpModule组件]() +- - [中间件]() +- - - [缓存中间件]() +- - - [消息中间件]() +- - [网关]() +- - - [配置gatewaySettings.json文件]() +- - - [jwt鉴权]() +- - - [基于Stage生成的第三方接口网关]() +- [示例]() +- - [缓存中间件使用]() +- - [消息中间件使用]() +- - [服务之间本地和远程调用]() +- [部署]() +- - [引擎部署到window环境中]() +- - [引擎部署到linux环境容器中]() +- - [引擎构建镜像push到镜像库]() +- - [扫描业务模块组件和中间件装载到引擎中]() +- - [基于rancher 服务编排 ]() diff --git a/docs/quick-start/index.md b/docs/quick-start/index.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/toc.yml b/docs/toc.yml new file mode 100644 index 000000000..fb70c2c4d --- /dev/null +++ b/docs/toc.yml @@ -0,0 +1,5 @@ +- name: 开发者文档 + href: index.md +- name: 快速开始 + href: quick-start/index.md + topicHref: quick-start/ \ No newline at end of file diff --git a/index.md b/index.md new file mode 100644 index 000000000..da1316874 --- /dev/null +++ b/index.md @@ -0,0 +1,15 @@ +--- +layout: HubPage +ms.topic: hub-page +hide_bc: true +title: +description: +ms.date: "2019.6.29" +--- + +# Surging + +## 简介 + +## 社区愿景 + diff --git a/samples/.gitignore b/samples/.gitignore deleted file mode 100644 index befad6a88..000000000 --- a/samples/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -/Centa.Agency.HostService/bin -/Centa.Agency.HostService/obj -/Centa.Agency.Application.Service/bin -/Centa.Agency.Application.Service/obj -/DDD.Core/bin -/DDD.Core/obj -/Centa.Agency.Web/bin -bin -obj -/Centa.HostService.SysLog/obj -/Centa.HostService.SysLog/bin -/Centa.Agency.Application.Interface/obj -/Centa.Agency.Domain/obj -/Centa.Agency.Domain/bin -/Centa.Agency.Query/bin -/Centa.Agency.Query/obj -/Centa.Agency.Web/obj diff --git a/samples/AuthServer/Application.Interface.Auth/Application.Interface.Auth.csproj b/samples/AuthServer/Application.Interface.Auth/Application.Interface.Auth.csproj deleted file mode 100644 index 8c27115ea..000000000 --- a/samples/AuthServer/Application.Interface.Auth/Application.Interface.Auth.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - netcoreapp2.0 - - - - ..\HostService\bin\Debug - - - - - - - - - - - diff --git a/samples/AuthServer/Application.Interface.Auth/Dto/LoginReq.cs b/samples/AuthServer/Application.Interface.Auth/Dto/LoginReq.cs deleted file mode 100644 index acbad5813..000000000 --- a/samples/AuthServer/Application.Interface.Auth/Dto/LoginReq.cs +++ /dev/null @@ -1,14 +0,0 @@ -using DTO.Core; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Application.Service.Auth.Dto -{ - public class LoginReq : BaseDto - { - public string UserName { get; set; } - public string Pwd { get; set; } - public Guid CorporationKeyId { get; set; } - } -} diff --git a/samples/AuthServer/Application.Interface.Auth/Event/CorporationActivated.cs b/samples/AuthServer/Application.Interface.Auth/Event/CorporationActivated.cs deleted file mode 100644 index 11f421dad..000000000 --- a/samples/AuthServer/Application.Interface.Auth/Event/CorporationActivated.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Surging.Core.CPlatform.EventBus.Events; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Application.Interface.Auth.EVENT -{ - // /// - // /// 新注册公司被激活的事件 - // /// - //public class CorporationActivatedEvent: IntegrationEvent - // { - - // } -} diff --git a/samples/AuthServer/Application.Interface.Auth/Event/IAuthEventHandler.cs b/samples/AuthServer/Application.Interface.Auth/Event/IAuthEventHandler.cs deleted file mode 100644 index 93ae5b0b7..000000000 --- a/samples/AuthServer/Application.Interface.Auth/Event/IAuthEventHandler.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Application.Interface.Org.EVENT; -using Surging.Core.CPlatform.EventBus.Events; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Application.Interface.Auth.EVENT -{ - /// - /// 事件处理器 - /// - public interface IAuthEventHandler : IIntegrationEventHandler - { - } -} diff --git a/samples/AuthServer/Application.Interface.Auth/IAuthAppService.cs b/samples/AuthServer/Application.Interface.Auth/IAuthAppService.cs deleted file mode 100644 index 3b899c1ea..000000000 --- a/samples/AuthServer/Application.Interface.Auth/IAuthAppService.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Application.Service.Auth.Dto; -using DTO.Core; -using Surging.Core.CPlatform.Ioc; -using Surging.Core.CPlatform.Runtime.Server.Implementation.ServiceDiscovery.Attributes; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace Application.Interface.Auth -{ - [ServiceBundle("api/{Service}")] - public interface IAuthAppService : IServiceKey - { - - /// - /// 登录系统 - /// - /// - [Service(Date = "2018-1-30", Director = "刘旭东", Name = "登录系统")] - Task SignIn( LoginReq req); - - /// - /// 退出系统 - /// - /// - [Service(Date = "2018-1-30", Director = "刘旭东", Name = "退出系统")] - Task SignUp(CommonCMDReq req); - - [Service(Date = "2018-1-30", Director = "刘旭东", Name = "查询系统模块下的所有权限")] - Task FindDomainPermissions(CommonCMDReq req); - } -} diff --git a/samples/AuthServer/Application.Service.Auth/Application.Service.Auth.csproj b/samples/AuthServer/Application.Service.Auth/Application.Service.Auth.csproj deleted file mode 100644 index 0e9898f87..000000000 --- a/samples/AuthServer/Application.Service.Auth/Application.Service.Auth.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - - netcoreapp2.0 - - - - ..\HostService\bin\Debug - - - - - - - - - - - - - - - diff --git a/samples/AuthServer/Application.Service.Auth/EventHandling/AuthEventHandler.cs b/samples/AuthServer/Application.Service.Auth/EventHandling/AuthEventHandler.cs deleted file mode 100644 index ab81150ff..000000000 --- a/samples/AuthServer/Application.Service.Auth/EventHandling/AuthEventHandler.cs +++ /dev/null @@ -1,55 +0,0 @@ -using App.Core.Security; -using Application.Interface.Auth.EVENT; -using Application.Interface.Org.EVENT; -using Domain.Auth.Aggregate; -using Repository.Auth; -using Surging.Core.ProxyGenerator; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace Application.Service.Auth.EventHandling -{ - //[QueueConsumerAttribute] - public class AuthEventHandler : IAuthEventHandler - { - private readonly UserRepository _userRepository; - private readonly SubDomainRepository _subDomainRepository; - private readonly UserQueryRepository _queryUserRepository; - private readonly SubDomainQueryRepository _querySubDomainRepository; - // private ICacheProvider _cacheProvider; - public AuthEventHandler(UserRepository userRepository, UserQueryRepository queryUserRepository, - SubDomainRepository subDomainRepository, SubDomainQueryRepository querySubDomainRepository) - { - _userRepository = userRepository; - _subDomainRepository = subDomainRepository; - _queryUserRepository = queryUserRepository; - _querySubDomainRepository = querySubDomainRepository; - } - - - public Task Handle(CorporationActivatedEvent @event) - { - //需要为企业管理做初始化,并生成管理员账号 - return Task.Run(() => - { - var encryptionService = new EncryptionService(); - _userRepository.Add(new User - { - CorporationKeyId = @event.CorpId, - IsDelete = false, - EmployeeKeyID = Guid.Parse(@event.EmpId), - KeyId = Guid.NewGuid(), - Name = "超级管理员", - No = "SuperMan", - Version = 1, - Pwd = encryptionService.EncryptText("123456") - }); - - _userRepository.Commit(); - }); - - } - } -} diff --git a/samples/AuthServer/Application.Service.Auth/Query/AuthAppService.cs b/samples/AuthServer/Application.Service.Auth/Query/AuthAppService.cs deleted file mode 100644 index d6db7d3de..000000000 --- a/samples/AuthServer/Application.Service.Auth/Query/AuthAppService.cs +++ /dev/null @@ -1,32 +0,0 @@ -using DTO.Core; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Application.Service.Auth -{ - public partial class AuthAppService - { - public Task FindDomainPermissions(CommonCMDReq req) - { - BaseListResponseDto rsp = new BaseListResponseDto(); - var rows= _querySubDomainRepository.Get(a => !a.IsDelete,b=>b.SubDomainPermissions).ToList(); - rsp.Result = rows.Select(a => new { - keyId = a.KeyId, - domainNmae = a.Name, - action = a.SubDomainPermissions.Where(b=>b.PermissionType== Domain.Auth.Entity.PermissionCategory.Action)?.GroupBy(b => b.GroupName, c => new { - name=c.Name, - no=c.No - }).ToDictionary(b=>b.Key,c=>c), - page = a.SubDomainPermissions.Where(b => b.PermissionType == Domain.Auth.Entity.PermissionCategory.Page)?.Select(c => new { - name = c.Name, - no = c.No - }).ToList() - }).ToList(); - return Task.FromResult(rsp); - } - - } -} diff --git a/samples/AuthServer/Application.Service.Auth/UseCases/AuthAppService.cs b/samples/AuthServer/Application.Service.Auth/UseCases/AuthAppService.cs deleted file mode 100644 index f3d351d92..000000000 --- a/samples/AuthServer/Application.Service.Auth/UseCases/AuthAppService.cs +++ /dev/null @@ -1,65 +0,0 @@ -using App.Core.Security; -using Application.Interface.Auth; -using Application.Service.Auth.Dto; -using Domain.Auth.Aggregate; -using DTO.Core; -using Repository.Auth; -using Surging.Core.Caching; -using Surging.Core.CPlatform.Ioc; -using Surging.Core.ProxyGenerator; - -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace Application.Service.Auth -{ - [ModuleName("Auth")] - public partial class AuthAppService : ProxyServiceBase, IAuthAppService - { - private readonly UserRepository _userRepository; - private readonly SubDomainRepository _subDomainRepository; - private readonly UserQueryRepository _queryUserRepository; - private readonly SubDomainQueryRepository _querySubDomainRepository; - // private ICacheProvider _cacheProvider; - public AuthAppService(UserRepository userRepository, UserQueryRepository queryUserRepository, - SubDomainRepository subDomainRepository, SubDomainQueryRepository querySubDomainRepository) - { - _userRepository = userRepository; - _subDomainRepository = subDomainRepository; - _queryUserRepository = queryUserRepository; - _querySubDomainRepository = querySubDomainRepository; - } - - public Task SignIn(LoginReq req) - { - User user=null; - try { - //缓存增加当前用户相关信息 - //_cacheProvider= CacheContainer.GetInstances("Redis"); - //_cacheProvider.Add("UserKeyId=22", "{ UserKeyId=22,TenantId=3}"); - var encryptionService = new EncryptionService(); - var pwde = encryptionService.EncryptText(req.Pwd); - user = _queryUserRepository.GetSingle(a => a.CorporationKeyId == req.CorporationKeyId && !a.IsDelete && a.Pwd == pwde && a.No == req.UserName); - } - catch (Exception ex) - { - string ss = ex.Message; - } - if (user != null) - { - return Task.FromResult(new TokenDto { CorporationKeyId = user.CorporationKeyId, Token = user.EmployeeKeyID.ToString() }); - - } - else - { - return Task.FromResult(null); - } - } - - public Task SignUp(CommonCMDReq req) - { - throw new NotImplementedException(); - } - } -} diff --git a/samples/AuthServer/Domain/Aggregate/SubDomain.cs b/samples/AuthServer/Domain/Aggregate/SubDomain.cs deleted file mode 100644 index ba5963c54..000000000 --- a/samples/AuthServer/Domain/Aggregate/SubDomain.cs +++ /dev/null @@ -1,24 +0,0 @@ -using DDD.Core; -using Domain.Auth.Entity; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text; - -namespace Domain.Auth.Aggregate -{ - /// - /// 服务模块(子领域) - /// - [Table("Auth_SubDomains")] - public class SubDomain : IAggregate - { - - /// - /// 模块下的权限 - /// - public virtual List SubDomainPermissions { get; set; } - - } -} diff --git a/samples/AuthServer/Domain/Aggregate/User.cs b/samples/AuthServer/Domain/Aggregate/User.cs deleted file mode 100644 index 2135d1a39..000000000 --- a/samples/AuthServer/Domain/Aggregate/User.cs +++ /dev/null @@ -1,32 +0,0 @@ -using DDD.Core; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text; - -namespace Domain.Auth.Aggregate -{ - /// - /// 平台用户(账号) - /// - [Table("Auth_Users")] - public class User : IAggregate - { - - /// - /// 密码 - /// - public string Pwd { get; set; } - - - /// - /// 归属员工 - /// - public Guid EmployeeKeyID { get; set; } - - - //public virtual List Departments { get; set; } - - } -} diff --git a/samples/AuthServer/Domain/Domain.Auth.csproj b/samples/AuthServer/Domain/Domain.Auth.csproj deleted file mode 100644 index 557735dc9..000000000 --- a/samples/AuthServer/Domain/Domain.Auth.csproj +++ /dev/null @@ -1,27 +0,0 @@ - - - - netcoreapp2.0 - - - - ..\HostService\bin\Debug - - - - - - - - - - - - - - - - - - - diff --git a/samples/AuthServer/Domain/Entity/SubDomainPermission.cs b/samples/AuthServer/Domain/Entity/SubDomainPermission.cs deleted file mode 100644 index b34a3e9dc..000000000 --- a/samples/AuthServer/Domain/Entity/SubDomainPermission.cs +++ /dev/null @@ -1,40 +0,0 @@ -using DDD.Core; -using Domain.Auth.Aggregate; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text; - -namespace Domain.Auth.Entity -{ - /// - /// 模块下的权限 - /// - [Table("Auth_SubDomain_Permissions")] - public class SubDomainPermission : BaseEntity - { - public string GroupName { get; set; } - public string GroupNo { get; set; } - - public PermissionCategory PermissionType { get; set; } - - public Guid SubDomainKeyId { get; set; } - - [ForeignKey("SubDomainKeyId")] - public SubDomain SubDomain { get; set; } - } - - public enum PermissionCategory - { - /// - /// 页面 - /// - Page=1, - - /// - /// 动作 - /// - Action=2 - } -} diff --git a/samples/AuthServer/Domain/Repository/UserRepository.cs b/samples/AuthServer/Domain/Repository/UserRepository.cs deleted file mode 100644 index 00c3f69c7..000000000 --- a/samples/AuthServer/Domain/Repository/UserRepository.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Domain.Auth.Aggregate; -using Microsoft.EntityFrameworkCore; -using Repository.EF.Core; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Domain.Auth.Repository -{ - -} diff --git a/samples/AuthServer/Domain/ValueObject/InquiryParameter.cs b/samples/AuthServer/Domain/ValueObject/InquiryParameter.cs deleted file mode 100644 index 4dcf8b670..000000000 --- a/samples/AuthServer/Domain/ValueObject/InquiryParameter.cs +++ /dev/null @@ -1,29 +0,0 @@ -using DDD.Core; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text; - -namespace Domain.ValueObject.Inquiry -{ - - public class InquiryParameter: BaseValueObject - { - // [Column("InquiryKeyId")] - public Guid InquiryKeyId { get; set; } - // [ForeignKey("InquiryKeyId")] - // public CusInquiry OwnCusInquiry { get; set; } - - public Guid SysParameterItemKeyId { get; set; } - public int ParameterType { get; set; } - public int Seq { get; set; } - /* - [InverseProperty("Author")] - public List AuthoredPosts { get; set; } - - [InverseProperty("Contributor")] - public List ContributedToPosts { get; set; } - */ - - } -} diff --git a/samples/AuthServer/HostService/Configs/log4net.config b/samples/AuthServer/HostService/Configs/log4net.config deleted file mode 100644 index 42fd16880..000000000 --- a/samples/AuthServer/HostService/Configs/log4net.config +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/AuthServer/HostService/HostService.csproj b/samples/AuthServer/HostService/HostService.csproj deleted file mode 100644 index 6fc04dddc..000000000 --- a/samples/AuthServer/HostService/HostService.csproj +++ /dev/null @@ -1,39 +0,0 @@ - - - - Exe - netcoreapp2.0 - - - - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - diff --git a/samples/AuthServer/HostService/Program.cs b/samples/AuthServer/HostService/Program.cs deleted file mode 100644 index fd254ab5b..000000000 --- a/samples/AuthServer/HostService/Program.cs +++ /dev/null @@ -1,66 +0,0 @@ -using Autofac; -using Surging.Core.Codec.MessagePack; -using Surging.Core.Consul; -using Surging.Core.Consul.Configurations; -using Surging.Core.CPlatform; -using Surging.Core.CPlatform.Utilities; -using Surging.Core.DotNetty; -using Surging.Core.EventBusRabbitMQ; -using Surging.Core.ServiceHosting; -using Surging.Core.ServiceHosting.Internal.Implementation; -using System; -using System.Text; -using Surging.Core.Log4net; -using Surging.Core.ProxyGenerator; - -namespace Centa.HostService.Auth -{ - public class Program - { - static void Main(string[] args) - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - var host = new ServiceHostBuilder() - .RegisterServices(builder => - { - // builder.RegisterAssemblyModules(); - //这里写自己的注册 - }) - .RegisterServices(builder => - { - builder.AddMicroService(option => - { - option.AddServiceRuntime(); - option.AddRelateService(); - option.UseConsulManager(new ConfigInfo("127.0.0.1:8500")); - option.UseDotNettyTransport(); - option.UseRabbitMQTransport(); - option.AddRabbitMQAdapt(); - //option.UseMessagePackCodec(); - option.UseJsonCodec(); - builder.Register(p => new CPlatformContainer(ServiceLocator.Current)); - }); - }) - .SubscribeAt() - .UseLog4net("Configs/log4net.config") - .UseServer(options => - { - options.Ip = "127.0.0.1"; - options.Port = 10241; - options.Token = "True"; - options.ExecutionTimeoutInMilliseconds = 30000; - options.MaxConcurrentRequests = 200; - }) - .UseProxy() - .UseStartup() - .Build(); - - using (host.Run()) - { - Console.Title = "认证授权"; - Console.WriteLine($"认证授权——服务端启动成功,{DateTime.Now}。"); - Console.ReadLine(); - } - } - } -} diff --git a/samples/AuthServer/HostService/Startup.cs b/samples/AuthServer/HostService/Startup.cs deleted file mode 100644 index 84043e018..000000000 --- a/samples/AuthServer/HostService/Startup.cs +++ /dev/null @@ -1,71 +0,0 @@ -using Autofac; -using Autofac.Extensions.DependencyInjection; -using Config.Core.Extensions; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Surging.Core.Caching.Configurations; -using Surging.Core.CPlatform.Utilities; -using Surging.Core.EventBusRabbitMQ.Configurations; -using System; - -namespace Centa.HostService.Auth -{ - public class Startup - { - public Startup() - { - var config = new ConfigurationBuilder() - .SetBasePath(AppContext.BaseDirectory); - ConfigureEventBus(config); - ConfigureCache(config); - ConfigureDB(config); - - } - - public IContainer ConfigureServices(ContainerBuilder builder) - { - var services = new ServiceCollection(); - ConfigureLogging(services); - builder.Populate(services); - ServiceLocator.Current = builder.Build(); - return ServiceLocator.Current; - } - - public void Configure(IContainer app) - { - app.Resolve().AddConsole((c, l) => (int)l >= 3); - } - - #region 私有方法 - /// - /// 配置日志服务 - /// - /// - private void ConfigureLogging(IServiceCollection services) - { - services.AddLogging(); - } - - private static void ConfigureEventBus(IConfigurationBuilder build) - { - build - .AddEventBusFile("eventBusSettings.json", optional: false); - } - - /// - /// 配置缓存服务 - /// - private void ConfigureCache(IConfigurationBuilder build) - { - build.AddCacheFile("cacheSettings.json", optional: false); - } - - private void ConfigureDB(IConfigurationBuilder build) - { - build.AddDBFile("dbSettings.json", optional: false); - } - #endregion - - } -} diff --git a/samples/AuthServer/HostService/cacheSettings.json b/samples/AuthServer/HostService/cacheSettings.json deleted file mode 100644 index ab9c7e43d..000000000 --- a/samples/AuthServer/HostService/cacheSettings.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "CachingSettings": [ - { - "Id": "ddlCache", - "Class": "Surging.Core.Caching.RedisCache.RedisContext,Surging.Core.Caching", - "Properties": [ - { - "Name": "appRuleFile", - "Ref": "rule" - }, - { - "Name": "dataContextPool", - "Ref": "ddls_sample", - "Maps": [ - { - "Name": "Redis", - "Properties": [ - { - "value": "127.0.0.1:6379::1" - } - ] - }, - { - "Name": "MemoryCache" - } - ] - }, - { - "Name": "defaultExpireTime", - "value": "120" - }, - { - "Name": "connectTimeout", - "Value": "120" - }, - { - "Name": "minSize", - "Value": "1" - }, - { - "Name": "maxSize", - "Value": "10" - } - ] - } - ] -} diff --git a/samples/AuthServer/HostService/dbSettings.json b/samples/AuthServer/HostService/dbSettings.json deleted file mode 100644 index 9903dfd68..000000000 --- a/samples/AuthServer/HostService/dbSettings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Web_A2;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False", - "ModelAssemblyName": "Domain.Auth" -} - diff --git a/samples/AuthServer/HostService/eventBusSettings.json b/samples/AuthServer/HostService/eventBusSettings.json deleted file mode 100644 index d5d4487b7..000000000 --- a/samples/AuthServer/HostService/eventBusSettings.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "EventBusConnection": "localhost", - "EventBusUserName": "guest", - "EventBusPassword": "guest" -} - diff --git a/samples/AuthServer/Repository.Auth/AuthRepository.cs b/samples/AuthServer/Repository.Auth/AuthRepository.cs deleted file mode 100644 index 25ce7ba6c..000000000 --- a/samples/AuthServer/Repository.Auth/AuthRepository.cs +++ /dev/null @@ -1,48 +0,0 @@ -using DDD.Core; -using Domain.Auth.Aggregate; -using Microsoft.EntityFrameworkCore; -using Repository.EF.Core; -using Surging.Core.CPlatform.Ioc; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; - -namespace Repository.Auth -{ - - - - public class UserRepository : BaseImpRepository - { - public override User FindBy(Guid key) - { - return _set //.Include(a => a.Departments).ThenInclude(a => a.Employees) - .SingleOrDefault(a => a.KeyId == key); - } - } - - public class SubDomainRepository : BaseImpRepository - { - public override SubDomain FindBy(Guid key) - { - return _set //.Include(a => a.Departments).ThenInclude(a => a.Employees) - .SingleOrDefault(a => a.KeyId == key); - } - } - - public class UserQueryRepository : BaseImpQueryOnlyRepository - { - } - - public class SubDomainQueryRepository : BaseImpQueryOnlyRepository - { - - public override IQueryable Get(Expression> where = null) - { - return _set.Include(a => a.SubDomainPermissions).Where(where); - } - } - -} diff --git a/samples/AuthServer/Repository.Auth/Repository.Auth.csproj b/samples/AuthServer/Repository.Auth/Repository.Auth.csproj deleted file mode 100644 index 9fb3bffee..000000000 --- a/samples/AuthServer/Repository.Auth/Repository.Auth.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - netcoreapp2.0 - - - - ..\HostService\bin\Debug - - - - - - - - diff --git a/samples/Common/App.Core/App.Core.csproj b/samples/Common/App.Core/App.Core.csproj deleted file mode 100644 index df1909e24..000000000 --- a/samples/Common/App.Core/App.Core.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - netcoreapp2.0 - - - - - - - - - - - diff --git a/samples/Common/App.Core/BaseAppService.cs b/samples/Common/App.Core/BaseAppService.cs deleted file mode 100644 index a7b6e682c..000000000 --- a/samples/Common/App.Core/BaseAppService.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Repository.EF.Core; -using Surging.Core.ProxyGenerator; -using System; - -namespace App.Core -{ - public class BaseAppService : ProxyServiceBase - { - // protected BaseImpRepository _repository; - //protected QueryOrgRepository _queryOnlyRepository; - public BaseAppService()//(BaseImpRepository repository)//, QueryOrgRepository queryOnlyRepository) - { - // _repository = repository; - //_queryOnlyRepository = queryOnlyRepository; - } - } -} diff --git a/samples/Common/App.Core/Security/EncryptionService.cs b/samples/Common/App.Core/Security/EncryptionService.cs deleted file mode 100644 index 36159e03e..000000000 --- a/samples/Common/App.Core/Security/EncryptionService.cs +++ /dev/null @@ -1,159 +0,0 @@ -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; - -namespace App.Core.Security -{ - /// - /// Encryption service - /// - public class EncryptionService : IEncryptionService - { - #region Fields - - private readonly dynamic _securitySettings ; - private readonly string EncryptionKey = "loveC#loveC#loveC#"; - #endregion - - #region Ctor - public EncryptionService() - { - //_securitySettings.EncryptionKey = "loveC#"; - } - - - #endregion - - #region Utilities - - private byte[] EncryptTextToMemory(string data, byte[] key, byte[] iv) - { - using (var ms = new MemoryStream()) { - using (var cs = new CryptoStream(ms, new TripleDESCryptoServiceProvider().CreateEncryptor(key, iv), CryptoStreamMode.Write)) { - var toEncrypt = Encoding.Unicode.GetBytes(data); - cs.Write(toEncrypt, 0, toEncrypt.Length); - cs.FlushFinalBlock(); - } - - return ms.ToArray(); - } - } - - private string DecryptTextFromMemory(byte[] data, byte[] key, byte[] iv) - { - using (var ms = new MemoryStream(data)) { - using (var cs = new CryptoStream(ms, new TripleDESCryptoServiceProvider().CreateDecryptor(key, iv), CryptoStreamMode.Read)) - { - using (var sr = new StreamReader(cs, Encoding.Unicode)) - { - return sr.ReadToEnd(); - } - } - } - } - - #endregion - - #region Methods - - /// - /// Create salt key - /// - /// Key size - /// Salt key - public virtual string CreateSaltKey(int size) - { - //generate a cryptographic random number - using (var provider = new RNGCryptoServiceProvider()) - { - var buff = new byte[size]; - provider.GetBytes(buff); - - // Return a Base64 string representation of the random number - return Convert.ToBase64String(buff); - } - } - - /// - /// Create a password hash - /// - /// Password - /// Salk key - /// Password format (hash algorithm) - /// Password hash - public virtual string CreatePasswordHash(string password, string saltkey, string passwordFormat) - { - return CreateHash(Encoding.UTF8.GetBytes(string.Concat(password, saltkey)), passwordFormat); - } - - /// - /// Create a data hash - /// - /// The data for calculating the hash - /// Hash algorithm - /// Data hash - public virtual string CreateHash(byte[] data, string hashAlgorithm) - { - if (string.IsNullOrEmpty(hashAlgorithm)) - throw new ArgumentNullException(nameof(hashAlgorithm)); - - var algorithm = HashAlgorithm.Create(hashAlgorithm); - if (algorithm == null) - throw new ArgumentException("Unrecognized hash name"); - - var hashByteArray = algorithm.ComputeHash(data); - return BitConverter.ToString(hashByteArray).Replace("-", ""); - } - - /// - /// Encrypt text - /// - /// Text to encrypt - /// Encryption private key - /// Encrypted text - public virtual string EncryptText(string plainText, string encryptionPrivateKey = "") - { - if (string.IsNullOrEmpty(plainText)) - return plainText; - - if (string.IsNullOrEmpty(encryptionPrivateKey)) - encryptionPrivateKey = EncryptionKey;// _securitySettings.EncryptionKey; - - using (var provider = new TripleDESCryptoServiceProvider()) - { - provider.Key = Encoding.ASCII.GetBytes(encryptionPrivateKey.Substring(0, 16)); - provider.IV = Encoding.ASCII.GetBytes(encryptionPrivateKey.Substring(8, 8)); - - var encryptedBinary = EncryptTextToMemory(plainText, provider.Key, provider.IV); - return Convert.ToBase64String(encryptedBinary); - } - } - - /// - /// Decrypt text - /// - /// Text to decrypt - /// Encryption private key - /// Decrypted text - public virtual string DecryptText(string cipherText, string encryptionPrivateKey = "") - { - if (string.IsNullOrEmpty(cipherText)) - return cipherText; - - if (string.IsNullOrEmpty(encryptionPrivateKey)) - encryptionPrivateKey = EncryptionKey;// _securitySettings.EncryptionKey; - - using (var provider = new TripleDESCryptoServiceProvider()) - { - provider.Key = Encoding.ASCII.GetBytes(encryptionPrivateKey.Substring(0, 16)); - provider.IV = Encoding.ASCII.GetBytes(encryptionPrivateKey.Substring(8, 8)); - - var buffer = Convert.FromBase64String(cipherText); - return DecryptTextFromMemory(buffer, provider.Key, provider.IV); - } - } - - #endregion - } -} diff --git a/samples/Common/App.Core/Security/IEncryptionService.cs b/samples/Common/App.Core/Security/IEncryptionService.cs deleted file mode 100644 index 57c6af36c..000000000 --- a/samples/Common/App.Core/Security/IEncryptionService.cs +++ /dev/null @@ -1,48 +0,0 @@ -namespace App.Core.Security -{ - /// - /// Encryption service - /// - public interface IEncryptionService - { - /// - /// Create salt key - /// - /// Key size - /// Salt key - string CreateSaltKey(int size); - - /// - /// Create a password hash - /// - /// Password - /// Salk key - /// Password format (hash algorithm) - /// Password hash - string CreatePasswordHash(string password, string saltkey, string passwordFormat); - - /// - /// Create a data hash - /// - /// The data for calculating the hash - /// Hash algorithm - /// Data hash - string CreateHash(byte [] data, string hashAlgorithm); - - /// - /// Encrypt text - /// - /// Text to encrypt - /// Encryption private key - /// Encrypted text - string EncryptText(string plainText, string encryptionPrivateKey = ""); - - /// - /// Decrypt text - /// - /// Text to decrypt - /// Encryption private key - /// Decrypted text - string DecryptText(string cipherText, string encryptionPrivateKey = ""); - } -} diff --git a/samples/Common/Config.Core/Config.Core.csproj b/samples/Common/Config.Core/Config.Core.csproj deleted file mode 100644 index 89c8baf3a..000000000 --- a/samples/Common/Config.Core/Config.Core.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - netcoreapp2.0 - - - - - - - - - C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.extensions.configuration.fileextensions\2.0.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.FileExtensions.dll - - - - diff --git a/samples/Common/Config.Core/DBConfigurationExtensions.cs b/samples/Common/Config.Core/DBConfigurationExtensions.cs deleted file mode 100644 index 15a651324..000000000 --- a/samples/Common/Config.Core/DBConfigurationExtensions.cs +++ /dev/null @@ -1,101 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.FileProviders; -using Surging.Core.CPlatform.Configurations.Remote; -using Surging.Core.CPlatform.Utilities; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace Config.Core.Extensions -{ - public static class DBConfigurationExtensions - { - public static IConfigurationBuilder AddDBFile(this IConfigurationBuilder builder, string path) - { - return AddDBFile(builder, provider: null, path: path, optional: false, reloadOnChange: false); - } - - public static IConfigurationBuilder AddDBFile(this IConfigurationBuilder builder, string path, bool optional) - { - return AddDBFile(builder, provider: null, path: path, optional: optional, reloadOnChange: false); - } - - public static IConfigurationBuilder AddDBFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange) - { - return AddDBFile(builder, provider: null, path: path, optional: optional, reloadOnChange: reloadOnChange); - } - - public static IConfigurationBuilder AddDBFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange) - { - Check.NotNull(builder, "builder"); - Check.CheckCondition(() => string.IsNullOrEmpty(path), "path"); - if (provider == null && Path.IsPathRooted(path)) - { - provider = new PhysicalFileProvider(Path.GetDirectoryName(path)); - path = Path.GetFileName(path); - } - var source = new DBConfigurationSource - { - FileProvider = provider, - Path = path, - Optional = optional, - ReloadOnChange = reloadOnChange - }; - builder.Add(source); - DBConfig.Configuration = builder.Build(); - return builder; - } - } - public class DBConfig - { - - public static IConfiguration Configuration { get; set; } - /* static ConfigHelper() - { - configuration = AutofacContainer.Resolve(); - } - - public static IConfigurationSection GetSection(string key) - { - return configuration.GetSection(key); - } - - public static string GetConfigurationValue(string key) - { - return configuration[key]; - } - - public static string GetConfigurationValue(string section, string key) - { - return GetSection(section)?[key]; - } - - public static string GetConnectionString(string key) - { - return configuration.GetConnectionString(key); - } - */ - } - - public class DBConfigurationSource : FileConfigurationSource - { - public string ConfigurationKeyPrefix { get; set; } - - public override IConfigurationProvider Build(IConfigurationBuilder builder) - { - FileProvider = FileProvider ?? builder.GetFileProvider(); - return new DBConfigurationProvider(this); - } - } - public class DBConfigurationProvider : FileConfigurationProvider - { - public DBConfigurationProvider(DBConfigurationSource source) : base(source) { } - - public override void Load(Stream stream) - { - var parser = new JsonConfigurationParser(); - this.Data = parser.Parse(stream, null); - } - } -} diff --git a/samples/Common/DDD.Core/BaseEntity.cs b/samples/Common/DDD.Core/BaseEntity.cs deleted file mode 100644 index 9093f51b4..000000000 --- a/samples/Common/DDD.Core/BaseEntity.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Text; - -namespace DDD.Core -{ - public abstract class BaseEntity : IDBModel - { - [Key] - public Guid KeyId { get; set; } - public virtual Guid CorporationKeyId { get; set; } - public virtual DateTime CreateTime { get; set; } - public virtual Guid CreateUserKeyId { get; set; } - public virtual DateTime UpdateTime { get; set; } - public virtual Guid UpdateUserKeyId { get; set; } - public virtual bool IsDelete { get; set; } - public virtual int Version { get; set; } - - //2-12增加名字、编号 - public string Name { get; set; } - - public string No { get; set; } - - public virtual void SetEditer(Guid? editer) - { - if(this.KeyId==Guid.Empty) - { - this.CreateTime = DateTime.Now; - this.CreateUserKeyId = Guid.Empty; - this.UpdateUserKeyId = Guid.Empty; - this.UpdateTime = DateTime.Now; - } - else - { - if (editer.HasValue) - { - this.UpdateUserKeyId = editer.Value; - this.UpdateTime = DateTime.Now; - } - } - } - } -} diff --git a/samples/Common/DDD.Core/BaseValueObject.cs b/samples/Common/DDD.Core/BaseValueObject.cs deleted file mode 100644 index 91399b62b..000000000 --- a/samples/Common/DDD.Core/BaseValueObject.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Text; - -namespace DDD.Core -{ - public abstract class BaseValueObject : IDBModel - { - [Key] - public Guid KeyId { get; set; } - public virtual Guid CorporationKeyId { get; set; } - public virtual DateTime CreateTime { get; set; } - public virtual Guid CreateUserKeyId { get; set; } - public virtual DateTime UpdateTime { get; set; } - public virtual Guid UpdateUserKeyId { get; set; } - public virtual bool IsDelete { get; set; } - public virtual int Version { get; set; } - - public string Name { get; set; } - - public string No { get; set; } - } -} diff --git a/samples/Common/DDD.Core/DDD.Core.Extensions/GenericExtension.cs b/samples/Common/DDD.Core/DDD.Core.Extensions/GenericExtension.cs deleted file mode 100644 index 35919f27c..000000000 --- a/samples/Common/DDD.Core/DDD.Core.Extensions/GenericExtension.cs +++ /dev/null @@ -1,140 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Reflection; - -namespace DDD.Core.Extensions -{ - /// - /// 泛型扩展 - /// - public static class GenericExtension - { - public static bool Equal(this T x, T y) - { - return ((IComparable)(x)).CompareTo(y) == 0; - } - - #region ToDictionary - - public static Dictionary ToDictionary(this T t, Dictionary dic = null) where T : class - { - if (dic == null) - dic = new Dictionary(); - var properties = t.GetType().GetProperties(); - foreach (var property in properties) - { - var value = property.GetValue(t, null); - dic.Add(property.Name, value?.ToString() ?? ""); - } - return dic; - } - - public static Dictionary ToDictionary(this TInterface t, Dictionary dic = null) where T : class, TInterface - { - if (dic == null) - dic = new Dictionary(); - var properties = typeof(T).GetProperties(); - foreach (var property in properties) - { - var value = property.GetValue(t, null); - if (value == null) continue; - dic.Add(property.Name, value?.ToString() ?? ""); - } - return dic; - } - - #endregion - - /// - /// 将字符串转换为指定的类型,如果转换不成功,返回默认值。 - /// - /// 结构体类型或枚举类型 - /// 需要转换的字符串 - /// 返回指定的类型。 - public static T ParseTo(this string str) where T : struct - { - return str.ParseTo(default(T)); - } - - /// - /// 将字符串转换为指定的类型,如果转换不成功,返回默认值。 - /// - /// 结构体类型或枚举类型 - /// 需要转换的字符串 - /// 如果转换失败,需要使用的默认值 - /// 返回指定的类型。 - public static T ParseTo(this string str, T defaultValue) where T : struct - { - var t = str.ParseToNullable(); - if (t.HasValue) - { - return t.Value; - } - return defaultValue; - } - - /// - /// 将字符串转换为指定的类型,如果转换不成功,返回null - /// - /// 结构体类型或枚举类型 - /// 需要转换的字符串 - /// 返回指定的类型 - public static T? ParseToNullable(this string str) where T : struct - { - if (string.IsNullOrEmpty(str)) - { - return null; - } - var typeFromHandle = typeof(T); - if (typeFromHandle.IsEnum) - { - return str.ToEnum(); - } - return (T?)str.ParseTo(typeFromHandle.FullName); - } - - public static DataTable ToDataTable(this IEnumerable source) - { - DataTable dtReturn = new DataTable(); - - // column names - PropertyInfo[] oProps = null; - - if (source == null) return dtReturn; - - foreach (var rec in source) - { - // Use reflection to get property names, to create table, Only first time, others will follow - if (oProps == null) - { - oProps = rec.GetType().GetProperties(); - foreach (var pi in oProps) - { - var colType = pi.PropertyType; - - if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) - { - colType = colType.GetGenericArguments()[0]; - } - - dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); - } - } - - var dr = dtReturn.NewRow(); - - foreach (var pi in oProps) - { - dr[pi.Name] = pi.GetValue(rec, null) == null - ? DBNull.Value - : pi.GetValue - (rec, null); - } - - dtReturn.Rows.Add(dr); - } - return dtReturn; - } - } -} diff --git a/samples/Common/DDD.Core/DDD.Core.Extensions/ObjectExtension.cs b/samples/Common/DDD.Core/DDD.Core.Extensions/ObjectExtension.cs deleted file mode 100644 index 306776e06..000000000 --- a/samples/Common/DDD.Core/DDD.Core.Extensions/ObjectExtension.cs +++ /dev/null @@ -1,1181 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.IO; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.Serialization.Formatters.Binary; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Xml; -using System.Xml.Linq; - -namespace DDD.Core.Extensions -{ - public static class ObjectExtension - { - /// - /// 将集合转换为数据集。 - /// - /// 转换的元素类型。 - /// 集合。 - /// 是否生成泛型数据集。 - /// 数据集。 - public static DataSet ToDataSet(this IEnumerable list, bool generic = true) - { - return ListToDataSet(list, generic); - } - - /// - /// 将集合转换为数据集。 - /// - /// 集合。 - /// 是否生成泛型数据集。 - /// 数据集。 - public static DataSet ToDataSet(this IEnumerable list, bool generic = true) - { - return ListToDataSet(list, generic); - } - - /// - /// 将集合转换为数据集。 - /// - /// 转换的元素类型。 - /// 集合。 - /// 是否生成泛型数据集。 - /// 数据集。 - public static DataSet ToDataSet(this IEnumerable list, bool generic = true) - { - return ListToDataSet(list, typeof(T), generic); - } - - /// - /// 将实例转换为集合数据集。 - /// - /// 实例类型。 - /// 实例。 - /// 是否生成泛型数据集。 - /// 数据集。 - public static DataSet ToListSet(this T o, bool generic = true) - { - if (o is IEnumerable) - { - return ListToDataSet(o as IEnumerable, generic); - } - else - { - return ListToDataSet(new T[] { o }, generic); - } - } - - /// - /// 将可序列化实例转换为XmlDocument。 - /// - /// 实例类型。 - /// 实例。 - /// XmlDocument。 - public static XmlDocument ToXmlDocument(this T o) - { - XmlDocument xmlDocument = new XmlDocument(); - xmlDocument.InnerXml = o.ToListSet().GetXml(); - return xmlDocument; - } - - /// - /// 将集合转换为数据集。 - /// - /// 集合。 - /// 转换的元素类型。 - /// 是否生成泛型数据集。 - /// 转换后的数据集。 - private static DataSet ListToDataSet(IEnumerable list, Type t, bool generic) - { - DataSet ds = new DataSet("Data"); - if (t == null) - { - if (list != null) - { - foreach (var i in list) - { - if (i == null) - { - continue; - } - t = i.GetType(); - break; - } - } - if (t == null) - { - return ds; - } - } - ds.Tables.Add(t.Name); - //如果集合中元素为DataSet扩展涉及到的基本类型时,进行特殊转换。 - if (t.IsValueType || t == typeof(string)) - { - ds.Tables[0].TableName = "Info"; - ds.Tables[0].Columns.Add(t.Name); - if (list != null) - { - foreach (var i in list) - { - DataRow addRow = ds.Tables[0].NewRow(); - addRow[t.Name] = i; - ds.Tables[0].Rows.Add(addRow); - } - } - return ds; - } - //处理模型的字段和属性。 - var fields = t.GetFields(); - var properties = t.GetProperties(); - foreach (var j in fields) - { - if (!ds.Tables[0].Columns.Contains(j.Name)) - { - if (generic) - { - ds.Tables[0].Columns.Add(j.Name, j.FieldType); - } - else - { - ds.Tables[0].Columns.Add(j.Name); - } - } - } - foreach (var j in properties) - { - if (!ds.Tables[0].Columns.Contains(j.Name)) - { - if (generic) - { - ds.Tables[0].Columns.Add(j.Name, j.PropertyType); - } - else - { - ds.Tables[0].Columns.Add(j.Name); - } - } - } - if (list == null) - { - return ds; - } - //读取list中元素的值。 - foreach (var i in list) - { - if (i == null) - { - continue; - } - DataRow addRow = ds.Tables[0].NewRow(); - foreach (var j in fields) - { - MemberExpression field = Expression.Field(Expression.Constant(i), j.Name); - LambdaExpression lambda = Expression.Lambda(field, new ParameterExpression[] { }); - Delegate func = lambda.Compile(); - object value = func.DynamicInvoke(); - addRow[j.Name] = value; - } - foreach (var j in properties) - { - MemberExpression property = Expression.Property(Expression.Constant(i), j); - LambdaExpression lambda = Expression.Lambda(property, new ParameterExpression[] { }); - Delegate func = lambda.Compile(); - object value = func.DynamicInvoke(); - addRow[j.Name] = value; - } - ds.Tables[0].Rows.Add(addRow); - } - return ds; - } - - /// - /// 将集合转换为数据集。 - /// - /// 转换的元素类型。 - /// 集合。 - /// 是否生成泛型数据集。 - /// 数据集。 - private static DataSet ListToDataSet(IEnumerable list, bool generic) - { - return ListToDataSet(list, typeof(T), generic); - } - - /// - /// 将集合转换为数据集。 - /// - /// 集合。 - /// 是否转换为字符串形式。 - /// 转换后的数据集。 - private static DataSet ListToDataSet(IEnumerable list, bool generic) - { - return ListToDataSet(list, null, generic); - } - - /// - /// 获取DataSet第一表,第一行,第一列的值。 - /// - /// DataSet数据集。 - /// 值。 - public static object GetData(this DataSet ds) - { - if ( - ds == null - || ds.Tables.Count == 0 - ) - { - return string.Empty; - } - else - { - return ds.Tables[0].GetData(); - } - } - - /// - /// 获取DataTable第一行,第一列的值。 - /// - /// DataTable数据集表。 - /// 值。 - public static object GetData(this DataTable dt) - { - if ( - dt.Columns.Count == 0 - || dt.Rows.Count == 0 - ) - { - return string.Empty; - } - else - { - return dt.Rows[0][0]; - } - } - - /// - /// 获取DataSet第一个匹配columnName的值。 - /// - /// 数据集。 - /// 列名。 - /// 值。 - public static object GetData(this DataSet ds, string columnName) - { - if ( - ds == null - || ds.Tables.Count == 0 - ) - { - return string.Empty; - } - foreach (DataTable dt in ds.Tables) - { - object o = dt.GetData(columnName); - if (!string.IsNullOrEmpty(o.ToString())) - { - return o; - } - } - return string.Empty; - } - - /// - /// 获取DataTable第一个匹配columnName的值。 - /// - /// 数据表。 - /// 列名。 - /// 值。 - public static object GetData(this DataTable dt, string columnName) - { - if (string.IsNullOrEmpty(columnName)) - { - return GetData(dt); - } - if ( - dt.Columns.Count == 0 - || dt.Columns.IndexOf(columnName) == -1 - || dt.Rows.Count == 0 - ) - { - return string.Empty; - } - return dt.Rows[0][columnName]; - } - - /// - /// 将object转换为string类型信息。 - /// - /// object。 - /// 默认值。 - /// string。 - public static string ToString(this object o, string t) - { - string info = string.Empty; - if (o == null) - { - info = t; - } - else - { - info = o.ToString(); - } - return info; - } - - /// - /// 将DateTime?转换为string类型信息。 - /// - /// DateTime?。 - /// 标准或自定义日期和时间格式的字符串。 - /// 默认值。 - /// string。 - public static string ToString(this DateTime? o, string format, string t) - { - string info = string.Empty; - if (o == null) - { - info = t; - } - else - { - info = o.Value.ToString(format); - } - return info; - } - - /// - /// 将TimeSpan?转换为string类型信息。 - /// - /// TimeSpan?。 - /// 标准或自定义时间格式的字符串。 - /// 默认值。 - /// string。 - public static string ToString(this TimeSpan? o, string format, string t) - { - string info = string.Empty; - if (o == null) - { - info = t; - } - else - { - info = o.Value.ToString(format); - } - return info; - } - - /// - /// 将object转换为截取后的string类型信息。 - /// - /// object。 - /// 此实例中子字符串的起始字符位置(从零开始)。 - /// 子字符串中的字符数。 - /// 后缀。如果没有截取则不添加。 - /// 截取后的string类型信息。 - public static string ToSubString(this object o, int startIndex, int length, string suffix = null) - { - string inputString = o.ToString(string.Empty); - startIndex = Math.Max(startIndex, 0); - startIndex = Math.Min(startIndex, (inputString.Length - 1)); - length = Math.Max(length, 1); - if (startIndex + length > inputString.Length) - { - length = inputString.Length - startIndex; - } - if (inputString.Length == startIndex + length) - { - return inputString; - } - else - { - return inputString.Substring(startIndex, length) + suffix; - } - } - - /// - /// 将object转换为byte类型信息。 - /// - /// object。 - /// 默认值。 - /// byte。 - public static byte ToByte(this object o, byte t = default(byte)) - { - byte info; - if (!byte.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - public static byte[] ToBytes(this object obj) - { - if (obj == null) - return null; - var bf = new BinaryFormatter(); - using (var ms = new MemoryStream()) - { - bf.Serialize(ms, obj); - return ms.ToArray(); - } - } - - public static object ToObject(this byte[] source) - { - using (var memStream = new MemoryStream()) - { - var bf = new BinaryFormatter(); - memStream.Write(source, 0, source.Length); - memStream.Seek(0, SeekOrigin.Begin); - var obj = bf.Deserialize(memStream); - return obj; - } - } - - /// - /// 将object转换为char类型信息。 - /// - /// object。 - /// 默认值。 - /// char。 - public static char ToChar(this object o, char t = default(char)) - { - char info; - if (!char.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为int类型信息。 - /// - /// object。 - /// 默认值。 - /// int。 - public static int ToInt(this object o, int t = default(int)) - { - int info; - if (!int.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为double类型信息。 - /// - /// object。 - /// 默认值。 - /// double。 - public static double ToDouble(this object o, double t = default(double)) - { - double info; - if (!double.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为decimal类型信息。 - /// - /// object。 - /// 默认值。 - /// decimal。 - public static decimal ToDecimal(this object o, decimal t = default(decimal)) - { - decimal info; - if (!decimal.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为float类型信息。 - /// - /// object。 - /// 默认值。 - /// float。 - public static float ToFloat(this object o, float t = default(float)) - { - float info; - if (!float.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为long类型信息。 - /// - /// object。 - /// 默认值。 - /// long。 - public static long ToLong(this object o, long t = default(long)) - { - long info; - if (!long.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为bool类型信息。 - /// - /// object。 - /// 默认值。 - /// bool。 - public static bool ToBool(this object o, bool t = default(bool)) - { - bool info; - if (!bool.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为sbyte类型信息。 - /// - /// object。 - /// 默认值。 - /// sbyte。 - public static sbyte ToSbyte(this object o, sbyte t = default(sbyte)) - { - sbyte info; - if (!sbyte.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为short类型信息。 - /// - /// object。 - /// 默认值。 - /// short。 - public static short ToShort(this object o, short t = default(short)) - { - short info; - if (!short.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为ushort类型信息。 - /// - /// object。 - /// 默认值。 - /// ushort。 - public static ushort ToUShort(this object o, ushort t = default(ushort)) - { - ushort info; - if (!ushort.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为ulong类型信息。 - /// - /// object。 - /// 默认值。 - /// ulong。 - public static ulong ToULong(this object o, ulong t = default(ulong)) - { - ulong info; - if (!ulong.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为Enum[T]类型信息。 - /// - /// object。 - /// 默认值。 - /// Enum[T]。 - public static T ToEnum(this object o, T t = default(T)) - where T : struct - { - T info; - if (!Enum.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为DateTime类型信息。 - /// - /// object。 - /// 默认值。 - /// DateTime。 - public static DateTime ToDateTime(this object o, DateTime t = default(DateTime)) - { - if (t == default(DateTime)) - { - t = new DateTime(1753, 1, 1); - } - DateTime info; - if (!DateTime.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为TimeSpan类型信息。 - /// - /// object。 - /// 默认值。 - /// TimeSpan。 - public static TimeSpan ToTimeSpan(this object o, TimeSpan t = default(TimeSpan)) - { - if (t == default(TimeSpan)) - { - t = new TimeSpan(0, 0, 0); - } - TimeSpan info; - if (!TimeSpan.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - /// - /// 将object转换为Guid类型信息。 - /// - /// object。 - /// 默认值。 - /// Guid。 - public static Guid ToGuid(this object o, Guid t = default(Guid)) - { - Guid info; - if (!Guid.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - return info; - } - - private static Regex BoolRegex = new Regex("(?(true|false))", RegexOptions.IgnoreCase | RegexOptions.Singleline); - - /// - /// 从object中获取bool类型信息。 - /// - /// object。 - /// bool。 - public static bool? GetBool(this object o) - { - bool info; - if (!bool.TryParse(BoolRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out info)) - { - return null; - } - return info; - } - - private static Regex IntRegex = new Regex("(?-?\\d+)", RegexOptions.IgnoreCase | RegexOptions.Singleline); - - /// - /// 从object中获取int类型信息。 - /// - /// object。 - /// int。 - public static int? GetInt(this object o) - { - int info; - if (!int.TryParse(IntRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out info)) - { - return null; - } - return info; - } - - private static Regex DecimalRegex = new Regex("(?-?\\d+(\\.\\d+)?)", RegexOptions.IgnoreCase | RegexOptions.Singleline); - - /// - /// 从object中获取decimal类型信息。 - /// - /// object。 - /// decimal。 - public static decimal? GetDecimal(this object o) - { - decimal info; - if (!decimal.TryParse(DecimalRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out info)) - { - return null; - } - return info; - } - - /// - /// 从object中获取double类型信息。 - /// - /// object。 - /// double。 - public static double? GetDouble(this object o) - { - double info; - if (!double.TryParse(DecimalRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out info)) - { - return null; - } - return info; - } - - /// - /// 从object中获取正数信息。 - /// - /// object。 - /// decimal。 - public static decimal? GetPositiveNumber(this object o) - { - decimal info; - if (!decimal.TryParse(DecimalRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out info)) - { - return null; - } - return Math.Abs(info); - } - - private static Regex DateTimeRegex = new Regex("(?(((\\d+)[/年-](0?[13578]|1[02])[/月-](3[01]|[12]\\d|0?\\d)[日]?)|((\\d+)[/年-](0?[469]|11)[/月-](30|[12]\\d|0?\\d)[日]?)|((\\d+)[/年-]0?2[/月-](2[0-8]|1\\d|0?\\d)[日]?))(\\s((2[0-3]|[0-1]\\d)):[0-5]\\d:[0-5]\\d)?)", RegexOptions.IgnoreCase | RegexOptions.Singleline); - - /// - /// 从object中获取DateTime?类型信息。 - /// - /// object。 - /// DateTime?。 - public static DateTime? GetDateTime(this object o) - { - DateTime info; - if (!DateTime.TryParse(DateTimeRegex.Match(o.ToString(string.Empty)).Groups["info"].Value.Replace("年", "-").Replace("月", "-").Replace("/", "-").Replace("日", ""), out info)) - { - return null; - } - return info; - } - - private static Regex TimeSpanRegex = new Regex("(?-?(\\d+\\.(([0-1]\\d)|(2[0-3])):[0-5]\\d:[0-5]\\d)|((([0-1]\\d)|(2[0-3])):[0-5]\\d:[0-5]\\d)|(\\d+))", RegexOptions.IgnoreCase | RegexOptions.Singleline); - - /// - /// 从object中获取TimeSpan?类型信息。 - /// - /// object。 - /// TimeSpan?。 - public static TimeSpan? GetTimeSpan(this object o) - { - TimeSpan info; - if (!TimeSpan.TryParse(TimeSpanRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out info)) - { - return null; - } - return info; - } - - private static Regex GuidRegex = new Regex("(?\\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\\}{0,1})", RegexOptions.IgnoreCase | RegexOptions.Singleline); - - /// - /// 从object中获取Guid?类型信息。 - /// - /// object。 - /// Guid?。 - public static Guid? GetGuid(this object o) - { - Guid info; - if (!Guid.TryParse(GuidRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out info)) - { - return null; - } - return info; - } - - /// - /// 将object转换为SqlServer中的DateTime?类型信息。 - /// - /// object。 - /// 默认值。 - /// DateTime?。 - public static DateTime? GetSqlDateTime(this object o, DateTime t = default(DateTime)) - { - DateTime info; - if (!DateTime.TryParse(o.ToString(string.Empty), out info)) - { - info = t; - } - if (info < new DateTime(1753, 1, 1) || info > new DateTime(9999, 12, 31)) - { - return null; - } - return info; - } - - /// - /// 读取XElement节点的文本内容。 - /// - /// XElement节点。 - /// 默认值。 - /// 文本内容。 - public static string Value(this XElement xElement, string t = default(string)) - { - if (xElement == null) - { - return t; - } - else - { - return xElement.Value; - } - } - - /// - /// 获取与指定键相关的值。 - /// - /// 键类型。 - /// 值类型。 - /// 表示键/值对象的泛型集合。 - /// 键。 - /// 默认值。 - /// 值。 - public static TValue GetValue(this IDictionary dictionary, TKey key, TValue t = default(TValue)) - { - TValue value = default(TValue); - if (dictionary == null || key == null) - { - return t; - } - if (!dictionary.TryGetValue(key, out value)) - { - value = t; - } - return value; - } - - /// - /// 获取与指定键相关或者第一个的值。 - /// - /// 键类型。 - /// 值类型。 - /// 表示键/值对象的泛型集合。 - /// 键。 - /// 默认值。 - /// 值。 - public static TValue GetFirstOrDefaultValue(this IDictionary dictionary, TKey key, TValue t = default(TValue)) - { - TValue value = default(TValue); - if (dictionary == null || key == null) - { - return t; - } - if (!dictionary.TryGetValue(key, out value)) - { - if (dictionary.Count() == 0) - { - value = t; - } - else - { - value = dictionary.FirstOrDefault().Value; - } - } - return value; - } - - /// - /// 获取具有指定 System.Xml.Linq.XName 的第一个(按文档顺序)子元素。 - /// - /// XContainer。 - /// 要匹配的 System.Xml.Linq.XName。 - /// 是否返回同名默认值。 - /// 与指定 System.Xml.Linq.XName 匹配的 System.Xml.Linq.XElement,或者为 null。 - public static XElement Element(this XContainer xContainer, XName xName, bool t) - { - XElement info; - if (xContainer == null) - { - info = null; - } - else - { - info = xContainer.Element(xName); - } - if (t && info == null) - { - info = new XElement(xName); - } - return info; - } - - /// - /// 按文档顺序返回此元素或文档的子元素集合。 - /// - /// XContainer。 - /// 是否返回非空默认值。 - /// System.Xml.Linq.XElement 的按文档顺序包含此System.Xml.Linq.XContainer 的子元素,或者非空默认值。 - public static IEnumerable Elements(this XContainer xContainer, bool t) - { - IEnumerable info; - if (xContainer == null) - { - info = null; - } - else - { - info = xContainer.Elements(); - } - if (t && info == null) - { - info = new List(); - } - return info; - } - - /// - /// 按文档顺序返回此元素或文档的经过筛选的子元素集合。集合中只包括具有匹配 System.Xml.Linq.XName 的元素。 - /// - /// XContainer。 - /// 要匹配的 System.Xml.Linq.XName。 - /// 是否返回非空默认值。 - /// System.Xml.Linq.XElement 的按文档顺序包含具有匹配System.Xml.Linq.XName 的 System.Xml.Linq.XContainer 的子级,或者非空默认值。 - public static IEnumerable Elements(this XContainer xContainer, XName xName, bool t) - { - IEnumerable info; - if (xContainer == null) - { - info = null; - } - else - { - info = xContainer.Elements(xName); - } - if (t && info == null) - { - info = new List(); - } - return info; - } - - /// - /// 删除html标签。 - /// - /// 输入的字符串。 - /// 没有html标签的字符串。 - public static string RemoveHTMLTags(this string html) - { - return Regex.Replace(Regex.Replace(Regex.Replace((html ?? string.Empty).Replace(" ", " ").Replace("\r\n", " ").Replace("\n", " ").Replace("\r", " ").Replace("\t", " "), "<\\/?[^>]+>", "\r\n"), "(\r\n)+", "\r\n"), "(\\s)+", " ").Trim(); - } - - /// - /// 字符串转换为文件名。 - /// - /// 字符串。 - /// 文件名。 - public static string ToFileName(this string s) - { - return Regex.Replace(s.ToString(string.Empty), @"[\\/:*?<>|]", "_").Replace("\t", " ").Replace("\r\n", " ").Replace("\"", " "); - } - - /// - /// 获取星期一的日期。 - /// - /// 日期。 - /// 星期一的日期。 - public static DateTime? GetMonday(this DateTime dateTime) - { - return dateTime.AddDays(-1 * (int)dateTime.AddDays(-1).DayOfWeek).ToString("yyyy-MM-dd").GetDateTime(); - } - - /// - /// 获取默认非空字符串。 - /// - /// 首选默认非空字符串。 - /// 依次非空字符串可选项。 - /// 默认非空字符串。若无可选项则返回string.Empty。 - public static string DefaultStringIfEmpty(this string s, params string[] args) - { - if (string.IsNullOrEmpty(s)) - { - foreach (string i in args) - { - if (!string.IsNullOrEmpty(i) && !string.IsNullOrEmpty(i.Trim())) - { - return i; - } - } - } - return (s ?? string.Empty); - } - - /// - /// 对 URL 字符串进行编码。 - /// - /// 要编码的文本。 - /// 匹配要编码的文本。 - /// 指定编码方案的 System.Text.Encoding 对象。 - /// 一个已编码的字符串。 - public static string ToUrlEncodeString(this string s, Regex regex = default(Regex), Encoding encoding = null) - { - if (encoding == null) - { - encoding = Encoding.UTF8; - } - if (regex == null) - { - return HttpUtility.UrlEncode(s, encoding); - } - List l = new List(); - foreach (char i in s) - { - string t = i.ToString(); - l.Add(regex.IsMatch(t) ? HttpUtility.UrlEncode(t, encoding) : t); - } - return string.Join(string.Empty, l); - } - - /// - /// 对 URL 字符串进行编码。 - /// - /// 要编码的文本。 - /// 匹配要编码的文本。 - /// 指定编码方案的 System.Text.Encoding 对象。 - /// 一个已编码的字符串。 - public static string ToUrlEncodeString(this string s, string regex, Encoding encoding = null) - { - return ToUrlEncodeString(s, new Regex(regex), encoding); - } - - /// - /// 将日期转换为UNIX时间戳字符串 - /// - /// - /// - public static string ToUnixTimeStamp(this DateTime date) - { - DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1)); - string timeStamp = date.Subtract(startTime).Ticks.ToString(); - return timeStamp.Substring(0, timeStamp.Length - 7); - } - - private static Regex MobileRegex = new Regex("^1[3|4|5|7|8][0-9]\\d{4,8}$"); - private static Regex EmailRegex = new Regex("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$"); - - /// - /// 判断当前字符串是否是移动电话号码 - /// - /// - /// - public static bool IsMobile(this string mobile) - { - return MobileRegex.IsMatch(mobile); - } - - /// - /// 判断当前字符串是否为邮箱 - /// - /// - /// - public static bool IsEmail(this string email) - { - return EmailRegex.IsMatch(email); - } - } - - /// - /// 结果。 - /// - /// 结果返回值类型。 - public class Result - { - /// - /// 标记。 - /// - public Flag Flag { get; set; } - - /// - /// 返回值。 - /// - public T Return { get; set; } - - /// - /// 消息。 - /// - public string Message { get; set; } - - /// - /// 异常。 - /// - public Exception Exception { get; set; } - - /// - /// 时间。 - /// - public DateTime DateTime { get; set; } - - /// - /// 整型数据。 - /// - public int Int { get; set; } - - /// - /// 浮点数据。 - /// - public decimal Decimal { get; set; } - - /// - /// 布尔数据。 - /// - public bool Bool { get; set; } - - /// - /// 对象。 - /// - public object Object { get; set; } - } - - /// - /// 标记。 - /// - public enum Flag - { - /// - /// 默认。 - /// - Default, - - /// - /// 真。 - /// - True, - - /// - /// 假。 - /// - False - } -} \ No newline at end of file diff --git a/samples/Common/DDD.Core/DDD.Core.Extensions/StringExtensions.cs b/samples/Common/DDD.Core/DDD.Core.Extensions/StringExtensions.cs deleted file mode 100644 index b1c191880..000000000 --- a/samples/Common/DDD.Core/DDD.Core.Extensions/StringExtensions.cs +++ /dev/null @@ -1,247 +0,0 @@ -using System; -using System.Text.RegularExpressions; - -namespace DDD.Core.Extensions -{ - public static class StringExtensions - { - public static object ParseTo(this string str, string type) - { - switch (type) - { - case "System.Boolean": - return ToBoolean(str); - case "System.SByte": - return ToSByte(str); - case "System.Byte": - return ToByte(str); - case "System.UInt16": - return ToUInt16(str); - case "System.Int16": - return ToInt16(str); - case "System.uInt32": - return ToUInt32(str); - case "System.Int32": - return str.ToInt32(); - case "System.UInt64": - return ToUInt64(str); - case "System.Int64": - return ToInt64(str); - case "System.Single": - return ToSingle(str); - case "System.Double": - return ToDouble(str); - case "System.Decimal": - return ToDecimal(str); - case "System.DateTime": - return ToDateTime(str); - case "System.Guid": - return ToGuid(str); - } - throw new NotSupportedException(string.Format("The string of \"{0}\" can not be parsed to {1}", str, type)); - } - - public static sbyte? ToSByte(this string value) - { - sbyte value2; - if (sbyte.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static byte? ToByte(this string value) - { - byte value2; - if (byte.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static ushort? ToUInt16(this string value) - { - ushort value2; - if (ushort.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static short? ToInt16(this string value) - { - short value2; - if (short.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static uint? ToUInt32(this string value) - { - uint value2; - if (uint.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static ulong? ToUInt64(this string value) - { - ulong value2; - if (ulong.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static long? ToInt64(this string value) - { - long value2; - if (long.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static float? ToSingle(this string value) - { - float value2; - if (float.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static double? ToDouble(this string value) - { - double value2; - if (double.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static decimal? ToDecimal(this string value) - { - decimal value2; - if (decimal.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static bool? ToBoolean(this string value) - { - bool value2; - if (bool.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static T? ToEnum(this string str) where T : struct - { - T t; - if (Enum.TryParse(str, true, out t) && Enum.IsDefined(typeof(T), t)) - { - return t; - } - return null; - } - - public static Guid? ToGuid(this string str) - { - Guid value; - if (Guid.TryParse(str, out value)) - { - return value; - } - return null; - } - - public static DateTime? ToDateTime(this string value) - { - DateTime value2; - if (DateTime.TryParse(value, out value2)) - { - return value2; - } - return null; - } - - public static int? ToInt32(this string input) - { - if (string.IsNullOrEmpty(input)) - { - return null; - } - int value; - if (int.TryParse(input, out value)) - { - return value; - } - return null; - } - - /// - /// 替换空格字符 - /// - /// - /// 替换为该字符 - /// 替换后的字符串 - public static string ReplaceWhitespace(this string input, string replacement = "") - { - return string.IsNullOrEmpty(input) ? null : Regex.Replace(input, "\\s", replacement, RegexOptions.Compiled); - } - - /// - /// 返回一个值,该值指示指定的 String 对象是否出现在此字符串中。 - /// - /// - /// 要搜寻的字符串。 - /// 指定搜索规则的枚举值之一。 - /// 如果 value 参数出现在此字符串中则为 true;否则为 false。 - public static bool Contains(this string source, string value, - StringComparison comparisonType = StringComparison.OrdinalIgnoreCase) - { - return source.IndexOf(value, comparisonType) >= 0; - } - - /// - /// 清除 Html 代码,并返回指定长度的文本。(连续空行或空格会被替换为一个) - /// - /// - /// 返回的文本长度(为0返回所有文本) - /// - public static string StripHtml(this string text, int maxLength = 0) - { - if (string.IsNullOrEmpty(text)) return string.Empty; - text = text.Trim(); - - text = Regex.Replace(text, "[\\r\\n]{2,}", "<&rn>"); //替换回车和换行为<&rn>,防止下一行代码替换空格的时候被替换掉 - text = Regex.Replace(text, "[\\s]{2,}", " "); //替换 2 个以上的空格为 1 个 - text = Regex.Replace(text, "(<&rn>)+", "\n"); //还原 <&rn> 为 \n - text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " "); //  - - text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //
- text = Regex.Replace(text, "<(.|\n)+?>", " ", RegexOptions.IgnoreCase); //any other tags - - if (maxLength > 0 && text.Length > maxLength) - text = text.Substring(0, maxLength); - - return text; - } - } -} diff --git a/samples/Common/DDD.Core/DDD.Core.csproj b/samples/Common/DDD.Core/DDD.Core.csproj deleted file mode 100644 index 3cfd4024c..000000000 --- a/samples/Common/DDD.Core/DDD.Core.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - netstandard2.0 - - - - - - - - - - - - - C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.extensions.configuration.abstractions\2.0.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll - - - C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.extensions.fileproviders.physical\2.0.0\lib\netstandard2.0\Microsoft.Extensions.FileProviders.Physical.dll - - - - diff --git a/samples/Common/DDD.Core/IAggregate.cs b/samples/Common/DDD.Core/IAggregate.cs deleted file mode 100644 index 0edd419b1..000000000 --- a/samples/Common/DDD.Core/IAggregate.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; - -namespace DDD.Core -{ - - /// Represents an aggregate root. - /// - public abstract class IAggregate: IDBModel - { - [Key] - public virtual Guid KeyId { get; set; } - /// - /// 归属公司 - /// - public virtual Guid CorporationKeyId { get; set; } - public DateTime CreateTime { get; set; } - public Guid CreateUserKeyId { get; set; } - public DateTime UpdateTime { get; set; } - public Guid UpdateUserKeyId { get; set; } - public bool IsDelete { get; set; } - public int Version { get; set; } - - public string Name { get; set; } - - public string No { get; set; } - } -} diff --git a/samples/Common/DDD.Core/IQueryOnlyRepository.cs b/samples/Common/DDD.Core/IQueryOnlyRepository.cs deleted file mode 100644 index 0d17da9b7..000000000 --- a/samples/Common/DDD.Core/IQueryOnlyRepository.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; - -namespace DDD.Core -{ - /// - /// 只读的查询资源库接口 - /// - public interface IQueryOnlyRepository where T : class,IDBModel - { - - int Count(Expression> @where = null); - - bool Exist(Expression> @where = null); - bool Exist(Expression> @where = null, params Expression>[] includes); - int ExecuteSqlWithNonQuery(string sql, params object[] parameters); - T GetSingle(TKey key); - T GetSingle(TKey key, params Expression>[] includes); - T GetSingle(Expression> @where = null); - T GetSingle(Expression> @where = null, params Expression>[] includes); - IQueryable Get(Expression> @where = null); - IQueryable Get(Expression> @where = null, params Expression>[] includes); - IEnumerable GetByPagination(Expression> @where, int pageSize, int pageIndex, - Expression>[] include,bool asc = true, params Func[] @orderby); - - IList SqlQuery(string sql, params object[] parameters) where TView : class, new(); - - - } -} diff --git a/samples/Common/DDD.Core/IRepository.cs b/samples/Common/DDD.Core/IRepository.cs deleted file mode 100644 index 8d0d5ac01..000000000 --- a/samples/Common/DDD.Core/IRepository.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; - -namespace DDD.Core -{ - public interface IDBModel - { - TKey KeyId { get; set; } - - TKey CorporationKeyId { get; set; } - DateTime CreateTime { get; set; } - TKey CreateUserKeyId { get; set; } - DateTime UpdateTime { get; set; } - TKey UpdateUserKeyId { get; set; } - bool IsDelete { get; set; } - int Version { get; set; } - - - } - public interface IRepository: IUnitOfWork where T : IAggregate - { - void Add(T aggregate); //where T : IAggregate; - T FindBy(TKey key); //where T : IAggregate; - void Update(T aggregate); //where T : IAggregate; - void Delete(TKey key); - - - } -} diff --git a/samples/Common/DDD.Core/IUnitOfWork.cs b/samples/Common/DDD.Core/IUnitOfWork.cs deleted file mode 100644 index d687b586b..000000000 --- a/samples/Common/DDD.Core/IUnitOfWork.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace DDD.Core -{ - public interface IUnitOfWork: IDisposable - { - #region for transaction - /// - /// 提交一个聚合内的所有变更 - /// - /// - /// If the entity have fixed properties and any optimistic concurrency problem exists, - /// then an exception is thrown - /// - int Commit(); - - - #endregion - - // int SaveChanges(); - //int SaveChangesAsync(); - - } -} diff --git a/samples/Common/DTO.Core/BasePagedRequestDto.cs b/samples/Common/DTO.Core/BasePagedRequestDto.cs deleted file mode 100644 index 03a9bbd71..000000000 --- a/samples/Common/DTO.Core/BasePagedRequestDto.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace DTO.Core -{ - public class BasePagedRequestDto: BaseRequestDto - { - /// - /// 页码号,从1开始,可空(返回全部记录) - /// - public int PageIndex { get; set; } - - /// - /// 每页显示的记录数,可空(返回全部记录) - /// - public int PageSize { get; set; } - } -} diff --git a/samples/Common/DTO.Core/BaseRequestDto.cs b/samples/Common/DTO.Core/BaseRequestDto.cs deleted file mode 100644 index 9220bf810..000000000 --- a/samples/Common/DTO.Core/BaseRequestDto.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace DTO.Core -{ - /// - /// 接口参数 dto抽象基类 - /// - public abstract class BaseRequestDto : BaseDto - { - /// - /// 服务访问身份信息 - /// - public TokenDto Identify { get; set; } - - - } - /// - /// 实体的增、删、改 - /// - public class EntityCUDReq : BaseRequestDto - { - public Guid? KeyId { get; set; } - } - /// - /// 实体上的命令 - /// - public class EntityCMDReq : BaseRequestDto - { - - } - - /// - /// 简单的请求 - /// 参数不确定 - /// - public class CommonCMDReq : BaseRequestDto - { - public string CommonCMD { get; set; } - } - - - /// - /// 树形列表的搜索 - /// - public class BaseTreeSearchReq : BaseRequestDto - { - /// - /// 搜索条件 - /// - public string SearchKey { get; set; } - - } -} diff --git a/samples/Common/DTO.Core/BaseResponseDto.cs b/samples/Common/DTO.Core/BaseResponseDto.cs deleted file mode 100644 index 4cada02d1..000000000 --- a/samples/Common/DTO.Core/BaseResponseDto.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace DTO.Core -{ - public class BaseResponseDto:BaseDto - { - /// - /// 请求结果,请求成功/失败 - /// - public bool OperateFlag { get; set; } - - /// - /// 服务端错误信息 - /// - public string FlagErrorMsg { get; set; } - - - } - - public class BaseTreeResponseDto: BaseResponseDto - { - public List Tree { get; set; } - } - - public class BaseTreeDto - { - public string Id { get; set; } - public string PId { get; set; } - public string Name { get; set; } - } - - public class BaseListResponseDto : BaseResponseDto - { - public dynamic Result { get; set; } - } - -} diff --git a/samples/Common/DTO.Core/BaseSearchCriteriaDto.cs b/samples/Common/DTO.Core/BaseSearchCriteriaDto.cs deleted file mode 100644 index a9e983098..000000000 --- a/samples/Common/DTO.Core/BaseSearchCriteriaDto.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace DTO.Core -{ - public abstract class BaseSearchCriteriaDto : BaseDto - { - - } -} diff --git a/samples/Common/DTO.Core/BaseSortCriteriaDto.cs b/samples/Common/DTO.Core/BaseSortCriteriaDto.cs deleted file mode 100644 index bb0b01142..000000000 --- a/samples/Common/DTO.Core/BaseSortCriteriaDto.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace DTO.Core -{ - /// - /// 搜索条件排序基类Dto。 - /// - public abstract class BaseSortCriteriaDto : BaseDto - { - /// - /// 创建时间 - /// - - public static readonly string CREATE_TIME = "CreateTime"; - - /// - /// 修改时间 - /// - - public static readonly string UPDATE_TIME = "UpdateTime"; - - /// - /// 正向/反向排序 - /// - - public bool Ascending { set; get; } - - /// - /// 排序名称 - /// - - public string SortPropertyName { set; get; } - } -} diff --git a/samples/Common/DTO.Core/DTO.Core.csproj b/samples/Common/DTO.Core/DTO.Core.csproj deleted file mode 100644 index 5766db614..000000000 --- a/samples/Common/DTO.Core/DTO.Core.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - - netcoreapp2.0 - - - diff --git a/samples/Common/DTO.Core/IdentifyDto.cs b/samples/Common/DTO.Core/IdentifyDto.cs deleted file mode 100644 index 61a276b6e..000000000 --- a/samples/Common/DTO.Core/IdentifyDto.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace DTO.Core -{ - public abstract class BaseDto - { - - } - public class TokenDto: BaseDto - { - /// - /// 员工编号 - /// - public string Token { get; set; } - public Guid CorporationKeyId { get; set; } - - } - public class IdentifyDto : BaseDto - { - /// - /// 当前用户keyId - /// - - public Guid UserKeyId { get; set; } - - /// - /// 当前用户名 - /// - - public string UserName { get; set; } - - /// - /// 当前用户部门keyId - /// - - public Guid DepartmentKeyId { get; set; } - - /// - /// 部门编号 - /// - - public string DepartmentNo { get; set; } - - /// - /// 当前用户部门名称 - /// - - public string DepartmentName { get; set; } - - /// - /// 当前用户所属公司keyId - /// - - public Guid CorporationKeyId { get; set; } - - - /// - /// 用户登录方式 - /// - - public string LoginType { get; set; } - - /// - /// 用户账号 - /// - - public string UserNo { get; set; } - - /// - /// 当前用户手机号 - /// - - public string UserPhone { get; set; } - - /// - /// 角色code - /// - - public string RoleCode { get; set; } - - /// - /// 角色名称 - /// - - public string RoleName { get; set; } - } - } diff --git a/samples/Common/DTO.Core/KeyIdReq.cs b/samples/Common/DTO.Core/KeyIdReq.cs deleted file mode 100644 index aebc1b302..000000000 --- a/samples/Common/DTO.Core/KeyIdReq.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace DTO.Core -{ - public class KeyIdReq:BaseRequestDto - { - public Guid KeyId { get; set; } - } -} diff --git a/samples/Common/DTO.Core/OperateResultDto.cs b/samples/Common/DTO.Core/OperateResultDto.cs deleted file mode 100644 index a8a88f3f4..000000000 --- a/samples/Common/DTO.Core/OperateResultDto.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace DTO.Core -{ - public class OperateResultRsp : BaseResponseDto - { - /// - /// 操作结果 - /// - public string OperateResult { get; set; } - - } -} diff --git a/samples/Common/Repository.Dapper.Core/BaseImpQueryOnlyRepository.cs b/samples/Common/Repository.Dapper.Core/BaseImpQueryOnlyRepository.cs deleted file mode 100644 index 614dbd9a3..000000000 --- a/samples/Common/Repository.Dapper.Core/BaseImpQueryOnlyRepository.cs +++ /dev/null @@ -1,72 +0,0 @@ -using DDD.Core; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; - -namespace Repository.Dapper.Core -{ - public class BaseImpQueryOnlyRepository : IQueryOnlyRepository where T : class, IDBModel - { - public int Count(Expression> where = null) - { - throw new NotImplementedException(); - } - - public int ExecuteSqlWithNonQuery(string sql, params object[] parameters) - { - throw new NotImplementedException(); - } - - public bool Exist(Expression> where = null) - { - throw new NotImplementedException(); - } - - public bool Exist(Expression> where = null, params Expression>[] includes) - { - throw new NotImplementedException(); - } - - public IQueryable Get(Expression> where = null) - { - throw new NotImplementedException(); - } - - public IQueryable Get(Expression> where = null, params Expression>[] includes) - { - throw new NotImplementedException(); - } - - public IEnumerable GetByPagination(Expression> where, int pageSize, int pageIndex, Expression>[] include, bool asc = true, params Func[] orderby) - { - throw new NotImplementedException(); - } - - public T GetSingle(Guid key) - { - throw new NotImplementedException(); - } - - public T GetSingle(Guid key, params Expression>[] includes) - { - throw new NotImplementedException(); - } - - public T GetSingle(Expression> where = null) - { - throw new NotImplementedException(); - } - - public T GetSingle(Expression> where = null, params Expression>[] includes) - { - throw new NotImplementedException(); - } - - public IList SqlQuery(string sql, params object[] parameters) where TView : class, new() - { - throw new NotImplementedException(); - } - } -} diff --git a/samples/Common/Repository.Dapper.Core/BaseImpRepository.cs b/samples/Common/Repository.Dapper.Core/BaseImpRepository.cs deleted file mode 100644 index a22e182ad..000000000 --- a/samples/Common/Repository.Dapper.Core/BaseImpRepository.cs +++ /dev/null @@ -1,40 +0,0 @@ -using DDD.Core; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Repository.Dapper.Core -{ - public class BaseImpRepository : IRepository where T : IAggregate - { - public void Add(T aggregate) - { - throw new NotImplementedException(); - } - - public int Commit() - { - throw new NotImplementedException(); - } - - public void Delete(Guid key) - { - throw new NotImplementedException(); - } - - public void Dispose() - { - throw new NotImplementedException(); - } - - public T FindBy(Guid key) - { - throw new NotImplementedException(); - } - - public void Update(T aggregate) - { - throw new NotImplementedException(); - } - } -} diff --git a/samples/Common/Repository.Dapper.Core/DapperExtensions.cs b/samples/Common/Repository.Dapper.Core/DapperExtensions.cs deleted file mode 100644 index 61b4a2146..000000000 --- a/samples/Common/Repository.Dapper.Core/DapperExtensions.cs +++ /dev/null @@ -1,567 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Reflection; -using System.Text; -using Repository.Dapper.Core.Sql; -using Repository.Dapper.Core.Mapper; -using System.Text.RegularExpressions; -using System.Threading.Tasks; - -namespace Repository.Dapper.Core -{ - public static class DapperExtensions - { - #region other - private readonly static object _lock = new object(); - - private static Func _instanceFactory; - private static IDapperImplementor _instance; - private static IDapperExtensionsConfiguration _configuration; - - /// - /// Gets or sets the default class mapper to use when generating class maps. If not specified, AutoClassMapper is used. - /// Repository.Dapper.Core.Configure(Type, IList, ISqlDialect) can be used instead to set all values at once - /// - public static Type DefaultMapper - { - get - { - return _configuration.DefaultMapper; - } - - set - { - Configure(value, _configuration.MappingAssemblies, _configuration.Dialect); - } - } - - /// - /// Gets or sets the type of sql to be generated. - /// DapperExtensions.Configure(Type, IList, ISqlDialect) can be used instead to set all values at once - /// - public static ISqlDialect SqlDialect - { - get - { - return _configuration.Dialect; - } - - set - { - Configure(_configuration.DefaultMapper, _configuration.MappingAssemblies, value); - } - } - - /// - /// Get or sets the Dapper Extensions Implementation Factory. - /// - public static Func InstanceFactory - { - get - { - if (_instanceFactory == null) - { - _instanceFactory = config => new DapperImplementor(new SqlGeneratorImpl(config)); - } - - return _instanceFactory; - } - set - { - _instanceFactory = value; - Configure(_configuration.DefaultMapper, _configuration.MappingAssemblies, _configuration.Dialect); - } - } - - /// - /// Gets the Dapper Extensions Implementation - /// - private static IDapperImplementor Instance - { - get - { - if (_instance == null) - { - lock (_lock) - { - if (_instance == null) - { - _instance = InstanceFactory(_configuration); - } - } - } - - return _instance; - } - } - - //static DapperExtensions() - //{ - // Configure(typeof(AutoClassMapper<>), new List(), new SqlServerDialect()); - //} - - /// - /// Add other assemblies that Dapper Extensions will search if a mapping is not found in the same assembly of the POCO. - /// - /// - public static void SetMappingAssemblies(IList assemblies) - { - Configure(_configuration.DefaultMapper, assemblies, _configuration.Dialect); - } - - /// - /// Configure DapperExtensions extension methods. - /// - /// - /// - /// - public static void Configure(IDapperExtensionsConfiguration configuration) - { - _instance = null; - _configuration = configuration; - } - - /// - /// Configure DapperExtensions extension methods. - /// - /// - /// - /// - public static void Configure(Type defaultMapper, IList mappingAssemblies, ISqlDialect sqlDialect) - { - Configure(new DapperExtensionsConfiguration(defaultMapper, mappingAssemblies, sqlDialect)); - } - - public static void Configure(ISqlDialect sqlDialect, Type defaultMapper = null, IList mappingAssemblies = null) - { - defaultMapper = defaultMapper ?? typeof(AutoClassMapper<>); - mappingAssemblies = mappingAssemblies ?? new List(); - Configure(new DapperExtensionsConfiguration(defaultMapper, mappingAssemblies, sqlDialect)); - } - - #endregion - - #region Get - /// - /// Executes a query for the specified id, returning the data typed as per T - /// - public static T Get(this IDbConnection connection, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Get(connection, null, id, transaction, commandTimeout); - - public static T Get(this IDbConnection connection, string tableName, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Get(connection, tableName, null, id, transaction, commandTimeout); - - public static T Get(this IDbConnection connection, string tableName, string schemaName, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => (T)Instance.Get(connection, id, transaction, commandTimeout, tableName, schemaName, null, null); - - public static async Task GetAsync(this IDbConnection connection, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetAsync(connection, null, id, transaction, commandTimeout); - - public static async Task GetAsync(this IDbConnection connection, string tableName, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetAsync(connection, tableName, null, id, transaction, commandTimeout); - - public static async Task GetAsync(this IDbConnection connection, string tableName, string schemaName, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.GetAsync(connection, id, transaction, commandTimeout, tableName, schemaName, null, null); - - public static T Get(this IDbConnection connection, IList join, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Get(connection, join, null, id, transaction, commandTimeout); - - public static T Get(this IDbConnection connection, IList join, IList alias, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => (T)Instance.Get(connection, id, transaction, commandTimeout, null, null, join, alias); - - public static async Task GetAsync(this IDbConnection connection, IList join, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetAsync(connection, join, null, id, transaction, commandTimeout); - - public static async Task GetAsync(this IDbConnection connection, IList join, IList alias, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.GetAsync(connection, id, transaction, commandTimeout, null, null, join, alias); - - #endregion - - #region Insert - /// - /// Executes an insert query for the specified entity. - /// - public static void Insert(this IDbConnection connection, IEnumerable entities, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Insert(connection, null, entities, transaction, commandTimeout); - - public static void Insert(this IDbConnection connection, string tableName, IEnumerable entities, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Insert(connection, tableName, null, entities, transaction, commandTimeout); - - public static void Insert(this IDbConnection connection, string tableName, string schemaName, IEnumerable entities, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Instance.Insert(connection, entities, transaction, commandTimeout, tableName, schemaName); - - - /// - /// Executes an insert query for the specified entity, returning the primary key. - /// If the entity has a single key, just the value is returned. - /// If the entity has a composite key, an IDictionary<string, object> is returned with the key values. - /// The key value for the entity will also be updated if the KeyType is a Guid or Identity. - /// - public static dynamic Insert(this IDbConnection connection, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Insert(connection, null, entity, transaction, commandTimeout); - - public static dynamic Insert(this IDbConnection connection, string tableName, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Insert(connection, tableName, null, entity, transaction, commandTimeout); - - public static dynamic Insert(this IDbConnection connection, string tableName, string schemaName, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Instance.Insert(connection, entity, transaction, commandTimeout, tableName, schemaName); - - #endregion - - #region Update - /// - /// Executes an update query for the specified entity. - /// - public static bool Update(this IDbConnection connection, T entity, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => Update(connection, null, entity, transaction, commandTimeout, ignoreAllKeyProperties); - - public static bool Update(this IDbConnection connection, string tableName, T entity, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => Update(connection, tableName, null, entity, transaction, commandTimeout, ignoreAllKeyProperties); - - public static bool Update(this IDbConnection connection, string tableName, string schemaName, T entity, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => Instance.Update(connection, entity, null, transaction, commandTimeout, tableName, schemaName, ignoreAllKeyProperties); - - - public static bool Update(this IDbConnection connection, T entity, object predicate, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => Update(connection, null, entity, predicate, transaction, commandTimeout, ignoreAllKeyProperties); - - public static bool Update(this IDbConnection connection, string tableName, T entity, object predicate, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => Update(connection, tableName, null, entity, predicate, transaction, commandTimeout, ignoreAllKeyProperties); - - public static bool Update(this IDbConnection connection, string tableName, string schemaName, T entity, object predicate, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => Instance.Update(connection, entity, predicate, transaction, commandTimeout, tableName, schemaName, ignoreAllKeyProperties); - - - public static async Task UpdateAsync(this IDbConnection connection, T entity, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => await UpdateAsync(connection, null, entity, transaction, commandTimeout, ignoreAllKeyProperties); - - public static async Task UpdateAsync(this IDbConnection connection, string tableName, T entity, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => await UpdateAsync(connection, tableName, null, entity, transaction, commandTimeout, ignoreAllKeyProperties); - - public static async Task UpdateAsync(this IDbConnection connection, string tableName, string schemaName, T entity, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => await Instance.UpdateAsync(connection, entity, null, transaction, commandTimeout, tableName, schemaName, ignoreAllKeyProperties); - - public static async Task UpdateAsync(this IDbConnection connection, T entity, object predicate, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => await UpdateAsync(connection, null, entity, predicate, transaction, commandTimeout, ignoreAllKeyProperties); - - public static async Task UpdateAsync(this IDbConnection connection, string tableName, T entity, object predicate, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => await UpdateAsync(connection, tableName, null, entity, predicate, transaction, commandTimeout, ignoreAllKeyProperties); - - public static async Task UpdateAsync(this IDbConnection connection, string tableName, string schemaName, T entity, object predicate, IDbTransaction transaction = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => await Instance.UpdateAsync(connection, entity, predicate, transaction, commandTimeout, tableName, schemaName, ignoreAllKeyProperties); - - - - public static bool UpdateSet(this IDbConnection connection, object entity, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => UpdateSet(connection, null, entity, predicate, transaction, commandTimeout); - - public static bool UpdateSet(this IDbConnection connection, string tableName, object entity, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => UpdateSet(connection, tableName, null, entity, predicate, transaction, commandTimeout); - - public static bool UpdateSet(this IDbConnection connection, string tableName, string schemaName, object entity, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Instance.UpdateSet(connection, entity, predicate, transaction, commandTimeout, tableName, schemaName); - - - public static async Task UpdateSetAsync(this IDbConnection connection, object entity, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await UpdateSetAsync(connection, null, entity, predicate, transaction, commandTimeout); - - public static async Task UpdateSetAsync(this IDbConnection connection, string tableName, object entity, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await UpdateSetAsync(connection, tableName, null, entity, predicate, transaction, commandTimeout); - - public static async Task UpdateSetAsync(this IDbConnection connection, string tableName, string schemaName, object entity, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.UpdateSetAsync(connection, entity, predicate, transaction, commandTimeout, tableName, schemaName); - - - #endregion - - #region Delete - /// - /// Executes a delete query for the specified entity. - /// - public static bool Delete(this IDbConnection connection, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Delete(connection, null, entity, transaction, commandTimeout); - - public static bool Delete(this IDbConnection connection, string tableName, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Delete(connection, tableName, null, entity, transaction, commandTimeout); - - public static bool Delete(this IDbConnection connection, string tableName, string schemaName, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Instance.Delete(connection, entity, transaction, commandTimeout, tableName, schemaName); - - - public static async Task DeleteAsync(this IDbConnection connection, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await DeleteAsync(connection, null, entity, transaction, commandTimeout); - - public static async Task DeleteAsync(this IDbConnection connection, string tableName, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await DeleteAsync(connection, tableName, null, entity, transaction, commandTimeout); - - public static async Task DeleteAsync(this IDbConnection connection, string tableName, string schemaName, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.DeleteAsync(connection, entity, transaction, commandTimeout, tableName, schemaName); - - - /// - /// Executes a delete query using the specified predicate. - /// - public static bool Delete(this IDbConnection connection, object predicate, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Delete(connection, null, predicate, transaction, commandTimeout); - - public static bool Delete(this IDbConnection connection, string tableName, object predicate, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Delete(connection, tableName, null, predicate, transaction, commandTimeout); - - public static bool Delete(this IDbConnection connection, string tableName, string schemaName, object predicate, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Instance.Delete(connection, predicate, transaction, commandTimeout, tableName, schemaName); - - public static async Task DeleteAsync(this IDbConnection connection, object predicate, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await DeleteAsync(connection, null, predicate, transaction, commandTimeout); - - public static async Task DeleteAsync(this IDbConnection connection, string tableName, object predicate, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await DeleteAsync(connection, tableName, null, predicate, transaction, commandTimeout); - - public static async Task DeleteAsync(this IDbConnection connection, string tableName, string schemaName, object predicate, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.DeleteAsync(connection, predicate, transaction, commandTimeout, tableName, schemaName); - - - #endregion - - #region GetList - /// - /// Executes a select query using the specified predicate, returning an IEnumerable data typed as per T. - /// - public static IEnumerable GetList(this IDbConnection connection, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => GetList(connection, (string)null, null, predicate, sort, transaction, commandTimeout, buffered); - - public static IEnumerable GetList(this IDbConnection connection, string tableName, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => GetList(connection, tableName, null, predicate, sort, transaction, commandTimeout, buffered); - - public static IEnumerable GetList(this IDbConnection connection, string tableName, string schemaName, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => Instance.GetList(connection, predicate, sort, transaction, commandTimeout, buffered, tableName, schemaName, null, null); - - - public static async Task> GetListAsync(this IDbConnection connection, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetListAsync(connection, (string)null, null, predicate, sort, transaction, commandTimeout); - - public static async Task> GetListAsync(this IDbConnection connection, string tableName, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetListAsync(connection, tableName, null, predicate, sort, transaction, commandTimeout); - - public static async Task> GetListAsync(this IDbConnection connection, string tableName, string schemaName, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.GetListAsync(connection, predicate, sort, transaction, commandTimeout, tableName, schemaName, null, null); - - - public static IEnumerable GetList(this IDbConnection connection, IList join, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => GetList(connection, join, null, predicate, sort, transaction, commandTimeout, buffered); - - public static IEnumerable GetList(this IDbConnection connection, IList join, IList alias, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => Instance.GetList(connection, predicate, sort, transaction, commandTimeout, buffered, null, null, join, alias); - - public static async Task> GetListAsync(this IDbConnection connection, IList join, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetListAsync(connection, join, null, predicate, sort, transaction, commandTimeout); - - public static async Task> GetListAsync(this IDbConnection connection, IList join, IList alias, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.GetListAsync(connection, predicate, sort, transaction, commandTimeout, null, null, join, alias); - - - #endregion - - #region GetPage - /// - /// Executes a select query using the specified predicate, returning an IEnumerable data typed as per T. - /// Data returned is dependent upon the specified page and resultsPerPage. - /// - public static IEnumerable GetPage(this IDbConnection connection, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => GetPage(connection, (string)null, page, resultsPerPage, predicate, sort, transaction, commandTimeout, buffered); - - public static IEnumerable GetPage(this IDbConnection connection, string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => GetPage(connection, tableName, null, page, resultsPerPage, predicate, sort, transaction, commandTimeout, buffered); - - public static IEnumerable GetPage(this IDbConnection connection, string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => Instance.GetPage(connection, predicate, sort, page, resultsPerPage, transaction, commandTimeout, buffered, tableName, schemaName, null, null); - - - public static async Task> GetPageAsync(this IDbConnection connection, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetPageAsync(connection, (string)null, page, resultsPerPage, predicate, sort, transaction, commandTimeout); - - public static async Task> GetPageAsync(this IDbConnection connection, string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetPageAsync(connection, tableName, null, page, resultsPerPage, predicate, sort, transaction, commandTimeout); - - public static async Task> GetPageAsync(this IDbConnection connection, string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.GetPageAsync(connection, predicate, sort, page, resultsPerPage, transaction, commandTimeout, tableName, schemaName, null, null); - - public static IEnumerable GetPage(this IDbConnection connection, IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => GetPage(connection, join, null, page, resultsPerPage, predicate, sort, transaction, commandTimeout, buffered); - - public static IEnumerable GetPage(this IDbConnection connection, IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => Instance.GetPage(connection, predicate, sort, page, resultsPerPage, transaction, commandTimeout, buffered, null, null, join, alias); - - public static async Task> GetPageAsync(this IDbConnection connection, IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetPageAsync(connection, join, null, page, resultsPerPage, predicate, sort, transaction, commandTimeout); - - public static async Task> GetPageAsync(this IDbConnection connection, IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.GetPageAsync(connection, predicate, sort, page, resultsPerPage, transaction, commandTimeout, null, null, join, alias); - #endregion - - #region GetPages - - /// - /// Executes a select query using the specified predicate, returning an IEnumerable data typed as per T. - /// Data returned is dependent upon the specified page and resultsPerPage. - /// - public static Page GetPages(this IDbConnection connection, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => GetPages(connection, (string)null, page, resultsPerPage, predicate, sort, transaction, commandTimeout); - - public static Page GetPages(this IDbConnection connection, string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => GetPages(connection, tableName, null, page, resultsPerPage, predicate, sort, transaction, commandTimeout); - - public static Page GetPages(this IDbConnection connection, string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Instance.GetPages(connection, predicate, sort, page, resultsPerPage, transaction, commandTimeout, tableName, schemaName, null, null); - - public static async Task> GetPagesAsync(this IDbConnection connection, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetPagesAsync(connection, (string)null, page, resultsPerPage, predicate, sort, transaction, commandTimeout); - - public static async Task> GetPagesAsync(this IDbConnection connection, string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetPagesAsync(connection, tableName, null, page, resultsPerPage, predicate, sort, transaction, commandTimeout); - - public static async Task> GetPagesAsync(this IDbConnection connection, string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.GetPagesAsync(connection, predicate, sort, page, resultsPerPage, transaction, commandTimeout, tableName, schemaName, null, null); - - public static Page GetPages(this IDbConnection connection, IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => GetPages(connection, join, null, page, resultsPerPage, predicate, sort, transaction, commandTimeout); - - public static Page GetPages(this IDbConnection connection, IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Instance.GetPages(connection, predicate, sort, page, resultsPerPage, transaction, commandTimeout, null, null, join, alias); - - public static async Task> GetPagesAsync(this IDbConnection connection, IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetPagesAsync(connection, join, null, page, resultsPerPage, predicate, sort, transaction, commandTimeout); - - public static async Task> GetPagesAsync(this IDbConnection connection, IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.GetPagesAsync(connection, predicate, sort, page, resultsPerPage, transaction, commandTimeout, null, null, join, alias); - - - #endregion - - #region GetSet - /// - /// Executes a select query using the specified predicate, returning an IEnumerable data typed as per T. - /// Data returned is dependent upon the specified firstResult and maxResults. - /// - public static IEnumerable GetSet(this IDbConnection connection, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => GetSet(connection, (string)null, predicate, sort, firstResult, maxResults, transaction, commandTimeout, buffered); - - public static IEnumerable GetSet(this IDbConnection connection, string tableName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => GetSet(connection, tableName, null, predicate, sort, firstResult, maxResults, transaction, commandTimeout, buffered); - - public static IEnumerable GetSet(this IDbConnection connection, string tableName, string schemaName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => Instance.GetSet(connection, predicate, sort, firstResult, maxResults, transaction, commandTimeout, buffered, tableName, schemaName, null, null); - - public static async Task> GetSetAsync(this IDbConnection connection, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetSetAsync(connection, (string)null, predicate, sort, firstResult, maxResults, transaction, commandTimeout); - - public static async Task> GetSetAsync(this IDbConnection connection, string tableName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetSetAsync(connection, tableName, null, predicate, sort, firstResult, maxResults, transaction, commandTimeout); - - public static async Task> GetSetAsync(this IDbConnection connection, string tableName, string schemaName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.GetSetAsync(connection, predicate, sort, firstResult, maxResults, transaction, commandTimeout, tableName, schemaName, null, null); - - public static IEnumerable GetSet(this IDbConnection connection, IList join, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => GetSet(connection, join, null, predicate, sort, firstResult, maxResults, transaction, commandTimeout, buffered); - - public static IEnumerable GetSet(this IDbConnection connection, IList join, IList alias, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class - => Instance.GetSet(connection, predicate, sort, firstResult, maxResults, transaction, commandTimeout, buffered, null, null, join, alias); - - public static async Task> GetSetAsync(this IDbConnection connection, IList join, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await GetSetAsync(connection, join, null, predicate, sort, firstResult, maxResults, transaction, commandTimeout); - - public static async Task> GetSetAsync(this IDbConnection connection, IList join, IList alias, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.GetSetAsync(connection, predicate, sort, firstResult, maxResults, transaction, commandTimeout, null, null, join, alias); - - #endregion - - #region Count - /// - /// Executes a query using the specified predicate, returning an integer that represents the number of rows that match the query. - /// - public static long Count(this IDbConnection connection, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Count(connection, (string)null, predicate, transaction, commandTimeout); - - public static long Count(this IDbConnection connection, string tableName, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Count(connection, tableName, null, predicate, transaction, commandTimeout); - - public static long Count(this IDbConnection connection, string tableName, string schemaName, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Instance.Count(connection, predicate, transaction, commandTimeout, tableName, schemaName, null); - - - public static async Task CountAsync(this IDbConnection connection, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await CountAsync(connection, (string)null, predicate, transaction, commandTimeout); - - public static async Task CountAsync(this IDbConnection connection, string tableName, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await CountAsync(connection, tableName, null, predicate, transaction, commandTimeout); - - public static async Task CountAsync(this IDbConnection connection, string tableName, string schemaName, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.CountAsync(connection, predicate, transaction, commandTimeout, tableName, schemaName, null); - - public static long Count(this IDbConnection connection, IList join, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => Instance.Count(connection, predicate, transaction, commandTimeout, null, null, join); - - public static async Task CountAsync(this IDbConnection connection, IList join, object predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class - => await Instance.CountAsync(connection, predicate, transaction, commandTimeout, null, null, join); - #endregion - - #region GetMultiple - - /// - /// Executes a select query for multiple objects, returning IMultipleResultReader for each predicate. - /// - public static IMultipleResultReader GetMultiple(this IDbConnection connection, GetMultiplePredicate predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) - => GetMultiple(connection, null, null, predicate, transaction, commandTimeout); - - public static IMultipleResultReader GetMultiple(this IDbConnection connection, string tableName, GetMultiplePredicate predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) - => GetMultiple(connection, tableName, null, predicate, transaction, commandTimeout); - - public static IMultipleResultReader GetMultiple(this IDbConnection connection, string tableName, string schemaName, GetMultiplePredicate predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) - { - return Instance.GetMultiple(connection, predicate, transaction, commandTimeout, tableName, schemaName); - } - - public static async Task GetMultipleAsync(this IDbConnection connection, GetMultiplePredicate predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) - => await GetMultipleAsync(connection, null, null, predicate, transaction, commandTimeout); - - public static async Task GetMultipleAsync(this IDbConnection connection, string tableName, GetMultiplePredicate predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) - => await GetMultipleAsync(connection, tableName, null, predicate, transaction, commandTimeout); - - public static async Task GetMultipleAsync(this IDbConnection connection, string tableName, string schemaName, GetMultiplePredicate predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) - { - return await Instance.GetMultipleAsync(connection, predicate, transaction, commandTimeout, tableName, schemaName); - } - #endregion - - #region - /// - /// Gets the appropriate mapper for the specified type T. - /// If the mapper for the type is not yet created, a new mapper is generated from the mapper type specifed by DefaultMapper. - /// - public static IClassMapper GetMap() where T : class - { - return Instance.SqlGenerator.Configuration.GetMap(); - } - - /// - /// Clears the ClassMappers for each type. - /// - public static void ClearCache() - { - Instance.SqlGenerator.Configuration.ClearCache(); - } - - /// - /// Generates a COMB Guid which solves the fragmented index issue. - /// See: http://davybrion.com/blog/2009/05/using-the-guidcomb-identifier-strategy - /// - public static Guid GetNextGuid() - { - return Instance.SqlGenerator.Configuration.GetNextGuid(); - } - - - #endregion - } -} diff --git a/samples/Common/Repository.Dapper.Core/DapperExtensionsConfiguration.cs b/samples/Common/Repository.Dapper.Core/DapperExtensionsConfiguration.cs deleted file mode 100644 index 8ae8b3df5..000000000 --- a/samples/Common/Repository.Dapper.Core/DapperExtensionsConfiguration.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using Repository.Dapper.Core.Mapper; -using Repository.Dapper.Core.Sql; -using Microsoft.Extensions.Options; - -namespace Repository.Dapper.Core -{ - public interface IDapperExtensionsConfiguration - { - Type DefaultMapper { get; } - IList MappingAssemblies { get; } - ISqlDialect Dialect { get; } - IClassMapper GetMap(Type entityType); - IClassMapper GetMap() where T : class; - void ClearCache(); - Guid GetNextGuid(); - } - - public class DapperExtensionsConfiguration : IDapperExtensionsConfiguration - { - public DateTime NowTime { get; set; } - - private readonly ConcurrentDictionary _classMaps = new ConcurrentDictionary(); - - public DapperExtensionsConfiguration() - : this(typeof(AutoClassMapper<>), new List(), new SqlServerDialect()) - { - } - public DapperExtensionsConfiguration(IOptions options) - : this(typeof(AutoClassMapper<>), new List(), options.Value.sqlDialect) - { - NowTime = DateTime.Now; - } - public DapperExtensionsConfiguration(ISqlDialect sqlDialect) - : this(typeof(AutoClassMapper<>), new List(), sqlDialect) - { - NowTime = DateTime.Now; - } - - - public DapperExtensionsConfiguration(Type defaultMapper, IList mappingAssemblies, ISqlDialect sqlDialect) - { - DefaultMapper = defaultMapper; - MappingAssemblies = mappingAssemblies ?? new List(); - Dialect = sqlDialect; - } - - public Type DefaultMapper { get; private set; } - public IList MappingAssemblies { get; private set; } - public ISqlDialect Dialect { get; private set; } - - public IClassMapper GetMap(Type entityType) - { - IClassMapper map; - if (!_classMaps.TryGetValue(entityType, out map)) - { - Type mapType = GetMapType(entityType); - if (mapType == null) - { - mapType = DefaultMapper.MakeGenericType(entityType); - } - - map = Activator.CreateInstance(mapType) as IClassMapper; - _classMaps[entityType] = map; - } - - return map; - } - - public IClassMapper GetMap() where T : class - { - return GetMap(typeof (T)); - } - - public void ClearCache() - { - _classMaps.Clear(); - } - - public Guid GetNextGuid() - { - byte[] b = Guid.NewGuid().ToByteArray(); - DateTime dateTime = new DateTime(1900, 1, 1); - DateTime now = DateTime.Now; - TimeSpan timeSpan = new TimeSpan(now.Ticks - dateTime.Ticks); - TimeSpan timeOfDay = now.TimeOfDay; - byte[] bytes1 = BitConverter.GetBytes(timeSpan.Days); - byte[] bytes2 = BitConverter.GetBytes((long)(timeOfDay.TotalMilliseconds / 3.333333)); - Array.Reverse(bytes1); - Array.Reverse(bytes2); - Array.Copy(bytes1, bytes1.Length - 2, b, b.Length - 6, 2); - Array.Copy(bytes2, bytes2.Length - 4, b, b.Length - 4, 4); - return new Guid(b); - } - - protected virtual Type GetMapType(Type entityType) - { - Func getType = a => - { - Type[] types = a.GetTypes(); - return (from type in types - let interfaceType = type.GetInterface(typeof(IClassMapper<>).FullName) - where - interfaceType != null && - interfaceType.GetGenericArguments()[0] == entityType - select type).SingleOrDefault(); - }; - - Type result = getType(entityType.Assembly); - if (result != null) - { - return result; - } - - foreach (var mappingAssembly in MappingAssemblies) - { - result = getType(mappingAssembly); - if (result != null) - { - return result; - } - } - - return getType(entityType.Assembly); - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/DapperImplementor.cs b/samples/Common/Repository.Dapper.Core/DapperImplementor.cs deleted file mode 100644 index 8b4162036..000000000 --- a/samples/Common/Repository.Dapper.Core/DapperImplementor.cs +++ /dev/null @@ -1,825 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Dynamic; -using System.Linq; -using System.Reflection; -using System.Text; -using Dapper; -using Repository.Dapper.Core.Mapper; -using Repository.Dapper.Core.Sql; -using System.Threading.Tasks; - -namespace Repository.Dapper.Core -{ - public interface IDapperImplementor - { - ISqlGenerator SqlGenerator { get; } - - #region Get - T Get(IDbConnection connection, dynamic id, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class; - Task GetAsync(IDbConnection connection, dynamic id, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class; - - #endregion - - #region Insert - void Insert(IDbConnection connection, IEnumerable entities, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class; - dynamic Insert(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class; - - #endregion - - #region Update - bool Update(IDbConnection connection, T entity, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, bool ignoreAllKeyProperties) where T : class; - Task UpdateAsync(IDbConnection connection, T entity, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, bool ignoreAllKeyProperties) where T : class; - bool UpdateSet(IDbConnection connection, object entity, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class; - Task UpdateSetAsync(IDbConnection connection, object entity, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class; - - #endregion - - #region Delete - bool Delete(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class; - Task DeleteAsync(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class; - bool Delete(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class; - Task DeleteAsync(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class; - #endregion - - #region GetList - IEnumerable GetList(IDbConnection connection, object predicate, IList sort, IDbTransaction transaction, int? commandTimeout, bool buffered, string tableName, string schemaName, IList join, IList alias) where T : class; - - Task> GetListAsync(IDbConnection connection, object predicate, IList sort, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class; - #endregion - - #region GetPage - IEnumerable GetPage(IDbConnection connection, object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, bool buffered, string tableName, string schemaName, IList join, IList alias) where T : class; - Task> GetPageAsync(IDbConnection connection, object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class; - #endregion - - #region GetPages - Page GetPages(IDbConnection connection, object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class; - Task> GetPagesAsync(IDbConnection connection, object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class; - #endregion - - #region GetSet - IEnumerable GetSet(IDbConnection connection, object predicate, IList sort, int firstResult, int maxResults, IDbTransaction transaction, int? commandTimeout, bool buffered, string tableName, string schemaName, IList join, IList alias) where T : class; - Task> GetSetAsync(IDbConnection connection, object predicate, IList sort, int firstResult, int maxResults, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class; - #endregion - - #region Count - long Count(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join) where T : class; - Task CountAsync(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join) where T : class; - #endregion - - #region GetMultiple - IMultipleResultReader GetMultiple(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName); - - Task GetMultipleAsync(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName); - #endregion - - } - - public class DapperImplementor : IDapperImplementor - { - public DapperImplementor(ISqlGenerator sqlGenerator) - { - SqlGenerator = sqlGenerator; - } - - public ISqlGenerator SqlGenerator { get; private set; } - - #region Get - - public T Get(IDbConnection connection, dynamic id, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class - { - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - IPredicate predicate = GetIdPredicate(classMap, id); - T result = GetList(connection, predicate, null, transaction, commandTimeout, true, tableName,schemaName, join, alias).SingleOrDefault(); - return result; - } - public async Task GetAsync(IDbConnection connection, dynamic id, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class - { - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - IPredicate predicate = GetIdPredicate(classMap, id); - return (await GetListAsync(connection, predicate, null, transaction, commandTimeout, tableName, schemaName, join, alias)).SingleOrDefault(); - } - - #endregion - - #region Insert - public void Insert(IDbConnection connection, IEnumerable entities, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class - { - IEnumerable properties = null; - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - var notKeyProperties = classMap.Properties.Where(p => p.KeyType != KeyType.NotAKey); - var triggerIdentityColumn = classMap.Properties.SingleOrDefault(p => p.KeyType == KeyType.TriggerIdentity); - - var parameters = new List(); - if (triggerIdentityColumn != null) - { - properties = typeof(T).GetProperties(BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public) - .Where(p => p.Name != triggerIdentityColumn.PropertyInfo.Name); - } - - foreach (var e in entities) - { - foreach (var column in notKeyProperties) - { - if (column.KeyType == KeyType.Guid && (Guid)column.PropertyInfo.GetValue(e, null) == Guid.Empty) - { - Guid comb = SqlGenerator.Configuration.GetNextGuid(); - column.PropertyInfo.SetValue(e, comb, null); - } - } - - if (triggerIdentityColumn != null) - { - var dynamicParameters = new DynamicParameters(); - foreach (var prop in properties) - { - dynamicParameters.Add(prop.Name, prop.GetValue(e, null)); - } - - // defaultValue need for identify type of parameter - var defaultValue = typeof(T).GetProperty(triggerIdentityColumn.PropertyInfo.Name).GetValue(e, null); - dynamicParameters.Add("IdOutParam", direction: ParameterDirection.Output, value: defaultValue); - - parameters.Add(dynamicParameters); - } - } - - string sql = SqlGenerator.Insert(classMap,schemaName, tableName); - - if (triggerIdentityColumn == null) - { - connection.Execute(sql, entities, transaction, commandTimeout, CommandType.Text); - } - else - { - connection.Execute(sql, parameters, transaction, commandTimeout, CommandType.Text); - } - } - - public dynamic Insert(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName = null) where T : class - { - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - List nonIdentityKeyProperties = classMap.Properties.Where(p => p.KeyType == KeyType.Guid || p.KeyType == KeyType.Assigned).ToList(); - var identityColumn = classMap.Properties.SingleOrDefault(p => p.KeyType == KeyType.Identity); - var triggerIdentityColumn = classMap.Properties.SingleOrDefault(p => p.KeyType == KeyType.TriggerIdentity); - foreach (var column in nonIdentityKeyProperties) - { - if (column.KeyType == KeyType.Guid && (Guid)column.PropertyInfo.GetValue(entity, null) == Guid.Empty) - { - Guid comb = SqlGenerator.Configuration.GetNextGuid(); - column.PropertyInfo.SetValue(entity, comb, null); - } - } - - IDictionary keyValues = new ExpandoObject(); - string sql = SqlGenerator.Insert(classMap,schemaName, tableName); - if (identityColumn != null) - { - IEnumerable result; - if (SqlGenerator.SupportsMultipleStatements()) - { - sql += SqlGenerator.Configuration.Dialect.BatchSeperator + SqlGenerator.IdentitySql(classMap,schemaName, tableName); - result = connection.Query(sql, entity, transaction, false, commandTimeout, CommandType.Text); - } - else - { - connection.Execute(sql, entity, transaction, commandTimeout, CommandType.Text); - sql = SqlGenerator.IdentitySql(classMap,schemaName, tableName); - result = connection.Query(sql, entity, transaction, false, commandTimeout, CommandType.Text); - } - - // We are only interested in the first identity, but we are iterating over all resulting items (if any). - // This makes sure that ADO.NET drivers (like MySql) won't actively terminate the query. - bool hasResult = false; - int identityInt = 0; - foreach (var identityValue in result) - { - if (hasResult) - { - continue; - } - identityInt = Convert.ToInt32(identityValue); - hasResult = true; - } - if (!hasResult) - { - throw new InvalidOperationException("The source sequence is empty."); - } - - keyValues.Add(identityColumn.Name, identityInt); - identityColumn.PropertyInfo.SetValue(entity, identityInt, null); - } - else if (triggerIdentityColumn != null) - { - var dynamicParameters = new DynamicParameters(); - foreach (var prop in entity.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public) - .Where(p => p.Name != triggerIdentityColumn.PropertyInfo.Name)) - { - dynamicParameters.Add(prop.Name, prop.GetValue(entity, null)); - } - - // defaultValue need for identify type of parameter - var defaultValue = entity.GetType().GetProperty(triggerIdentityColumn.PropertyInfo.Name).GetValue(entity, null); - dynamicParameters.Add("IdOutParam", direction: ParameterDirection.Output, value: defaultValue); - - connection.Execute(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text); - - var value = dynamicParameters.Get(SqlGenerator.Configuration.Dialect.ParameterPrefix + "IdOutParam"); - keyValues.Add(triggerIdentityColumn.Name, value); - triggerIdentityColumn.PropertyInfo.SetValue(entity, value, null); - } - else - { - connection.Execute(sql, entity, transaction, commandTimeout, CommandType.Text); - } - - foreach (var column in nonIdentityKeyProperties) - { - keyValues.Add(column.Name, column.PropertyInfo.GetValue(entity, null)); - } - - if (keyValues.Count == 1) - { - return keyValues.First().Value; - } - - return keyValues; - } - - - #endregion - - #region Update - - public bool Update(IDbConnection connection, T entity, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName = null, bool ignoreAllKeyProperties = false) where T : class - { - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - IPredicate wherePredicate = predicate == null ? GetKeyPredicate(classMap, entity) : GetPredicate(classMap, predicate); - Dictionary parameters = new Dictionary(); - string sql = SqlGenerator.Update(classMap, wherePredicate, parameters, schemaName, tableName); - DynamicParameters dynamicParameters = new DynamicParameters(); - - var columns = ignoreAllKeyProperties - ? classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly) && p.KeyType == KeyType.NotAKey) - : classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity || p.KeyType == KeyType.Assigned)); - - foreach (var property in ReflectionHelper.GetObjectValues(entity).Where(property => columns.Any(c => c.Name == property.Key))) - { - dynamicParameters.Add(property.Key, property.Value); - } - - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - - return connection.Execute(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0; - } - public async Task UpdateAsync(IDbConnection connection, T entity, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, bool ignoreAllKeyProperties) where T : class - { - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - IPredicate wherePredicate = predicate == null ? GetKeyPredicate(classMap, entity) : GetPredicate(classMap, predicate); - Dictionary parameters = new Dictionary(); - string sql = SqlGenerator.Update(classMap, wherePredicate, parameters, schemaName, tableName); - DynamicParameters dynamicParameters = new DynamicParameters(); - - var columns = ignoreAllKeyProperties - ? classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly) && p.KeyType == KeyType.NotAKey) - : classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity || p.KeyType == KeyType.Assigned)); - - foreach (var property in ReflectionHelper.GetObjectValues(entity).Where(property => columns.Any(c => c.Name == property.Key))) - { - dynamicParameters.Add(property.Key, property.Value); - } - - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - - return await connection.ExecuteAsync(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0; - } - - public bool UpdateSet(IDbConnection connection, object entity, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName = null) where T : class - { - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - IPredicate wherePredicate = predicate == null ? GetSetKeyPredicate(classMap, entity) : GetPredicate(classMap, predicate); - Dictionary parameters = new Dictionary(); - string sql = SqlGenerator.UpdateSet(classMap, entity, wherePredicate, parameters, schemaName, tableName); - DynamicParameters dynamicParameters = new DynamicParameters(); - - var columns = classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity || p.KeyType == KeyType.Assigned)); - - foreach (var property in ReflectionHelper.GetObjectValues(entity).Where(property => columns.Any(c => c.Name.Equals(property.Key)))) - { - dynamicParameters.Add(property.Key, property.Value); - } - - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - - return connection.Execute(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0; - } - public async Task UpdateSetAsync(IDbConnection connection, object entity, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class - { - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - IPredicate wherePredicate = predicate == null ? GetSetKeyPredicate(classMap, entity) : GetPredicate(classMap, predicate); - Dictionary parameters = new Dictionary(); - string sql = SqlGenerator.UpdateSet(classMap, entity, wherePredicate, parameters, schemaName, tableName); - DynamicParameters dynamicParameters = new DynamicParameters(); - - var columns = classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity || p.KeyType == KeyType.Assigned)); - - foreach (var property in ReflectionHelper.GetObjectValues(entity).Where(property => columns.Any(c => c.Name.Equals(property.Key)))) - { - dynamicParameters.Add(property.Key, property.Value); - } - - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - - return await connection.ExecuteAsync(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0; - } - #endregion - - #region Delete - public bool Delete(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName = null) where T : class - { - var build = BuildDelete(entity, null, tableName, schemaName); - return connection.Execute(build.sql, build.dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0; - } - public bool Delete(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class - { - var build = BuildDelete(null, predicate, tableName, schemaName); - return connection.Execute(build.sql, build.dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0; - } - - public async Task DeleteAsync(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class - { - var build = BuildDelete(entity, null, tableName, schemaName); - return await connection.ExecuteAsync(build.sql, build.dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0; - } - - - public async Task DeleteAsync(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) where T : class - { - var build = BuildDelete(null, predicate, tableName, schemaName); - return await connection.ExecuteAsync(build.sql, build.dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0; - } - - - protected (string sql, DynamicParameters dynamicParameters) BuildDelete(T entity, object predicate, string tableName, string schemaName) where T : class - { - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - IPredicate wherePredicate = entity == null && predicate != null ? GetPredicate(classMap, predicate) : GetKeyPredicate(classMap, entity); - - Dictionary parameters = new Dictionary(); - string sql = SqlGenerator.Delete(classMap, wherePredicate, parameters, schemaName, tableName); - DynamicParameters dynamicParameters = new DynamicParameters(); - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - return (sql, dynamicParameters); - } - - - #endregion - - #region GetList - public IEnumerable GetList(IDbConnection connection, object predicate, IList sort, IDbTransaction transaction, int? commandTimeout, bool buffered, string tableName, string schemaName, IList join, IList alias) where T : class - { - var build = BuildList(predicate, sort, tableName, schemaName, join, alias); - return connection.Query(build.sql, build.dynamicParameters, transaction, buffered, commandTimeout, CommandType.Text); - } - - public async Task> GetListAsync(IDbConnection connection, object predicate, IList sort, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class - { - var build = BuildList(predicate, sort, tableName, schemaName, join, alias); - return await connection.QueryAsync(build.sql, build.dynamicParameters, transaction, commandTimeout, CommandType.Text); - } - - protected (string sql, DynamicParameters dynamicParameters) BuildList(object predicate, IList sort, string tableName, string schemaName, IList join, IList alias) where T : class - { - VerifyJoinPredicate(join, predicate); - - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - Dictionary parameters = new Dictionary(); - IPredicate wherePredicate = GetPredicate(classMap, predicate); - string sql = SqlGenerator.Select(classMap, wherePredicate, sort, parameters, schemaName, tableName, join, alias); - - - DynamicParameters dynamicParameters = new DynamicParameters(); - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - return (sql, dynamicParameters); - } - - - #endregion - - #region GetPage - public IEnumerable GetPage(IDbConnection connection, object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, bool buffered, string tableName, string schemaName, IList join, IList alias) where T : class - { - var build = BuildPage(predicate, sort, page, resultsPerPage, tableName, schemaName, join, alias); - return connection.Query(build.sql, build.dynamicParameters, transaction, buffered, commandTimeout, CommandType.Text); - } - - public async Task> GetPageAsync(IDbConnection connection, object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class - { - var build = BuildPage(predicate, sort, page, resultsPerPage, tableName, schemaName, join, alias); - return await connection.QueryAsync(build.sql, build.dynamicParameters, transaction, commandTimeout, CommandType.Text); - } - - protected (string sql, DynamicParameters dynamicParameters) BuildPage(object predicate, IList sort, int page, int resultsPerPage, string tableName, string schemaName, IList join, IList alias) where T : class - { - VerifyJoinPredicate(join, predicate); - - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - IPredicate wherePredicate = GetPredicate(classMap, predicate); - Dictionary parameters = new Dictionary(); - - string sql = SqlGenerator.SelectPaged(classMap, wherePredicate, sort, page, resultsPerPage, parameters, schemaName, tableName, join, alias); - DynamicParameters dynamicParameters = new DynamicParameters(); - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - return (sql, dynamicParameters); - } - - - #endregion - - #region GetPages - - public Page GetPages(IDbConnection connection, object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class - { - var PageResult = new Page() { CurrentPage = page, ItemsPerPage = resultsPerPage }; - PageResult.TotalItems = Count(connection, predicate, transaction, commandTimeout, tableName, schemaName, join); - if (PageResult.TotalItems == 0) - { - PageResult.Items = new List(); - return PageResult; - } - var build = BuildPage(predicate, sort, page, resultsPerPage, tableName, schemaName, join, alias); - PageResult.Items = connection.Query(build.sql, build.dynamicParameters, transaction, false, commandTimeout, CommandType.Text); - return PageResult; - } - public async Task> GetPagesAsync(IDbConnection connection, object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class - { - var PageResult = new Page() { CurrentPage = page, ItemsPerPage = resultsPerPage }; - PageResult.TotalItems = await CountAsync(connection, predicate, transaction, commandTimeout, tableName, schemaName, join); - if (PageResult.TotalItems == 0) - { - PageResult.Items = new List(); - return PageResult; - } - var build = BuildPage(predicate, sort, page, resultsPerPage, tableName, schemaName, join, alias); - PageResult.Items = await connection.QueryAsync(build.sql, build.dynamicParameters, transaction, commandTimeout, CommandType.Text); - return PageResult; - } - #endregion - - #region GetSet - public IEnumerable GetSet(IDbConnection connection, object predicate, IList sort, int firstResult, int maxResults, IDbTransaction transaction, int? commandTimeout, bool buffered, string tableName, string schemaName, IList join, IList alias) where T : class - { - var build = BuildPage(predicate, sort, firstResult, maxResults, tableName, schemaName, join, alias); - return connection.Query(build.sql, build.dynamicParameters, transaction, buffered, commandTimeout, CommandType.Text); - } - - public async Task> GetSetAsync(IDbConnection connection, object predicate, IList sort, int firstResult, int maxResults, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join, IList alias) where T : class - { - var build = BuildPage(predicate, sort, firstResult, maxResults, tableName, schemaName, join, alias); - return await connection.QueryAsync(build.sql, build.dynamicParameters, transaction, commandTimeout, CommandType.Text); - } - - protected (string sql, DynamicParameters dynamicParameters) BuildGetSet(object predicate, IList sort, int firstResult, int maxResults, string tableName, string schemaName, IList join, IList alias) where T : class - { - VerifyJoinPredicate(join, predicate); - - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - IPredicate wherePredicate = GetPredicate(classMap, predicate); - Dictionary parameters = new Dictionary(); - string sql = SqlGenerator.SelectSet(classMap, wherePredicate, sort, firstResult, maxResults, parameters, schemaName, tableName, join, alias); - DynamicParameters dynamicParameters = new DynamicParameters(); - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - return (sql, dynamicParameters); - } - - #endregion - - #region Count - public long Count(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join) where T : class - { - var build = BuildCount(predicate, tableName, schemaName, join); - return (long)(connection.Query(build.sql, build.dynamicParameters, transaction, false, commandTimeout, CommandType.Text).Single().Total); - } - - public async Task CountAsync(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName, IList join) where T : class - { - var build = BuildCount(predicate, tableName, schemaName, join); - return (int)(await connection.QueryAsync(build.sql, build.dynamicParameters, transaction, commandTimeout, CommandType.Text)).Single().Total; - } - - protected (string sql, DynamicParameters dynamicParameters) BuildCount(object predicate, string tableName, string schemaName, IList join) where T : class - { - VerifyJoinPredicate(join, predicate); - - IClassMapper classMap = SqlGenerator.Configuration.GetMap(); - IPredicate wherePredicate = GetPredicate(classMap, predicate); - Dictionary parameters = new Dictionary(); - string sql = SqlGenerator.Count(classMap, wherePredicate, parameters, schemaName, tableName, join); - DynamicParameters dynamicParameters = new DynamicParameters(); - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - return (sql, dynamicParameters); - } - - #endregion - - #region GetMultiple - - public IMultipleResultReader GetMultiple(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) - { - if (SqlGenerator.SupportsMultipleStatements()) - { - return GetMultipleByBatch(connection, predicate, transaction, commandTimeout, tableName, schemaName); - } - - return GetMultipleBySequence(connection, predicate, transaction, commandTimeout, tableName, schemaName); - } - public async Task GetMultipleAsync(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) - { - if (SqlGenerator.SupportsMultipleStatements()) - { - return await GetMultipleByBatchAsync(connection, predicate, transaction, commandTimeout, tableName, schemaName); - } - - return await GetMultipleBySequenceAsync(connection, predicate, transaction, commandTimeout, tableName, schemaName); - } - - #endregion - - #region Helpers - - protected IPredicate GetPredicate(IClassMapper classMap, object predicate) - { - IPredicate wherePredicate = predicate as IPredicate; - if (wherePredicate == null && predicate != null) - { - wherePredicate = GetEntityPredicate(classMap, predicate); - } - - return wherePredicate; - } - - protected IPredicate GetIdPredicate(IClassMapper classMap, object id) - { - bool isSimpleType = ReflectionHelper.IsSimpleType(id.GetType()); - var keys = classMap.Properties.Where(p => p.KeyType != KeyType.NotAKey); - IDictionary paramValues = null; - IList predicates = new List(); - if (!isSimpleType) - { - paramValues = ReflectionHelper.GetObjectValues(id); - } - - foreach (var key in keys) - { - object value = id; - if (!isSimpleType) - { - value = paramValues[key.Name]; - } - - Type predicateType = typeof(FieldPredicate<>).MakeGenericType(classMap.EntityType); - - IFieldPredicate fieldPredicate = Activator.CreateInstance(predicateType) as IFieldPredicate; - fieldPredicate.Not = false; - fieldPredicate.Operator = Operator.Eq; - fieldPredicate.PropertyName = key.Name; - fieldPredicate.Value = value; - predicates.Add(fieldPredicate); - } - - return predicates.Count == 1 - ? predicates[0] - : new PredicateGroup - { - Operator = GroupOperator.And, - Predicates = predicates - }; - } - - protected IPredicate GetKeyPredicate(IClassMapper classMap, T entity) where T : class - { - var whereFields = classMap.Properties.Where(p => p.KeyType != KeyType.NotAKey); - if (!whereFields.Any()) - { - throw new ArgumentException("At least one Key column must be defined."); - } - - IList predicates = (from field in whereFields - select new FieldPredicate - { - Not = false, - Operator = Operator.Eq, - PropertyName = field.Name, - Value = field.PropertyInfo.GetValue(entity, null) - }).Cast().ToList(); - - return predicates.Count == 1 - ? predicates[0] - : new PredicateGroup - { - Operator = GroupOperator.And, - Predicates = predicates - }; - } - - protected IPredicate GetSetKeyPredicate(IClassMapper classMap, object entity) where T : class - { - var whereFields = classMap.Properties.Where(p => p.KeyType != KeyType.NotAKey); - if (!whereFields.Any()) - { - throw new ArgumentException("At least one Key column must be defined."); - } - var vKeyValue = ReflectionHelper.GetObjectValues(entity); - IList predicates = (from field in whereFields - select new FieldPredicate - { - Not = false, - Operator = Operator.Eq, - PropertyName = field.Name, - Value = vKeyValue.Where(w => w.Key.Equals(field.Name, StringComparison.OrdinalIgnoreCase)).First().Value - }).Cast().ToList(); - - return predicates.Count == 1 - ? predicates[0] - : new PredicateGroup - { - Operator = GroupOperator.And, - Predicates = predicates - }; - } - - protected IPredicate GetEntityPredicate(IClassMapper classMap, object entity) - { - Type predicateType = typeof(FieldPredicate<>).MakeGenericType(classMap.EntityType); - IList predicates = new List(); - foreach (var kvp in ReflectionHelper.GetObjectValues(entity)) - { - IFieldPredicate fieldPredicate = Activator.CreateInstance(predicateType) as IFieldPredicate; - fieldPredicate.Not = false; - fieldPredicate.Operator = Operator.Eq; - fieldPredicate.PropertyName = kvp.Key; - fieldPredicate.Value = kvp.Value; - predicates.Add(fieldPredicate); - } - - return predicates.Count == 1 - ? predicates[0] - : new PredicateGroup - { - Operator = GroupOperator.And, - Predicates = predicates - }; - } - - protected GridReaderResultReader GetMultipleByBatch(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) - { - Dictionary parameters = new Dictionary(); - StringBuilder sql = new StringBuilder(); - foreach (var item in predicate.Items) - { - IClassMapper classMap = SqlGenerator.Configuration.GetMap(item.Type); - IPredicate itemPredicate = item.Value as IPredicate; - if (itemPredicate == null && item.Value != null) - { - itemPredicate = GetPredicate(classMap, item.Value); - } - - sql.AppendLine(SqlGenerator.Select(classMap, itemPredicate, item.Sort, parameters,schemaName, tableName) + SqlGenerator.Configuration.Dialect.BatchSeperator); - } - - DynamicParameters dynamicParameters = new DynamicParameters(); - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - - SqlMapper.GridReader grid = connection.QueryMultiple(sql.ToString(), dynamicParameters, transaction, commandTimeout, CommandType.Text); - return new GridReaderResultReader(grid); - } - - protected SequenceReaderResultReader GetMultipleBySequence(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) - { - IList items = new List(); - foreach (var item in predicate.Items) - { - Dictionary parameters = new Dictionary(); - IClassMapper classMap = SqlGenerator.Configuration.GetMap(item.Type); - IPredicate itemPredicate = item.Value as IPredicate; - if (itemPredicate == null && item.Value != null) - { - itemPredicate = GetPredicate(classMap, item.Value); - } - - string sql = SqlGenerator.Select(classMap, itemPredicate, item.Sort, parameters,schemaName, tableName); - DynamicParameters dynamicParameters = new DynamicParameters(); - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - - SqlMapper.GridReader queryResult = connection.QueryMultiple(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text); - items.Add(queryResult); - } - - return new SequenceReaderResultReader(items); - } - - - protected async Task GetMultipleByBatchAsync(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) - { - Dictionary parameters = new Dictionary(); - StringBuilder sql = new StringBuilder(); - foreach (var item in predicate.Items) - { - IClassMapper classMap = SqlGenerator.Configuration.GetMap(item.Type); - IPredicate itemPredicate = item.Value as IPredicate; - if (itemPredicate == null && item.Value != null) - { - itemPredicate = GetPredicate(classMap, item.Value); - } - - sql.AppendLine(SqlGenerator.Select(classMap, itemPredicate, item.Sort, parameters, schemaName, tableName) + SqlGenerator.Configuration.Dialect.BatchSeperator); - } - - DynamicParameters dynamicParameters = new DynamicParameters(); - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - - SqlMapper.GridReader grid = await connection.QueryMultipleAsync(sql.ToString(), dynamicParameters, transaction, commandTimeout, CommandType.Text); - return new GridReaderResultReader(grid); - } - - protected async Task GetMultipleBySequenceAsync(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout, string tableName, string schemaName) - { - IList items = new List(); - foreach (var item in predicate.Items) - { - Dictionary parameters = new Dictionary(); - IClassMapper classMap = SqlGenerator.Configuration.GetMap(item.Type); - IPredicate itemPredicate = item.Value as IPredicate; - if (itemPredicate == null && item.Value != null) - { - itemPredicate = GetPredicate(classMap, item.Value); - } - - string sql = SqlGenerator.Select(classMap, itemPredicate, item.Sort, parameters, schemaName, tableName); - DynamicParameters dynamicParameters = new DynamicParameters(); - foreach (var parameter in parameters) - { - dynamicParameters.Add(parameter.Key, parameter.Value); - } - - SqlMapper.GridReader queryResult = await connection.QueryMultipleAsync(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text); - items.Add(queryResult); - } - - return new SequenceReaderResultReader(items); - } - - /// - /// 检测join模式下的条件参数类型 - /// - /// - /// - protected void VerifyJoinPredicate(IList join, object predicate) - { - //联合查询时,参数必须是IPredicate格式,不能是anonymoustype、IEnumerable> - if (join != null && join.Count > 0 && predicate != null && (predicate as IPredicate) == null) - { - throw new Exception(" join predicate = IPredicate"); - } - } - #endregion - } -} diff --git a/samples/Common/Repository.Dapper.Core/Database.cs b/samples/Common/Repository.Dapper.Core/Database.cs deleted file mode 100644 index 2bf0145bb..000000000 --- a/samples/Common/Repository.Dapper.Core/Database.cs +++ /dev/null @@ -1,159 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text; -using Repository.Dapper.Core.Mapper; -using Repository.Dapper.Core.Sql; -using System.Threading.Tasks; -using Microsoft.Extensions.Options; - -namespace Repository.Dapper.Core -{ - public partial interface IDatabase : IDisposable - { - bool HasActiveTransaction { get; } - IDbConnection Connection { get; } - void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted); - void Commit(); - void Rollback(); - void RunInTransaction(Action action); - T RunInTransaction(Func func); - void ClearCache(); - Guid GetNextGuid(); - IClassMapper GetMap() where T : class; - - } - - public partial class Database : IDatabase - { - - private readonly IDapperImplementor _dapper; - - private IDbTransaction _transaction; - - public Database(IDbConnection connection, ISqlGenerator sqlGenerator) - { - _dapper = new DapperImplementor(sqlGenerator); - Connection = connection; - - if (Connection.State != ConnectionState.Open) - { - Connection.Open(); - } - } - public Database(IOptions options, IDapperExtensionsConfiguration Configuration) - { - _dapper = new DapperImplementor(new SqlGeneratorImpl(Configuration)); - Connection = options.Value.DbConnection(); - - if (Connection.State != ConnectionState.Open) - { - Connection.Open(); - } - } - - public bool HasActiveTransaction - { - get - { - return _transaction != null; - } - } - - public IDbConnection Connection { get; private set; } - - public void Dispose() - { - if (Connection.State != ConnectionState.Closed) - { - if (_transaction != null) - { - _transaction.Rollback(); - } - - Connection.Close(); - } - } - - public void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted) - { - _transaction = Connection.BeginTransaction(isolationLevel); - } - - public void Commit() - { - _transaction.Commit(); - _transaction = null; - } - - public void Rollback() - { - _transaction.Rollback(); - _transaction = null; - } - - public void RunInTransaction(Action action) - { - BeginTransaction(); - try - { - action(); - Commit(); - } - catch (Exception ex) - { - if (HasActiveTransaction) - { - Rollback(); - } - - throw ex; - } - } - - public T RunInTransaction(Func func) - { - BeginTransaction(); - try - { - T result = func(); - Commit(); - return result; - } - catch (Exception ex) - { - if (HasActiveTransaction) - { - Rollback(); - } - - throw ex; - } - } - - public void ClearCache() - { - _dapper.SqlGenerator.Configuration.ClearCache(); - } - - public Guid GetNextGuid() - { - return _dapper.SqlGenerator.Configuration.GetNextGuid(); - } - - public IClassMapper GetMap() where T : class - { - return _dapper.SqlGenerator.Configuration.GetMap(); - } - - - } - - public class DataBaseOptions - { - public ISqlDialect sqlDialect { get; set; } - - public Func DbConnection { get; set; } - } -} diff --git a/samples/Common/Repository.Dapper.Core/DatabasePartial.cs b/samples/Common/Repository.Dapper.Core/DatabasePartial.cs deleted file mode 100644 index 4cd8ba6dd..000000000 --- a/samples/Common/Repository.Dapper.Core/DatabasePartial.cs +++ /dev/null @@ -1,514 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Text; -using System.Threading.Tasks; - -namespace Repository.Dapper.Core -{ - public partial interface IDatabase - { - #region Count - long Count(object predicate = null, int? commandTimeout = null) where T : class; - long Count(string tableName, object predicate = null, int? commandTimeout = null) where T : class; - long Count(string tableName, string schemaName, object predicate = null, int? commandTimeout = null) where T : class; - - Task CountAsync(object predicate = null, int? commandTimeout = null) where T : class; - Task CountAsync(string tableName, object predicate = null, int? commandTimeout = null) where T : class; - Task CountAsync(string tableName, string schemaName, object predicate = null, int? commandTimeout = null) where T : class; - - - long Count(IList join, object predicate = null, int? commandTimeout = null) where T : class; - - Task CountAsync(IList join, object predicate = null, int? commandTimeout = null) where T : class; - - #endregion - - #region Delete - bool Delete(T entity, int? commandTimeout = null) where T : class; - bool Delete(string tableName, T entity, int? commandTimeout = null) where T : class; - bool Delete(string tableName, string schemaName, T entity, int? commandTimeout = null) where T : class; - - bool Delete(object predicate, int? commandTimeout = null) where T : class; - bool Delete(string tableName, object predicate, int? commandTimeout = null) where T : class; - bool Delete(string tableName, string schemaName, object predicate, int? commandTimeout = null) where T : class; - - Task DeleteAsync(T entity, int? commandTimeout = null) where T : class; - Task DeleteAsync(string tableName, T entity, int? commandTimeout = null) where T : class; - Task DeleteAsync(string tableName, string schemaName, T entity, int? commandTimeout = null) where T : class; - - Task DeleteAsync(object predicate, int? commandTimeout = null) where T : class; - Task DeleteAsync(string tableName, object predicate, int? commandTimeout = null) where T : class; - Task DeleteAsync(string tableName, string schemaName, object predicate, int? commandTimeout = null) where T : class; - #endregion - - #region Get - T Get(dynamic id, int? commandTimeout = null) where T : class; - T Get(dynamic id, string tableName, int? commandTimeout = null) where T : class; - T Get(dynamic id, string tableName, string schemaName, int? commandTimeout = null) where T : class; - - Task GetAsync(dynamic id, int? commandTimeout = null) where T : class; - Task GetAsync(dynamic id, string tableName, int? commandTimeout = null) where T : class; - Task GetAsync(dynamic id, string tableName, string schemaName, int? commandTimeout = null) where T : class; - - T Get(IList join, dynamic id, int? commandTimeout = null) where T : class; - T Get(IList join, IList alias, dynamic id, int? commandTimeout = null) where T : class; - - Task GetAsync(IList join, dynamic id, int? commandTimeout = null) where T : class; - Task GetAsync(IList join, IList alias, dynamic id, int? commandTimeout = null) where T : class; - #endregion - - #region GetList - IEnumerable GetList(object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class; - IEnumerable GetList(string tableName, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class; - IEnumerable GetList(string tableName, string schemaName, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class; - - Task> GetListAsync(object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - Task> GetListAsync(string tableName, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - Task> GetListAsync(string tableName, string schemaName, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - - - IEnumerable GetList(IList join, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class; - - IEnumerable GetList(IList join, IList alias = null, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class; - - Task> GetListAsync(IList join, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - - Task> GetListAsync(IList join, IList alias = null, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - - #endregion - - #region GetMultiple - IMultipleResultReader GetMultiple(GetMultiplePredicate predicate = null, int? commandTimeout = null); - IMultipleResultReader GetMultiple(string tableName, GetMultiplePredicate predicate = null, int? commandTimeout = null); - IMultipleResultReader GetMultiple(string tableName, string schemaName, GetMultiplePredicate predicate = null, int? commandTimeout = null); - Task GetMultipleAsync(GetMultiplePredicate predicate = null, int? commandTimeout = null); - Task GetMultipleAsync(string tableName, GetMultiplePredicate predicate = null, int? commandTimeout = null); - Task GetMultipleAsync(string tableName, string schemaName, GetMultiplePredicate predicate = null, int? commandTimeout = null); - #endregion - - #region GetPage - IEnumerable GetPage(int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class; - IEnumerable GetPage(string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class; - IEnumerable GetPage(string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class; - - - Task> GetPageAsync(int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - Task> GetPageAsync(string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - Task> GetPageAsync(string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - - IEnumerable GetPage(IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class; - - IEnumerable GetPage(IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class; - - Task> GetPageAsync(IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - - Task> GetPageAsync(IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - - #endregion - - - #region GetPages - Page GetPages(int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - Page GetPages(string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - Page GetPages(string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - - Task> GetPagesAsync(int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - Task> GetPagesAsync(string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - Task> GetPagesAsync(string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - - Page GetPages(IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - Page GetPages(IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - Task> GetPagesAsync(IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - - Task> GetPagesAsync(IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class; - - #endregion - - #region GetSet - IEnumerable GetSet(object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null, bool buffered = true) where T : class; - IEnumerable GetSet(string tableName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null, bool buffered = true) where T : class; - IEnumerable GetSet(string tableName, string schemaName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null, bool buffered = true) where T : class; - Task> GetSetAsync(object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null) where T : class; - Task> GetSetAsync(string tableName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null) where T : class; - Task> GetSetAsync(string tableName, string schemaName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null) where T : class; - - IEnumerable GetSet(IList join, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null, bool buffered = true) where T : class; - - IEnumerable GetSet(IList join, IList alias, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null, bool buffered = true) where T : class; - Task> GetSetAsync(IList join, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null) where T : class; - - Task> GetSetAsync(IList join, IList alias, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null) where T : class; - - #endregion - - #region Insert - void Insert(IEnumerable entities, int? commandTimeout = null) where T : class; - void Insert(string tableName, IEnumerable entities, int? commandTimeout = null) where T : class; - void Insert(string tableName, string schemaName, IEnumerable entities, int? commandTimeout = null) where T : class; - - dynamic Insert(T entity, int? commandTimeout = null) where T : class; - dynamic Insert(string tableName, T entity, int? commandTimeout = null) where T : class; - dynamic Insert(string tableName, string schemaName, T entity, int? commandTimeout = null) where T : class; - #endregion - - #region Update - - bool Update(T entity, object predicate = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class; - bool Update(string tableName, T entity, object predicate = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class; - bool Update(string tableName, string schemaName, T entity, object predicate = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class; - - - bool UpdateSet(object entity, object predicate = null, int? commandTimeout = null) where T : class; - bool UpdateSet(string tableName, object entity, object predicate = null, int? commandTimeout = null) where T : class; - bool UpdateSet(string tableName, string schemaName, object entity, object predicate = null, int? commandTimeout = null) where T : class; - - - - - Task UpdateAsync(T entity, object predicate = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class; - Task UpdateAsync(string tableName, T entity, object predicate = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class; - Task UpdateAsync(string tableName, string schemaName, T entity, object predicate = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class; - - Task UpdateSetAsync(object entity, object predicate = null, int? commandTimeout = null) where T : class; - Task UpdateSetAsync(string tableName, object entity, object predicate = null, int? commandTimeout = null) where T : class; - Task UpdateSetAsync(string tableName, string schemaName, object entity, object predicate = null, int? commandTimeout = null) where T : class; - - - #endregion - - } - public partial class Database - { - #region Count - public long Count(object predicate = null, int? commandTimeout = null) where T : class - => Count((string)null, predicate, commandTimeout); - - public long Count(string tableName, object predicate = null, int? commandTimeout = null) where T : class - => Count(tableName, null, predicate, commandTimeout); - - public long Count(string tableName, string schemaName, object predicate = null, int? commandTimeout = null) where T : class - => _dapper.Count(Connection, predicate, _transaction, commandTimeout, tableName, schemaName, null); - - public async Task CountAsync(object predicate = null, int? commandTimeout = null) where T : class - => await CountAsync((string)null, predicate, commandTimeout); - - public async Task CountAsync(string tableName, object predicate = null, int? commandTimeout = null) where T : class - => await CountAsync(tableName, null, predicate, commandTimeout); - - public async Task CountAsync(string tableName, string schemaName, object predicate = null, int? commandTimeout = null) where T : class - => await _dapper.CountAsync(Connection, predicate, _transaction, commandTimeout, tableName, schemaName, null); - - public long Count(IList join, object predicate = null, int? commandTimeout = null) where T : class - => _dapper.Count(Connection, predicate, _transaction, commandTimeout, null, null, join); - - public async Task CountAsync(IList join, object predicate = null, int? commandTimeout = null) where T : class - => await _dapper.CountAsync(Connection, predicate, _transaction, commandTimeout, null, null, join); - #endregion - - #region Delete - public bool Delete(T entity, int? commandTimeout = null) where T : class - => Delete(null, entity, commandTimeout); - - public bool Delete(string tableName, T entity, int? commandTimeout = null) where T : class - => Delete(tableName, null, entity, commandTimeout); - - public bool Delete(string tableName, string schemaName, T entity, int? commandTimeout = null) where T : class - => _dapper.Delete(Connection, entity, _transaction, commandTimeout, tableName, schemaName); - - - public bool Delete(object predicate, int? commandTimeout = null) where T : class - => Delete(null, predicate, commandTimeout); - - public bool Delete(string tableName, object predicate, int? commandTimeout = null) where T : class - => Delete(tableName, null, predicate, commandTimeout); - - public bool Delete(string tableName, string schemaName, object predicate, int? commandTimeout = null) where T : class - => _dapper.Delete(Connection, predicate, _transaction, commandTimeout, tableName, schemaName); - - - public async Task DeleteAsync(T entity, int? commandTimeout = null) where T : class - => await DeleteAsync(null, entity, commandTimeout); - - public async Task DeleteAsync(string tableName, T entity, int? commandTimeout = null) where T : class - => await DeleteAsync(tableName, null, entity, commandTimeout); - - public async Task DeleteAsync(string tableName, string schemaName, T entity, int? commandTimeout = null) where T : class - => await _dapper.DeleteAsync(Connection, entity, _transaction, commandTimeout, tableName, schemaName); - - - public async Task DeleteAsync(object predicate, int? commandTimeout = null) where T : class - => await DeleteAsync(null, predicate, commandTimeout); - - public async Task DeleteAsync(string tableName, object predicate, int? commandTimeout = null) where T : class - => await DeleteAsync(tableName, null, predicate, commandTimeout); - - public async Task DeleteAsync(string tableName, string schemaName, object predicate, int? commandTimeout = null) where T : class - => await _dapper.DeleteAsync(Connection, predicate, _transaction, commandTimeout, tableName, schemaName); - - #endregion - - #region Get - public T Get(dynamic id, int? commandTimeout = null) where T : class - => Get(id, (string)null, commandTimeout); - - public T Get(dynamic id, string tableName, int? commandTimeout = null) where T : class - => Get(id, tableName, (string)null, commandTimeout); - - public T Get(dynamic id, string tableName, string schemaName, int? commandTimeout = null) where T : class - => (T)_dapper.Get(Connection, id, _transaction, commandTimeout, tableName, schemaName, null, null); - - - public async Task GetAsync(dynamic id, int? commandTimeout = null) where T : class - => await GetAsync(id, (string)null, commandTimeout); - - public async Task GetAsync(dynamic id, string tableName, int? commandTimeout = null) where T : class - => await GetAsync(id, tableName, (string)null, commandTimeout); - - public async Task GetAsync(dynamic id, string tableName, string schemaName, int? commandTimeout = null) where T : class - => await _dapper.GetAsync(Connection, id, _transaction, commandTimeout, tableName, schemaName, null, null); - - - - public T Get(IList join, dynamic id, int? commandTimeout = null) where T : class - => Get(join, null, id, commandTimeout); - - public T Get(IList join, IList alias, dynamic id, int? commandTimeout = null) where T : class - => (T)_dapper.Get(Connection, id, _transaction, commandTimeout, null, null, join, alias); - - public async Task GetAsync(IList join, dynamic id, int? commandTimeout = null) where T : class - => await GetAsync(join, null, id, commandTimeout); - public async Task GetAsync(IList join, IList alias, dynamic id, int? commandTimeout = null) where T : class - => await _dapper.GetAsync(Connection, id, _transaction, commandTimeout, null, null, join, alias); - #endregion - - #region GetList - - public IEnumerable GetList(object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class - => GetList((string)null, predicate, sort, commandTimeout, buffered); - - public IEnumerable GetList(string tableName, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class - => GetList(tableName, null, predicate, sort, commandTimeout, buffered); - - public IEnumerable GetList(string tableName, string schemaName, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class - => _dapper.GetList(Connection, predicate, sort, _transaction, commandTimeout, buffered, tableName, schemaName, null, null); - - - public async Task> GetListAsync(object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await GetListAsync((string)null, predicate, sort, commandTimeout); - - public async Task> GetListAsync(string tableName, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await GetListAsync(tableName, null, predicate, sort, commandTimeout); - - public async Task> GetListAsync(string tableName, string schemaName, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await _dapper.GetListAsync(Connection, predicate, sort, _transaction, commandTimeout, tableName, schemaName, null, null); - - - - public IEnumerable GetList(IList join, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class - => GetList(join, null, predicate, sort, commandTimeout, buffered); - - public IEnumerable GetList(IList join, IList alias = null, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class - => _dapper.GetList(Connection, predicate, sort, _transaction, commandTimeout, buffered, null, null, join, alias); - - public async Task> GetListAsync(IList join, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await GetListAsync(join, null, predicate, sort, commandTimeout); - - public async Task> GetListAsync(IList join, IList alias = null, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await _dapper.GetListAsync(Connection, predicate, sort, _transaction, commandTimeout, null, null, join, alias); - - #endregion - - #region GetMultiple - - public IMultipleResultReader GetMultiple(GetMultiplePredicate predicate = null, int? commandTimeout = null) - => GetMultiple(null, predicate, commandTimeout); - public IMultipleResultReader GetMultiple(string tableName, GetMultiplePredicate predicate = null, int? commandTimeout = null) - => GetMultiple(tableName, null, predicate, commandTimeout); - public IMultipleResultReader GetMultiple(string tableName, string schemaName, GetMultiplePredicate predicate = null, int? commandTimeout = null) - => _dapper.GetMultiple(Connection, predicate, _transaction, commandTimeout, tableName, schemaName); - - - - - public async Task GetMultipleAsync(GetMultiplePredicate predicate = null, int? commandTimeout = null) - => await GetMultipleAsync(null, predicate, commandTimeout); - - public async Task GetMultipleAsync(string tableName, GetMultiplePredicate predicate = null, int? commandTimeout = null) - => await GetMultipleAsync(tableName, null, predicate, commandTimeout); - - public async Task GetMultipleAsync(string tableName, string schemaName, GetMultiplePredicate predicate = null, int? commandTimeout = null) - => await _dapper.GetMultipleAsync(Connection, predicate, _transaction, commandTimeout, tableName, schemaName); - - #endregion - - - #region GetPage - public IEnumerable GetPage(int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class - => GetPage((string)null, page, resultsPerPage, predicate, sort, commandTimeout); - - public IEnumerable GetPage(string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class - => GetPage(tableName, null, page, resultsPerPage, predicate, sort, commandTimeout); - - public IEnumerable GetPage(string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class - => _dapper.GetPage(Connection, predicate, sort, page, resultsPerPage, _transaction, commandTimeout, buffered, tableName, schemaName, null, null); - - - public async Task> GetPageAsync(int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await GetPageAsync((string)null, page, resultsPerPage, predicate, sort, commandTimeout); - - public async Task> GetPageAsync(string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await GetPageAsync(tableName, null, page, resultsPerPage, predicate, sort, commandTimeout); - - public async Task> GetPageAsync(string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await _dapper.GetPageAsync(Connection, predicate, sort, page, resultsPerPage, _transaction, commandTimeout, tableName, schemaName, null, null); - - public IEnumerable GetPage(IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class - => GetPage(join, null, page, resultsPerPage, predicate, sort, commandTimeout); - public IEnumerable GetPage(IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class - => _dapper.GetPage(Connection, predicate, sort, page, resultsPerPage, _transaction, commandTimeout, buffered, null, null, join, alias); - public async Task> GetPageAsync(IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await GetPageAsync(join, null, page, resultsPerPage, predicate, sort, commandTimeout); - public async Task> GetPageAsync(IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await _dapper.GetPageAsync(Connection, predicate, sort, page, resultsPerPage, _transaction, commandTimeout, null, null, join, alias); - - #endregion - - #region GetPages - - public Page GetPages(int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => GetPages((string)null, page, resultsPerPage, predicate, sort, commandTimeout); - - public Page GetPages(string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => GetPages(tableName, null, page, resultsPerPage, predicate, sort, commandTimeout); - - public Page GetPages(string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => _dapper.GetPages(Connection, predicate, sort, page, resultsPerPage, _transaction, commandTimeout, tableName, schemaName, null, null); - - - public async Task> GetPagesAsync(int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await GetPagesAsync((string)null, page, resultsPerPage, predicate, sort, commandTimeout); - - public async Task> GetPagesAsync(string tableName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await GetPagesAsync(tableName, null, page, resultsPerPage, predicate, sort, commandTimeout); - - public async Task> GetPagesAsync(string tableName, string schemaName, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await _dapper.GetPagesAsync(Connection, predicate, sort, page, resultsPerPage, _transaction, commandTimeout, tableName, schemaName, null, null); - - public Page GetPages(IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => GetPages(join, null, page, resultsPerPage, predicate, sort, commandTimeout); - - public Page GetPages(IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => _dapper.GetPages(Connection, predicate, sort, page, resultsPerPage, _transaction, commandTimeout, null, null, join, alias); - public async Task> GetPagesAsync(IList join, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await GetPagesAsync(join, null, page, resultsPerPage, predicate, sort, commandTimeout); - public async Task> GetPagesAsync(IList join, IList alias, int page = 1, int resultsPerPage = 10, object predicate = null, IList sort = null, int? commandTimeout = null) where T : class - => await _dapper.GetPagesAsync(Connection, predicate, sort, page, resultsPerPage, _transaction, commandTimeout, null, null, join, alias); - - - #endregion - - #region GetSet - public IEnumerable GetSet(object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null, bool buffered = true) where T : class - => GetSet((string)null, predicate, sort, firstResult, maxResults, commandTimeout, buffered); - - public IEnumerable GetSet(string tableName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null, bool buffered = true) where T : class - => GetSet(tableName, null, predicate, sort, firstResult, maxResults, commandTimeout, buffered); - - public IEnumerable GetSet(string tableName, string schemaName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null, bool buffered = true) where T : class - => _dapper.GetSet(Connection, predicate, sort, firstResult, maxResults, _transaction, commandTimeout, buffered, tableName, schemaName, null, null); - - - public async Task> GetSetAsync(object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null) where T : class - => await GetSetAsync((string)null, predicate, sort, firstResult, maxResults, commandTimeout); - - public async Task> GetSetAsync(string tableName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null) where T : class - => await GetSetAsync(tableName, null, predicate, sort, firstResult, maxResults, commandTimeout); - - public async Task> GetSetAsync(string tableName, string schemaName, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null) where T : class - => await _dapper.GetSetAsync(Connection, predicate, sort, firstResult, maxResults, _transaction, commandTimeout, tableName, schemaName, null, null); - - public IEnumerable GetSet(IList join, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null, bool buffered = true) where T : class - => GetSet(join, null, predicate, sort, firstResult, maxResults, commandTimeout, buffered); - - public IEnumerable GetSet(IList join, IList alias, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null, bool buffered = true) where T : class - => _dapper.GetSet(Connection, predicate, sort, firstResult, maxResults, _transaction, commandTimeout, buffered, null, null, join, alias); - - public async Task> GetSetAsync(IList join, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null) where T : class - => await GetSetAsync(join, null, predicate, sort, firstResult, maxResults, commandTimeout); - - public async Task> GetSetAsync(IList join, IList alias, object predicate = null, IList sort = null, int firstResult = 1, int maxResults = 10, int? commandTimeout = null) where T : class - => await _dapper.GetSetAsync(Connection, predicate, sort, firstResult, maxResults, _transaction, commandTimeout, null, null, join, alias); - - #endregion - - #region Insert - public void Insert(IEnumerable entities, int? commandTimeout = null) where T : class - => Insert(null, entities, commandTimeout); - - public void Insert(string tableName, IEnumerable entities, int? commandTimeout = null) where T : class - => Insert(tableName, null, entities, commandTimeout); - - public void Insert(string tableName, string schemaName, IEnumerable entities, int? commandTimeout = null) where T : class - => _dapper.Insert(Connection, entities, _transaction, commandTimeout, tableName, schemaName); - - public dynamic Insert(T entity, int? commandTimeout = null) where T : class - => Insert(null, entity, commandTimeout); - - public dynamic Insert(string tableName, T entity, int? commandTimeout = null) where T : class - => Insert(tableName, null, entity, commandTimeout); - - public dynamic Insert(string tableName, string schemaName, T entity, int? commandTimeout = null) where T : class - => _dapper.Insert(Connection, entity, _transaction, commandTimeout, tableName, schemaName); - #endregion - - #region Update - - public bool Update(T entity, object predicate = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => Update(null, entity, predicate, commandTimeout, ignoreAllKeyProperties); - - public bool Update(string tableName, T entity, object predicate = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => Update(tableName, null, entity, predicate, commandTimeout, ignoreAllKeyProperties); - - public bool Update(string tableName, string schemaName, T entity, object predicate = null, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => _dapper.Update(Connection, entity, predicate, _transaction, commandTimeout, tableName, schemaName, ignoreAllKeyProperties); - - - - public bool UpdateSet(object entity, object predicate = null, int? commandTimeout = null) where T : class - => UpdateSet(null, entity, predicate, commandTimeout); - - public bool UpdateSet(string tableName, object entity, object predicate = null, int? commandTimeout = null) where T : class - => UpdateSet(tableName, null, entity, predicate, commandTimeout); - - public bool UpdateSet(string tableName, string schemaName, object entity, object predicate = null, int? commandTimeout = null) where T : class - => _dapper.UpdateSet(Connection, entity, predicate, _transaction, commandTimeout, tableName, schemaName); - - - - - public async Task UpdateAsync(T entity, object predicate, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => await UpdateAsync(null, entity, predicate, commandTimeout, ignoreAllKeyProperties); - - public async Task UpdateAsync(string tableName, T entity, object predicate, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => await UpdateAsync(tableName, null, entity, predicate, commandTimeout, ignoreAllKeyProperties); - - public async Task UpdateAsync(string tableName, string schemaName, T entity, object predicate, int? commandTimeout = null, bool ignoreAllKeyProperties = false) where T : class - => await _dapper.UpdateAsync(Connection, entity, predicate, _transaction, commandTimeout, tableName, schemaName, ignoreAllKeyProperties); - - - - public async Task UpdateSetAsync(object entity, object predicate = null, int? commandTimeout = null) where T : class - => await UpdateSetAsync(null, entity, predicate, commandTimeout); - - public async Task UpdateSetAsync(string tableName, object entity, object predicate = null, int? commandTimeout = null) where T : class - => await UpdateSetAsync(tableName, null, entity, predicate, commandTimeout); - - public async Task UpdateSetAsync(string tableName, string schemaName, object entity, object predicate = null, int? commandTimeout = null) where T : class - => await _dapper.UpdateSetAsync(Connection, entity, predicate, _transaction, commandTimeout, tableName, schemaName); - - - #endregion - - } -} diff --git a/samples/Common/Repository.Dapper.Core/DatabaseServiceCollectionExtensions.cs b/samples/Common/Repository.Dapper.Core/DatabaseServiceCollectionExtensions.cs deleted file mode 100644 index ea01dcf60..000000000 --- a/samples/Common/Repository.Dapper.Core/DatabaseServiceCollectionExtensions.cs +++ /dev/null @@ -1,105 +0,0 @@ -using Repository.Dapper.Core.Sql; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Data; -using System.Text; - -namespace Repository.Dapper.Core -{ - public enum ESqlDialect - { - DB2, - MySQL, - Oracle, - PostgreSql, - SqlCe, - Sqlite, - SqlServer - } - public class SqlDialectUtil - { - public static ISqlDialect ConvertESqlDialect(ESqlDialect sqlDialect) - { - ISqlDialect SqlDialect = null; - switch (sqlDialect) - { - case ESqlDialect.DB2: - SqlDialect = new DB2Dialect(); - break; - case ESqlDialect.MySQL: - SqlDialect = new MySqlDialect(); - break; - case ESqlDialect.Oracle: - SqlDialect = new OracleDialect(); - break; - case ESqlDialect.PostgreSql: - SqlDialect = new PostgreSqlDialect(); - break; - case ESqlDialect.SqlCe: - SqlDialect = new SqlCeDialect(); - break; - case ESqlDialect.Sqlite: - SqlDialect = new SqliteDialect(); - break; - case ESqlDialect.SqlServer: - SqlDialect = new SqlServerDialect(); - break; - } - return SqlDialect; - } - } - public static class DatabaseServiceCollectionExtensions - { - - /// - /// 设置SqlDialect,使用默认用法 - /// - /// - /// - /// - /// using(var con=new SqlConnection(Configuration.GetConnectionString("DefaultConnection")) - /// { - /// con.Insert(data); - /// } - /// - /// - public static IServiceCollection AddDapper(this IServiceCollection services, ESqlDialect SqlDialect) - { - DapperExtensions.Configure(SqlDialectUtil.ConvertESqlDialect(SqlDialect)); - - return services; - } - - /// - /// 使用IDatabase用法 - /// - /// - /// - /// - /// 是否同时使用扩展方法 - /// - public static IServiceCollection AddDapperDataBase(this IServiceCollection services, ESqlDialect sqlDialect, Func CreateConnection, bool UseExtension = false) - { - var SqlDialect = SqlDialectUtil.ConvertESqlDialect(sqlDialect); - services.AddOptions(); - services.Configure(opt => - { - opt.DbConnection = CreateConnection; - opt.sqlDialect = SqlDialectUtil.ConvertESqlDialect(sqlDialect); - }); - - if (UseExtension) - { - var Configuration = new DapperExtensionsConfiguration(SqlDialect); - DapperExtensions.Configure(Configuration); - services.AddSingleton(Configuration); - } - else - services.AddSingleton(); - - services.AddTransient(); - return services; - } - } -} diff --git a/samples/Common/Repository.Dapper.Core/GetMultiplePredicate.cs b/samples/Common/Repository.Dapper.Core/GetMultiplePredicate.cs deleted file mode 100644 index e931c2423..000000000 --- a/samples/Common/Repository.Dapper.Core/GetMultiplePredicate.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Repository.Dapper.Core -{ - public class GetMultiplePredicate - { - private readonly List _items; - - public GetMultiplePredicate() - { - _items = new List(); - } - - public IEnumerable Items - { - get { return _items.AsReadOnly(); } - } - - public void Add(IPredicate predicate, IList sort = null) where T : class - { - _items.Add(new GetMultiplePredicateItem - { - Value = predicate, - Type = typeof(T), - Sort = sort - }); - } - - public void Add(object id) where T : class - { - _items.Add(new GetMultiplePredicateItem - { - Value = id, - Type = typeof (T) - }); - } - - public class GetMultiplePredicateItem - { - public object Value { get; set; } - public Type Type { get; set; } - public IList Sort { get; set; } - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/GetMultipleResult.cs b/samples/Common/Repository.Dapper.Core/GetMultipleResult.cs deleted file mode 100644 index 752a8f1d6..000000000 --- a/samples/Common/Repository.Dapper.Core/GetMultipleResult.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Dapper; - -namespace Repository.Dapper.Core -{ - public interface IMultipleResultReader - { - IEnumerable Read(); - } - - public class GridReaderResultReader : IMultipleResultReader - { - private readonly SqlMapper.GridReader _reader; - - public GridReaderResultReader(SqlMapper.GridReader reader) - { - _reader = reader; - } - - public IEnumerable Read() - { - return _reader.Read(); - } - } - - public class SequenceReaderResultReader : IMultipleResultReader - { - private readonly Queue _items; - - public SequenceReaderResultReader(IEnumerable items) - { - _items = new Queue(items); - } - - public IEnumerable Read() - { - SqlMapper.GridReader reader = _items.Dequeue(); - return reader.Read(); - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Mapper/AutoClassMapper.cs b/samples/Common/Repository.Dapper.Core/Mapper/AutoClassMapper.cs deleted file mode 100644 index 29b1cc6c7..000000000 --- a/samples/Common/Repository.Dapper.Core/Mapper/AutoClassMapper.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Text; -using System.Linq; -using System.Collections.Generic; -using System; -using System.Reflection; -using System.ComponentModel.DataAnnotations.Schema; - -namespace Repository.Dapper.Core.Mapper -{ - /// - /// Automatically maps an entity to a table using a combination of reflection and naming conventions for keys. - /// - public class AutoClassMapper : ClassMapper where T : class - { - public AutoClassMapper() - { - Type type = typeof(T); - var vTable = type.GetTypeInfo().GetCustomAttributes(typeof(TableAttribute), true).ToArray(); - var TableName = vTable.Length == 0 ? type.Name : (vTable[0] as TableAttribute).Name; - Table(TableName);// Table(type.Name); - if (vTable.Length > 0 && !string.IsNullOrWhiteSpace((vTable[0] as TableAttribute).Schema)) - Schema((vTable[0] as TableAttribute).Schema); - - var vNotKey = type.GetTypeInfo().GetCustomAttributes(typeof(NotKeyAttribute), true).ToArray(); - if (vNotKey.Length > 0) - DefinedKey(false); - AutoMap(); - } - } - - [AttributeUsage(AttributeTargets.Class)] - public sealed class NotKeyAttribute : Attribute - { - public NotKeyAttribute() - { - NoDefinedKey = true; - } - - public bool NoDefinedKey { get; set; } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Mapper/ClassMapper.cs b/samples/Common/Repository.Dapper.Core/Mapper/ClassMapper.cs deleted file mode 100644 index 4ba847cab..000000000 --- a/samples/Common/Repository.Dapper.Core/Mapper/ClassMapper.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System.Numerics; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.ComponentModel.DataAnnotations; - -namespace Repository.Dapper.Core.Mapper -{ - public interface IClassMapper - { - string SchemaName { get; } - string TableName { get; } - IList Properties { get; } - Type EntityType { get; } - } - - public interface IClassMapper : IClassMapper where T : class - { - } - - /// - /// Maps an entity to a table through a collection of property maps. - /// - public class ClassMapper : IClassMapper where T : class - { - /// - /// Gets or sets the schema to use when referring to the corresponding table name in the database. - /// - public string SchemaName { get; protected set; } - - /// - /// Gets or sets the table to use in the database. - /// - public string TableName { get; protected set; } - private bool _HasDefinedKey = true; - public bool HasDefinedKey { get { return _HasDefinedKey; } protected set { _HasDefinedKey = value; } } - - /// - /// A collection of properties that will map to columns in the database table. - /// - public IList Properties { get; private set; } - - public Type EntityType - { - get { return typeof(T); } - } - - public ClassMapper() - { - PropertyTypeKeyTypeMapping = new Dictionary - { - { typeof(byte), KeyType.Identity }, { typeof(byte?), KeyType.Identity }, - { typeof(sbyte), KeyType.Identity }, { typeof(sbyte?), KeyType.Identity }, - { typeof(short), KeyType.Identity }, { typeof(short?), KeyType.Identity }, - { typeof(ushort), KeyType.Identity }, { typeof(ushort?), KeyType.Identity }, - { typeof(int), KeyType.Identity }, { typeof(int?), KeyType.Identity }, - { typeof(uint), KeyType.Identity}, { typeof(uint?), KeyType.Identity }, - { typeof(long), KeyType.Identity }, { typeof(long?), KeyType.Identity }, - { typeof(ulong), KeyType.Identity }, { typeof(ulong?), KeyType.Identity }, - { typeof(BigInteger), KeyType.Identity }, { typeof(BigInteger?), KeyType.Identity }, - { typeof(Guid), KeyType.Guid }, { typeof(Guid?), KeyType.Guid }, - }; - - Properties = new List(); - Table(typeof(T).Name); - } - - protected Dictionary PropertyTypeKeyTypeMapping { get; private set; } - - public virtual void Schema(string schemaName) - { - SchemaName = schemaName; - } - - public virtual void Table(string tableName) - { - TableName = tableName; - } - public virtual void DefinedKey(bool hasDefinedKey) - { - HasDefinedKey = hasDefinedKey; - } - - protected virtual void AutoMap() - { - AutoMap(null); - } - - protected virtual void AutoMap(Func canMap) - { - Type type = typeof(T); - bool hasDefinedKey = Properties.Any(p => p.KeyType != KeyType.NotAKey); - PropertyMap keyMap = null; - foreach (var propertyInfo in type.GetProperties()) - { - if (Properties.Any(p => p.Name.Equals(propertyInfo.Name, StringComparison.InvariantCultureIgnoreCase))) - { - continue; - } - - if ((canMap != null && !canMap(type, propertyInfo))) - { - continue; - } - - PropertyMap map = Map(propertyInfo); - if (!hasDefinedKey && _HasDefinedKey) - { - if (string.Equals(map.PropertyInfo.Name, "id", StringComparison.InvariantCultureIgnoreCase) && !map.Ignored && !map.IsReadOnly) - { - keyMap = map; - } - - if (keyMap == null && map.PropertyInfo.Name.EndsWith("id", true, CultureInfo.InvariantCulture) && !map.Ignored && !map.IsReadOnly) - { - keyMap = map; - } - var KeyAttr = propertyInfo.GetCustomAttributes(typeof(KeyAttribute), true).ToArray(); - if (KeyAttr.Length > 0) - keyMap = map; - } - } - - if (keyMap != null) - { - keyMap.Key(PropertyTypeKeyTypeMapping.ContainsKey(keyMap.PropertyInfo.PropertyType) - ? PropertyTypeKeyTypeMapping[keyMap.PropertyInfo.PropertyType] - : KeyType.Assigned); - } - } - - /// - /// Fluently, maps an entity property to a column - /// - protected PropertyMap Map(Expression> expression) - { - PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; - return Map(propertyInfo); - } - - /// - /// Fluently, maps an entity property to a column - /// - protected PropertyMap Map(PropertyInfo propertyInfo) - { - PropertyMap result = new PropertyMap(propertyInfo); - this.GuardForDuplicatePropertyMap(result); - Properties.Add(result); - return result; - } - - /// - /// Removes a propertymap entry - /// - /// - protected void UnMap(Expression> expression) - { - var propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; - var mapping = this.Properties.Where(w => w.Name == propertyInfo.Name).SingleOrDefault(); - - if (mapping == null) - { - throw new ApplicationException("Unable to UnMap because mapping does not exist."); - } - - this.Properties.Remove(mapping); - } - - private void GuardForDuplicatePropertyMap(PropertyMap result) - { - if (Properties.Any(p => p.Name.Equals(result.Name))) - { - throw new ArgumentException(string.Format("Duplicate mapping for property {0} detected.",result.Name)); - } - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Mapper/PluralizedAutoClassMapper.cs b/samples/Common/Repository.Dapper.Core/Mapper/PluralizedAutoClassMapper.cs deleted file mode 100644 index 19c74af0e..000000000 --- a/samples/Common/Repository.Dapper.Core/Mapper/PluralizedAutoClassMapper.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.Text; -using System.Linq; -using System.Collections.Generic; -using System; -using System.Text.RegularExpressions; - -namespace Repository.Dapper.Core.Mapper -{ - /// - /// Automatically maps an entity to a table using a combination of reflection and naming conventions for keys. - /// Identical to AutoClassMapper, but attempts to pluralize table names automatically. - /// Example: Person entity maps to People table - /// - public class PluralizedAutoClassMapper : AutoClassMapper where T : class - { - public override void Table(string tableName) - { - base.Table(Formatting.Pluralize(tableName)); - } - - // Adapted from: http://mattgrande.wordpress.com/2009/10/28/pluralization-helper-for-c/ - public static class Formatting - { - private static readonly IList Unpluralizables = new List { "equipment", "information", "rice", "money", "species", "series", "fish", "sheep", "deer" }; - private static readonly IDictionary Pluralizations = new Dictionary - { - // Start with the rarest cases, and move to the most common - { "person", "people" }, - { "ox", "oxen" }, - { "child", "children" }, - { "foot", "feet" }, - { "tooth", "teeth" }, - { "goose", "geese" }, - // And now the more standard rules. - { "(.*)fe?$", "$1ves" }, // ie, wolf, wife - { "(.*)man$", "$1men" }, - { "(.+[aeiou]y)$", "$1s" }, - { "(.+[^aeiou])y$", "$1ies" }, - { "(.+z)$", "$1zes" }, - { "([m|l])ouse$", "$1ice" }, - { "(.+)(e|i)x$", @"$1ices"}, // ie, Matrix, Index - { "(octop|vir)us$", "$1i"}, - { "(.+(s|x|sh|ch))$", @"$1es"}, - { "(.+)", @"$1s" } - }; - - public static string Pluralize(string singular) - { - if (Unpluralizables.Contains(singular)) - return singular; - - var plural = string.Empty; - - foreach (var pluralization in Pluralizations) - { - if (Regex.IsMatch(singular, pluralization.Key)) - { - plural = Regex.Replace(singular, pluralization.Key, pluralization.Value); - break; - } - } - - return plural; - } - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Mapper/PropertyMap.cs b/samples/Common/Repository.Dapper.Core/Mapper/PropertyMap.cs deleted file mode 100644 index ab5b14ba3..000000000 --- a/samples/Common/Repository.Dapper.Core/Mapper/PropertyMap.cs +++ /dev/null @@ -1,162 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; -using System.Linq; -using System.Reflection; - -namespace Repository.Dapper.Core.Mapper -{ - /// - /// Maps an entity property to its corresponding column in the database. - /// - public interface IPropertyMap - { - string Name { get; } - string ColumnName { get; } - bool Ignored { get; } - bool IsReadOnly { get; } - KeyType KeyType { get; } - PropertyInfo PropertyInfo { get; } - } - - /// - /// Maps an entity property to its corresponding column in the database. - /// - public class PropertyMap : IPropertyMap - { - public PropertyMap(PropertyInfo propertyInfo) - { - PropertyInfo = propertyInfo; - var ColumnAttr = propertyInfo.GetCustomAttributes(typeof(ColumnAttribute), true).ToArray(); - ColumnName = ColumnAttr.Length == 0 ? PropertyInfo.Name : (ColumnAttr[0] as ColumnAttribute).Name; // PropertyInfo.Name; - - var cIgnore = propertyInfo.GetCustomAttributes(typeof(NotMappedAttribute), true).ToArray(); - Ignored = cIgnore.Length > 0; - - //var cReadOnly = propertyInfo.GetCustomAttributes(typeof(DatabaseGeneratedAttribute), true).ToArray(); - //IsReadOnly = cReadOnly.Length > 0; - } - - /// - /// Gets the name of the property by using the specified propertyInfo. - /// - public string Name - { - get { return PropertyInfo.Name; } - } - - /// - /// Gets the column name for the current property. - /// - public string ColumnName { get; private set; } - - /// - /// Gets the key type for the current property. - /// - public KeyType KeyType { get; private set; } - - /// - /// Gets the ignore status of the current property. If ignored, the current property will not be included in queries. - /// - public bool Ignored { get; private set; } - - /// - /// Gets the read-only status of the current property. If read-only, the current property will not be included in INSERT and UPDATE queries. - /// - public bool IsReadOnly { get; private set; } - - /// - /// Gets the property info for the current property. - /// - public PropertyInfo PropertyInfo { get; private set; } - - /// - /// Fluently sets the column name for the property. - /// - /// The column name as it exists in the database. - public PropertyMap Column(string columnName) - { - ColumnName = columnName; - return this; - } - - /// - /// Fluently sets the key type of the property. - /// - /// The column name as it exists in the database. - public PropertyMap Key(KeyType keyType) - { - if (Ignored) - { - throw new ArgumentException(string.Format("'{0}' is ignored and cannot be made a key field. ", Name)); - } - - if (IsReadOnly) - { - throw new ArgumentException(string.Format("'{0}' is readonly and cannot be made a key field. ", Name)); - } - - KeyType = keyType; - return this; - } - - /// - /// Fluently sets the ignore status of the property. - /// - public PropertyMap Ignore() - { - if (KeyType != KeyType.NotAKey) - { - throw new ArgumentException(string.Format("'{0}' is a key field and cannot be ignored.", Name)); - } - - Ignored = true; - return this; - } - - /// - /// Fluently sets the read-only status of the property. - /// - public PropertyMap ReadOnly() - { - if (KeyType != KeyType.NotAKey) - { - throw new ArgumentException(string.Format("'{0}' is a key field and cannot be marked readonly.", Name)); - } - - IsReadOnly = true; - return this; - } - } - - /// - /// Used by ClassMapper to determine which entity property represents the key. - /// - public enum KeyType - { - /// - /// The property is not a key and is not automatically managed. - /// - NotAKey, - - /// - /// The property is an integery-based identity generated from the database. - /// - Identity, - - /// - /// The property is an identity generated by the database trigger. - /// - TriggerIdentity, - - /// - /// The property is a Guid identity which is automatically managed. - /// - Guid, - - /// - /// The property is a key that is not automatically managed. - /// - Assigned - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Page.cs b/samples/Common/Repository.Dapper.Core/Page.cs deleted file mode 100644 index 4788c368d..000000000 --- a/samples/Common/Repository.Dapper.Core/Page.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Repository.Dapper.Core -{ - public class Page - { - - /// - /// Ŀ - /// - public long TotalItems { get; set; } - - /// - /// ÿҳĿ - /// - public long ItemsPerPage { get; set; } - - /// - /// ǰҳ - /// - public long CurrentPage { get; set; } - - public IEnumerable Items { get; set; } - - /// - /// ҳ - /// - public long TotalPages - { - get { return (long)Math.Ceiling((decimal)TotalItems / ItemsPerPage); } - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Predicates.cs b/samples/Common/Repository.Dapper.Core/Predicates.cs deleted file mode 100644 index be96f22eb..000000000 --- a/samples/Common/Repository.Dapper.Core/Predicates.cs +++ /dev/null @@ -1,732 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Text; -using Repository.Dapper.Core.Mapper; -using Repository.Dapper.Core.Sql; - -namespace Repository.Dapper.Core -{ - public static class Predicates - { - /// - /// 创建条件 - /// Factory method that creates a new IFieldPredicate predicate: [FieldName] [Operator] [Value]. - /// Example: WHERE FirstName = 'Foo' - /// - /// The type of the entity. - /// An expression that returns the left operand [FieldName]. - /// The comparison operator. - /// The value for the predicate. - /// Effectively inverts the comparison operator. Example: WHERE FirstName <> 'Foo'. - /// An instance of IFieldPredicate. - public static IFieldPredicate Field(Expression> expression, Operator op, object value, string tableName = null, string schemaName = null, bool not = false) where T : class - { - PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; - return new FieldPredicate - { - PropertyName = propertyInfo.Name, - Operator = op, - Value = value, - Not = not, - SchemaName = schemaName, - TableName = tableName - }; - } - - public static IFieldPredicate Field(Type type,string PropertyName, Operator op, object value, string tableName = null, string schemaName = null, bool not = false) - { - PropertyInfo propertyInfo = type.GetProperties().Where(w => w.Name == PropertyName).First(); - return new FieldPredicate - { - FieldType = type, - PropertyName = propertyInfo.Name, - Operator = op, - Value = value, - Not = not, - SchemaName = schemaName, - TableName = tableName - }; - } - - /// - /// Factory method that creates a new IPropertyPredicate predicate: [FieldName1] [Operator] [FieldName2] - /// Example: WHERE FirstName = LastName - /// - /// The type of the entity for the left operand. - /// The type of the entity for the right operand. - /// An expression that returns the left operand [FieldName1]. - /// The comparison operator. - /// An expression that returns the right operand [FieldName2]. - /// Effectively inverts the comparison operator. Example: WHERE FirstName <> LastName - /// An instance of IPropertyPredicate. - public static IPropertyPredicate Property(Expression> expression, Operator op, Expression> expression2, string tableName = null, string tableName2 = null, string schemaName = null, string schemaName2 = null, bool not = false) - where T : class - where T2 : class - { - PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; - PropertyInfo propertyInfo2 = ReflectionHelper.GetProperty(expression2) as PropertyInfo; - return new PropertyPredicate - { - SchemaName = schemaName, - TableName = tableName, - SchemaName2 = schemaName2, - TableName2 = tableName2, - PropertyName = propertyInfo.Name, - PropertyName2 = propertyInfo2.Name, - Operator = op, - Not = not - }; - } - - /// - /// 关联查询列表重复设置 - /// - /// - /// - /// - /// - /// - public static IJoinAliasPredicate JoinAlia(Expression> expression, Expression> expression2) - where T : class - where T2 : class - { - PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; - PropertyInfo propertyInfo2 = ReflectionHelper.GetProperty(expression2) as PropertyInfo; - return new JoinAliasPredicate - { - PropertyName = propertyInfo.Name, - PropertyName2 = propertyInfo2.Name - }; - } - - /// - /// 设置关联查询 - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static IJoinPredicate Join(Expression> expression, Operator op, Expression> expression2, JoinOperator join = JoinOperator.Inner, string tableName = null, string tableName2 = null, string schemaName = null, string schemaName2 = null, bool not = false) - where T : class - where T2 : class - { - PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; - PropertyInfo propertyInfo2 = ReflectionHelper.GetProperty(expression2) as PropertyInfo; - return new JoinPredicate - { - SchemaName = schemaName, - TableName = tableName, - SchemaName2 = schemaName2, - TableName2 = tableName2, - Join = join, - PropertyName = propertyInfo.Name, - PropertyName2 = propertyInfo2.Name, - Operator = op, - Not = not - }; - } - - /// - /// Factory method that creates a new IPredicateGroup predicate. - /// Predicate groups can be joined together with other predicate groups. - /// - /// The grouping operator to use when joining the predicates (AND / OR). - /// A list of predicates to group. - /// An instance of IPredicateGroup. - public static IPredicateGroup Group(GroupOperator op, params IPredicate[] predicate) - { - return new PredicateGroup - { - Operator = op, - Predicates = predicate - }; - } - - /// - /// Factory method that creates a new IExistsPredicate predicate. - /// - public static IExistsPredicate Exists(IPredicate predicate, bool not = false) - where TSub : class - { - return new ExistsPredicate - { - Not = not, - Predicate = predicate - }; - } - - /// - /// Factory method that creates a new IBetweenPredicate predicate. - /// - public static IBetweenPredicate Between(Expression> expression, BetweenValues values, string tableName = null, string schemaName = null, bool not = false) - where T : class - { - PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; - return new BetweenPredicate - { - Not = not, - PropertyName = propertyInfo.Name, - Value = values, - SchemaName = schemaName, - TableName = tableName - }; - } - - /// - /// Factory method that creates a new Sort which controls how the results will be sorted. - /// - public static ISort Sort(Expression> expression, bool ascending = true, string tableName = null, string schemaName = null) - { - PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; - return new Sort - { - PropertyName = propertyInfo.Name, - Ascending = ascending, - SchemaName = schemaName, - TableName = tableName - }; - } - } - - /// - /// 条件 - /// - public interface IPredicate - { - /// - /// 返回条件的类 - /// - /// - Type GetPredicateType(); - - /// - /// 返回条件的sql - /// - /// - /// - /// - /// - /// - string GetSql(bool prefix, ISqlGenerator sqlGenerator, IDictionary parameters, string schemaName, string tableName); - } - - /// - /// 基本条件 - /// - public interface IBasePredicate : IPredicate - { - /// - /// 前缀 - /// - string SchemaName { get; set; } - /// - /// 表名 - /// - string TableName { get; set; } - - /// - /// 条件属性 - /// - string PropertyName { get; set; } - - } - - /// - /// 基本条件 - /// - public abstract class BasePredicate : IBasePredicate - { - public abstract Type GetPredicateType(); - - /// - /// 返回sql - /// - /// - /// - /// - /// - /// - public abstract string GetSql(bool prefix, ISqlGenerator sqlGenerator, IDictionary parameters, string schemaName, string tableName); - /// - /// 条件属性 - /// - public string PropertyName { get; set; } - /// - /// 前缀 - /// - public string SchemaName { get; set; } - /// - /// 表名 - /// - public string TableName { get; set; } - - /// - /// 返回列名 - /// - /// - /// - /// - /// - /// - /// - protected virtual string GetColumnName(bool prefix, Type entityType, ISqlGenerator sqlGenerator, string propertyName, string schemaName, string tableName) - { - IClassMapper map = GetMapper(entityType, sqlGenerator); - if (map == null) - { - throw new NullReferenceException(string.Format("Map was not found for {0}", entityType)); - } - - IPropertyMap propertyMap = map.Properties.SingleOrDefault(p => p.Name == propertyName); - if (propertyMap == null) - { - throw new NullReferenceException(string.Format("{0} was not found for {1}", propertyName, entityType)); - } - return sqlGenerator.GetColumnName(prefix,map, propertyMap, false, schemaName, tableName); - } - - protected virtual IClassMapper GetMapper(Type entityType, ISqlGenerator sqlGenerator) - { - return sqlGenerator.Configuration.GetMap(entityType); - } - } - - /// - /// 比较条件 - /// - public interface IComparePredicate : IBasePredicate - { - /// - /// 操作符 - /// - Operator Operator { get; set; } - /// - /// 操作符取反 - /// - bool Not { get; set; } - } - - public abstract class ComparePredicate : BasePredicate - { - public Operator Operator { get; set; } - public bool Not { get; set; } - - public virtual string GetOperatorString(ISqlGenerator sqlGenerator) => sqlGenerator.GetOperatorString(Operator, Not); - } - - public interface IFieldPredicate : IComparePredicate - { - object Value { get; set; } - } - - public class FieldPredicate : ComparePredicate, IFieldPredicate - where T : class - { - public override Type GetPredicateType() - { - return typeof(T); - } - public object Value { get; set; } - - public override string GetSql(bool prefix, ISqlGenerator sqlGenerator, IDictionary parameters, string schemaName, string tableName) - { - string columnName = GetColumnName(prefix,typeof(T), sqlGenerator, PropertyName, SchemaName ?? schemaName, TableName ?? tableName); - if (Value == null) - { - return string.Format("({0} IS {1}NULL)", columnName, Not ? "NOT " : string.Empty); - } - - if (Value is IEnumerable && !(Value is string)) - { - if (Operator != Operator.Eq) - { - throw new ArgumentException("Operator must be set to Eq for Enumerable types"); - } - - List @params = new List(); - foreach (var value in (IEnumerable)Value) - { - string valueParameterName = parameters.SetParameterName(this.PropertyName, value, sqlGenerator.Configuration.Dialect.ParameterPrefix); - @params.Add(valueParameterName); - } - - string paramStrings = @params.Aggregate(new StringBuilder(), (sb, s) => sb.Append((sb.Length != 0 ? ", " : string.Empty) + s), sb => sb.ToString()); - return string.Format("({0} {1}IN ({2}))", columnName, Not ? "NOT " : string.Empty, paramStrings); - } - - string parameterName = parameters.SetParameterName(this.PropertyName, this.Value, sqlGenerator.Configuration.Dialect.ParameterPrefix); - return string.Format("({0} {1} {2})", columnName, GetOperatorString(sqlGenerator), parameterName); - } - } - - public class FieldPredicate : ComparePredicate, IFieldPredicate - { - public override Type GetPredicateType() - { - return FieldType; - } - public Type FieldType { get; set; } - - public object Value { get; set; } - - public override string GetSql(bool prefix, ISqlGenerator sqlGenerator, IDictionary parameters, string schemaName, string tableName) - { - string columnName = GetColumnName(prefix,FieldType, sqlGenerator, PropertyName, SchemaName ?? schemaName, TableName ?? tableName); - if (Value == null) - { - return string.Format("({0} IS {1}NULL)", columnName, Not ? "NOT " : string.Empty); - } - - if (Value is IEnumerable && !(Value is string)) - { - if (Operator != Operator.Eq) - { - throw new ArgumentException("Operator must be set to Eq for Enumerable types"); - } - - List @params = new List(); - foreach (var value in (IEnumerable)Value) - { - string valueParameterName = parameters.SetParameterName(this.PropertyName, value, sqlGenerator.Configuration.Dialect.ParameterPrefix); - @params.Add(valueParameterName); - } - - string paramStrings = @params.Aggregate(new StringBuilder(), (sb, s) => sb.Append((sb.Length != 0 ? ", " : string.Empty) + s), sb => sb.ToString()); - return string.Format("({0} {1}IN ({2}))", columnName, Not ? "NOT " : string.Empty, paramStrings); - } - - string parameterName = parameters.SetParameterName(this.PropertyName, this.Value, sqlGenerator.Configuration.Dialect.ParameterPrefix); - return string.Format("({0} {1} {2})", columnName, GetOperatorString(sqlGenerator), parameterName); - } - } - - public interface IJoinPredicate : IComparePredicate - { - - string SchemaName2 { get; set; } - string TableName2 { get; set; } - string PropertyName2 { get; set; } - JoinOperator Join { get; set; } - IClassMapper GetLeftMapper(ISqlGenerator sqlGenerator); - IClassMapper GetRightMapper(ISqlGenerator sqlGenerator); - } - - public class JoinPredicate : ComparePredicate, IJoinPredicate - where T : class - where T2 : class - { - public override Type GetPredicateType() - { - return typeof(T); - } - public string PropertyName2 { get; set; } - - public JoinOperator Join { get; set; } - - public string SchemaName2 { get; set; } - public string TableName2 { get; set; } - - public IClassMapper GetLeftMapper(ISqlGenerator sqlGenerator) - { - return GetMapper(typeof(T), sqlGenerator); - } - - public IClassMapper GetRightMapper(ISqlGenerator sqlGenerator) - { - return GetMapper(typeof(T2), sqlGenerator); - } - - public override string GetSql(bool prefix, ISqlGenerator sqlGenerator, IDictionary parameters, string schemaName, string tableName) - { - string righttable = sqlGenerator.GetTableName(GetRightMapper(sqlGenerator), SchemaName2, TableName2); - string columnName = GetColumnName(true,typeof(T), sqlGenerator, PropertyName, SchemaName ?? schemaName, TableName ?? tableName); - string columnName2 = GetColumnName(true,typeof(T2), sqlGenerator, PropertyName2, SchemaName2, TableName2); - string vjoin = Join == JoinOperator.Full ? "full join" : Join == JoinOperator.Left ? "left join" : Join == JoinOperator.Right ? "right join" : "inner join"; - return $" {vjoin} {righttable} on {columnName} {GetOperatorString(sqlGenerator)} {columnName2}"; - } - } - - public interface IJoinAliasPredicate : IComparePredicate - { - string PropertyName2 { get; set; } - - IClassMapper GetRightMapper(ISqlGenerator sqlGenerator); - IPropertyMap GetPropertyMap(ISqlGenerator sqlGenerator); - } - public class JoinAliasPredicate : ComparePredicate, IJoinAliasPredicate - where T : class - where T2 : class - { - public override Type GetPredicateType() - { - return typeof(T); - } - public string PropertyName2 { get; set; } - - public IClassMapper GetRightMapper(ISqlGenerator sqlGenerator) - { - return GetMapper(typeof(T2), sqlGenerator); - } - - public IPropertyMap GetPropertyMap(ISqlGenerator sqlGenerator) - { - var rightMap = GetRightMapper(sqlGenerator); - var property = rightMap.Properties.Where(w => w.Name.Equals(PropertyName2)).First(); - return property; - } - - public override string GetSql(bool prefix, ISqlGenerator sqlGenerator, IDictionary parameters, string schemaName, string tableName) - { - return string.Empty; - } - } - - public interface IPropertyPredicate : IComparePredicate - { - string SchemaName2 { get; set; } - string TableName2 { get; set; } - string PropertyName2 { get; set; } - } - - - public class PropertyPredicate : ComparePredicate, IPropertyPredicate - where T : class - where T2 : class - { - public override Type GetPredicateType() - { - return typeof(T); - } - public string PropertyName2 { get; set; } - public string SchemaName2 { get; set; } - public string TableName2 { get; set; } - - public override string GetSql(bool prefix, ISqlGenerator sqlGenerator, IDictionary parameters, string schemaName, string tableName) - { - string columnName = GetColumnName(prefix,typeof(T), sqlGenerator, PropertyName, SchemaName ?? schemaName, TableName ?? tableName); - string columnName2 = GetColumnName(prefix, typeof(T2), sqlGenerator, PropertyName2, schemaName, tableName); - return string.Format("({0} {1} {2})", columnName, GetOperatorString(sqlGenerator), columnName2); - } - } - - public struct BetweenValues - { - public object Value1 { get; set; } - public object Value2 { get; set; } - } - - public interface IBetweenPredicate : IPredicate - { - string PropertyName { get; set; } - BetweenValues Value { get; set; } - bool Not { get; set; } - - } - - public class BetweenPredicate : BasePredicate, IBetweenPredicate - where T : class - { - public override Type GetPredicateType() - { - return typeof(T); - } - public override string GetSql(bool prefix, ISqlGenerator sqlGenerator, IDictionary parameters, string schemaName, string tableName) - { - string columnName = GetColumnName(prefix, typeof(T), sqlGenerator, PropertyName, SchemaName ?? schemaName, TableName ?? tableName); - string propertyName1 = parameters.SetParameterName(this.PropertyName, this.Value.Value1, sqlGenerator.Configuration.Dialect.ParameterPrefix); - string propertyName2 = parameters.SetParameterName(this.PropertyName, this.Value.Value2, sqlGenerator.Configuration.Dialect.ParameterPrefix); - return string.Format("({0} {1}BETWEEN {2} AND {3})", columnName, Not ? "NOT " : string.Empty, propertyName1, propertyName2); - } - - public BetweenValues Value { get; set; } - - public bool Not { get; set; } - } - - /// - /// Comparison operator for predicates. - /// - public enum Operator - { - /// - /// Equal to = - /// - Eq, - - /// - /// Greater than > - /// - Gt, - - /// - /// Greater than or equal to >= - /// - Ge, - - /// - /// Less than < - /// - Lt, - - /// - /// Less than or equal to <= - /// - Le, - - /// - /// Like (You can use % in the value to do wilcard searching) - /// - Like - } - - public interface IPredicateGroup : IPredicate - { - GroupOperator Operator { get; set; } - IList Predicates { get; set; } - } - - /// - /// Groups IPredicates together using the specified group operator. - /// - public class PredicateGroup : IPredicateGroup - { - public Type GetPredicateType() - { - return null; - } - public GroupOperator Operator { get; set; } - public IList Predicates { get; set; } - public string GetSql(bool prefix, ISqlGenerator sqlGenerator, IDictionary parameters, string schemaName, string tableName) - { - string seperator = Operator == GroupOperator.And ? " AND " : " OR "; - return "(" + Predicates.Aggregate(new StringBuilder(), - (sb, p) => (sb.Length == 0 ? sb : sb.Append(seperator)).Append(p.GetSql(prefix, sqlGenerator, parameters, schemaName, tableName)), - sb => - { - var s = sb.ToString(); - if (s.Length == 0) return sqlGenerator.Configuration.Dialect.EmptyExpression; - return s; - } - ) + ")"; - } - } - - public interface IExistsPredicate : IPredicate - { - IPredicate Predicate { get; set; } - bool Not { get; set; } - } - - public class ExistsPredicate : IExistsPredicate - where TSub : class - { - public Type GetPredicateType() - { - return typeof(TSub); - } - public IPredicate Predicate { get; set; } - public bool Not { get; set; } - - public string GetSql(bool prefix, ISqlGenerator sqlGenerator, IDictionary parameters, string schemaName, string tableName) - { - IClassMapper mapSub = sqlGenerator.Configuration.GetMap(typeof(TSub)); - string sql = string.Format("({0}EXISTS (SELECT 1 FROM {1} WHERE {2}))", - Not ? "NOT " : string.Empty, - sqlGenerator.GetTableName(mapSub, schemaName, tableName), - Predicate.GetSql(prefix, sqlGenerator, parameters, schemaName, tableName)); - return sql; - } - } - - public interface ISort - { - string SchemaName { get; set; } - /// - /// 表名 - /// - string TableName { get; set; } - string PropertyName { get; set; } - bool Ascending { get; set; } - string GetSql(bool prefix, ISqlGenerator sqlGenerator, string schemaName, string tableName); - } - - public class Sort : ISort - { - /// - /// 前缀 - /// - public string SchemaName { get; set; } - /// - /// 表名 - /// - public string TableName { get; set; } - public string PropertyName { get; set; } - public bool Ascending { get; set; } - - public string GetSql(bool prefix, ISqlGenerator sqlGenerator, string schemaName, string tableName) - { - return sqlGenerator.GetColumnName(prefix,sqlGenerator.Configuration.GetMap(typeof(T)), PropertyName, false, SchemaName ?? schemaName, TableName ?? tableName) + (Ascending ? " ASC" : " DESC"); - } - } - internal class SortKey : ISort - { - private IClassMapper classMapper { get; set; } - public SortKey(IClassMapper classMapper) - { - this.classMapper = classMapper; - } - - /// - /// 前缀 - /// - public string SchemaName { get; set; } - /// - /// 表名 - /// - public string TableName { get; set; } - public string PropertyName { get; set; } - public bool Ascending { get; set; } - - public string GetSql(bool prefix, ISqlGenerator sqlGenerator, string schemaName, string tableName) - { - return sqlGenerator.GetColumnName(prefix,classMapper, PropertyName, false, SchemaName ?? schemaName, TableName ?? tableName) + (Ascending ? " ASC" : " DESC"); - } - } - - /// - /// 在条件组中的操作符 Operator to use when joining predicates in a PredicateGroup. - /// - public enum GroupOperator - { - And, - Or - } - - public enum JoinOperator - { - /// - /// 内关联 - /// - Inner, - /// - /// 左关联 - /// - Left, - /// - /// 右关联 - /// - Right, - /// - /// 全关联 - /// - Full - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/ReflectionHelper.cs b/samples/Common/Repository.Dapper.Core/ReflectionHelper.cs deleted file mode 100644 index ab21ff211..000000000 --- a/samples/Common/Repository.Dapper.Core/ReflectionHelper.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Text; - -namespace Repository.Dapper.Core -{ - public static class ReflectionHelper - { - private static List _simpleTypes = new List - { - typeof(byte), - typeof(sbyte), - typeof(short), - typeof(ushort), - typeof(int), - typeof(uint), - typeof(long), - typeof(ulong), - typeof(float), - typeof(double), - typeof(decimal), - typeof(bool), - typeof(string), - typeof(char), - typeof(Guid), - typeof(DateTime), - typeof(DateTimeOffset), - typeof(byte[]) - }; - - public static MemberInfo GetProperty(LambdaExpression lambda) - { - Expression expr = lambda; - for (; ; ) - { - switch (expr.NodeType) - { - case ExpressionType.Lambda: - expr = ((LambdaExpression)expr).Body; - break; - case ExpressionType.Convert: - expr = ((UnaryExpression)expr).Operand; - break; - case ExpressionType.MemberAccess: - MemberExpression memberExpression = (MemberExpression)expr; - MemberInfo mi = memberExpression.Member; - return mi; - default: - return null; - } - } - } - - public static IDictionary GetObjectValues(object obj) - { - IDictionary result = new Dictionary(); - if (obj == null) - { - return result; - } - if (obj is IDictionary) - return obj as IDictionary; - - foreach (var propertyInfo in obj.GetType().GetProperties()) - { - string name = propertyInfo.Name; - object value = propertyInfo.GetValue(obj, null); - result[name] = value; - } - - return result; - } - - public static string AppendStrings(this IEnumerable list, string seperator = ", ") - { - return list.Aggregate( - new StringBuilder(), - (sb, s) => (sb.Length == 0 ? sb : sb.Append(seperator)).Append(s), - sb => sb.ToString()); - } - - public static bool IsSimpleType(Type type) - { - Type actualType = type; - if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) - { - actualType = type.GetGenericArguments()[0]; - } - - return _simpleTypes.Contains(actualType); - } - - public static string GetParameterName(this IDictionary parameters, string parameterName, char parameterPrefix) - { - return string.Format("{0}{1}_{2}", parameterPrefix, parameterName, parameters.Count); - } - - public static string SetParameterName(this IDictionary parameters, string parameterName, object value, char parameterPrefix) - { - string name = parameters.GetParameterName(parameterName, parameterPrefix); - parameters.Add(name, value); - return name; - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Repository.Dapper.Core.csproj b/samples/Common/Repository.Dapper.Core/Repository.Dapper.Core.csproj deleted file mode 100644 index fac8c0a0b..000000000 --- a/samples/Common/Repository.Dapper.Core/Repository.Dapper.Core.csproj +++ /dev/null @@ -1,34 +0,0 @@ - - - - - DapperExtensions - Xakep - netstandard2.0 - DapperExtensions - Xakep.DapperExtensions - 1.6.2.91 - true - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Common/Repository.Dapper.Core/Sql/DB2Dialect.cs b/samples/Common/Repository.Dapper.Core/Sql/DB2Dialect.cs deleted file mode 100644 index 836960bbd..000000000 --- a/samples/Common/Repository.Dapper.Core/Sql/DB2Dialect.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Repository.Dapper.Core.Sql -{ - public class DB2Dialect : SqlDialectBase - { - public override string GetIdentitySql(string tableName) - { - return "SELECT CAST(IDENTITY_VAL_LOCAL() AS BIGINT) AS \"ID\" FROM SYSIBM.SYSDUMMY1"; - } - - public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) - { - var startValue = ((page - 1) * resultsPerPage) + 1; - var endValue = (page * resultsPerPage); - return GetSetSql(sql, startValue, endValue, parameters); - } - - public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) - { - if (string.IsNullOrEmpty(sql)) - { - throw new ArgumentNullException("SQL"); - } - - if (parameters == null) - { - throw new ArgumentNullException("Parameters"); - } - - int selectIndex = GetSelectEnd(sql) + 1; - string orderByClause = GetOrderByClause(sql); - if (orderByClause == null) - { - orderByClause = "ORDER BY CURRENT_TIMESTAMP"; - } - - - string projectedColumns = GetColumnNames(sql).Aggregate(new StringBuilder(), (sb, s) => (sb.Length == 0 ? sb : sb.Append(", ")).Append(GetColumnName("_TEMP", s, null)), sb => sb.ToString()); - string newSql = sql - .Replace(" " + orderByClause, string.Empty) - .Insert(selectIndex, string.Format("ROW_NUMBER() OVER(ORDER BY {0}) AS {1}, ", orderByClause.Substring(9), GetColumnName(null, "_ROW_NUMBER", null))); - - string result = string.Format("SELECT {0} FROM ({1}) AS \"_TEMP\" WHERE {2} BETWEEN @_pageStartRow AND @_pageEndRow", - projectedColumns.Trim(), newSql, GetColumnName("_TEMP", "_ROW_NUMBER", null)); - - parameters.Add("@_pageStartRow", firstResult); - parameters.Add("@_pageEndRow", maxResults); - return result; - } - - protected string GetOrderByClause(string sql) - { - int orderByIndex = sql.LastIndexOf(" ORDER BY ", StringComparison.InvariantCultureIgnoreCase); - if (orderByIndex == -1) - { - return null; - } - - string result = sql.Substring(orderByIndex).Trim(); - - int whereIndex = result.IndexOf(" WHERE ", StringComparison.InvariantCultureIgnoreCase); - if (whereIndex == -1) - { - return result; - } - - return result.Substring(0, whereIndex).Trim(); - } - - protected int GetFromStart(string sql) - { - int selectCount = 0; - string[] words = sql.Split(' '); - int fromIndex = 0; - foreach (var word in words) - { - if (word.Equals("SELECT", StringComparison.InvariantCultureIgnoreCase)) - { - selectCount++; - } - - if (word.Equals("FROM", StringComparison.InvariantCultureIgnoreCase)) - { - selectCount--; - if (selectCount == 0) - { - break; - } - } - - fromIndex += word.Length + 1; - } - - return fromIndex; - } - - protected virtual int GetSelectEnd(string sql) - { - if (sql.StartsWith("SELECT DISTINCT", StringComparison.InvariantCultureIgnoreCase)) - { - return 15; - } - - if (sql.StartsWith("SELECT", StringComparison.InvariantCultureIgnoreCase)) - { - return 6; - } - - throw new ArgumentException("SQL must be a SELECT statement.", "sql"); - } - - protected virtual IList GetColumnNames(string sql) - { - int start = GetSelectEnd(sql); - int stop = GetFromStart(sql); - string[] columnSql = sql.Substring(start, stop - start).Split(','); - List result = new List(); - foreach (string c in columnSql) - { - int index = c.IndexOf(" AS ", StringComparison.InvariantCultureIgnoreCase); - if (index > 0) - { - result.Add(c.Substring(index + 4).Trim()); - continue; - } - - string[] colParts = c.Split('.'); - result.Add(colParts[colParts.Length - 1].Trim()); - } - - return result; - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Sql/MySqlDialect.cs b/samples/Common/Repository.Dapper.Core/Sql/MySqlDialect.cs deleted file mode 100644 index a8adde9b5..000000000 --- a/samples/Common/Repository.Dapper.Core/Sql/MySqlDialect.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Repository.Dapper.Core.Sql -{ - public class MySqlDialect : SqlDialectBase - { - public override char OpenQuote - { - get { return '`'; } - } - - public override char CloseQuote - { - get { return '`'; } - } - - public override string GetIdentitySql(string tableName) - { - return "SELECT CONVERT(LAST_INSERT_ID(), SIGNED INTEGER) AS ID"; - } - - public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) - { - int startValue = page * resultsPerPage; - return GetSetSql(sql, startValue, resultsPerPage, parameters); - } - - public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) - { - string result = string.Format("{0} LIMIT @firstResult, @maxResults", sql); - parameters.Add("@firstResult", firstResult); - parameters.Add("@maxResults", maxResults); - return result; - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Sql/OracleDialect.cs b/samples/Common/Repository.Dapper.Core/Sql/OracleDialect.cs deleted file mode 100644 index 336cf7720..000000000 --- a/samples/Common/Repository.Dapper.Core/Sql/OracleDialect.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.Collections.Generic; -using System.Text; - -namespace Repository.Dapper.Core.Sql -{ - public class OracleDialect : SqlDialectBase - { - public OracleDialect() { } - - public override string GetIdentitySql(string tableName) - { - throw new System.NotImplementedException("Oracle does not support get last inserted identity."); - } - - public override bool SupportsMultipleStatements - { - get { return false; } - } - - //from Simple.Data.Oracle implementation https://github.com/flq/Simple.Data.Oracle/blob/master/Simple.Data.Oracle/OraclePager.cs - public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) - { - var toSkip = page * resultsPerPage; - var topLimit = (page + 1) * resultsPerPage; - - var sb = new StringBuilder(); - sb.AppendLine("SELECT * FROM ("); - sb.AppendLine("SELECT \"_ss_dapper_1_\".*, ROWNUM RNUM FROM ("); - sb.Append(sql); - sb.AppendLine(") \"_ss_dapper_1_\""); - sb.AppendLine("WHERE ROWNUM <= :topLimit) \"_ss_dapper_2_\" "); - sb.AppendLine("WHERE \"_ss_dapper_2_\".RNUM > :toSkip"); - - parameters.Add(":topLimit", topLimit); - parameters.Add(":toSkip", toSkip); - - return sb.ToString(); - } - - public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) - { - var sb = new StringBuilder(); - sb.AppendLine("SELECT * FROM ("); - sb.AppendLine("SELECT \"_ss_dapper_1_\".*, ROWNUM RNUM FROM ("); - sb.Append(sql); - sb.AppendLine(") \"_ss_dapper_1_\""); - sb.AppendLine("WHERE ROWNUM <= :topLimit) \"_ss_dapper_2_\" "); - sb.AppendLine("WHERE \"_ss_dapper_2_\".RNUM > :toSkip"); - - parameters.Add(":topLimit", maxResults + firstResult); - parameters.Add(":toSkip", firstResult); - - return sb.ToString(); - } - - public override string QuoteString(string value) - { - if (value != null && value[0]=='`') - { - return string.Format("{0}{1}{2}", OpenQuote, value.Substring(1, value.Length - 2), CloseQuote); - } - return value.ToUpper(); - } - - public override char ParameterPrefix - { - get { return ':'; } - } - - public override char OpenQuote - { - get { return '"'; } - } - - public override char CloseQuote - { - get { return '"'; } - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Sql/PostgreSqlDialect.cs b/samples/Common/Repository.Dapper.Core/Sql/PostgreSqlDialect.cs deleted file mode 100644 index 9af35d41d..000000000 --- a/samples/Common/Repository.Dapper.Core/Sql/PostgreSqlDialect.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Repository.Dapper.Core.Sql -{ - public class PostgreSqlDialect : SqlDialectBase - { - public override string GetIdentitySql(string tableName) - { - return "SELECT LASTVAL() AS Id"; - } - - public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) - { - int startValue = (page-1) * resultsPerPage; - return GetSetSql(sql, startValue < 0 ? 0 : startValue, resultsPerPage, parameters); - } - - public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) - { - string result = string.Format("{0} LIMIT @maxResults OFFSET @pageStartRowNbr", sql); - parameters.Add("@maxResults", maxResults); - parameters.Add("@pageStartRowNbr", firstResult); - return result; - } - - public override string GetColumnName(string prefix, string columnName, string alias) - { - return base.GetColumnName(prefix, columnName, alias);//.ToLower(); - } - - public override string GetTableName(string schemaName, string tableName, string alias) - { - return base.GetTableName(schemaName, tableName, alias);//.ToLower(); - } - public override string GetOperatorString(Operator Operator, bool Not) - { - switch (Operator) - { - case Operator.Gt: - return Not ? "<=" : ">"; - case Operator.Ge: - return Not ? "<" : ">="; - case Operator.Lt: - return Not ? ">=" : "<"; - case Operator.Le: - return Not ? ">" : "<="; - case Operator.Like: - return Not ? "NOT ILIKE" : "ILIKE"; - default: - return Not ? "<>" : "="; - } - } - } - -} diff --git a/samples/Common/Repository.Dapper.Core/Sql/SqlCeDialect.cs b/samples/Common/Repository.Dapper.Core/Sql/SqlCeDialect.cs deleted file mode 100644 index e5a74145a..000000000 --- a/samples/Common/Repository.Dapper.Core/Sql/SqlCeDialect.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Repository.Dapper.Core.Sql -{ - public class SqlCeDialect : SqlDialectBase - { - public override char OpenQuote - { - get { return '['; } - } - - public override char CloseQuote - { - get { return ']'; } - } - - public override bool SupportsMultipleStatements - { - get { return false; } - } - - public override string GetTableName(string schemaName, string tableName, string alias) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentNullException("TableName"); - } - - StringBuilder result = new StringBuilder(); - result.Append(OpenQuote); - if (!string.IsNullOrWhiteSpace(schemaName)) - { - result.AppendFormat("{0}_", schemaName); - } - - result.AppendFormat("{0}{1}", tableName, CloseQuote); - - - if (!string.IsNullOrWhiteSpace(alias)) - { - result.AppendFormat(" AS {0}{1}{2}", OpenQuote, alias, CloseQuote); - } - - return result.ToString(); - } - - public override string GetIdentitySql(string tableName) - { - return "SELECT CAST(@@IDENTITY AS BIGINT) AS [Id]"; - } - - public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) - { - int startValue = (page * resultsPerPage); - return GetSetSql(sql, startValue, resultsPerPage, parameters); - } - - public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) - { - string result = string.Format("{0} OFFSET @firstResult ROWS FETCH NEXT @maxResults ROWS ONLY", sql); - parameters.Add("@firstResult", firstResult); - parameters.Add("@maxResults", maxResults); - return result; - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Sql/SqlDialectBase.cs b/samples/Common/Repository.Dapper.Core/Sql/SqlDialectBase.cs deleted file mode 100644 index 339111991..000000000 --- a/samples/Common/Repository.Dapper.Core/Sql/SqlDialectBase.cs +++ /dev/null @@ -1,156 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Repository.Dapper.Core.Sql -{ - public interface ISqlDialect - { - char OpenQuote { get; } - char CloseQuote { get; } - string BatchSeperator { get; } - bool SupportsMultipleStatements { get; } - char ParameterPrefix { get; } - string EmptyExpression { get; } - string GetTableName(string schemaName, string tableName, string alias); - string GetColumnName(string prefix, string columnName, string alias); - string GetIdentitySql(string tableName); - string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters); - string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters); - bool IsQuoted(string value); - string QuoteString(string value); - string GetOperatorString(Operator Operator, bool Not); - } - - public abstract class SqlDialectBase : ISqlDialect - { - public virtual char OpenQuote - { - get { return '"'; } - } - - public virtual char CloseQuote - { - get { return '"'; } - } - - public virtual string BatchSeperator - { - get { return ";" + Environment.NewLine; } - } - - public virtual bool SupportsMultipleStatements - { - get { return true; } - } - - public virtual char ParameterPrefix - { - get - { - return '@'; - } - } - - public string EmptyExpression - { - get - { - return "1=1"; - } - } - - public virtual string GetTableName(string schemaName, string tableName, string alias) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentNullException("TableName", "tableName cannot be null or empty."); - } - - StringBuilder result = new StringBuilder(); - if (!string.IsNullOrWhiteSpace(schemaName)) - { - result.AppendFormat(QuoteString(schemaName) + "."); - } - - result.AppendFormat(QuoteString(tableName)); - - if (!string.IsNullOrWhiteSpace(alias)) - { - result.AppendFormat(" AS {0}", QuoteString(alias)); - } - return result.ToString(); - } - - public virtual string GetColumnName(string prefix, string columnName, string alias) - { - if (string.IsNullOrWhiteSpace(columnName)) - { - throw new ArgumentNullException("ColumnName", "columnName cannot be null or empty."); - } - - StringBuilder result = new StringBuilder(); - if (!string.IsNullOrWhiteSpace(prefix)) - { - result.AppendFormat(QuoteString(prefix) + "."); - } - - result.AppendFormat(QuoteString(columnName)); - - if (!string.IsNullOrWhiteSpace(alias)) - { - result.AppendFormat(" AS {0}", QuoteString(alias)); - } - - return result.ToString(); - } - - public abstract string GetIdentitySql(string tableName); - public abstract string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters); - public abstract string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters); - - public virtual bool IsQuoted(string value) - { - if (value.Trim()[0] == OpenQuote) - { - return value.Trim().Last() == CloseQuote; - } - - return false; - } - - public virtual string QuoteString(string value) - { - if (IsQuoted(value) || value == "*") - { - return value; - } - return string.Format("{0}{1}{2}", OpenQuote, value.Trim(), CloseQuote); - } - - public virtual string UnQuoteString(string value) - { - return IsQuoted(value) ? value.Substring(1, value.Length - 2) : value; - } - - public virtual string GetOperatorString(Operator Operator, bool Not) - { - switch (Operator) - { - case Operator.Gt: - return Not ? "<=" : ">"; - case Operator.Ge: - return Not ? "<" : ">="; - case Operator.Lt: - return Not ? ">=" : "<"; - case Operator.Le: - return Not ? ">" : "<="; - case Operator.Like: - return Not ? "NOT LIKE" : "LIKE"; - default: - return Not ? "<>" : "="; - } - } - } -} diff --git a/samples/Common/Repository.Dapper.Core/Sql/SqlGenerator.cs b/samples/Common/Repository.Dapper.Core/Sql/SqlGenerator.cs deleted file mode 100644 index dfd5379e0..000000000 --- a/samples/Common/Repository.Dapper.Core/Sql/SqlGenerator.cs +++ /dev/null @@ -1,413 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Repository.Dapper.Core.Mapper; - -namespace Repository.Dapper.Core.Sql -{ - public interface ISqlGenerator - { - IDapperExtensionsConfiguration Configuration { get; } - - string Select(IClassMapper classMap, IPredicate predicate, IList sort, IDictionary parameters, string schemaName, string tableName, IList join=null, IList alias = null); - - string SelectPaged(IClassMapper classMap, IPredicate predicate, IList sort, int page, int resultsPerPage, IDictionary parameters, string schemaName, string tableName, IList join, IList alias); - string SelectSet(IClassMapper classMap, IPredicate predicate, IList sort, int firstResult, int maxResults, IDictionary parameters, string schemaName, string tableName, IList join, IList alias); - string Count(IClassMapper classMap, IPredicate predicate, IDictionary parameters, string schemaName, string tableName, IList join); - - string Insert(IClassMapper classMap, string schemaName, string tableName); - string Update(IClassMapper classMap, IPredicate predicate, IDictionary parameters, string schemaName, string tableName); - string UpdateSet(IClassMapper classMap,object entity, IPredicate predicate, IDictionary parameters, string schemaName, string tableName); - string Delete(IClassMapper classMap, IPredicate predicate, IDictionary parameters, string schemaName, string tableName); - - string IdentitySql(IClassMapper classMap, string schemaName, string tableName); - string GetTableName(IClassMapper map, string schemaName, string tableName, IList join = null); - string GetColumnName(bool prefix,IClassMapper map, IPropertyMap property, bool includeAlias, string schemaName, string tableName, string aliasName = null); - string GetColumnName(bool prefix, IClassMapper map, string propertyName, bool includeAlias, string schemaName, string tableName); - bool SupportsMultipleStatements(); - string GetOperatorString(Operator Operator, bool Not); - } - - public class SqlGeneratorImpl : ISqlGenerator - { - public SqlGeneratorImpl(IDapperExtensionsConfiguration configuration) - { - Configuration = configuration; - } - - public IDapperExtensionsConfiguration Configuration { get; private set; } - - public virtual string Select(IClassMapper classMap, IPredicate predicate, IList sort, IDictionary parameters, string schemaName, string tableName, IList join=null, IList alias=null) - { - if (parameters == null) - { - throw new ArgumentNullException("Parameters"); - } - - StringBuilder sql = new StringBuilder(string.Format("SELECT {0} FROM {1}", - BuildSelectColumns(classMap, schemaName, tableName,join,alias), - GetTableName(classMap, schemaName, tableName,join))); - - if (predicate != null) - { - sql.Append(" WHERE ") - .Append(predicate.GetSql(join!=null,this, parameters,schemaName,tableName)); - } - - if (sort != null && sort.Any()) - { - sql.Append(" ORDER BY ") - .Append(sort.Select(s => s.GetSql(join != null,this, schemaName,tableName)).AppendStrings()); - } - - return sql.ToString(); - } - - public virtual string SelectPaged(IClassMapper classMap, IPredicate predicate, IList sort, int page, int resultsPerPage, IDictionary parameters, string schemaName, string tableName, IList join, IList alias) - { - if (sort == null || !sort.Any()) - { - sort = classMap.Properties.Where(w => w.KeyType != KeyType.NotAKey).Select(w => (ISort)new SortKey(classMap) { PropertyName = w.Name, Ascending = true }).ToList(); - //throw new ArgumentNullException("Sort", "Sort cannot be null or empty."); - } - - if (parameters == null) - { - throw new ArgumentNullException("Parameters"); - } - - StringBuilder innerSql = new StringBuilder(string.Format("SELECT {0} FROM {1}", - BuildSelectColumns(classMap, schemaName, tableName,join,alias), - GetTableName(classMap, schemaName, tableName,join))); - if (predicate != null) - { - innerSql.Append(" WHERE ") - .Append(predicate.GetSql(join!=null,this, parameters,schemaName,tableName)); - } - - string orderBy = sort.Select(s => s.GetSql(join != null, this, schemaName, tableName)).AppendStrings(); - innerSql.Append(" ORDER BY " + orderBy); - - string sql = Configuration.Dialect.GetPagingSql(innerSql.ToString(), page, resultsPerPage, parameters); - return sql; - } - - public virtual string SelectSet(IClassMapper classMap, IPredicate predicate, IList sort, int firstResult, int maxResults, IDictionary parameters, string schemaName, string tableName, IList join, IList alias) - { - if (sort == null || !sort.Any()) - { - sort = classMap.Properties.Where(w => w.KeyType != KeyType.NotAKey).Select(w => (ISort)new SortKey(classMap) { PropertyName = w.Name, Ascending = true }).ToList(); - //throw new ArgumentNullException("Sort", "Sort cannot be null or empty."); - } - - if (parameters == null) - { - throw new ArgumentNullException("Parameters"); - } - - StringBuilder innerSql = new StringBuilder(string.Format("SELECT {0} FROM {1}", - BuildSelectColumns(classMap, schemaName, tableName,join,alias), - GetTableName(classMap, schemaName, tableName,join))); - if (predicate != null) - { - innerSql.Append(" WHERE ") - .Append(predicate.GetSql(join != null, this, parameters,schemaName,tableName)); - } - - string orderBy = sort.Select(s => s.GetSql(join != null, this, schemaName, tableName)).AppendStrings(); - innerSql.Append(" ORDER BY " + orderBy); - - string sql = Configuration.Dialect.GetSetSql(innerSql.ToString(), firstResult, maxResults, parameters); - return sql; - } - - - public virtual string Count(IClassMapper classMap, IPredicate predicate, IDictionary parameters, string schemaName, string tableName, IList join) - { - if (parameters == null) - { - throw new ArgumentNullException("Parameters"); - } - - StringBuilder sql = new StringBuilder(string.Format("SELECT COUNT(*) AS {0}Total{1} FROM {2}", - Configuration.Dialect.OpenQuote, - Configuration.Dialect.CloseQuote, - GetTableName(classMap, schemaName, tableName,join))); - if (predicate != null) - { - sql.Append(" WHERE ") - .Append(predicate.GetSql(join != null, this, parameters,schemaName,tableName)); - } - - return sql.ToString(); - } - - public virtual string Insert(IClassMapper classMap, string schemaName, string tableName) - { - var columns = classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity || p.KeyType == KeyType.TriggerIdentity)); - if (!columns.Any()) - { - throw new ArgumentException("No columns were mapped."); - } - - var columnNames = columns.Select(p => GetColumnName(false,classMap, p, false, schemaName, tableName)); - var parameters = columns.Select(p => Configuration.Dialect.ParameterPrefix + p.Name); - - string sql = string.Format("INSERT INTO {0} ({1}) VALUES ({2})", - GetTableName(classMap, schemaName, tableName), - columnNames.AppendStrings(), - parameters.AppendStrings()); - - var triggerIdentityColumn = classMap.Properties.Where(p => p.KeyType == KeyType.TriggerIdentity).ToList(); - - if (triggerIdentityColumn.Count > 0) - { - if (triggerIdentityColumn.Count > 1) - throw new ArgumentException("TriggerIdentity generator cannot be used with multi-column keys"); - - sql += string.Format(" RETURNING {0} INTO {1}IdOutParam", triggerIdentityColumn.Select(p => GetColumnName(false,classMap, p, false, schemaName, tableName)).First(), Configuration.Dialect.ParameterPrefix); - } - - return sql; - } - - public virtual string Update(IClassMapper classMap, IPredicate predicate, IDictionary parameters, string schemaName, string tableName) - { - if (predicate == null) - { - throw new ArgumentNullException("Predicate"); - } - - if (parameters == null) - { - throw new ArgumentNullException("Parameters"); - } - - var columns = classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity || p.KeyType == KeyType.Assigned)); - if (!columns.Any()) - { - throw new ArgumentException("No columns were mapped."); - } - - var setSql = - columns.Select( - p => - string.Format( - "{0} = {1}{2}", GetColumnName(false,classMap, p, false, schemaName, tableName), Configuration.Dialect.ParameterPrefix, p.Name)); - - return string.Format("UPDATE {0} SET {1} WHERE {2}", - GetTableName(classMap, schemaName, tableName), - setSql.AppendStrings(), - predicate.GetSql(false,this, parameters,schemaName,tableName)); - } - - public virtual string UpdateSet(IClassMapper classMap, object entity, IPredicate predicate, IDictionary parameters, string schemaName, string tableName) - { - if (predicate == null) - { - throw new ArgumentNullException("Predicate"); - } - - if (parameters == null) - { - throw new ArgumentNullException("Parameters"); - } - - var columns = classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity || p.KeyType == KeyType.Assigned)); - if (!columns.Any()) - { - throw new ArgumentException("No columns were mapped."); - } - var vColName = ReflectionHelper.GetObjectValues(entity).Select(w => w.Key); - var setSql = - columns.Where(w => vColName.Contains(w.Name)).Select( - p => - string.Format( - "{0} = {1}{2}", GetColumnName(false,classMap, p, false, schemaName, tableName), Configuration.Dialect.ParameterPrefix, p.Name)); - - return string.Format("UPDATE {0} SET {1} WHERE {2}", - GetTableName(classMap, schemaName, tableName), - setSql.AppendStrings(), - predicate.GetSql(false,this, parameters, schemaName, tableName)); - } - - public virtual string Delete(IClassMapper classMap, IPredicate predicate, IDictionary parameters, string schemaName, string tableName) - { - if (predicate == null) - { - throw new ArgumentNullException("Predicate"); - } - - if (parameters == null) - { - throw new ArgumentNullException("Parameters"); - } - - StringBuilder sql = new StringBuilder(string.Format("DELETE FROM {0}", GetTableName(classMap, schemaName, tableName))); - sql.Append(" WHERE ").Append(predicate.GetSql(false,this, parameters,schemaName,tableName)); - return sql.ToString(); - } - - public virtual string IdentitySql(IClassMapper classMap, string schemaName, string tableName) - { - return Configuration.Dialect.GetIdentitySql(GetTableName(classMap, schemaName, tableName)); - } - - public virtual string GetTableName(IClassMapper map, string schemaName, string tableName, IList join = null) - { - if (join != null && join.Count > 0) - { - var baseClassMap = join[0].GetLeftMapper(this); - var baseTable = GetTableName(baseClassMap, join[0].SchemaName, join[0].TableName); - return $"{baseTable} {string.Join(" ", join.Select(w => w.GetSql(join != null, this, null, null, null)))}"; - } - - schemaName = string.IsNullOrWhiteSpace(schemaName) ? map.SchemaName : schemaName; - tableName = string.IsNullOrWhiteSpace(tableName) ? map.TableName : tableName; - return Configuration.Dialect.GetTableName(schemaName, tableName, null); - } - - public virtual string GetColumnName(bool prefix, IClassMapper map, IPropertyMap property, bool includeAlias, string schemaName, string tableName, string aliasName = null) - { - string alias = null; - string propertyName = property.Name; - if (aliasName != null) - { - propertyName = aliasName; - } - if (property.ColumnName != propertyName && includeAlias) - { - alias = propertyName; - } - - return Configuration.Dialect.GetColumnName(prefix ? GetTableName(map, schemaName, tableName) : null, property.ColumnName, alias); - } - - public virtual string GetColumnName(bool prefix, IClassMapper map, string propertyName, bool includeAlias, string schemaName, string tableName) - { - IPropertyMap propertyMap = map.Properties.SingleOrDefault(p => p.Name.Equals(propertyName, StringComparison.InvariantCultureIgnoreCase)); - if (propertyMap == null) - { - throw new ArgumentException(string.Format("Could not find '{0}' in Mapping.", propertyName)); - } - - return GetColumnName(prefix,map, propertyMap, includeAlias,schemaName, tableName); - } - - public virtual bool SupportsMultipleStatements() - { - return Configuration.Dialect.SupportsMultipleStatements; - } - - public virtual string BuildSelectColumns(IClassMapper classMap, string schemaName, string tableName, IList join = null, IList alias = null) - { - if (join != null && join.Count > 0) - { - Dictionary joinMap = new Dictionary(); - - foreach (var itemJoin in join) - { - var leftMap = itemJoin.GetLeftMapper(this); - var tablename = $"{leftMap.SchemaName}.{leftMap.TableName}"; - if (!joinMap.ContainsKey(tablename)) - joinMap.Add(tablename, new JoinMapper() - { - Mapper = leftMap, - SchemaName = itemJoin.SchemaName, - TableName = itemJoin.TableName - }); - var rightMap = itemJoin.GetRightMapper(this); - tablename = $"{rightMap.SchemaName}.{rightMap.TableName}"; - if (!joinMap.ContainsKey(tablename)) - joinMap.Add(tablename, new JoinMapper() - { - Mapper = rightMap, - SchemaName = itemJoin.SchemaName2, - TableName = itemJoin.TableName2 - }); - } - - var vMapPro = classMap.Properties.Select(w => w.Name).ToList(); - - List ListColumn = new List(); - - foreach (var itemMap in joinMap) - { - if (vMapPro.Count == 0) - break; - var vAllProperty = itemMap.Value.Mapper.Properties.Where(w => !w.Ignored); - for (int i = vMapPro.Count - 1; i >= 0; i--) - { - var jitem = vAllProperty.Where(w => w.Name.Equals(vMapPro[i], StringComparison.OrdinalIgnoreCase)); - if (jitem.Count() > 0) - { - ListColumn.Add(new JoinMapper() - { - AliasName = null, - Mapper = itemMap.Value.Mapper, - Propertry = jitem.First(), - SchemaName = itemMap.Value.SchemaName, - TableName = itemMap.Value.TableName - }); - vMapPro.RemoveAt(i); - } - } - } - - if (alias != null && vMapPro.Count > 0) - { - foreach (var itemAlia in alias) - { - if (vMapPro.Count == 0) - break; - - var rightMap = itemAlia.GetRightMapper(this); - var tablename = $"{rightMap.SchemaName}.{rightMap.TableName}"; - if (!joinMap.ContainsKey(tablename)) - break; - - var vrightSchemaMap = joinMap[tablename]; - var propertyMap = itemAlia.GetPropertyMap(this); - for (int i = vMapPro.Count - 1; i >= 0; i--) - { - if (itemAlia.PropertyName.Equals(vMapPro[i])) - { - ListColumn.Add(new JoinMapper() - { - AliasName = itemAlia.PropertyName, - Mapper = vrightSchemaMap.Mapper, - Propertry = propertyMap, - SchemaName = vrightSchemaMap.SchemaName, - TableName = vrightSchemaMap.TableName - }); - vMapPro.RemoveAt(i); - break; - } - } - } - } - - var jcolumns = ListColumn.Select(p => GetColumnName(true,p.Mapper, p.Propertry, true, p.SchemaName, p.TableName, p.AliasName)); - return jcolumns.AppendStrings(); - } - - var columns = classMap.Properties - .Where(p => !p.Ignored) - .Select(p => GetColumnName(false,classMap, p, true, schemaName, tableName)); - return columns.AppendStrings(); - } - - public string GetOperatorString(Operator Operator, bool Not) => Configuration.Dialect.GetOperatorString(Operator, Not); - - internal class JoinMapper - { - public IPropertyMap Propertry { get; set; } - public IClassMapper Mapper { get; set; } - public string SchemaName { get; set; } - public string TableName { get; set; } - - public string AliasName { get; set; } - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Sql/SqlServerDialect.cs b/samples/Common/Repository.Dapper.Core/Sql/SqlServerDialect.cs deleted file mode 100644 index 53e09f788..000000000 --- a/samples/Common/Repository.Dapper.Core/Sql/SqlServerDialect.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Repository.Dapper.Core.Sql -{ - public class SqlServerDialect : SqlDialectBase - { - public override char OpenQuote - { - get { return '['; } - } - - public override char CloseQuote - { - get { return ']'; } - } - - public override string GetIdentitySql(string tableName) - { - return string.Format("SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [Id]"); - } - - public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) - { - int startValue = ((page-1) * resultsPerPage) + 1; - return GetSetSql(sql, startValue < 1 ? 1 : startValue, resultsPerPage, parameters); - } - - public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) - { - if (string.IsNullOrEmpty(sql)) - { - throw new ArgumentNullException("SQL"); - } - - if (parameters == null) - { - throw new ArgumentNullException("Parameters"); - } - - int selectIndex = GetSelectEnd(sql) + 1; - string orderByClause = GetOrderByClause(sql); - if (orderByClause == null) - { - orderByClause = "ORDER BY CURRENT_TIMESTAMP"; - } - - - string projectedColumns = GetColumnNames(sql).Aggregate(new StringBuilder(), (sb, s) => (sb.Length == 0 ? sb : sb.Append(", ")).Append(GetColumnName("_proj", s, null)), sb => sb.ToString()); - string newSql = sql - .Replace(" " + orderByClause, string.Empty) - .Insert(selectIndex, string.Format("ROW_NUMBER() OVER(ORDER BY {0}) AS {1}, ", orderByClause.Substring(9), GetColumnName(null, "_row_number", null))); - - string result = string.Format("SELECT TOP({0}) {1} FROM ({2}) [_proj] WHERE {3} >= @_pageStartRow ORDER BY {3}", - maxResults, projectedColumns.Trim(), newSql, GetColumnName("_proj", "_row_number", null)); - - parameters.Add("@_pageStartRow", firstResult); - return result; - } - - protected string GetOrderByClause(string sql) - { - int orderByIndex = sql.LastIndexOf(" ORDER BY ", StringComparison.InvariantCultureIgnoreCase); - if (orderByIndex == -1) - { - return null; - } - - string result = sql.Substring(orderByIndex).Trim(); - - int whereIndex = result.IndexOf(" WHERE ", StringComparison.InvariantCultureIgnoreCase); - if (whereIndex == -1) - { - return result; - } - - return result.Substring(0, whereIndex).Trim(); - } - - protected int GetFromStart(string sql) - { - int selectCount = 0; - string[] words = sql.Split(' '); - int fromIndex = 0; - foreach (var word in words) - { - if (word.Equals("SELECT", StringComparison.InvariantCultureIgnoreCase)) - { - selectCount++; - } - - if (word.Equals("FROM", StringComparison.InvariantCultureIgnoreCase)) - { - selectCount--; - if (selectCount == 0) - { - break; - } - } - - fromIndex += word.Length + 1; - } - - return fromIndex; - } - - protected virtual int GetSelectEnd(string sql) - { - if (sql.StartsWith("SELECT DISTINCT", StringComparison.InvariantCultureIgnoreCase)) - { - return 15; - } - - if (sql.StartsWith("SELECT", StringComparison.InvariantCultureIgnoreCase)) - { - return 6; - } - - throw new ArgumentException("SQL must be a SELECT statement.", "sql"); - } - - protected virtual IList GetColumnNames(string sql) - { - int start = GetSelectEnd(sql); - int stop = GetFromStart(sql); - string[] columnSql = sql.Substring(start, stop - start).Split(','); - List result = new List(); - foreach (string c in columnSql) - { - int index = c.IndexOf(" AS ", StringComparison.InvariantCultureIgnoreCase); - if (index > 0) - { - result.Add(c.Substring(index + 4).Trim()); - continue; - } - - string[] colParts = c.Split('.'); - result.Add(colParts[colParts.Length - 1].Trim()); - } - - return result; - } - } -} \ No newline at end of file diff --git a/samples/Common/Repository.Dapper.Core/Sql/SqliteDialect.cs b/samples/Common/Repository.Dapper.Core/Sql/SqliteDialect.cs deleted file mode 100644 index e21bbba56..000000000 --- a/samples/Common/Repository.Dapper.Core/Sql/SqliteDialect.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Repository.Dapper.Core.Sql -{ - public class SqliteDialect : SqlDialectBase - { - public override string GetIdentitySql(string tableName) - { - return "SELECT LAST_INSERT_ROWID() AS [Id]"; - } - - public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) - { - int startValue = (page - 1) * resultsPerPage; - return GetSetSql(sql, startValue < 0 ? 0 : startValue, resultsPerPage, parameters); - } - - public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) - { - if (string.IsNullOrEmpty(sql)) - { - throw new ArgumentNullException("SQL"); - } - - if (parameters == null) - { - throw new ArgumentNullException("Parameters"); - } - - var result = string.Format("{0} LIMIT @Offset, @Count", sql); - parameters.Add("@Offset", firstResult); - parameters.Add("@Count", maxResults); - return result; - } - - public override string GetColumnName(string prefix, string columnName, string alias) - { - if (string.IsNullOrWhiteSpace(columnName)) - { - throw new ArgumentNullException(columnName, "columnName cannot be null or empty."); - } - var result = new StringBuilder(); - result.AppendFormat(columnName); - if (!string.IsNullOrWhiteSpace(alias)) - { - result.AppendFormat(" AS {0}", QuoteString(alias)); - } - return result.ToString(); - } - } -} diff --git "a/samples/Common/Repository.EF.Core/BaseImpQueryOnlyRepository - \345\244\215\345\210\266.cs" "b/samples/Common/Repository.EF.Core/BaseImpQueryOnlyRepository - \345\244\215\345\210\266.cs" deleted file mode 100644 index a5cb78318..000000000 --- "a/samples/Common/Repository.EF.Core/BaseImpQueryOnlyRepository - \345\244\215\345\210\266.cs" +++ /dev/null @@ -1,150 +0,0 @@ -using DDD.Core; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Query; -using Surging.Core.CPlatform.Ioc; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; - -namespace Repository.EF.Core -{ - public class BaseImpQueryOnlyRepository: BaseRepository,IQueryOnlyRepository //where T : class, IDBModel - { - private readonly DefaultDbContext _dbContext; - private readonly DbSet _set; - public BaseImpQueryOnlyRepository(string modelAssemblyName)//DefaultDbContext dbContext) - { - //if (dbContext == null) throw new ArgumentNullException(nameof(dbContext)); - - _dbContext = new DefaultDbContext(modelAssemblyName); - _dbContext.Database.EnsureCreated(); - _set = _dbContext.Set(); - } - - - - #region 所有跟添加/修改/删除无关的界面查询,也不包含报表查询 - - public virtual int Count(Expression> @where = null) where T : class, IDBModel - { - return where == null ? _set.Count() : _set.Count(@where); - } - - public virtual bool Exist(Expression> @where = null) where T : class, IDBModel - { - return Get(where).Any(); - } - - public virtual bool Exist(Expression> @where = null, params Expression>[] includes) - { - return Get(where, includes).Any(); - } - - public virtual int ExecuteSqlWithNonQuery(string sql, params object[] parameters) - { - return _dbContext.ExecuteSqlWithNonQuery(sql, parameters); - } - - public virtual T GetSingle(Guid key) - { - return _set.Find(key); - } - - public T GetSingle(Guid key, params Expression>[] includes) - { - if (includes == null) return GetSingle(key); - var query = _set.AsQueryable(); - foreach (var include in includes) - { - query = query.Include(include); - } - Expression> filter = m => m.KeyId.Equals(key); - return query.SingleOrDefault(filter.Compile()); - } - - public T GetSingle(Expression> @where = null) - { - if (where == null) return _set.SingleOrDefault(); - return _set.SingleOrDefault(@where); - } - - public T GetSingle(Expression> @where = null, params Expression>[] includes) - { - if (includes == null) return GetSingle(where); - var query = _set.AsQueryable(); - foreach (var include in includes) - { - query = query.Include(include); - } - if (where == null) return query.SingleOrDefault(); - return query.SingleOrDefault(where); - } - - public virtual IQueryable Get(Expression> @where = null) - { - return @where != null ? _set.AsNoTracking().Where(@where) : _set.AsNoTracking(); - } - - - public virtual IQueryable Get(Expression> @where = null, params Expression>[] includes) - { - if (includes == null) - return Get(where); - var query = _set.AsQueryable(); - foreach (var include in includes) - { - query = query.Include(include); - } - return @where != null ? query.AsNoTracking().Where(@where) : query.AsNoTracking(); - } - public class IncludeTree - { - public Expression> Property { get; set; } - public Expression>[] navigationPropertyPath { get; set; } - - public List< IncludeTree>[] Childs { get; set; } - } - - //static IIncludableQueryable IncludeTable( IIncludableQueryable queryable, List< IncludeTree> includeTrees) - // { - // foreach (var includeTree in includeTrees) - // { - // queryable.Include(includeTree.Property).ThenInclude((includeTree.ChildInclude)); - - // } - // } - - - - - - public virtual IList SqlQuery(string sql, params object[] parameters) where TView : class, new() - { - return _dbContext.SqlQuery(sql, parameters); - } - - - public virtual IEnumerable GetByPagination(Expression> @where, int pageSize, int pageIndex, Expression>[] includes, bool asc = true, params Func[] @orderby) - { - var filter = Get(where).AsQueryable(); - if (includes != null) - { - foreach (var include in includes) - { - filter = filter.Include(include); - } - } - if (orderby != null) - { - foreach (var func in orderby) - { - filter = asc ? filter.OrderBy(func).AsQueryable() : filter.OrderByDescending(func).AsQueryable(); - } - } - return filter.Skip(pageSize * (pageIndex - 1)).Take(pageSize); - } - #endregion - } -} diff --git a/samples/Common/Repository.EF.Core/BaseImpQueryOnlyRepository.cs b/samples/Common/Repository.EF.Core/BaseImpQueryOnlyRepository.cs deleted file mode 100644 index 82c9efda4..000000000 --- a/samples/Common/Repository.EF.Core/BaseImpQueryOnlyRepository.cs +++ /dev/null @@ -1,149 +0,0 @@ -using DDD.Core; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Query; -using Surging.Core.CPlatform.Ioc; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; - -namespace Repository.EF.Core -{ - public class BaseImpQueryOnlyRepository: BaseRepository,IQueryOnlyRepository where T : class, IDBModel - { - protected readonly DefaultDbContext _dbContext; - protected readonly DbSet _set; - public BaseImpQueryOnlyRepository()//DefaultDbContext dbContext) - { - //if (dbContext == null) throw new ArgumentNullException(nameof(dbContext)); - - _dbContext = new DefaultDbContext(); - _set = _dbContext.Set(); - } - - - - #region 所有跟添加/修改/删除无关的界面查询,也不包含报表查询 - - public virtual int Count(Expression> @where = null) - { - return where == null ? _set.Count() : _set.Count(@where); - } - - public virtual bool Exist(Expression> @where = null) - { - return Get(where).Any(); - } - - public virtual bool Exist(Expression> @where = null, params Expression>[] includes) - { - return Get(where, includes).Any(); - } - - public virtual int ExecuteSqlWithNonQuery(string sql, params object[] parameters) - { - return _dbContext.ExecuteSqlWithNonQuery(sql, parameters); - } - - public virtual T GetSingle(Guid key) - { - return _set.Find(key); - } - - public T GetSingle(Guid key, params Expression>[] includes) - { - if (includes == null) return GetSingle(key); - var query = _set.AsQueryable(); - foreach (var include in includes) - { - query = query.Include(include); - } - Expression> filter = m => m.KeyId.Equals(key); - return query.SingleOrDefault(filter.Compile()); - } - - public T GetSingle(Expression> @where = null) - { - if (where == null) return _set.SingleOrDefault(); - return _set.SingleOrDefault(@where); - } - - public T GetSingle(Expression> @where = null, params Expression>[] includes) - { - if (includes == null) return GetSingle(where); - var query = _set.AsQueryable(); - foreach (var include in includes) - { - query = query.Include(include); - } - if (where == null) return query.SingleOrDefault(); - return query.SingleOrDefault(where); - } - - public virtual IQueryable Get(Expression> @where = null) - { - return @where != null ? _set.AsNoTracking().Where(@where) : _set.AsNoTracking(); - } - - - public virtual IQueryable Get(Expression> @where = null, params Expression>[] includes) - { - if (includes == null) - return Get(where); - var query = _set.AsQueryable(); - foreach (var include in includes) - { - query = query.Include(include); - } - return @where != null ? query.AsNoTracking().Where(@where) : query.AsNoTracking(); - } - public class IncludeTree - { - public Expression> Property { get; set; } - public Expression>[] navigationPropertyPath { get; set; } - - public List< IncludeTree>[] Childs { get; set; } - } - - //static IIncludableQueryable IncludeTable( IIncludableQueryable queryable, List< IncludeTree> includeTrees) - // { - // foreach (var includeTree in includeTrees) - // { - // queryable.Include(includeTree.Property).ThenInclude((includeTree.ChildInclude)); - - // } - // } - - - - - - public virtual IList SqlQuery(string sql, params object[] parameters) where TView : class, new() - { - return _dbContext.SqlQuery(sql, parameters); - } - - - public virtual IEnumerable GetByPagination(Expression> @where, int pageSize, int pageIndex, Expression>[] includes, bool asc = true, params Func[] @orderby) - { - var filter = Get(where).AsQueryable(); - if (includes != null) - { - foreach (var include in includes) - { - filter = filter.Include(include); - } - } - if (orderby != null) - { - foreach (var func in orderby) - { - filter = asc ? filter.OrderBy(func).AsQueryable() : filter.OrderByDescending(func).AsQueryable(); - } - } - return filter.Skip(pageSize * (pageIndex - 1)).Take(pageSize); - } - #endregion - } -} diff --git a/samples/Common/Repository.EF.Core/BaseImpRepository.cs b/samples/Common/Repository.EF.Core/BaseImpRepository.cs deleted file mode 100644 index 8a8312319..000000000 --- a/samples/Common/Repository.EF.Core/BaseImpRepository.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using DDD.Core; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Query; -using Surging.Core.CPlatform.Ioc; - -namespace Repository.EF.Core -{ - public class BaseImpRepository : BaseRepository,IRepository where T : IAggregate - { - private readonly string _modelAssemblyName; - private readonly DefaultDbContext _dbContext; - protected readonly DbSet _set; - public BaseImpRepository()//DefaultDbContext dbContext) - { - //if (dbContext == null) throw new ArgumentNullException(nameof(dbContext)); - - _dbContext = new DefaultDbContext(); - //_dbContext.Database.EnsureCreated(); - _set = _dbContext.Set(); - } - - - - public virtual void Delete(Guid key) - { - } - - - - public virtual void Dispose() - { - if (_dbContext != null) - { - _dbContext.Dispose(); - } - } - - public virtual T FindBy(Guid key) //where T : IAggregate - { - //TODO:想要动态地加载聚合的所有数据 - return null;// _dbContext.Set().First(a => a.KeyId == key); - } - - public void Add(T aggregate)// where T : IAggregate - { - // using (var _dbContext=new DefaultDbContext(_modelAssemblyName)) - // { - _dbContext.Set().Add(aggregate); - // _dbContext.SaveChanges(); - // } - } - public void Update(T aggregate)// where T : IAggregate - { - _dbContext.Set().Update(aggregate); - } - - public int Commit() - { - return _dbContext.SaveChanges(); - } - } -} diff --git a/samples/Common/Repository.EF.Core/ConfigHelper.cs b/samples/Common/Repository.EF.Core/ConfigHelper.cs deleted file mode 100644 index 41670aff7..000000000 --- a/samples/Common/Repository.EF.Core/ConfigHelper.cs +++ /dev/null @@ -1,101 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.FileProviders; -using Surging.Core.CPlatform.Configurations.Remote; -using Surging.Core.CPlatform.Utilities; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace Repository.EF.Extensions -{ - public static class DBConfigurationExtensions - { - public static IConfigurationBuilder AddDBFile(this IConfigurationBuilder builder, string path) - { - return AddDBFile(builder, provider: null, path: path, optional: false, reloadOnChange: false); - } - - public static IConfigurationBuilder AddDBFile(this IConfigurationBuilder builder, string path, bool optional) - { - return AddDBFile(builder, provider: null, path: path, optional: optional, reloadOnChange: false); - } - - public static IConfigurationBuilder AddDBFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange) - { - return AddDBFile(builder, provider: null, path: path, optional: optional, reloadOnChange: reloadOnChange); - } - - public static IConfigurationBuilder AddDBFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange) - { - Check.NotNull(builder, "builder"); - Check.CheckCondition(() => string.IsNullOrEmpty(path), "path"); - if (provider == null && Path.IsPathRooted(path)) - { - provider = new PhysicalFileProvider(Path.GetDirectoryName(path)); - path = Path.GetFileName(path); - } - var source = new DBConfigurationSource - { - FileProvider = provider, - Path = path, - Optional = optional, - ReloadOnChange = reloadOnChange - }; - builder.Add(source); - DBConfig.Configuration = builder.Build(); - return builder; - } - } - public class DBConfig - { - - public static IConfiguration Configuration { get; set; } - /* static ConfigHelper() - { - configuration = AutofacContainer.Resolve(); - } - - public static IConfigurationSection GetSection(string key) - { - return configuration.GetSection(key); - } - - public static string GetConfigurationValue(string key) - { - return configuration[key]; - } - - public static string GetConfigurationValue(string section, string key) - { - return GetSection(section)?[key]; - } - - public static string GetConnectionString(string key) - { - return configuration.GetConnectionString(key); - } - */ - } - - public class DBConfigurationSource : FileConfigurationSource - { - public string ConfigurationKeyPrefix { get; set; } - - public override IConfigurationProvider Build(IConfigurationBuilder builder) - { - FileProvider = FileProvider ?? builder.GetFileProvider(); - return new DBConfigurationProvider(this); - } - } - public class DBConfigurationProvider : FileConfigurationProvider - { - public DBConfigurationProvider(DBConfigurationSource source) : base(source) { } - - public override void Load(Stream stream) - { - var parser = new JsonConfigurationParser(); - this.Data = parser.Parse(stream, null); - } - } -} diff --git a/samples/Common/Repository.EF.Core/DbContextOption.cs b/samples/Common/Repository.EF.Core/DbContextOption.cs deleted file mode 100644 index 9f11e290b..000000000 --- a/samples/Common/Repository.EF.Core/DbContextOption.cs +++ /dev/null @@ -1,50 +0,0 @@ -namespace Repository.EF.Core -{ - - public class DbContextOption - { - /// - /// 数据库连接字符串 - /// - public string ConnectionString { get; set; } - /// - /// 实体程序集名称 - /// - public string ModelAssemblyName { get; set; } - /// - /// 数据库类型 - /// - public DbType DbType { get; set; } = DbType.MSSQLSERVER; - } - - /// - /// 数据库类型枚举 - /// - public enum DbType - { - /// - /// MS SQL Server - /// - MSSQLSERVER=0, - /// - /// Oracle - /// - ORACLE, - /// - /// MySQL - /// - MYSQL, - /// - /// Sqlite - /// - SQLITE, - /// - /// in-memory database - /// - MEMORY, - /// - /// PostgreSQL - /// - NPGSQL - } -} diff --git a/samples/Common/Repository.EF.Core/DefaultDbContext.cs b/samples/Common/Repository.EF.Core/DefaultDbContext.cs deleted file mode 100644 index c15bc3696..000000000 --- a/samples/Common/Repository.EF.Core/DefaultDbContext.cs +++ /dev/null @@ -1,233 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Threading; -using Config.Core.Extensions; -using DDD.Core; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Extensions; -using Microsoft.Extensions.Configuration; -using Surging.Core.CPlatform; -using Z.EntityFramework.Plus; - -namespace Repository.EF.Core -{ - public sealed class DefaultDbContext : DbContext - { - private DbContextOption _option; - - - public DefaultDbContext() - { - _option = new DbContextOption - { - ConnectionString = DBConfig.Configuration["ConnectionString"], - ModelAssemblyName = DBConfig.Configuration["ModelAssemblyName"], - DbType = DbType.MSSQLSERVER - }; - } - /// - /// 构造函数 - /// - /// - public DefaultDbContext(DbContextOption option) - { - if(option==null) - throw new ArgumentNullException(nameof(option)); - if(string.IsNullOrEmpty(option.ConnectionString)) - throw new ArgumentNullException(nameof(option.ConnectionString)); - if (string.IsNullOrEmpty(option.ModelAssemblyName)) - throw new ArgumentNullException(nameof(option.ModelAssemblyName)); - _option = option; - } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - switch (_option.DbType) - { - case DbType.ORACLE: - throw new NotSupportedException("Oracle EF Core Database Provider is not yet available."); - //case DbType.MYSQL: - // optionsBuilder.UseMySql(_option.ConnectionString); - // break; - //case DbType.SQLITE: - // optionsBuilder.UseSqlite(_option.ConnectionString); - // break; - //case DbType.MEMORY: - // optionsBuilder.UseInMemoryDatabase(_option.ConnectionString); - // break; - //case DbType.NPGSQL: - // optionsBuilder.UseNpgsql(_option.ConnectionString); - // break; - default: - optionsBuilder.UseSqlServer(_option.ConnectionString); - break; - } - base.OnConfiguring(optionsBuilder); - } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - AddEntityTypes(modelBuilder); - base.OnModelCreating(modelBuilder); - } - - private void AddEntityTypes(ModelBuilder modelBuilder) - { - var assembly = Assembly.Load(_option.ModelAssemblyName); - var types = assembly?.GetTypes(); - var list = types?.Where(t => - t.IsClass && !t.IsGenericType && !t.IsAbstract&& - t.GetInterfaces().Any(m => m.IsGenericType && m.GetGenericTypeDefinition() == typeof(IDBModel<>))).ToList(); - if (list != null && list.Any()) - { - list.ForEach(t => - { - if (modelBuilder.Model.FindEntityType(t) == null) - modelBuilder.Model.AddEntityType(t); - }); - } - } - - /// - /// ExecuteSqlWithNonQuery - /// - /// - /// - /// - public int ExecuteSqlWithNonQuery(string sql, params object[] parameters) - { - return Database.ExecuteSqlCommand(sql, - CancellationToken.None, - parameters); - } - - /// - /// edit an entity. - /// - /// - /// - /// - public int Edit(T entity) where T : class - { - Entry(entity).State = EntityState.Modified; - return SaveChanges(); - } - - /// - /// edit entities. - /// - /// - /// - /// - public int EditRange(ICollection entities) where T : class - { - Set().AttachRange(entities.ToArray()); - return SaveChanges(); - } - - /// - /// update query datas by columns. - /// - /// - /// - /// - /// - public int Update(Expression> @where, Expression> updateExp) - where T : class - { - return Set().Where(@where).Update(updateExp); - } - - /// - /// update data by columns. - /// - /// - /// - /// - /// - public int Update(T model, params string[] updateColumns) where T : class - { - if (updateColumns != null && updateColumns.Length > 0) - { - if (Entry(model).State == EntityState.Added || - Entry(model).State == EntityState.Detached) Set().Attach(model); - foreach (var propertyName in updateColumns) - { - Entry(model).Property(propertyName).IsModified = true; - } - } - else - { - Entry(model).State = EntityState.Modified; - } - return SaveChanges(); - } - - /// - /// delete by query. - /// - /// - /// - /// - public int Delete(Expression> @where) where T : class - { - Set().Where(@where).Delete(); - return SaveChanges(); - } - - /* - /// - /// bulk insert by sqlbulkcopy, and with transaction. - /// - /// - /// - /// - public void BulkInsert(IList entities, string destinationTableName = null) where T : class - { - if (entities == null || !entities.Any()) return; - if (string.IsNullOrEmpty(destinationTableName)) - { - var mappingTableName = typeof(T).GetCustomAttribute()?.Name; - destinationTableName = string.IsNullOrEmpty(mappingTableName) ? typeof(T).Name : mappingTableName; - } - using (var dt = entities.ToDataTable()) - { - using (var conn = new SqlConnection(_option.ConnectionString)) - { - conn.Open(); - using (var tran = conn.BeginTransaction()) - { - try - { - var bulk = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, tran); - bulk.BatchSize = entities.Count; - bulk.DestinationTableName = destinationTableName; - bulk.EnableStreaming = true; - bulk.WriteToServerAsync(dt); - tran.Commit(); - } - catch (Exception) - { - tran.Rollback(); - throw; - } - } - conn.Close(); - } - } - } - */ - public List SqlQuery(string sql, params object[] parameters) - where T : class - where TView : class - { - return Set().FromSql(sql, parameters).Cast().ToList(); - } - - } -} \ No newline at end of file diff --git a/samples/Common/Repository.EF.Core/IQueryableExtension.cs b/samples/Common/Repository.EF.Core/IQueryableExtension.cs deleted file mode 100644 index 6a9b9ef56..000000000 --- a/samples/Common/Repository.EF.Core/IQueryableExtension.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Linq.Expressions; -using System.Text; -using System.Data.Entity.Infrastructure.DbQuery; -namespace Centa.Agency.Repository.EF -{ - /// - /// Class for IQuerable extensions methods - /// - /// Include method in IQueryable ( base contract for IObjectSet ) is - /// intended for mock Include method in ObjectQuery{T}. - /// Paginate solve not parametrized queries issues with skip and take L2E methods - /// - /// - public static class IQueryableExtensions - { - - #region Extension Methods - - /// - /// Include method for IQueryable - /// - /// Type of elements - /// Queryable object - /// Path to include - /// Queryable object with include path information - public static IQueryable Include(this IQueryable queryable, string path) - where TEntity : class - { - if (String.IsNullOrEmpty(path)) - throw new ArgumentNullException("path can not empty"); - // var query = queryable as ObjectQuery;//ObjectContext時用 - var query = queryable as DbQuery;//DbContext時用 - - if (query != null)//if is a EF ObjectQuery object - return query.Include(path); - return null; - } - - /// - /// Include extension method for IQueryable - /// - /// Type of elements in IQueryable - /// Queryable object - /// Expression with path to include - /// Queryable object with include path information - public static IQueryable Include(this IQueryable queryable, Expression> path) - where TEntity : class - { - return Include(queryable, AnalyzeExpressionPath(path)); - } - - /// - /// Paginate query in a specific page range - /// - /// Typeof entity in underlying query - /// Typeof ordered data value - /// Query to paginate - /// Order by expression used in paginate method - /// - /// At this moment Order by expression only support simple order by c=>c.CustomerCode. If you need - /// add more complex order functionality don't use this extension method - /// - /// - /// Page index - /// Page count - /// order direction - /// A paged queryable - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] - public static IQueryable Paginate(this IQueryable queryable, Expression> orderBy, int pageIndex, int pageCount, bool ascending) - where TEntity : class - { - ObjectQuery query = queryable as ObjectQuery; - - if (query != null) - { - //this paginate method use ESQL for solve problems with Parametrized queries - //in L2E and Skip/Take methods - - string orderPath = AnalyzeExpressionPath(orderBy); - - return query.Skip(string.Format(CultureInfo.InvariantCulture, "it.{0} {1}", orderPath, (ascending) ? "asc" : "desc"), "@skip", new ObjectParameter("skip", (pageIndex) * pageCount)) - .Top("@limit", new ObjectParameter("limit", pageCount)); - - } - else // for In-Memory object set - return queryable.OrderBy(orderBy).Skip((pageIndex * pageCount)).Take(pageCount); - } - - #endregion - - #region Private Methods - - static string AnalyzeExpressionPath(Expression> expression) - where TEntity : class - { - if (expression == (Expression>)null) - throw new ArgumentNullException("Argument error"); - - MemberExpression body = expression.Body as MemberExpression; - if ( - ( - (body == null) - || - !body.Member.DeclaringType.IsAssignableFrom(typeof(TEntity)) - ) - || - (body.Expression.NodeType != ExpressionType.Parameter)) - { - throw new ArgumentException("Argument error"); - } - else - return body.Member.Name; - } - #endregion - } - } diff --git a/samples/Common/Repository.EF.Core/InquiryRepository.cs b/samples/Common/Repository.EF.Core/InquiryRepository.cs deleted file mode 100644 index 1c79f86c0..000000000 --- a/samples/Common/Repository.EF.Core/InquiryRepository.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Microsoft.EntityFrameworkCore; -using System.Linq.Expressions; -using System.Linq; -using Microsoft.EntityFrameworkCore.Query; - - - -namespace Repository.EF.Core.Inquiry -{ - //public class InquiryRepository : BaseImpRepository - //{ - - // public override Customer FindBy(Guid key) - // { - // return _set.Include(a => a.CusInquirys).ThenInclude(b => b.InquiryParameters).Where(a => a.KeyId == key).FirstOrDefault(); - // } - - //} -} diff --git a/samples/Common/Repository.EF.Core/Properties/PublishProfiles/FolderProfile.pubxml b/samples/Common/Repository.EF.Core/Properties/PublishProfiles/FolderProfile.pubxml deleted file mode 100644 index 6c005a7a9..000000000 --- a/samples/Common/Repository.EF.Core/Properties/PublishProfiles/FolderProfile.pubxml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - FileSystem - Debug - netcoreapp2.0 - bin\Release\PublishOutput - - \ No newline at end of file diff --git a/samples/Common/Repository.EF.Core/Repository.EF.Core.csproj b/samples/Common/Repository.EF.Core/Repository.EF.Core.csproj deleted file mode 100644 index a7952b432..000000000 --- a/samples/Common/Repository.EF.Core/Repository.EF.Core.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - netcoreapp2.0 - - - - bin\Debug\netstandard2.0\ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Common/Repository.EF.Core/SqlHelper.cs b/samples/Common/Repository.EF.Core/SqlHelper.cs deleted file mode 100644 index aede601d6..000000000 --- a/samples/Common/Repository.EF.Core/SqlHelper.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; - -namespace Repository.EF.Core -{ - public class SqlHelper - { - /// - /// 参数拼装 - /// - /// 参数名称 - /// 参数类型 - /// 参数值 - /// 拼装后的参数对象 - public static SqlParameter MakeParam(string parameterName, SqlDbType parameterType, object parameterValue) - { - SqlParameter p = new SqlParameter(); - p.ParameterName = parameterName; - p.SqlDbType = parameterType; - if (parameterValue == null) - { - p.Value = DBNull.Value; - } - else - { - if (parameterType == SqlDbType.Structured) - { - Type type = parameterValue.GetType(); - if (type.IsGenericType)//判断是否是泛型 - { - string t = type.GetGenericArguments()[0].Name; //泛型的类型 - switch (t) - { - case "Guid": - p.TypeName = "GuidCollectionTVP"; - p.Value = InitialCollectionTVP(parameterValue as List); - break; - case "Int32": - p.TypeName = "IntCollectionTVP"; - p.Value = InitialCollectionTVP(parameterValue as List); - break; - case "String": - p.TypeName = "StringCollectionTVP"; - p.Value = InitialCollectionTVP(parameterValue as List); - break; - default: - p.Value = parameterValue; - break; - } - } - else - { - p.Value = parameterValue; - } - - } - else - { - p.Value = parameterValue; - } - } - - return p; - } - - /* - /// - /// 参数拼装 - /// - /// 参数名称 - /// 参数类型 - /// 参数值 - /// 拼装后的参数对象 - public static SqlParameter MakeParam(string parameterName, DbType parameterType, object parameterValue) - { - SqlParameter p = new SqlParameter(); - p.ParameterName = parameterName; - p.DbType = parameterType; - if (parameterValue == null) - { - p.Value = DBNull.Value; - } - else - { - p.Value = parameterValue; - } - - return p; - } - - */ - /// - /// 初始化CollectionTVP - /// - /// 数据列表 - /// DataTable - public static DataTable InitialCollectionTVP(List list) - { - DataTable dt = new DataTable(); - dt.Columns.Add("Item", typeof(T)); - if (list == null | list.Count == 0) - { - return dt; - } - - foreach (T item in list) - { - dt.Rows.Add(item); - } - - return dt; - } - /// - /// 过滤sql注入2015/7/25 xingyongkang - /// - /// - /// - public static string CheckKeyWord(string keyWord) - { - //过滤关键字 - string StrKeyWord = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and"; - if (Regex.IsMatch(keyWord, StrKeyWord, RegexOptions.IgnoreCase)) - { - return ""; - } - return keyWord; - } - } -} diff --git a/samples/Common/Repository.EF.Core/UnitOfWork.cs b/samples/Common/Repository.EF.Core/UnitOfWork.cs deleted file mode 100644 index 4a12170a3..000000000 --- a/samples/Common/Repository.EF.Core/UnitOfWork.cs +++ /dev/null @@ -1,64 +0,0 @@ -using DDD.Core; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Centa.Agency.Repository.EF -{ - public class UnitOfWork : IUnitOfWork - { - private bool disposed = false; - private DefaultDbContext _context; - public UnitOfWork()//DefaultDbContext context) - { - _context = new DefaultDbContext();// context; - } - /* - dbContext = CallContext.GetData(provider.ConnectionStringName) as AppDbContext; - if (dbContext == null) - { - dbContext = new AppDbContext(provider.ConnectionString); - dbContext.Configuration.ValidateOnSaveEnabled = false; - //将新创建的 ef上下文对象 存入线程 - CallContext.SetData(provider.ConnectionStringName, dbContext); - } - - */ - public int Commit() - { - using (var tran = _context.Database.CurrentTransaction ?? _context.Database.BeginTransaction()) - { - try - { - var result = _context.SaveChanges(); - tran.Commit(); - return result; - } - catch (Exception) - { - tran.Rollback(); - throw; - } - } - } - - protected virtual void Dispose(bool disposing) - { - if (!this.disposed) - { - if (disposing) - { - _context.Dispose(); - } - } - this.disposed = true; - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - } -} diff --git a/samples/GateWay.WebApi/Areas/AuthManger/Controllers/AuthController.cs b/samples/GateWay.WebApi/Areas/AuthManger/Controllers/AuthController.cs deleted file mode 100644 index 665bcbd7b..000000000 --- a/samples/GateWay.WebApi/Areas/AuthManger/Controllers/AuthController.cs +++ /dev/null @@ -1,250 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Security.Cryptography; -using System.Text; -using System.Threading.Tasks; -using Application.Interface.Auth; -using Application.Interface.Org; -using Application.Service.Auth.Dto; -using DTO.Core; -using GateWay.WebApi.Controllers; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; -using Surging.Core.ApiGateWay; -using Surging.Core.ApiGateWay.OAuth; -using Surging.Core.Caching.DependencyResolution; -using Surging.Core.CPlatform; -using Surging.Core.CPlatform.Filters.Implementation; -using Surging.Core.CPlatform.Routing; -using Surging.Core.CPlatform.Utilities; -using Surging.Core.ProxyGenerator; -using Surging.Core.ProxyGenerator.Implementation; -using GateWayAppConfig = Surging.Core.ApiGateWay.AppConfig; - -namespace GateWay.WebApi.Areas.OrgManger.Controllers -{ - - [Produces("application/json")] - [Route("api/[controller]")] - public class AuthController : BaseApiController - { - private readonly IServiceProxyProvider _serviceProxyProvider; - private readonly IServiceRouteProvider _serviceRouteProvider; - private readonly IAuthorizationServerProvider _authorizationServerProvider; - - private IAuthAppService _authProxy; - public AuthController() - { - _authProxy = serviceProxyFactory.CreateProxy(); - _serviceProxyProvider = ServiceLocator.GetService(); - _serviceRouteProvider = ServiceLocator.GetService(); //serviceRouteProvider; - _authorizationServerProvider = ServiceLocator.GetService();// authorizationServerProvider; - - } - #region 角色 - [HttpGet] - private async Task Get() - { - Dictionary model = new Dictionary(); - model.Add("req",JsonConvert.SerializeObject( new { - UserName= "SuperMan", - Pwd= "123456", - CorporationKeyId= Guid.Parse("8C100FEE-2D1D-4B70-A27D-13D65DCD5E38") - })); - string path = "api/authapp/signin"; - string serviceKey = "Auth"; - var serviceProxyProvider = ServiceLocator.GetService(); - var res = await serviceProxyProvider.Invoke(model, path, serviceKey); - return res; - } - - [HttpGet] - public async Task> DomainPermissions(CommonCMDReq req) - { - var result = await _authProxy.FindDomainPermissions(req); - return ServiceResult.Create(true, result); - } - - - [HttpPost("SignIn")] - public async Task> SignIn(LoginReq req) - { - //要注意参数类型 - var model = new Dictionary(); - model.Add("req", JsonConvert.SerializeObject(req)); - var serviceKey = "Auth"; - ServiceResult result = ServiceResult.Create(false, null); - var path = GateWayAppConfig.AuthorizationRoutePath; - if (OnAuthorization(path, model, ref result)) - { - if (path == GateWayAppConfig.AuthorizationRoutePath) - { - var token = await _authorizationServerProvider.GenerateTokenCredential(model); - if (token != null) - { - //查询当前用户的权限,返回给客户端 - var tmp = JsonConvert.DeserializeObject(_authorizationServerProvider.GetPayloadString(token)); - var identify = JsonConvert.DeserializeObject(tmp); - Dictionary reqQueryUserPermission = new Dictionary(); - reqQueryUserPermission.Add("req", JsonConvert.SerializeObject(new - { - Identify = identify - })); - string servicePath = "api/orgapp/QueryUserPermission"; - var res = await _serviceProxyProvider.Invoke(reqQueryUserPermission, servicePath); - if (res!=null&&res.OperateFlag) - { - result = ServiceResult.Create(true,new { token = token, auth=res.Result }); - result.StatusCode = (int)ServiceStatusCode.Success; - } - else - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; - } - } - else - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; - } - } - else - { - if (!string.IsNullOrEmpty(serviceKey)) - { - - result = ServiceResult.Create(true, await _serviceProxyProvider.Invoke(model, path, serviceKey)); - result.StatusCode = (int)ServiceStatusCode.Success; - } - else - { - result = ServiceResult.Create(true, await _serviceProxyProvider.Invoke(model, path)); - result.StatusCode = (int)ServiceStatusCode.Success; - } - } - } - return result; - } - #endregion - - #region Private - private bool OnAuthorization(string path, Dictionary model, ref ServiceResult result) - { - bool isSuccess = true; - var route = _serviceRouteProvider.GetRouteByPath(path).Result; - if (route.ServiceDescriptor.EnableAuthorization()) - { - if (route.ServiceDescriptor.AuthType() == AuthorizationType.JWT.ToString()) - { - isSuccess = ValidateJwtAuthentication(route, model, ref result); - } - else - { - isSuccess = ValidateAppSecretAuthentication(route, path, model, ref result); - } - - } - return isSuccess; - } - - private bool ValidateJwtAuthentication(ServiceRoute route, Dictionary model, ref ServiceResult result) - { - bool isSuccess = true; - var author = HttpContext.Request.Headers["Authorization"]; - if (author.Count > 0) - { - if (route.Address.Any(p => p.DisableAuth == false)) - { - isSuccess = _authorizationServerProvider.ValidateClientAuthentication(author).Result; - if (!isSuccess) - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; - } - else - { - var keyValue = model.FirstOrDefault(); - if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType())) - { - dynamic instance = keyValue.Value; - instance.Payload = _authorizationServerProvider.GetPayloadString(author); - model.Remove(keyValue.Key); - model.Add(keyValue.Key, instance); - } - } - } - } - else - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error" }; - isSuccess = false; - } - return isSuccess; - } - - private bool ValidateAppSecretAuthentication(ServiceRoute route, string path, - Dictionary model, ref ServiceResult result) - { - bool isSuccess = true; - DateTime time; - var author = HttpContext.Request.Headers["Authorization"]; - if (route.Address.Any(p => p.DisableAuth == false)) - { - if (!string.IsNullOrEmpty(path) && model.ContainsKey("timeStamp") && author.Count > 0) - { - if (DateTime.TryParse(model["timeStamp"].ToString(), out time)) - { - var seconds = (DateTime.Now - time).TotalSeconds; - if (seconds <= 3560 && seconds >= 0) - { - if (!route.Address.Any(p => GetMD5($"{p.Token}{time.ToString("yyyy-MM-dd hh:mm:ss") }") == author.ToString())) - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; - isSuccess = false; - } - } - else - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; - isSuccess = false; - } - } - else - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; - isSuccess = false; - } - } - else - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error" }; - isSuccess = false; - } - } - return isSuccess; - } - - private string GetMD5(string encypStr) - { - try - { - var md5 = MD5.Create(); - var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(encypStr)); - var sb = new StringBuilder(); - foreach (byte b in bs) - { - sb.Append(b.ToString("X2")); - } - //所有字符转为大写 - return sb.ToString().ToLower(); - } - catch (Exception e) - { - Console.Error.WriteLine(e.StackTrace); - return null; - } - } - #endregion - } -} \ No newline at end of file diff --git a/samples/GateWay.WebApi/Areas/OrgManger/Controllers/CorpMangerController.cs b/samples/GateWay.WebApi/Areas/OrgManger/Controllers/CorpMangerController.cs deleted file mode 100644 index bdcd0cd9e..000000000 --- a/samples/GateWay.WebApi/Areas/OrgManger/Controllers/CorpMangerController.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Application.Interface.Org; -using DTO.Core; -using GateWay.WebApi.Controllers; -using Microsoft.AspNetCore.Mvc; -using Surging.Core.ApiGateWay; -using Surging.Core.CPlatform.Utilities; -using Surging.Core.ProxyGenerator; - -namespace GateWay.WebApi -{ - [Route("api/corp"), CustomAuthorizeFilter] - public class CorpController : BaseApiController - { - private IOrgAppService _orgProxy; - - public CorpController() - { - _orgProxy = serviceProxyFactory.CreateProxy(); - } - - - #region 公司 - [HttpPost] - public async Task> RegisterCorporation(CorpEditReq req) - { - var result = await _orgProxy.RegisterCorporation(req); - return ServiceResult.Create(result.OperateFlag, result.OperateResult); - } - - [HttpPut("activate")] - public async Task> ActivateCorporation(CommonCMDReq req) - { - var result = await _orgProxy.ActivateCorporation(req); - return ServiceResult.Create(result.OperateFlag, result.OperateResult); - } - - [HttpGet("tree")] - public async Task> GetCorpTree(BaseTreeSearchReq req) - { - - var result = await _orgProxy.FindCorps(req); - return ServiceResult.Create(true, result); - } - - #endregion - #region 部门管理 - [HttpGet("org/tree")] - public async Task> GetOrgTree(BaseTreeSearchReq req) - { - - var result = await _orgProxy.FindDepartments(req); - return ServiceResult.Create(true, result); - } - - [HttpGet("org/info")] - public ServiceResult GetInfo(KeyIdReq req) - { - return ServiceResult.Create(true, ""); - } - - [HttpPost("org")] - public async Task> Post(DeptEditReq req) - { - - var result = await _orgProxy.CreateDepartment(req); - return ServiceResult.Create(result.OperateFlag, result.OperateResult); - } - - [HttpPut("org")] - public async Task> Put(DeptEditReq req) - { - - var result = await _orgProxy.ModifyDepartment(req); - return ServiceResult.Create(result.OperateFlag, result.OperateResult); - } - - [HttpDelete("org")] - public async Task> Delete(KeyIdReq req) - { - var result = await _orgProxy.RemoveDepartment(req); - return ServiceResult.Create(result.OperateFlag, result.OperateResult); - } - - #endregion - - } -} diff --git a/samples/GateWay.WebApi/Areas/OrgManger/Controllers/EmployeeController.cs b/samples/GateWay.WebApi/Areas/OrgManger/Controllers/EmployeeController.cs deleted file mode 100644 index 94e923900..000000000 --- a/samples/GateWay.WebApi/Areas/OrgManger/Controllers/EmployeeController.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Application.Interface.Org; -using DTO.Core; -using GateWay.WebApi.Controllers; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Surging.Core.ApiGateWay; - -namespace GateWay.WebApi.Areas.OrgManger.Controllers -{ - //[Produces("application/json")] - [Route("api/[controller]")] - public class EmployeeController : BaseApiController - { - private IOrgAppService _orgProxy; - - public EmployeeController() - { - _orgProxy = serviceProxyFactory.CreateProxy(); - } - - - #region 员工 - [HttpPost] - public async Task> Post(EmployeeEditReq req) - { - //HttpContext.Request.Headers - var result = await _orgProxy.CreateEmployee(req); - return ServiceResult.Create(result.OperateFlag, result.OperateResult); - } - - [HttpGet("list")] - public async Task> GetRoleTree(BasePagedRequestDto req) - { - var result = await _orgProxy.FindEmployeePageBy(req); - return ServiceResult.Create(true, result); - } - - - #endregion - - - } -} \ No newline at end of file diff --git a/samples/GateWay.WebApi/Areas/OrgManger/Controllers/RoleMangerController.cs b/samples/GateWay.WebApi/Areas/OrgManger/Controllers/RoleMangerController.cs deleted file mode 100644 index b1fd0dfc0..000000000 --- a/samples/GateWay.WebApi/Areas/OrgManger/Controllers/RoleMangerController.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Application.Interface.Org; -using DTO.Core; -using GateWay.WebApi.Controllers; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Surging.Core.ApiGateWay; - -namespace GateWay.WebApi.Areas.OrgManger.Controllers -{ - //[Produces("application/json")] - [Route("api/[controller]")] - public class RoleController : BaseApiController - { - private IOrgAppService _orgProxy; - - public RoleController() - { - _orgProxy = serviceProxyFactory.CreateProxy(); - } - - - #region 角色 - [HttpPost] - public async Task> Post(RoleEditReq req) - { - var result = await _orgProxy.CreateRole(req); - return ServiceResult.Create(result.OperateFlag, result.OperateResult); - } - - [HttpGet("list")] - public async Task> GetRoleTree(CommonCMDReq req) - { - var result = await _orgProxy.FindCorpRoles(req); - return ServiceResult.Create(true, result); - } - - - #endregion - - #region 角色包含的权限 - - #endregion - } -} \ No newline at end of file diff --git a/samples/GateWay.WebApi/Configs/appsettings.Development.json b/samples/GateWay.WebApi/Configs/appsettings.Development.json deleted file mode 100644 index fa8ce71a9..000000000 --- a/samples/GateWay.WebApi/Configs/appsettings.Development.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "Logging": { - "IncludeScopes": false, - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } - } -} diff --git a/samples/GateWay.WebApi/Configs/appsettings.json b/samples/GateWay.WebApi/Configs/appsettings.json deleted file mode 100644 index 26bb0ac7a..000000000 --- a/samples/GateWay.WebApi/Configs/appsettings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning" - } - } - } -} diff --git a/samples/GateWay.WebApi/Configs/cacheSettings.json b/samples/GateWay.WebApi/Configs/cacheSettings.json deleted file mode 100644 index ab9c7e43d..000000000 --- a/samples/GateWay.WebApi/Configs/cacheSettings.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "CachingSettings": [ - { - "Id": "ddlCache", - "Class": "Surging.Core.Caching.RedisCache.RedisContext,Surging.Core.Caching", - "Properties": [ - { - "Name": "appRuleFile", - "Ref": "rule" - }, - { - "Name": "dataContextPool", - "Ref": "ddls_sample", - "Maps": [ - { - "Name": "Redis", - "Properties": [ - { - "value": "127.0.0.1:6379::1" - } - ] - }, - { - "Name": "MemoryCache" - } - ] - }, - { - "Name": "defaultExpireTime", - "value": "120" - }, - { - "Name": "connectTimeout", - "Value": "120" - }, - { - "Name": "minSize", - "Value": "1" - }, - { - "Name": "maxSize", - "Value": "10" - } - ] - } - ] -} diff --git a/samples/GateWay.WebApi/Configs/gatewaySettings.json b/samples/GateWay.WebApi/Configs/gatewaySettings.json deleted file mode 100644 index 24fa1cba2..000000000 --- a/samples/GateWay.WebApi/Configs/gatewaySettings.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "AccessTokenExpireTimeSpan": "30", - "AuthorizationRoutePath": "api/authapp/signin", - "AuthorizationServiceKey": "Auth", - "TokenEndpointPath": "api/Auth", - "Register": { - "Provider": "Consul", - "Address": "127.0.0.1:8500" - } -} diff --git a/samples/GateWay.WebApi/Controllers/AuthController.cs b/samples/GateWay.WebApi/Controllers/AuthController.cs deleted file mode 100644 index 93e141624..000000000 --- a/samples/GateWay.WebApi/Controllers/AuthController.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; -using Surging.Core.CPlatform.Utilities; -using Surging.Core.ProxyGenerator; - -namespace Centa.Agency.WebApi.Controllers -{ - /// - /// 身份认证 - /// - [Route("api/[controller]")] - public class AuthController : Controller - { - /// - /// 登录 - /// - /// - [HttpPost("token")] - public object SignIn( [FromBody]Dictionary model) - { - model.Add("user", JsonConvert.SerializeObject(new - { - Name = "fanly", - Age = 18, - UserId = 1 - })); - string path = "api/AuthApp/SignIn"; - string serviceKey = "Auth"; - - - var serviceProxyProvider = ServiceLocator.GetService(); - return serviceProxyProvider.Invoke(model, path, serviceKey).Result; - - } - } -} diff --git a/samples/GateWay.WebApi/Controllers/BaseApiController.cs b/samples/GateWay.WebApi/Controllers/BaseApiController.cs deleted file mode 100644 index d484b5799..000000000 --- a/samples/GateWay.WebApi/Controllers/BaseApiController.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Caching.Distributed; -using Surging.Core.CPlatform.Utilities; -using Surging.Core.ProxyGenerator; - -namespace GateWay.WebApi.Controllers -{ - [Produces("application/json")] - [Route("api/BaseApi")] - public class BaseApiController : Controller //ControllerBase - { - protected IServiceProxyFactory serviceProxyFactory = ServiceLocator.GetService(); - protected readonly IDistributedCache _cache; - } -} \ No newline at end of file diff --git a/samples/GateWay.WebApi/Controllers/ServicesController.cs b/samples/GateWay.WebApi/Controllers/ServicesController.cs deleted file mode 100644 index c298b28fb..000000000 --- a/samples/GateWay.WebApi/Controllers/ServicesController.cs +++ /dev/null @@ -1,219 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Surging.Core.ApiGateWay; -using Surging.Core.ApiGateWay.OAuth; -using Surging.Core.CPlatform; -using Surging.Core.CPlatform.Filters.Implementation; -using Surging.Core.CPlatform.Routing; -using Surging.Core.ProxyGenerator; -using Surging.Core.ProxyGenerator.Utilitys; -using System; -using System.Collections.Generic; -using System.Security.Cryptography; -using System.Text; -using System.Threading.Tasks; -using System.Linq; -using GateWayAppConfig = Surging.Core.ApiGateWay.AppConfig; -using System.Reflection; -using Surging.Core.CPlatform.Utilities; - -namespace GateWay.WebApi -{ - /// - /// 身份认证 - /// - [Route("api/[controller]")] - public class AuthController : Controller - { - private readonly IServiceProxyProvider _serviceProxyProvider; - private readonly IServiceRouteProvider _serviceRouteProvider; - private readonly IAuthorizationServerProvider _authorizationServerProvider; - - - public AuthController() - /* IServiceProxyProvider serviceProxyProvider, - IServiceRouteProvider serviceRouteProvider, - IAuthorizationServerProvider authorizationServerProvider) - */ - { - // ServiceLocator.GetService(); // - //_serviceProxyProvider = serviceProxyProvider; - //_serviceRouteProvider = serviceRouteProvider; - //_authorizationServerProvider = authorizationServerProvider; - - _serviceProxyProvider = ServiceLocator.GetService(); - _serviceRouteProvider = ServiceLocator.GetService(); //serviceRouteProvider; - _authorizationServerProvider = ServiceLocator.GetService();// authorizationServerProvider; - - - } - - [HttpGet] - public IEnumerable Get() - { - return new string[] { "value1", "value2" }; - } - - /// - /// 登录 - /// - /// - /// - /// - /// - [HttpPost] - public async Task> Post(string path, string serviceKey, Dictionary model) - { - model = model ?? new Dictionary(); - ServiceResult result = ServiceResult.Create(false, null); - path = string.IsNullOrEmpty(path) ? - GateWayAppConfig.AuthorizationRoutePath : path.ToLower(); - if (OnAuthorization(path, model, ref result)) - { - if (path == GateWayAppConfig.AuthorizationRoutePath) - { - var token = await _authorizationServerProvider.GenerateTokenCredential(model); - if (token != null) - { - result = ServiceResult.Create(true, token); - result.StatusCode = (int)ServiceStatusCode.Success; - } - else - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; - } - } - else - { - if (!string.IsNullOrEmpty(serviceKey)) - { - - result = ServiceResult.Create(true, await _serviceProxyProvider.Invoke(model, path, serviceKey)); - result.StatusCode = (int)ServiceStatusCode.Success; - } - else - { - result = ServiceResult.Create(true, await _serviceProxyProvider.Invoke(model, path)); - result.StatusCode = (int)ServiceStatusCode.Success; - } - } - } - return result; - } - - private bool OnAuthorization(string path, Dictionary model, ref ServiceResult result) - { - bool isSuccess = true; - var route = _serviceRouteProvider.GetRouteByPath(path).Result; - if (route.ServiceDescriptor.EnableAuthorization()) - { - if (route.ServiceDescriptor.AuthType() == AuthorizationType.JWT.ToString()) - { - isSuccess = ValidateJwtAuthentication(route, model, ref result); - } - else - { - isSuccess = ValidateAppSecretAuthentication(route, path, model, ref result); - } - - } - return isSuccess; - } - - public bool ValidateJwtAuthentication(ServiceRoute route, Dictionary model, ref ServiceResult result) - { - bool isSuccess = true; - var author = HttpContext.Request.Headers["Authorization"]; - if (author.Count > 0) - { - if (route.Address.Any(p => p.DisableAuth == false)) - { - isSuccess = _authorizationServerProvider.ValidateClientAuthentication(author).Result; - if (!isSuccess) - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; - } - else - { - var keyValue = model.FirstOrDefault(); - if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType())) - { - dynamic instance = keyValue.Value; - instance.Payload = _authorizationServerProvider.GetPayloadString(author); - model.Remove(keyValue.Key); - model.Add(keyValue.Key, instance); - } - } - } - } - else - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error" }; - isSuccess = false; - } - return isSuccess; - } - - private bool ValidateAppSecretAuthentication(ServiceRoute route, string path, - Dictionary model, ref ServiceResult result) - { - bool isSuccess = true; - DateTime time; - var author = HttpContext.Request.Headers["Authorization"]; - if (route.Address.Any(p => p.DisableAuth == false)) - { - if (!string.IsNullOrEmpty(path) && model.ContainsKey("timeStamp") && author.Count > 0) - { - if (DateTime.TryParse(model["timeStamp"].ToString(), out time)) - { - var seconds = (DateTime.Now - time).TotalSeconds; - if (seconds <= 3560 && seconds >= 0) - { - if (!route.Address.Any(p => GetMD5($"{p.Token}{time.ToString("yyyy-MM-dd hh:mm:ss") }") == author.ToString())) - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; - isSuccess = false; - } - } - else - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; - isSuccess = false; - } - } - else - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; - isSuccess = false; - } - } - else - { - result = new ServiceResult { IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error" }; - isSuccess = false; - } - } - return isSuccess; - } - - public static string GetMD5(string encypStr) - { - try - { - var md5 = MD5.Create(); - var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(encypStr)); - var sb = new StringBuilder(); - foreach (byte b in bs) - { - sb.Append(b.ToString("X2")); - } - //所有字符转为大写 - return sb.ToString().ToLower(); - } - catch (Exception e) - { - Console.Error.WriteLine(e.StackTrace); - return null; - } - } - } -} diff --git a/samples/GateWay.WebApi/Controllers/ValuesController.cs b/samples/GateWay.WebApi/Controllers/ValuesController.cs deleted file mode 100644 index f09497629..000000000 --- a/samples/GateWay.WebApi/Controllers/ValuesController.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; - -namespace GateWay.WebApi -{ - [Route("api/[controller]")] - public class ValuesController : Controller - { - [HttpGet] - public IEnumerable Get() - { - return new string[] { "value1", "value2" }; - } - - [HttpGet("{id}")] - public string Get(int id) - { - return "value"; - } - - [HttpPost] - public void Post([FromBody]string value) - { - } - - [HttpPut("{id}")] - public void Put(int id, [FromBody]string value) - { - } - - [HttpDelete("{id}")] - public void Delete(int id) - { - } - } -} diff --git a/samples/GateWay.WebApi/CustomExceptionFilterAttribute.cs b/samples/GateWay.WebApi/CustomExceptionFilterAttribute.cs deleted file mode 100644 index 93393e9e7..000000000 --- a/samples/GateWay.WebApi/CustomExceptionFilterAttribute.cs +++ /dev/null @@ -1,76 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using Surging.Core.ApiGateWay; -using Surging.Core.ApiGateWay.OAuth; -using Surging.Core.CPlatform.Utilities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace GateWay.WebApi -{ - public class ResponeMsg - { - public string IsSucceed { get; set; } - public int StatusCode { get; set; } - public string Message { get; set; } - } - - public class CustomExceptionFilterAttribute : ExceptionFilterAttribute - { - private readonly IHostingEnvironment _hostingEnvironment; - private readonly IModelMetadataProvider _modelMetadataProvider; - - public CustomExceptionFilterAttribute( - IHostingEnvironment hostingEnvironment, - IModelMetadataProvider modelMetadataProvider) - { - _hostingEnvironment = hostingEnvironment; - _modelMetadataProvider = modelMetadataProvider; - } - - public override void OnException(ExceptionContext context) - { - if (!_hostingEnvironment.IsDevelopment()) - { - return; - } - var result = ServiceResult.Create(false, errorMessage: "request fail"); - result.StatusCode = 400; - context.Result = new JsonResult(result); - } - } - - public class CustomAuthorizeFilter : Attribute, IAuthorizationFilter - { - public void OnAuthorization(AuthorizationFilterContext context) - { - var isSuccess = false; - var _authorizationServerProvider = ServiceLocator.GetService(); - var author = context.HttpContext.Request.Headers["Authorization"]; - if(author.Count > 0) - { - isSuccess = _authorizationServerProvider.ValidateClientAuthentication(author).Result; - } - if (true||!isSuccess) - { - context.Result = new UnauthorizedResult(); - } - - /* var entry = - Dns.GetHostEntryAsync(context.HttpContext.Connection.RemoteIpAddress) - .GetAwaiter() - .GetResult(); - if (!entry.HostName.EndsWith(".MyDomain", - StringComparison.OrdinalIgnoreCase)) - { - context.Result = new UnauthorizedResult(); - } - */ - } - } -} - diff --git a/samples/GateWay.WebApi/GateWay.WebApi.csproj b/samples/GateWay.WebApi/GateWay.WebApi.csproj deleted file mode 100644 index b97ec5f3d..000000000 --- a/samples/GateWay.WebApi/GateWay.WebApi.csproj +++ /dev/null @@ -1,51 +0,0 @@ - - - - netcoreapp2.0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ..\pack\Surging.Core.ApiGateWay.dll - - - - diff --git a/samples/GateWay.WebApi/HiddenApiFilter.cs b/samples/GateWay.WebApi/HiddenApiFilter.cs deleted file mode 100644 index bc9021507..000000000 --- a/samples/GateWay.WebApi/HiddenApiFilter.cs +++ /dev/null @@ -1,45 +0,0 @@ -using Microsoft.AspNetCore.Mvc.ApiExplorer; -using Swashbuckle.AspNetCore.Swagger; -using Swashbuckle.AspNetCore.SwaggerGen; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace GateWay.WebApi -{ - /// - /// 隐藏接口,不生成到swagger文档展示 - /// - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] - - public partial class HiddenApiAttribute : Attribute { } - public class HiddenApiFilter : IDocumentFilter - { - /// - /// 重写Apply方法,移除隐藏接口的生成 - /// - /// - /// - public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) - { - foreach (ApiDescriptionGroup apiDescriptionGroup in context.ApiDescriptionsGroups.Items) - { - foreach (var apiDescription in apiDescriptionGroup.Items) - { - if(apiDescription.ControllerAttributes().First(c => c is HiddenApiAttribute)!=null) //if (Enumerable.OfType(apiDescription.ControllerAttributes().Where(c=>c is HiddenApiAttribute).ToList()) - { - string key = "/" + apiDescription.RelativePath; - if (key.Contains("?")) - { - int idx = key.IndexOf("?", StringComparison.Ordinal); - key = key.Substring(0, idx); - } - swaggerDoc.Paths.Remove(key); - } - } - - } - } - } -} diff --git a/samples/GateWay.WebApi/Program.cs b/samples/GateWay.WebApi/Program.cs deleted file mode 100644 index 42bc45609..000000000 --- a/samples/GateWay.WebApi/Program.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Server.Kestrel.Core; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; - -namespace GateWay.WebApi -{ - public class Program - { - public static void Main(string[] args) - { - var host = new WebHostBuilder() - .UseUrls("http://*:729") - .UseKestrel(options => - { - options.Limits.MaxConcurrentConnections = 100; - options.Limits.MaxConcurrentUpgradedConnections = 100; - options.Limits.MaxRequestBodySize = 10 * 1024; - options.Limits.MinRequestBodyDataRate = - new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10)); - options.Limits.MinResponseDataRate = - new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10)); - }) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseStartup() - .UseApplicationInsights() - .Build(); - host.Run(); - // BuildWebHost(args).Run(); - } - - public static IWebHost BuildWebHost(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup() - .Build(); - } -} diff --git a/samples/GateWay.WebApi/Properties/launchSettings.json b/samples/GateWay.WebApi/Properties/launchSettings.json deleted file mode 100644 index c5d069c3f..000000000 --- a/samples/GateWay.WebApi/Properties/launchSettings.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:729/", - "sslPort": 0 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "api/values", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "Centa.Agency.WebApi": { - "commandName": "Project", - "launchBrowser": true, - "launchUrl": "api/values", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "http://localhost:56956/" - } - } -} \ No newline at end of file diff --git a/samples/GateWay.WebApi/ScaffoldingReadMe.txt b/samples/GateWay.WebApi/ScaffoldingReadMe.txt deleted file mode 100644 index 19b66d8a3..000000000 --- a/samples/GateWay.WebApi/ScaffoldingReadMe.txt +++ /dev/null @@ -1,12 +0,0 @@ -Scaffolding has generated all the files and added the required dependencies. - -However the Application's Startup code may required additional changes for things to work end to end. -Add the following code to the Configure method in your Application's Startup class if not already done: - - app.UseMvc(routes => - { - route.MapRoute( - name : "areas", - template : "{area:exists}/{controller=Home}/{action=Index}/{id?}" - ); - }); diff --git a/samples/GateWay.WebApi/Startup.cs b/samples/GateWay.WebApi/Startup.cs deleted file mode 100644 index 942233503..000000000 --- a/samples/GateWay.WebApi/Startup.cs +++ /dev/null @@ -1,162 +0,0 @@ -using System; -using Autofac; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Swashbuckle.AspNetCore.Swagger; -using Newtonsoft.Json.Serialization; -using ApiGateWayConfig = Surging.Core.ApiGateWay.AppConfig; -using Surging.Core.CPlatform; -using Surging.Core.ProxyGenerator; -using Surging.Core.Consul; -using Surging.Core.CPlatform.Utilities; -using Surging.Core.DotNetty; -using Surging.Core.Consul.Configurations; -using Surging.Core.ApiGateWay.OAuth.Implementation.Configurations; -using Autofac.Extensions.DependencyInjection; -using Surging.Core.ApiGateWay; -using Surging.Core.Caching.Configurations; -using Surging.Core.Codec.MessagePack; -using Microsoft.AspNetCore.Mvc; - -namespace GateWay.WebApi -{ - public class Startup - { - public IConfiguration Configuration { get; } - public IContainer ApplicationContainer { get; private set; } - - public Startup(IHostingEnvironment env) - { - var builder = new ConfigurationBuilder() - .SetBasePath(env.ContentRootPath) - .AddCacheFile("Configs/cacheSettings.json", optional: false) - .AddJsonFile("Configs/appsettings.json", optional: true, reloadOnChange: true) - .AddGatewayFile("Configs/gatewaySettings.json", optional: false) - .AddJsonFile($"Configs/appsettings.{env.EnvironmentName}.json", optional: true); - Configuration = builder.Build(); - } - - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - RegisterAutofac(services); - // Register the Swagger generator, defining one or more Swagger documents - services.AddSwaggerGen(c => - { - c.SwaggerDoc("v1", new Info { Title = "网关 API", Version = "v1" }); - c.DescribeAllParametersInCamelCase(); - }); - - // services.AddResponseCaching(); - - //分布式缓存 Microsoft.Extensions.Caching.Redis NuGet package - /*services.AddDistributedRedisCache(options => - { - options.Configuration = "servername"; - options.InstanceName = "Shopping"; - });*/ - //基于 的身份认证 - /* services.AddCookieAuthentication(CookieAuthenticationDefaults.Authenticatio - nScheme, options => - { - options.LoginPath = "/Account/Login/"; - options.AccessDeniedPath = "/Account/Forbidden/"; - options.LogoutPath = "/Account/Logout"; - options.ReturnUrlParameter = "ReturnUrl"; - }); - - Microsoft.AspNetCore.Identity.EntityFrameworkCore - - services.AddEntityFramework() -.AddSqlServer() -.AddDbContext(options => -options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString -"])); -services.AddIdentity() -.AddEntityFrameworkStores() -.AddDefaultTokenProviders(); - - - services.AddCors(); - - - - - - - - */ - } - - private IServiceProvider RegisterAutofac(IServiceCollection services) - { - var registerConfig = ApiGateWayConfig.Register; - services.AddMvc(options => - { - options.Filters.Add(typeof(CustomExceptionFilterAttribute)); - //options.CacheProfiles.Add("5minutes", new CacheProfile - //{ - // Duration = 5 * 60, - // Location = ResponseCacheLocation.Any, - // VaryByHeader = "Accept-Language" - //}); - //[ResponseCache(CacheProfileName = "5minutes")] - }).AddJsonOptions(options => - { - options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; - options.SerializerSettings.ContractResolver = new DefaultContractResolver(); - }); - services.AddLogging(); - var builder = new ContainerBuilder(); - builder.Populate(services); - builder.AddMicroService(option => - { - option.AddClient(); - // option.AddClientIntercepted(typeof(CacheProviderInterceptor)); - option.UseConsulManager(new ConfigInfo(registerConfig.Address)); - option.UseDotNettyTransport(); - option.AddApiGateWay(); - option.UseJsonCodec(); - // option.UseMessagePackCodec(); - builder.Register(m => new CPlatformContainer(ServiceLocator.Current)); - }); - ServiceLocator.Current = builder.Build(); - return new AutofacServiceProvider(ServiceLocator.Current); - - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - - - } - else - { - app.UseExceptionHandler("/Home/Error"); - } - app.UseStaticFiles(); - - // app.UseAuthentication(); - //app.UseCors(builder => builder.WithOrigins("http://mysite.com")); - //app.UseResponseCaching(); - app.UseMvc(); - - // Enable middleware to serve generated Swagger as a JSON endpoint. - app.UseSwagger(); - - // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. - app.UseSwaggerUI(c => - { - c.SwaggerEndpoint("/swagger/v1/swagger.json", "网关 API V1"); - }); - - } - } -} diff --git a/samples/GateWay.WebApi/appsettings.Development.json b/samples/GateWay.WebApi/appsettings.Development.json deleted file mode 100644 index fa8ce71a9..000000000 --- a/samples/GateWay.WebApi/appsettings.Development.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "Logging": { - "IncludeScopes": false, - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } - } -} diff --git a/samples/GateWay.WebApi/appsettings.json b/samples/GateWay.WebApi/appsettings.json deleted file mode 100644 index 26bb0ac7a..000000000 --- a/samples/GateWay.WebApi/appsettings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning" - } - } - } -} diff --git a/samples/LogServer/Application.Interface.SysLog/Application.Interface.SysLog.csproj b/samples/LogServer/Application.Interface.SysLog/Application.Interface.SysLog.csproj deleted file mode 100644 index 8b977eded..000000000 --- a/samples/LogServer/Application.Interface.SysLog/Application.Interface.SysLog.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - netcoreapp2.0 - - - - ..\HostService\bin\Debug - - - - - - - diff --git a/samples/LogServer/Application.Interface.SysLog/ILogAppService.cs b/samples/LogServer/Application.Interface.SysLog/ILogAppService.cs deleted file mode 100644 index db0c2c0aa..000000000 --- a/samples/LogServer/Application.Interface.SysLog/ILogAppService.cs +++ /dev/null @@ -1,45 +0,0 @@ -using Surging.Core.CPlatform.Ioc; -using Surging.Core.CPlatform.Runtime.Server.Implementation.ServiceDiscovery.Attributes; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace Application.Interface.SysLog -{ - public class LogListViewDto - { - /// - /// 日志类型 - /// - public string LogType { get; set; } - - /// - /// 日志类型 - /// - public DateTime CreateTime { get; set; } - - /// - /// 操作部门 - /// - public string OpDept { get; set; } - - /// - /// 操作人 - /// - public string OpUser { get; set; } - } - [ServiceBundle("api/{Service}")] - public interface ILogAppService : IServiceKey - { - /// - /// 列表分页查询 - /// - /// - [Service(Date = "2018-1-20", Director = "刘旭东", Name = "查询日志")] - //[Authorization(AuthType = AuthorizationType.JWT)] - // [BindEvent("修改系统参数的事件|订单支付的事件")] - Task> PagedQuery(int pageIndex,int pageSize); - - - } -} diff --git a/samples/LogServer/Application.Service.SysLog/Application.Service.SysLog.csproj b/samples/LogServer/Application.Service.SysLog/Application.Service.SysLog.csproj deleted file mode 100644 index 72bd41272..000000000 --- a/samples/LogServer/Application.Service.SysLog/Application.Service.SysLog.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - - netcoreapp2.0 - - - - ..\HostService\bin\Debug - - - - - - - - - - - - - - - diff --git a/samples/LogServer/Application.Service.SysLog/LogAppService.cs b/samples/LogServer/Application.Service.SysLog/LogAppService.cs deleted file mode 100644 index 717e0794e..000000000 --- a/samples/LogServer/Application.Service.SysLog/LogAppService.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Application.Interface.SysLog; -using Surging.Core.ProxyGenerator; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace Application.Service.SysLog -{ - public class LogAppService : ProxyServiceBase, ILogAppService - { - public Task> PagedQuery(int pageIndex, int pageSize) - { - throw new NotImplementedException(); - } - } -} diff --git a/samples/LogServer/HostService/Configs/log4net.config b/samples/LogServer/HostService/Configs/log4net.config deleted file mode 100644 index 42fd16880..000000000 --- a/samples/LogServer/HostService/Configs/log4net.config +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/LogServer/HostService/HostService.csproj b/samples/LogServer/HostService/HostService.csproj deleted file mode 100644 index 2339f49f1..000000000 --- a/samples/LogServer/HostService/HostService.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - Exe - netcoreapp2.0 - - - - - - - - - - - - - - - - - - PreserveNewest - - - PreserveNewest - - - - diff --git a/samples/LogServer/HostService/Program.cs b/samples/LogServer/HostService/Program.cs deleted file mode 100644 index 0b4ed6bc8..000000000 --- a/samples/LogServer/HostService/Program.cs +++ /dev/null @@ -1,64 +0,0 @@ -using Autofac; -using Surging.Core.Codec.MessagePack; -using Surging.Core.Consul; -using Surging.Core.Consul.Configurations; -using Surging.Core.CPlatform; -using Surging.Core.CPlatform.Utilities; -using Surging.Core.DotNetty; -using Surging.Core.EventBusRabbitMQ; -using Surging.Core.ServiceHosting; -using Surging.Core.ServiceHosting.Internal.Implementation; -using System; -using System.Text; -using Surging.Core.Log4net; -using Surging.Core.ProxyGenerator; - -namespace Centa.HostService.SysLog -{ - public class Program - { - static void Main(string[] args) - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - var host = new ServiceHostBuilder() - //.RegisterServices(provider => - //{ - // //这里写自己的注册 - //}) - .RegisterServices(builder => - { - builder.AddMicroService(option => - { - option.AddServiceRuntime(); - option.AddRelateService(); - option.UseConsulManager(new ConfigInfo("127.0.0.1:8500")); - option.UseDotNettyTransport(); - option.UseRabbitMQTransport(); - option.AddRabbitMQAdapt(); - // option.UseMessagePackCodec(); - option.UseJsonCodec(); - builder.Register(p => new CPlatformContainer(ServiceLocator.Current)); - }); - }) - .SubscribeAt() - .UseLog4net("Configs/log4net.config") - .UseServer(options => - { - options.Ip = "127.0.0.1"; - options.Port = 2018; - options.Token = "True"; - options.ExecutionTimeoutInMilliseconds = 30000; - options.MaxConcurrentRequests = 200; - }) - // .UseProxy() - .UseStartup() - .Build(); - - using (host.Run()) - { - Console.WriteLine($"服务端启动成功,{DateTime.Now}。"); - Console.ReadLine(); - } - } - } -} diff --git a/samples/LogServer/HostService/Startup.cs b/samples/LogServer/HostService/Startup.cs deleted file mode 100644 index 1b90c95a5..000000000 --- a/samples/LogServer/HostService/Startup.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Autofac; -using Autofac.Extensions.DependencyInjection; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Surging.Core.CPlatform.Utilities; -using Surging.Core.EventBusRabbitMQ.Configurations; -using System; - -namespace Centa.HostService.SysLog -{ - public class Startup - { - public Startup() - { - var config = new ConfigurationBuilder() - .SetBasePath(AppContext.BaseDirectory); - ConfigureEventBus(config); - ConfigureCache(config); - } - - public IContainer ConfigureServices(ContainerBuilder builder) - { - var services = new ServiceCollection(); - ConfigureLogging(services); - builder.Populate(services); - ServiceLocator.Current = builder.Build(); - return ServiceLocator.Current; - } - - public void Configure(IContainer app) - { - app.Resolve().AddConsole((c, l) => (int)l >= 3); - } - - #region 私有方法 - /// - /// 配置日志服务 - /// - /// - private void ConfigureLogging(IServiceCollection services) - { - services.AddLogging(); - } - - private static void ConfigureEventBus(IConfigurationBuilder build) - { - build - .AddEventBusFile("eventBusSettings.json", optional: false); - } - - /// - /// 配置缓存服务 - /// - private void ConfigureCache(IConfigurationBuilder build) - { - // build.AddCacheFile("cacheSettings.json", optional: false); - } - #endregion - - } -} diff --git a/samples/LogServer/HostService/cacheSettings.json b/samples/LogServer/HostService/cacheSettings.json deleted file mode 100644 index ab9c7e43d..000000000 --- a/samples/LogServer/HostService/cacheSettings.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "CachingSettings": [ - { - "Id": "ddlCache", - "Class": "Surging.Core.Caching.RedisCache.RedisContext,Surging.Core.Caching", - "Properties": [ - { - "Name": "appRuleFile", - "Ref": "rule" - }, - { - "Name": "dataContextPool", - "Ref": "ddls_sample", - "Maps": [ - { - "Name": "Redis", - "Properties": [ - { - "value": "127.0.0.1:6379::1" - } - ] - }, - { - "Name": "MemoryCache" - } - ] - }, - { - "Name": "defaultExpireTime", - "value": "120" - }, - { - "Name": "connectTimeout", - "Value": "120" - }, - { - "Name": "minSize", - "Value": "1" - }, - { - "Name": "maxSize", - "Value": "10" - } - ] - } - ] -} diff --git a/samples/LogServer/HostService/eventBusSettings.json b/samples/LogServer/HostService/eventBusSettings.json deleted file mode 100644 index d5d4487b7..000000000 --- a/samples/LogServer/HostService/eventBusSettings.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "EventBusConnection": "localhost", - "EventBusUserName": "guest", - "EventBusPassword": "guest" -} - diff --git a/samples/MicroService.sln b/samples/MicroService.sln deleted file mode 100644 index 64818f727..000000000 --- a/samples/MicroService.sln +++ /dev/null @@ -1,206 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27130.2010 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "FrontEnd", "FrontEnd", "{16D922E9-E971-4E09-8957-2BEC03950B59}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Doc", "Doc", "{6B3A06FA-EF30-4CB4-955F-AF7FE2E9C60D}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{24CC1A19-D3EE-4B3E-89EC-012BA4AFD112}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "LogServer", "LogServer", "{11EC931F-CFB3-4395-BB64-1295DBA7CC3D}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "1-Distributed Services", "1-Distributed Services", "{7B1CB514-E30D-4D9D-B0DD-AC31AD7BB543}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "2-Application Services", "2-Application Services", "{4AE3BF33-FE59-4FD2-BB67-E4CB313708C5}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "4-Repository", "4-Repository", "{7ED005CB-4A0C-4E2A-8723-EF98EDC58037}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Repository.Dapper.Core", "Common\Repository.Dapper.Core\Repository.Dapper.Core.csproj", "{52B3EA74-1B2C-44B2-A617-9F32B3135818}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Repository.EF.Core", "Common\Repository.EF.Core\Repository.EF.Core.csproj", "{2F30368D-2ECE-4833-AE7B-0FDC34BA3102}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDD.Core", "Common\DDD.Core\DDD.Core.csproj", "{FABAFCF3-4A9A-4853-8178-CFA7FC93E8BB}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DTO.Core", "Common\DTO.Core\DTO.Core.csproj", "{93CC491E-83CD-47B6-8142-5F4CD28AC614}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HostService", "LogServer\HostService\HostService.csproj", "{FBB4AF83-CD4A-4428-8C10-676B2658006A}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Application.Interface.SysLog", "LogServer\Application.Interface.SysLog\Application.Interface.SysLog.csproj", "{631D7361-D683-4909-91F1-5C3324DCA282}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Application.Service.SysLog", "LogServer\Application.Service.SysLog\Application.Service.SysLog.csproj", "{53D00367-E40B-472A-935F-4C27B5762128}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AuthServer", "AuthServer", "{1AFE40BE-F129-457C-AA23-C9A19D6ADF4F}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "1-Distributed Services", "1-Distributed Services", "{0AB757EA-7849-4461-9849-40D49B3E86ED}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HostService", "AuthServer\HostService\HostService.csproj", "{6313CF74-D8EE-4D18-93FD-6F2DAC33D90E}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "2-Application Services", "2-Application Services", "{904FEED6-3597-4BFB-9BF3-5DA54DC705A3}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Application.Interface.Auth", "AuthServer\Application.Interface.Auth\Application.Interface.Auth.csproj", "{936B0D84-8B2A-4DEA-A287-0290EC64C017}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Application.Service.Auth", "AuthServer\Application.Service.Auth\Application.Service.Auth.csproj", "{6E4677D6-60A5-4868-B92A-6FE8FF1714D2}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "4-Repository", "4-Repository", "{95507E5B-2725-4263-93A0-4DF88A32C9D1}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OrgServer", "OrgServer", "{6850BB45-B72B-45FD-969B-58A5852FE52D}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "1-Distributed Services", "1-Distributed Services", "{977B9CD7-FA17-417F-8577-2A13E7D6AFB9}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "2-Application Services", "2-Application Services", "{7F1BD8CD-4F80-4586-B3BE-B8B159E224A5}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "4-Repository", "4-Repository", "{27935240-E1E5-4D55-AFA2-27AA92681789}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HostService", "OrgServer\HostService\HostService.csproj", "{C19A5D2C-8E75-41AE-A1FF-D63D25CB98A0}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Application.Interface.Org", "OrgServer\Application.Interface.Org\Application.Interface.Org.csproj", "{F47E8649-62A3-4B7F-8B81-13E995D17DAF}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Application.Service.Org", "OrgServer\Application.Service.Org\Application.Service.Org.csproj", "{797C2369-5E7D-4CA3-8AAC-15BE4604E7C7}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "App.Core", "Common\App.Core\App.Core.csproj", "{027BA86B-43EE-4825-A3E3-A988F847A1CA}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "3-Domain", "3-Domain", "{9924D2D9-6D66-44CA-B5F8-9A46ACD637C5}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Domain.Org", "OrgServer\Domain\Domain.Org.csproj", "{F44DCA50-03E6-46CF-9694-E15915C9F443}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "3-Domain", "3-Domain", "{13D4465F-E298-46DD-822D-048BCF99CC47}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Domain.Auth", "AuthServer\Domain\Domain.Auth.csproj", "{2D571933-83F7-4D36-A0DB-3A47EAC64930}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Repository.Auth", "AuthServer\Repository.Auth\Repository.Auth.csproj", "{543EEE3D-7A8D-44F1-86AB-B5EADB3579B2}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Repository.Org", "OrgServer\Repository.Org\Repository.Org.csproj", "{B884CB7A-70E7-4710-A49A-3F22E90BBF1E}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Config.Core", "Common\Config.Core\Config.Core.csproj", "{91E42C03-C901-4085-A89F-B6BEED95E25F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GateWay.WebApi", "GateWay.WebApi\GateWay.WebApi.csproj", "{49370CFD-21BC-4B4E-8AB9-8CC8B18C3180}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {52B3EA74-1B2C-44B2-A617-9F32B3135818}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {52B3EA74-1B2C-44B2-A617-9F32B3135818}.Debug|Any CPU.Build.0 = Debug|Any CPU - {52B3EA74-1B2C-44B2-A617-9F32B3135818}.Release|Any CPU.ActiveCfg = Release|Any CPU - {52B3EA74-1B2C-44B2-A617-9F32B3135818}.Release|Any CPU.Build.0 = Release|Any CPU - {2F30368D-2ECE-4833-AE7B-0FDC34BA3102}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2F30368D-2ECE-4833-AE7B-0FDC34BA3102}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2F30368D-2ECE-4833-AE7B-0FDC34BA3102}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2F30368D-2ECE-4833-AE7B-0FDC34BA3102}.Release|Any CPU.Build.0 = Release|Any CPU - {FABAFCF3-4A9A-4853-8178-CFA7FC93E8BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FABAFCF3-4A9A-4853-8178-CFA7FC93E8BB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FABAFCF3-4A9A-4853-8178-CFA7FC93E8BB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FABAFCF3-4A9A-4853-8178-CFA7FC93E8BB}.Release|Any CPU.Build.0 = Release|Any CPU - {93CC491E-83CD-47B6-8142-5F4CD28AC614}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {93CC491E-83CD-47B6-8142-5F4CD28AC614}.Debug|Any CPU.Build.0 = Debug|Any CPU - {93CC491E-83CD-47B6-8142-5F4CD28AC614}.Release|Any CPU.ActiveCfg = Release|Any CPU - {93CC491E-83CD-47B6-8142-5F4CD28AC614}.Release|Any CPU.Build.0 = Release|Any CPU - {FBB4AF83-CD4A-4428-8C10-676B2658006A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FBB4AF83-CD4A-4428-8C10-676B2658006A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FBB4AF83-CD4A-4428-8C10-676B2658006A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FBB4AF83-CD4A-4428-8C10-676B2658006A}.Release|Any CPU.Build.0 = Release|Any CPU - {631D7361-D683-4909-91F1-5C3324DCA282}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {631D7361-D683-4909-91F1-5C3324DCA282}.Debug|Any CPU.Build.0 = Debug|Any CPU - {631D7361-D683-4909-91F1-5C3324DCA282}.Release|Any CPU.ActiveCfg = Release|Any CPU - {631D7361-D683-4909-91F1-5C3324DCA282}.Release|Any CPU.Build.0 = Release|Any CPU - {53D00367-E40B-472A-935F-4C27B5762128}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {53D00367-E40B-472A-935F-4C27B5762128}.Debug|Any CPU.Build.0 = Debug|Any CPU - {53D00367-E40B-472A-935F-4C27B5762128}.Release|Any CPU.ActiveCfg = Release|Any CPU - {53D00367-E40B-472A-935F-4C27B5762128}.Release|Any CPU.Build.0 = Release|Any CPU - {6313CF74-D8EE-4D18-93FD-6F2DAC33D90E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6313CF74-D8EE-4D18-93FD-6F2DAC33D90E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6313CF74-D8EE-4D18-93FD-6F2DAC33D90E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6313CF74-D8EE-4D18-93FD-6F2DAC33D90E}.Release|Any CPU.Build.0 = Release|Any CPU - {936B0D84-8B2A-4DEA-A287-0290EC64C017}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {936B0D84-8B2A-4DEA-A287-0290EC64C017}.Debug|Any CPU.Build.0 = Debug|Any CPU - {936B0D84-8B2A-4DEA-A287-0290EC64C017}.Release|Any CPU.ActiveCfg = Release|Any CPU - {936B0D84-8B2A-4DEA-A287-0290EC64C017}.Release|Any CPU.Build.0 = Release|Any CPU - {6E4677D6-60A5-4868-B92A-6FE8FF1714D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6E4677D6-60A5-4868-B92A-6FE8FF1714D2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6E4677D6-60A5-4868-B92A-6FE8FF1714D2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6E4677D6-60A5-4868-B92A-6FE8FF1714D2}.Release|Any CPU.Build.0 = Release|Any CPU - {C19A5D2C-8E75-41AE-A1FF-D63D25CB98A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C19A5D2C-8E75-41AE-A1FF-D63D25CB98A0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C19A5D2C-8E75-41AE-A1FF-D63D25CB98A0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C19A5D2C-8E75-41AE-A1FF-D63D25CB98A0}.Release|Any CPU.Build.0 = Release|Any CPU - {F47E8649-62A3-4B7F-8B81-13E995D17DAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F47E8649-62A3-4B7F-8B81-13E995D17DAF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F47E8649-62A3-4B7F-8B81-13E995D17DAF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F47E8649-62A3-4B7F-8B81-13E995D17DAF}.Release|Any CPU.Build.0 = Release|Any CPU - {797C2369-5E7D-4CA3-8AAC-15BE4604E7C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {797C2369-5E7D-4CA3-8AAC-15BE4604E7C7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {797C2369-5E7D-4CA3-8AAC-15BE4604E7C7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {797C2369-5E7D-4CA3-8AAC-15BE4604E7C7}.Release|Any CPU.Build.0 = Release|Any CPU - {027BA86B-43EE-4825-A3E3-A988F847A1CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {027BA86B-43EE-4825-A3E3-A988F847A1CA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {027BA86B-43EE-4825-A3E3-A988F847A1CA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {027BA86B-43EE-4825-A3E3-A988F847A1CA}.Release|Any CPU.Build.0 = Release|Any CPU - {F44DCA50-03E6-46CF-9694-E15915C9F443}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F44DCA50-03E6-46CF-9694-E15915C9F443}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F44DCA50-03E6-46CF-9694-E15915C9F443}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F44DCA50-03E6-46CF-9694-E15915C9F443}.Release|Any CPU.Build.0 = Release|Any CPU - {2D571933-83F7-4D36-A0DB-3A47EAC64930}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2D571933-83F7-4D36-A0DB-3A47EAC64930}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2D571933-83F7-4D36-A0DB-3A47EAC64930}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2D571933-83F7-4D36-A0DB-3A47EAC64930}.Release|Any CPU.Build.0 = Release|Any CPU - {543EEE3D-7A8D-44F1-86AB-B5EADB3579B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {543EEE3D-7A8D-44F1-86AB-B5EADB3579B2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {543EEE3D-7A8D-44F1-86AB-B5EADB3579B2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {543EEE3D-7A8D-44F1-86AB-B5EADB3579B2}.Release|Any CPU.Build.0 = Release|Any CPU - {B884CB7A-70E7-4710-A49A-3F22E90BBF1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B884CB7A-70E7-4710-A49A-3F22E90BBF1E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B884CB7A-70E7-4710-A49A-3F22E90BBF1E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B884CB7A-70E7-4710-A49A-3F22E90BBF1E}.Release|Any CPU.Build.0 = Release|Any CPU - {91E42C03-C901-4085-A89F-B6BEED95E25F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {91E42C03-C901-4085-A89F-B6BEED95E25F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {91E42C03-C901-4085-A89F-B6BEED95E25F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {91E42C03-C901-4085-A89F-B6BEED95E25F}.Release|Any CPU.Build.0 = Release|Any CPU - {49370CFD-21BC-4B4E-8AB9-8CC8B18C3180}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {49370CFD-21BC-4B4E-8AB9-8CC8B18C3180}.Debug|Any CPU.Build.0 = Debug|Any CPU - {49370CFD-21BC-4B4E-8AB9-8CC8B18C3180}.Release|Any CPU.ActiveCfg = Release|Any CPU - {49370CFD-21BC-4B4E-8AB9-8CC8B18C3180}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {7B1CB514-E30D-4D9D-B0DD-AC31AD7BB543} = {11EC931F-CFB3-4395-BB64-1295DBA7CC3D} - {4AE3BF33-FE59-4FD2-BB67-E4CB313708C5} = {11EC931F-CFB3-4395-BB64-1295DBA7CC3D} - {7ED005CB-4A0C-4E2A-8723-EF98EDC58037} = {11EC931F-CFB3-4395-BB64-1295DBA7CC3D} - {52B3EA74-1B2C-44B2-A617-9F32B3135818} = {24CC1A19-D3EE-4B3E-89EC-012BA4AFD112} - {2F30368D-2ECE-4833-AE7B-0FDC34BA3102} = {24CC1A19-D3EE-4B3E-89EC-012BA4AFD112} - {FABAFCF3-4A9A-4853-8178-CFA7FC93E8BB} = {24CC1A19-D3EE-4B3E-89EC-012BA4AFD112} - {93CC491E-83CD-47B6-8142-5F4CD28AC614} = {24CC1A19-D3EE-4B3E-89EC-012BA4AFD112} - {FBB4AF83-CD4A-4428-8C10-676B2658006A} = {7B1CB514-E30D-4D9D-B0DD-AC31AD7BB543} - {631D7361-D683-4909-91F1-5C3324DCA282} = {4AE3BF33-FE59-4FD2-BB67-E4CB313708C5} - {53D00367-E40B-472A-935F-4C27B5762128} = {4AE3BF33-FE59-4FD2-BB67-E4CB313708C5} - {0AB757EA-7849-4461-9849-40D49B3E86ED} = {1AFE40BE-F129-457C-AA23-C9A19D6ADF4F} - {6313CF74-D8EE-4D18-93FD-6F2DAC33D90E} = {0AB757EA-7849-4461-9849-40D49B3E86ED} - {904FEED6-3597-4BFB-9BF3-5DA54DC705A3} = {1AFE40BE-F129-457C-AA23-C9A19D6ADF4F} - {936B0D84-8B2A-4DEA-A287-0290EC64C017} = {904FEED6-3597-4BFB-9BF3-5DA54DC705A3} - {6E4677D6-60A5-4868-B92A-6FE8FF1714D2} = {904FEED6-3597-4BFB-9BF3-5DA54DC705A3} - {95507E5B-2725-4263-93A0-4DF88A32C9D1} = {1AFE40BE-F129-457C-AA23-C9A19D6ADF4F} - {977B9CD7-FA17-417F-8577-2A13E7D6AFB9} = {6850BB45-B72B-45FD-969B-58A5852FE52D} - {7F1BD8CD-4F80-4586-B3BE-B8B159E224A5} = {6850BB45-B72B-45FD-969B-58A5852FE52D} - {27935240-E1E5-4D55-AFA2-27AA92681789} = {6850BB45-B72B-45FD-969B-58A5852FE52D} - {C19A5D2C-8E75-41AE-A1FF-D63D25CB98A0} = {977B9CD7-FA17-417F-8577-2A13E7D6AFB9} - {F47E8649-62A3-4B7F-8B81-13E995D17DAF} = {7F1BD8CD-4F80-4586-B3BE-B8B159E224A5} - {797C2369-5E7D-4CA3-8AAC-15BE4604E7C7} = {7F1BD8CD-4F80-4586-B3BE-B8B159E224A5} - {027BA86B-43EE-4825-A3E3-A988F847A1CA} = {24CC1A19-D3EE-4B3E-89EC-012BA4AFD112} - {9924D2D9-6D66-44CA-B5F8-9A46ACD637C5} = {6850BB45-B72B-45FD-969B-58A5852FE52D} - {F44DCA50-03E6-46CF-9694-E15915C9F443} = {9924D2D9-6D66-44CA-B5F8-9A46ACD637C5} - {13D4465F-E298-46DD-822D-048BCF99CC47} = {1AFE40BE-F129-457C-AA23-C9A19D6ADF4F} - {2D571933-83F7-4D36-A0DB-3A47EAC64930} = {13D4465F-E298-46DD-822D-048BCF99CC47} - {543EEE3D-7A8D-44F1-86AB-B5EADB3579B2} = {95507E5B-2725-4263-93A0-4DF88A32C9D1} - {B884CB7A-70E7-4710-A49A-3F22E90BBF1E} = {27935240-E1E5-4D55-AFA2-27AA92681789} - {91E42C03-C901-4085-A89F-B6BEED95E25F} = {24CC1A19-D3EE-4B3E-89EC-012BA4AFD112} - {49370CFD-21BC-4B4E-8AB9-8CC8B18C3180} = {16D922E9-E971-4E09-8957-2BEC03950B59} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {9536404C-EF7E-42FF-A785-CAADEA7C08A5} - EndGlobalSection -EndGlobal diff --git a/samples/OrgServer/Application.Interface.Org/Application.Interface.Org.csproj b/samples/OrgServer/Application.Interface.Org/Application.Interface.Org.csproj deleted file mode 100644 index e4da24ad5..000000000 --- a/samples/OrgServer/Application.Interface.Org/Application.Interface.Org.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - netcoreapp2.0 - - - - ..\HostService\bin\Debug - - - - - - - - - - - diff --git a/samples/OrgServer/Application.Interface.Org/DTO/DeptAddReq.cs b/samples/OrgServer/Application.Interface.Org/DTO/DeptAddReq.cs deleted file mode 100644 index ab9879432..000000000 --- a/samples/OrgServer/Application.Interface.Org/DTO/DeptAddReq.cs +++ /dev/null @@ -1,111 +0,0 @@ -using DTO.Core; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Application.Interface.Org -{ - public class DeptEditReq : EntityCUDReq - { - /// - /// 所属公司ID - /// - - public Guid CorporationKeyId { get; set; } - public Guid? DepartmentKeyId { get; set; } - - /// - /// 部门名称 - /// - - public string DepartmentName { get; set; } - - /// - /// 部门名称简拼 - /// - - public string NameSpell { get; set; } - - /// - /// 部门编号 - /// - - public string DepartmentNo { get; set; } - - - - /// - /// 部门负责人KeyId - /// - - public Guid? DeptCheifKeyId { get; set; } - /// - /// 部门上一级负责人 - /// - - public Guid? ParentDeptCheifKeyId { get; set; } - /// - /// 部门上一级负责人部门ID - /// - - public Guid? ParentDeptCheifDeptId { get; set; } - /// - /// 父部门KeyId - /// - - public Guid? ParentDeptKeyId { get; set; } - - /// - /// 部门电话 - /// - - public string Telephone { get; set; } - - /// - /// 部门来源(null为A+系统新增,1为CCAI系统新增) - /// - - public int? SourceObjectFlag { get; set; } - - /// - /// 纬度 - /// - - public string Latitude { get; set; } - /// - /// 经度 - /// - - public string Longitude { get; set; } - - /// - /// 部门类型(普通额外公客池、客源市场) - /// - - // public DepartmentTypeEnum? DepartmentType { get; set; } - } - - public class CorpEditReq: EntityCUDReq - { - public string CorpName { get; set; } - - } - - public class RoleEditReq : EntityCUDReq - { - public string RoleName { get; set; } - - } - - public class EmployeeEditReq : EntityCUDReq - { - public string Name { get; set; } - public string Mobile { get; set; } - public Guid DeptKeyId { get; set; } - public Guid RoleKeyId { get; set; } - public string RoleName { get; set; } - - - - } -} diff --git a/samples/OrgServer/Application.Interface.Org/DTO/EmployeePermission.cs b/samples/OrgServer/Application.Interface.Org/DTO/EmployeePermission.cs deleted file mode 100644 index 71978f5a5..000000000 --- a/samples/OrgServer/Application.Interface.Org/DTO/EmployeePermission.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Application.Interface.Org.DTO -{ - class EmployeePermission - { - } -} diff --git a/samples/OrgServer/Application.Interface.Org/EVENT/CorporationActivated.cs b/samples/OrgServer/Application.Interface.Org/EVENT/CorporationActivated.cs deleted file mode 100644 index a157e80bd..000000000 --- a/samples/OrgServer/Application.Interface.Org/EVENT/CorporationActivated.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Surging.Core.CPlatform.EventBus.Events; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Application.Interface.Org.EVENT -{ - /// - /// 新注册公司被激活的事件 - /// - public class CorporationActivatedEvent: IntegrationEvent - { - public Guid CorpId { get; set; } - public string Email { get; set; } - public string EmpId { get; set; } - - } -} diff --git a/samples/OrgServer/Application.Interface.Org/EVENT/ICorpEventHandler.cs b/samples/OrgServer/Application.Interface.Org/EVENT/ICorpEventHandler.cs deleted file mode 100644 index 2d1ae5637..000000000 --- a/samples/OrgServer/Application.Interface.Org/EVENT/ICorpEventHandler.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Application.Interface.Org -{ - /// - /// 事件处理器 - /// - public interface ICorpEventHandler //: IIntegrationEventHandler - { - } -} diff --git a/samples/OrgServer/Application.Interface.Org/IOrgAppService.cs b/samples/OrgServer/Application.Interface.Org/IOrgAppService.cs deleted file mode 100644 index e4ff25a6a..000000000 --- a/samples/OrgServer/Application.Interface.Org/IOrgAppService.cs +++ /dev/null @@ -1,142 +0,0 @@ -using DTO.Core; -using Surging.Core.CPlatform.Ioc; -using Surging.Core.CPlatform.Runtime.Server.Implementation.ServiceDiscovery.Attributes; -using Surging.Core.CPlatform.Support; -using Surging.Core.CPlatform.Support.Attributes; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace Application.Interface.Org -{ - [ServiceBundle("api/{Service}")] - public interface IOrgAppService : IServiceKey - { - #region CMD - #region 公司管理 - - /// - /// 注册一个新公司 - /// - /// - /// - [Service(Date = "2018-2-12", Director = "刘旭东", Name = "注册一个新公司")] - Task RegisterCorporation(CorpEditReq req); - - /// - /// 激活一个新公司 - /// 手机短信或者邮箱确认 - /// - /// - /// - [Service(Date = "2018-2-12", Director = "刘旭东", Name = "激活一个新公司")] - Task ActivateCorporation(CommonCMDReq req); - - /// - /// 修改公司信息 - /// - /// - /// - [Service(Date = "2018-2-12", Director = "刘旭东", Name = "修改公司信息")] - Task EditCorporation(CorpEditReq req); - #endregion - - #region 权限管理 - - #endregion - - #endregion - - - #region Query - - #region 公司 - /// - /// 所有公司列表 - /// - /// - /// - [Service(Date = "2018-1-30", Director = "刘旭东", Name = "所有公司列表")] - Task FindCorps(BaseTreeSearchReq req); - #endregion - - #region 部门管理 - - /// - /// 当前用户所在公司全部部门列表 - /// 使用场景:部门树加载显示 - /// - /// - /// 全部部门列表 - //[Command(Strategy = StrategyType.Failover, RequestCacheEnabled = false)] - [Service(Date = "2018-1-30", Director = "刘旭东", Name = "当前用户所在公司全部部门列表")] - Task FindDepartments(BaseTreeSearchReq req); - - /// - /// 添加一个新部门 - /// - /// - /// 操作结果 - [Service(Date = "2018-2-1", Director = "刘旭东", Name = "添加一个新部门")] - Task CreateDepartment(DeptEditReq req); - - /// - /// 修改一个部门 - /// - /// - /// - [Service(Date = "2018-2-1", Director = "刘旭东", Name = "修改一个部门")] - Task ModifyDepartment(DeptEditReq req); - - /// - /// 删除一个部门 - /// - /// - /// - [Service(Date = "2018-2-1", Director = "刘旭东", Name = "删除一个部门")] - Task RemoveDepartment(KeyIdReq req); - - #endregion 部门管理 - - #region 权限管理 - /// - /// 添加一个新角色 - /// - /// - /// - [Service(Date = "2018-2-1", Director = "刘旭东", Name = "添加一个新角色")] - Task CreateRole(RoleEditReq req); - - /// - /// 查询用户的所有权限 - /// - /// - /// - [Service(Date = "2018-2-14", Director = "刘旭东", Name = "查询用户的所有权限")] - Task QueryUserPermission(CommonCMDReq req); - - [Service(Date = "2018-2-14", Director = "刘旭东", Name = "查询公司的所有角色")] - Task FindCorpRoles(CommonCMDReq req); - - #endregion - - #region 员工管理 - /// - /// 添加一个新员工 - /// - /// - /// - [Service(Date = "2018-2-1", Director = "刘旭东", Name = "添加一个新员工")] - Task CreateEmployee(EmployeeEditReq req); - - /// - /// 分页查询员工 - /// - /// - /// - [Service(Date = "2018-2-1", Director = "刘旭东", Name = "分页查询员工")] - Task FindEmployeePageBy(BasePagedRequestDto req); - #endregion - #endregion - } -} diff --git a/samples/OrgServer/Application.Service.Org/Application.Service.Org.csproj b/samples/OrgServer/Application.Service.Org/Application.Service.Org.csproj deleted file mode 100644 index d80fece76..000000000 --- a/samples/OrgServer/Application.Service.Org/Application.Service.Org.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - netcoreapp2.0 - - - - ..\HostService\bin\Debug - - - - - - - - - - - - - - - - - - - - diff --git a/samples/OrgServer/Application.Service.Org/Query/OrgAppService.cs b/samples/OrgServer/Application.Service.Org/Query/OrgAppService.cs deleted file mode 100644 index b1613de4a..000000000 --- a/samples/OrgServer/Application.Service.Org/Query/OrgAppService.cs +++ /dev/null @@ -1,85 +0,0 @@ -using Application.Interface.Org; -using DTO.Core; -using Surging.Core.Caching; -using Surging.Core.CPlatform.Ioc; -using Surging.Core.ProxyGenerator; -using System; -using System.Linq; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Linq.Expressions; -using Domain.Org.Entity; - -namespace Application.Service.Org -{ - public partial class OrgAppService - { - public Task FindCorps(BaseTreeSearchReq req) - { - BaseTreeResponseDto rsp = new BaseTreeResponseDto(); - rsp.Tree = _queryCorpRepository.Get(a => !a.IsDelete).Select(a => new BaseTreeDto - { - Id = a.CorporationKeyId.ToString(), - Name = a.Name, - PId = Guid.Empty.ToString() - }).ToList(); - - return Task.FromResult(rsp); - } - - public Task FindDepartments(BaseTreeSearchReq req) - { - BaseTreeResponseDto rsp = new BaseTreeResponseDto(); - var rows = _queryOrgRepository.Get(a => !a.IsDelete && a.CorporationKeyId == req.Identify.CorporationKeyId).Select(a => new BaseTreeDto - { - Id = a.CorporationKeyId.ToString(), - Name = a.Name, - PId = a.ParentKeyId.ToString() - }).ToList(); - rsp.Tree = rows; - return Task.FromResult(rsp); - } - - public Task QueryUserPermission(CommonCMDReq req) - { - var rsp = new BaseListResponseDto(); - var rows = _queryEmployeeRepository.FindUserRolePermission(Guid.Parse(req.Identify.Token)); - rsp.Result = new - { - pages = rows.Where(a => a.PermissionType == 1)?.Select(a => new - { - name = a.Name, - no = a.No, - }), - actions = rows.Where(a => a.PermissionType == 2)?.Select(a => new - { - name = a.Name, - no = a.No, - }) - }; - rsp.OperateFlag = true; - return Task.FromResult(rsp); - - } - - - public Task FindCorpRoles(CommonCMDReq req) - { - var rsp = new BaseListResponseDto(); - var rows = _queryCorpRepository.Get(a=>a.CorporationKeyId== req.Identify.CorporationKeyId,a=>a.CorpRoles).FirstOrDefault()?.CorpRoles.ToList(); - rsp.Result = rows?.Select(a=>new { roleName=a.Name,roleId=a.KeyId }).ToList(); - rsp.OperateFlag = true; - return Task.FromResult(rsp); - - } - - public Task FindEmployeePageBy(BasePagedRequestDto req) - { - var rsp = new BaseListResponseDto(); - var rows = _queryEmployeeRepository.GetByPagination(a => !a.IsDelete&&a.CorporationKeyId==req.Identify.CorporationKeyId, req.PageSize, req.PageIndex,null).ToList(); - rsp.Result = rows; - rsp.OperateFlag = true; - return Task.FromResult(rsp); - } - } -} diff --git a/samples/OrgServer/Application.Service.Org/UseCases/OrgAppService.cs b/samples/OrgServer/Application.Service.Org/UseCases/OrgAppService.cs deleted file mode 100644 index 191bbc943..000000000 --- a/samples/OrgServer/Application.Service.Org/UseCases/OrgAppService.cs +++ /dev/null @@ -1,280 +0,0 @@ -using App.Core; -using Application.Interface.Org; -using Domain.Org.Entity; -using DTO.Core; -using Repository.EF.Core; -using Surging.Core.Caching; -using Surging.Core.CPlatform.Ioc; -using Surging.Core.ProxyGenerator; -using System; -using System.Linq; -using System.Collections.Generic; -using System.Threading.Tasks; -using Domain.Org.Aggregate; -using Application.Interface.Org.EVENT; -using Repository.Org; - -namespace Application.Service.Org -{ - [ModuleName("Org")] - public partial class OrgAppService : BaseAppService, IOrgAppService - { - private readonly OrgRepository _repository; - private readonly CorpQueryRepository _queryCorpRepository; - private readonly OrgQueryRepository _queryOrgRepository; - private readonly EmployeeQueryRepository _queryEmployeeRepository; - - // private ICacheProvider _cacheProvider; - public OrgAppService(OrgRepository repository, OrgQueryRepository queryOrgRepository, CorpQueryRepository queryCorpRepository, EmployeeQueryRepository queryEmployeeRepository) - // : base(repository)//, queryOnlyRepository) - { - _repository = repository; - _queryCorpRepository = queryCorpRepository; - _queryOrgRepository = queryOrgRepository; - _queryEmployeeRepository = queryEmployeeRepository; - } - #region 公司 - - public Task RegisterCorporation(CorpEditReq req) - { - //是否已经被注册? - var existCorp = _queryCorpRepository.Exist(a => !a.IsDelete && a.Name == req.CorpName); - if (!existCorp) - { - var aCorp = new Corporation - { - CorporationKeyId = Guid.NewGuid(), - Name = req.CorpName, - No = req.CorpName, - Version = 1, - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - IsDelete = false - }; - _repository.Add(aCorp); - _repository.Commit(); - return Task.FromResult(new OperateResultRsp - { - OperateFlag = true, - OperateResult = "注册成功" - }); - } - else - { - return Task.FromResult(new OperateResultRsp - { - OperateFlag = false, - OperateResult = "该企业已经被注册" - }); - } - - } - - public Task ActivateCorporation(CommonCMDReq req) - { - var rsp = new OperateResultRsp - { - OperateFlag = false, - OperateResult = "参数错误" - }; - try - { - if (!string.IsNullOrEmpty(req.CommonCMD)) - { - var corp = _queryCorpRepository.Get(a => a.CorporationKeyId == req.Identify.CorporationKeyId).FirstOrDefault(); - corp.IsDelete = false; - var empId = corp.Activate(); - - _repository.Commit(); - rsp.OperateFlag = true; - rsp.OperateResult = "激活成功"; - Publish(new CorporationActivatedEvent() - { - CorpId = req.Identify.CorporationKeyId, - Email = req.CommonCMD, - EmpId = empId - }); - } - } - catch (Exception ex) - { - string msg = ex.Message; - } - return Task.FromResult(rsp); - - // return rsp; - } - - public Task EditCorporation(CorpEditReq req) - { - throw new NotImplementedException(); - } - #endregion - - #region 部门 - - public Task CreateDepartment(DeptEditReq req) - { - if (req.CorporationKeyId != Guid.Empty) - { - var corp = _repository.FindBy(req.CorporationKeyId); - if (corp != null) - { - corp.Departments.Add(new Department() - { - Name = req.DepartmentName, - No = req.DepartmentNo, - DepartmentType = DepartmentCategory.Bizz, - ParentKeyId = req.ParentDeptKeyId.GetValueOrDefault(), - Version = 1, - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - IsDelete = false - }); - } - else - { - - } - } - else - { - return Task.FromResult(new OperateResultRsp - { - OperateFlag = false, - OperateResult = string.Empty - }); - } - _repository.Commit(); - return Task.FromResult(new OperateResultRsp - { - OperateFlag = true, - OperateResult = string.Empty - }); - } - - - - public Task ModifyDepartment(DeptEditReq req) - { - var corp = _repository.FindBy(req.CorporationKeyId); - if (corp != null) - { - var dept = corp.Departments.FirstOrDefault(c => c.KeyId == req.DepartmentKeyId.Value); - if (dept != null) - { - dept.Name = req.DepartmentName; - dept.No = req.DepartmentNo; - } - } - _repository.Commit(); - return Task.FromResult(new OperateResultRsp - { - OperateFlag = true, - OperateResult = string.Empty - }); - - } - - - - public Task RemoveDepartment(KeyIdReq req) - { - var corporation = _repository.FindBy(req.Identify.CorporationKeyId); - var dept = corporation.Departments.FirstOrDefault(c => c.KeyId == req.KeyId); - if (dept != null) - { - dept.IsDelete = true; - } - _repository.Commit(); - return Task.FromResult(new OperateResultRsp - { - OperateFlag = true, - OperateResult = string.Empty - }); - } - - - #endregion - - #region 角色 - public Task CreateRole(RoleEditReq req) - { - OperateResultRsp rsp = new OperateResultRsp(); - var corporation = _repository.FindBy(req.Identify.CorporationKeyId); - if (corporation != null) - { - if (!corporation.CorpRoles.Exists(a => a.Name == req.RoleName.Trim())) - { - var corpRole = new CorpRole - { - Name = req.RoleName, - CorporationKeyId = req.Identify.CorporationKeyId, - - }; - corpRole.SetEditer(null); - corpRole.KeyId = Guid.NewGuid(); - corporation.CorpRoles.Add(corpRole); - _repository.Commit(); - rsp.OperateFlag = true; - } - else - { - rsp.OperateFlag = false; - rsp.FlagErrorMsg = "角色名字已经存在"; - } - } - else - { - rsp.OperateFlag = false; - rsp.FlagErrorMsg = "当前公司编号错误"; - } - return Task.FromResult(rsp); - } - - - #endregion - - #region 员工 - public Task CreateEmployee(EmployeeEditReq req) - { - OperateResultRsp rsp = new OperateResultRsp(); - var corporation = _repository.FindBy(req.Identify.CorporationKeyId); - if (corporation != null) - { - var dept = corporation.Departments.FirstOrDefault(a => a.KeyId == req.DeptKeyId); - if (dept != null) - { - var emp = new Employee - { - Name = req.Name, - CorporationKeyId = req.Identify.CorporationKeyId, - DepartmentKeyId=req.DeptKeyId, - RoleKeyId = req.RoleKeyId, - RoleName = req.RoleName - - }; - emp.SetEditer(null); - emp.KeyId = Guid.NewGuid(); - dept.Employees.Add(emp); - _repository.Commit(); - rsp.OperateFlag = true; - } - else - { - rsp.OperateFlag = false; - rsp.FlagErrorMsg = "角色名字已经存在"; - } - } - else - { - rsp.OperateFlag = false; - rsp.FlagErrorMsg = "当前公司编号错误"; - } - return Task.FromResult(rsp); - } - - - #endregion - } -} diff --git a/samples/OrgServer/Domain/Aggregate/Corporation.cs b/samples/OrgServer/Domain/Aggregate/Corporation.cs deleted file mode 100644 index 95cc29c56..000000000 --- a/samples/OrgServer/Domain/Aggregate/Corporation.cs +++ /dev/null @@ -1,79 +0,0 @@ -using DDD.Core; -using Domain.Org.Entity; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text; - -namespace Domain.Org.Aggregate -{ - [Table("Org_Corporations")] - public class Corporation : IAggregate - { - /// - /// 这个字段没有用,禁止使用 - /// - [NotMapped] - public override Guid KeyId { get => base.KeyId; set => base.KeyId = value; } - - [Key] - public override Guid CorporationKeyId { get; set; } - - public virtual List Departments { get; set; } - public virtual List CorpRoles { get; set; } - - /// - /// 注册后激活,初始化管理员数据 - /// - public string Activate() - { - //是否已经存在虚拟部门 - var dept = this.Departments.Find(a => !a.IsDelete && a.Name == "" && a.ParentKeyId == CorporationKeyId); - if(dept==null) - { - //添加虚拟部门 - dept = new Department() - { - Name=string.Empty, - CorporationKeyId=CorporationKeyId, - KeyId=Guid.NewGuid(), - CreateTime=DateTime.Now, - CreateUserKeyId=Guid.Empty, - No="000000", - ParentKeyId=CorporationKeyId, - UpdateTime=DateTime.Now, - UpdateUserKeyId=Guid.Empty, - Address=string.Empty, - NameSpell=string.Empty, - Telephone=string.Empty, - DepartmentType= DepartmentCategory.Sysinternal, - Employees=new List (), - IsDelete=false, - Version=1 - - }; - //添加管理员对应的员工 - var empid = Guid.NewGuid(); - dept.Employees.Add(new Employee() - { - Name="超级管理员", - No = "SuperManger", - KeyId=empid, - CorporationKeyId=CorporationKeyId, - CreateTime=DateTime.Now, - CreateUserKeyId=Guid.Empty, - DepartmentKeyId= dept.KeyId, - UpdateTime=DateTime.Now, - UpdateUserKeyId=Guid.Empty, - Version=1 - }); - return empid.ToString(); - } - else - { - return string.Empty; - } - } - } -} diff --git a/samples/OrgServer/Domain/Domain.Org.csproj b/samples/OrgServer/Domain/Domain.Org.csproj deleted file mode 100644 index 3ca3b9dd8..000000000 --- a/samples/OrgServer/Domain/Domain.Org.csproj +++ /dev/null @@ -1,32 +0,0 @@ - - - - netcoreapp2.0 - - - - ..\HostService\bin\Debug - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/OrgServer/Domain/DomainEvents/EventHandling/InquiryEditedHandler.cs b/samples/OrgServer/Domain/DomainEvents/EventHandling/InquiryEditedHandler.cs deleted file mode 100644 index 8f8b1e201..000000000 --- a/samples/OrgServer/Domain/DomainEvents/EventHandling/InquiryEditedHandler.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Surging.Core.CPlatform.EventBus.Events; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace Domain.DomainEvents.Inquiry -{ - public class InquiryEditedHandler : IIntegrationEventHandler - { - public async Task Handle(InquiryEditedEvent @event) - { - - await Task.FromResult("InquiryEditedEvent更改名字》"+@event.CustomerName+"请进行下一步操作"); - } - } -} diff --git a/samples/OrgServer/Domain/DomainEvents/PublishEvent/InquiryEditedEvent.cs b/samples/OrgServer/Domain/DomainEvents/PublishEvent/InquiryEditedEvent.cs deleted file mode 100644 index 3807072ae..000000000 --- a/samples/OrgServer/Domain/DomainEvents/PublishEvent/InquiryEditedEvent.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Surging.Core.CPlatform.EventBus.Events; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Domain.DomainEvents.Inquiry -{ - public class InquiryEditedEvent: IntegrationEvent - { - public Guid CustomerKeyId { get; set; } - public string CustomerName { get; set; } - - } -} diff --git a/samples/OrgServer/Domain/Entity/CorpRole.cs b/samples/OrgServer/Domain/Entity/CorpRole.cs deleted file mode 100644 index eb58fd86a..000000000 --- a/samples/OrgServer/Domain/Entity/CorpRole.cs +++ /dev/null @@ -1,20 +0,0 @@ -using DDD.Core; -using Domain.Org.ValueObject; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text; - -namespace Domain.Org.Entity -{ - /// - /// 公司下的角色 - /// - [Table("Org_CorpRoles")] - public class CorpRole: BaseEntity - { - - public virtual List RolePermissions { get; set; } - - } -} diff --git a/samples/OrgServer/Domain/Entity/Department.cs b/samples/OrgServer/Domain/Entity/Department.cs deleted file mode 100644 index f10a8738a..000000000 --- a/samples/OrgServer/Domain/Entity/Department.cs +++ /dev/null @@ -1,40 +0,0 @@ -using DDD.Core; -using Domain.Org.Aggregate; -using Domain.Org.Entity; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text; - -namespace Domain.Org.Entity -{ - [Table("Org_Departments")] - public class Department : BaseEntity - { - public Guid ParentKeyId { get; set; } - - public string NameSpell { get; set; } - - public string Telephone { get; set; } - public string Address { get; set; } - public DepartmentCategory DepartmentType { get; set; } - - - [ForeignKey("CorporationKeyId")] - public Corporation OwnCorporation { get; set; } - public virtual List Employees { get; set; } - } - - public enum DepartmentCategory - { - /// - /// 系统为企业内置的虚拟部门 - /// - Sysinternal=0, - /// - /// 公司自己添加维护的部门 - /// - Bizz =1 - } -} diff --git a/samples/OrgServer/Domain/Entity/Employee.cs b/samples/OrgServer/Domain/Entity/Employee.cs deleted file mode 100644 index bf28259cb..000000000 --- a/samples/OrgServer/Domain/Entity/Employee.cs +++ /dev/null @@ -1,30 +0,0 @@ -using DDD.Core; -using Domain.Org.ValueObject; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text; - -namespace Domain.Org.Entity -{ - [Table("Org_Employees")] - public class Employee : BaseEntity - { - public string NameSpell { get; set; } - public string Mobile { get; set; } - public string WxNo { get; set; } - public string Email { get; set; } - public string PhotoPath { get; set; } - public string Sex { get; set; } - public string Signature { get; set; } - - public Guid DepartmentKeyId { get; set; } - [ForeignKey("DepartmentKeyId")] - public Department OwnDepartment { get; set; } - /// - /// 员工拥有的角色 - /// - public Guid RoleKeyId{ get;set;} - public string RoleName{ get;set; } - } -} diff --git a/samples/OrgServer/Domain/ValueObject/EmployeeRole.cs b/samples/OrgServer/Domain/ValueObject/EmployeeRole.cs deleted file mode 100644 index 64cd5616a..000000000 --- a/samples/OrgServer/Domain/ValueObject/EmployeeRole.cs +++ /dev/null @@ -1,15 +0,0 @@ -using DDD.Core; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text; - -namespace Domain.Org.ValueObject -{ - public class EmployeeRole: BaseValueObject - { - [ForeignKey("Employee")] - public Guid EmployeeKeyId { get; set; } - - } -} diff --git a/samples/OrgServer/Domain/ValueObject/RolePermission.cs b/samples/OrgServer/Domain/ValueObject/RolePermission.cs deleted file mode 100644 index 7abe11323..000000000 --- a/samples/OrgServer/Domain/ValueObject/RolePermission.cs +++ /dev/null @@ -1,32 +0,0 @@ -using DDD.Core; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text; - -namespace Domain.Org.ValueObject -{ - /// - /// 角色下的权限 - /// - [Table("Org_Role_Permissions")] - public class RolePermission : BaseValueObject - { - /// - /// 服务ID(模块) - /// - public Guid SubDomainKeyId { get; set; } - /// - /// 具体的权限,页面和动作 - /// - public Guid SubDomainPermissionKeyId { get; set; } - - public int PermissionType { get; set; } - - - - [ForeignKey("CorpRole")] - public Guid CorpRoleKeyId { get; set; } - - } -} diff --git a/samples/OrgServer/HostService/Configs/log4net.config b/samples/OrgServer/HostService/Configs/log4net.config deleted file mode 100644 index 42fd16880..000000000 --- a/samples/OrgServer/HostService/Configs/log4net.config +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/OrgServer/HostService/HostService.csproj b/samples/OrgServer/HostService/HostService.csproj deleted file mode 100644 index 6af0a37d2..000000000 --- a/samples/OrgServer/HostService/HostService.csproj +++ /dev/null @@ -1,40 +0,0 @@ - - - - Exe - netcoreapp2.0 - - - - - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - diff --git a/samples/OrgServer/HostService/Program.cs b/samples/OrgServer/HostService/Program.cs deleted file mode 100644 index 5133ac408..000000000 --- a/samples/OrgServer/HostService/Program.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Autofac; -using Surging.Core.Codec.MessagePack; -using Surging.Core.Consul; -using Surging.Core.Consul.Configurations; -using Surging.Core.CPlatform; -using Surging.Core.CPlatform.Utilities; -using Surging.Core.DotNetty; -using Surging.Core.EventBusRabbitMQ; -using Surging.Core.ServiceHosting; -using Surging.Core.ServiceHosting.Internal.Implementation; -using System; -using System.Text; -using Surging.Core.Log4net; -using Surging.Core.ProxyGenerator; - -namespace Centa.HostService.Org -{ - public class Program - { - static void Main(string[] args) - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - var host = new ServiceHostBuilder() - //.RegisterServices(provider => - //{ - // //这里写自己的注册 - //}) - .RegisterServices(builder => - { - builder.AddMicroService(option => - { - option.AddServiceRuntime(); - option.AddRelateService(); - option.UseConsulManager(new ConfigInfo("127.0.0.1:8500")); - option.UseDotNettyTransport(); - option.UseRabbitMQTransport(); - option.AddRabbitMQAdapt(); - //option.UseMessagePackCodec(); - option.UseJsonCodec(); - builder.Register(p => new CPlatformContainer(ServiceLocator.Current)); - }); - }) - .SubscribeAt() - .UseLog4net("Configs/log4net.config") - .UseServer(options => - { - options.Ip = "127.0.0.1"; - options.Port = 10242; - options.Token = "True"; - options.ExecutionTimeoutInMilliseconds = 30000; - options.MaxConcurrentRequests = 200; - }) - .UseProxy() - .UseStartup() - .Build(); - - using (host.Run()) - { - Console.Title = "组织管理"; - Console.WriteLine($"组织管理——服务端启动成功,{DateTime.Now}。"); - Console.ReadLine(); - } - } - } -} diff --git a/samples/OrgServer/HostService/Startup.cs b/samples/OrgServer/HostService/Startup.cs deleted file mode 100644 index 3f488ae1a..000000000 --- a/samples/OrgServer/HostService/Startup.cs +++ /dev/null @@ -1,70 +0,0 @@ -using Autofac; -using Autofac.Extensions.DependencyInjection; -using Config.Core.Extensions; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Surging.Core.CPlatform.Utilities; -using Surging.Core.EventBusRabbitMQ.Configurations; -using System; - -namespace Centa.HostService.Org -{ - public class Startup - { - public Startup() - { - var config = new ConfigurationBuilder() - .SetBasePath(AppContext.BaseDirectory); - ConfigureEventBus(config); - ConfigureCache(config); - ConfigureDB(config); - - } - - public IContainer ConfigureServices(ContainerBuilder builder) - { - var services = new ServiceCollection(); - ConfigureLogging(services); - builder.Populate(services); - ServiceLocator.Current = builder.Build(); - return ServiceLocator.Current; - } - - public void Configure(IContainer app) - { - app.Resolve().AddConsole((c, l) => (int)l >= 3); - } - - #region 私有方法 - /// - /// 配置日志服务 - /// - /// - private void ConfigureLogging(IServiceCollection services) - { - services.AddLogging(); - } - - private static void ConfigureEventBus(IConfigurationBuilder build) - { - build - .AddEventBusFile("eventBusSettings.json", optional: false); - } - - /// - /// 配置缓存服务 - /// - private void ConfigureCache(IConfigurationBuilder build) - { - // build.AddCacheFile("cacheSettings.json", optional: false); - } - - private void ConfigureDB(IConfigurationBuilder build) - { - build.AddDBFile("dbSettings.json", optional: false); - } - #endregion - - } -} diff --git a/samples/OrgServer/HostService/cacheSettings.json b/samples/OrgServer/HostService/cacheSettings.json deleted file mode 100644 index ab9c7e43d..000000000 --- a/samples/OrgServer/HostService/cacheSettings.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "CachingSettings": [ - { - "Id": "ddlCache", - "Class": "Surging.Core.Caching.RedisCache.RedisContext,Surging.Core.Caching", - "Properties": [ - { - "Name": "appRuleFile", - "Ref": "rule" - }, - { - "Name": "dataContextPool", - "Ref": "ddls_sample", - "Maps": [ - { - "Name": "Redis", - "Properties": [ - { - "value": "127.0.0.1:6379::1" - } - ] - }, - { - "Name": "MemoryCache" - } - ] - }, - { - "Name": "defaultExpireTime", - "value": "120" - }, - { - "Name": "connectTimeout", - "Value": "120" - }, - { - "Name": "minSize", - "Value": "1" - }, - { - "Name": "maxSize", - "Value": "10" - } - ] - } - ] -} diff --git a/samples/OrgServer/HostService/dbSettings.json b/samples/OrgServer/HostService/dbSettings.json deleted file mode 100644 index 35262d07c..000000000 --- a/samples/OrgServer/HostService/dbSettings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Web_A2;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False", - "ModelAssemblyName": "Domain.Org" -} - diff --git a/samples/OrgServer/HostService/eventBusSettings.json b/samples/OrgServer/HostService/eventBusSettings.json deleted file mode 100644 index d5d4487b7..000000000 --- a/samples/OrgServer/HostService/eventBusSettings.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "EventBusConnection": "localhost", - "EventBusUserName": "guest", - "EventBusPassword": "guest" -} - diff --git a/samples/OrgServer/Repository.Org/OrgRepository.cs b/samples/OrgServer/Repository.Org/OrgRepository.cs deleted file mode 100644 index e30e44e3e..000000000 --- a/samples/OrgServer/Repository.Org/OrgRepository.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Repository.EF.Core; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Domain.Org.Entity; -using Domain.Org.ValueObject; -using System.Data.SqlClient; -using System.Data; -using Domain.Org.Aggregate; - -namespace Repository.Org -{ - public class OrgRepository : BaseImpRepository - { - public override Corporation FindBy(Guid key) - { - return _set.Include(a => a.Departments).ThenInclude(a => a.Employees) - .Include(a=>a.CorpRoles) - .SingleOrDefault(a => a.CorporationKeyId == key); - } - } - - public class CorpQueryRepository : BaseImpQueryOnlyRepository - { - - } - - public class OrgQueryRepository : BaseImpQueryOnlyRepository - { - } - - public class EmployeeQueryRepository : BaseImpQueryOnlyRepository - { - - public List FindUserRolePermission(Guid empId) - { - return _dbContext.Set().AsNoTracking().Where(a=>a.KeyId==empId).Join(_dbContext.Set().AsNoTracking(), a => a.RoleKeyId, b => b.CorpRoleKeyId,(a,b)=>b).ToList(); - } - } - - public class RolePermissionQueryRepository : BaseImpQueryOnlyRepository - { - } -} diff --git a/samples/OrgServer/Repository.Org/Repository.Org.csproj b/samples/OrgServer/Repository.Org/Repository.Org.csproj deleted file mode 100644 index 3ed970561..000000000 --- a/samples/OrgServer/Repository.Org/Repository.Org.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - netcoreapp2.0 - - - - ..\HostService\bin\Debug - - - - - - - - diff --git a/samples/pack/Surging.Core.ApiGateWay.dll b/samples/pack/Surging.Core.ApiGateWay.dll deleted file mode 100644 index 8d68e8355..000000000 Binary files a/samples/pack/Surging.Core.ApiGateWay.dll and /dev/null differ diff --git a/sh.exe.stackdump b/sh.exe.stackdump index ddee04880..14051f161 100644 --- a/sh.exe.stackdump +++ b/sh.exe.stackdump @@ -1,11 +1,11 @@ Stack trace: Frame Function Args -001802FEFA0 0018005D14E (0018022B7F0, 0018021DC39, 001802FEFA0, 000FFFFB9F0) -001802FEFA0 00180046609 (00000000002, 00000000003, 00000000002, 000C0000000) -001802FEFA0 00180046642 (00000000002, 001802FF2B0, 001802FEFA0, 00000000008) -001802FEFA0 00180057602 (00000000000, 000FFFFCC35, 000FFFFCC53, 0018021C490) -000FFFFCCB0 001800576B0 (645C655C725C635C, 695C745C6E5C655C, 6D5C2D5C6C5C615C, 675C615C6E5C615C) -000FFFFCCB0 00180046DA5 (00000000000, 00000000000, 00000000000, 00000000000) -00000000000 00180045873 (00000000000, 00000000000, 00000000000, 00000000000) -000FFFFFFF0 00180045924 (00000000000, 00000000000, 00000000000, 00000000000) +00000010002 0018005E0DE (0018023E7F0, 00180230C39, 00000010002, 000FFFFBA00) +00000010002 001800468F9 (00000000002, 00180320420, 00000000002, 00180320420) +00000010002 00180046932 (00000000002, 00180320730, 00000010002, 00000000008) +00000010002 0018005799C (00000000000, 00180230F2F, 00180047D9E, 635C655C785C655C) +000FFFFCCD0 00180057A40 (745C685C275C205C, 3A5C735C705C745C, 695C675C2F5C2F5C, 625C755C685C745C) +000FFFFCCD0 00180047081 (00000000000, 00000000000, 00000000000, 00000000000) +00000000000 00180045A03 (00000000000, 00000000000, 00000000000, 00000000000) +000FFFFFFF0 00180045AB4 (00000000000, 00000000000, 00000000000, 00000000000) End of stack trace diff --git a/src/.editorconfig b/src/.editorconfig new file mode 100644 index 000000000..99dce6d7d --- /dev/null +++ b/src/.editorconfig @@ -0,0 +1,7 @@ +[*.cs] + +# CS8601: 引用类型赋值可能为 null。 +dotnet_diagnostic.CS8601.severity = none + +# CS8618: 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑声明为可以为 null。 +dotnet_diagnostic.CS8618.severity = none diff --git a/src/Coap/CoAP.NET/BlockOption.cs b/src/Coap/CoAP.NET/BlockOption.cs new file mode 100644 index 000000000..3cab12b82 --- /dev/null +++ b/src/Coap/CoAP.NET/BlockOption.cs @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2011-2012, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP +{ + /// + /// This class describes the block options of the CoAP messages + /// + public class BlockOption : Option + { + /// + /// Initializes a block option. + /// + /// The type of the option + public BlockOption(OptionType type) : base(type) + { + this.IntValue = 0; + } + + /// + /// Initializes a block option. + /// + /// The type of the option + /// Block number + /// Block size + /// More flag + public BlockOption(OptionType type, Int32 num, Int32 szx, Boolean m) : base(type) + { + this.IntValue = Encode(num, szx, m); + } + + /// + /// Sets block params. + /// + /// Block number + /// Block size + /// More flag + public void SetValue(Int32 num, Int32 szx, Boolean m) + { + this.IntValue = Encode(num, szx, m); + } + + /// + /// Gets or sets the block number. + /// + public Int32 NUM + { + get { return this.IntValue >> 4; } + set { SetValue(value, SZX, M); } + } + + /// + /// Gets or sets the block size. + /// + public Int32 SZX + { + get { return this.IntValue & 0x7; } + set { SetValue(NUM, value, M); } + } + + /// + /// Gets or sets the more flag. + /// + public Boolean M + { + get { return (this.IntValue >> 3 & 0x1) != 0; } + set { SetValue(NUM, SZX, value); } + } + + /// + /// Gets the decoded block size in bytes (B). + /// + public Int32 Size + { + get { return DecodeSZX(this.SZX); } + } + + /// + /// + /// + /// + public override String ToString() + { + return String.Format("{0}{1} ({2}B/block [{3}])", NUM, M ? "+" : String.Empty, Size, SZX); + } + + /// + /// Gets the real block size which is 2 ^ (SZX + 4). + /// + /// + /// + public static Int32 DecodeSZX(Int32 szx) + { + return 1 << (szx + 4); + } + + /// + /// Converts a block size into the corresponding SZX. + /// + /// + /// + public static Int32 EncodeSZX(Int32 blockSize) + { + if (blockSize < 16) + return 0; + if (blockSize > 1024) + return 6; + return (Int32)(Math.Log(blockSize) / Math.Log(2)) - 4; + } + + /// + /// Checks whether the given SZX is valid or not. + /// + /// + /// + public static Boolean ValidSZX(Int32 szx) + { + return (szx >= 0 && szx <= 6); + } + + private static Int32 Encode(Int32 num, Int32 szx, Boolean m) + { + Int32 value = 0; + value |= (szx & 0x7); + value |= (m ? 1 : 0) << 3; + value |= num << 4; + return value; + } + } +} diff --git a/src/Coap/CoAP.NET/Channel/DataReceivedEventArgs.cs b/src/Coap/CoAP.NET/Channel/DataReceivedEventArgs.cs new file mode 100644 index 000000000..2bc2a6c8a --- /dev/null +++ b/src/Coap/CoAP.NET/Channel/DataReceivedEventArgs.cs @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP.Channel +{ + /// + /// Provides data for event. + /// + public class DataReceivedEventArgs : EventArgs + { + readonly Byte[] _data; + readonly System.Net.EndPoint _endPoint; + + /// + /// + public DataReceivedEventArgs(Byte[] data, System.Net.EndPoint endPoint) + { + _data = data; + _endPoint = endPoint; + } + + /// + /// Gets the received bytes. + /// + public Byte[] Data { get { return _data; } } + + /// + /// Gets the where the data is received from. + /// + public System.Net.EndPoint EndPoint { get { return _endPoint; } } + } +} diff --git a/src/Coap/CoAP.NET/Channel/IChannel.cs b/src/Coap/CoAP.NET/Channel/IChannel.cs new file mode 100644 index 000000000..e82cfe737 --- /dev/null +++ b/src/Coap/CoAP.NET/Channel/IChannel.cs @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP.Channel +{ + /// + /// Represents a channel where bytes data can flow through. + /// + public interface IChannel : IDisposable + { + /// + /// Gets the local endpoint of this channel. + /// + System.Net.EndPoint LocalEndPoint { get; } + /// + /// Occurs when some bytes are received in this channel. + /// + event EventHandler DataReceived; + /// + /// Starts this channel. + /// + void Start(); + /// + /// Stops this channel. + /// + void Stop(); + /// + /// Sends data through this channel. This method should be non-blocking. + /// + /// the bytes to send + /// the target endpoint + void Send(Byte[] data, System.Net.EndPoint ep); + } +} diff --git a/src/Coap/CoAP.NET/Channel/IPAddressExtensions.cs b/src/Coap/CoAP.NET/Channel/IPAddressExtensions.cs new file mode 100644 index 000000000..f0d97a661 --- /dev/null +++ b/src/Coap/CoAP.NET/Channel/IPAddressExtensions.cs @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; +using System.Net; +using System.Net.Sockets; + +namespace CoAP.Channel +{ + /// + /// Extension methods for . + /// + public static class IPAddressExtensions + { + /// + /// Checks whether the IP address is an IPv4-mapped IPv6 address. + /// + /// the object to check + /// true if the IP address is an IPv4-mapped IPv6 address; otherwise, false. + public static Boolean IsIPv4MappedToIPv6(IPAddress address) + { + if (address.AddressFamily != AddressFamily.InterNetworkV6) + return false; + Byte[] bytes = address.GetAddressBytes(); + for (Int32 i = 0; i < 10; i++) + { + if (bytes[i] != 0) + return false; + } + return bytes[10] == 0xff && bytes[11] == 0xff; + } + + /// + /// Maps the object to an IPv4 address. + /// + /// the object + /// An IPv4 address. + public static IPAddress MapToIPv4(IPAddress address) + { + if (address.AddressFamily == AddressFamily.InterNetwork) + return address; + Byte[] bytes = address.GetAddressBytes(); + Int64 newAddress = (UInt32)(bytes[12] & 0xff) | (UInt32)(bytes[13] & 0xff) << 8 | (UInt32)(bytes[14] & 0xff) << 16 | (UInt32)(bytes[15] & 0xff) << 24; + return new IPAddress(newAddress); + } + + /// + /// Maps the object to an IPv6 address. + /// + /// the object + /// An IPv6 address. + public static IPAddress MapToIPv6(IPAddress address) + { + if (address.AddressFamily == AddressFamily.InterNetworkV6) + return address; + Byte[] bytes = address.GetAddressBytes(); + Byte[] newAddress = new Byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, bytes[0], bytes[1], bytes[2], bytes[3] }; + return new IPAddress(newAddress); + } + } +} diff --git a/src/Coap/CoAP.NET/Channel/UDPChannel.NET40.cs b/src/Coap/CoAP.NET/Channel/UDPChannel.NET40.cs new file mode 100644 index 000000000..0351b8aa3 --- /dev/null +++ b/src/Coap/CoAP.NET/Channel/UDPChannel.NET40.cs @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; +using System.Net; +using System.Net.Sockets; + +namespace CoAP.Channel +{ + public partial class UDPChannel + { + private UDPSocket NewUDPSocket(AddressFamily addressFamily, Int32 bufferSize) + { + return new UDPSocket(addressFamily, bufferSize, SocketAsyncEventArgs_Completed); + } + + private void BeginReceive(UDPSocket socket) + { + if (_running == 0) + return; + + if (socket.ReadBuffer.RemoteEndPoint == null) + { + socket.ReadBuffer.RemoteEndPoint = socket.Socket.Connected ? + socket.Socket.RemoteEndPoint : + new IPEndPoint(socket.Socket.AddressFamily == AddressFamily.InterNetwork ? + IPAddress.Any : IPAddress.IPv6Any, 0); + } + + Boolean willRaiseEvent; + try + { + willRaiseEvent = socket.Socket.ReceiveFromAsync(socket.ReadBuffer); + } + catch (ObjectDisposedException) + { + // do nothing + return; + } + catch (Exception ex) + { + EndReceive(socket, ex); + return; + } + + if (!willRaiseEvent) + { + ProcessReceive(socket.ReadBuffer); + } + } + + private void BeginSend(UDPSocket socket, Byte[] data, System.Net.EndPoint destination) + { + socket.SetWriteBuffer(data, 0, data.Length); + socket.WriteBuffer.RemoteEndPoint = destination; + + Boolean willRaiseEvent; + try + { + willRaiseEvent = socket.Socket.SendToAsync(socket.WriteBuffer); + } + catch (ObjectDisposedException) + { + // do nothing + return; + } + catch (Exception ex) + { + EndSend(socket, ex); + return; + } + + if (!willRaiseEvent) + { + ProcessSend(socket.WriteBuffer); + } + } + + private void ProcessReceive(SocketAsyncEventArgs e) + { + UDPSocket socket = (UDPSocket)e.UserToken; + + if (e.SocketError == SocketError.Success) + { + EndReceive(socket, e.Buffer, e.Offset, e.BytesTransferred, e.RemoteEndPoint); + } + else if (e.SocketError != SocketError.OperationAborted + && e.SocketError != SocketError.Interrupted) + { + EndReceive(socket, new SocketException((Int32)e.SocketError)); + } + } + + private void ProcessSend(SocketAsyncEventArgs e) + { + UDPSocket socket = (UDPSocket)e.UserToken; + + if (e.SocketError == SocketError.Success) + { + EndSend(socket, e.BytesTransferred); + } + else + { + EndSend(socket, new SocketException((Int32)e.SocketError)); + } + } + + void SocketAsyncEventArgs_Completed(Object sender, SocketAsyncEventArgs e) + { + switch (e.LastOperation) + { + case SocketAsyncOperation.ReceiveFrom: + ProcessReceive(e); + break; + case SocketAsyncOperation.SendTo: + ProcessSend(e); + break; + } + } + + partial class UDPSocket + { + public readonly SocketAsyncEventArgs ReadBuffer; + public readonly SocketAsyncEventArgs WriteBuffer; + readonly Byte[] _writeBuffer; + private Boolean _isOuterBuffer; + + public UDPSocket(AddressFamily addressFamily, Int32 bufferSize, + EventHandler completed) + { + Socket = new Socket(addressFamily, SocketType.Dgram, ProtocolType.Udp); + ReadBuffer = new SocketAsyncEventArgs(); + ReadBuffer.SetBuffer(new Byte[bufferSize], 0, bufferSize); + ReadBuffer.Completed += completed; + ReadBuffer.UserToken = this; + + _writeBuffer = new Byte[bufferSize]; + WriteBuffer = new SocketAsyncEventArgs(); + WriteBuffer.SetBuffer(_writeBuffer, 0, bufferSize); + WriteBuffer.Completed += completed; + WriteBuffer.UserToken = this; + } + + public void SetWriteBuffer(Byte[] data, Int32 offset, Int32 count) + { + if (count > _writeBuffer.Length) + { + WriteBuffer.SetBuffer(data, offset, count); + _isOuterBuffer = true; + } + else + { + if (_isOuterBuffer) + { + WriteBuffer.SetBuffer(_writeBuffer, 0, _writeBuffer.Length); + _isOuterBuffer = false; + } + Buffer.BlockCopy(data, offset, _writeBuffer, 0, count); + WriteBuffer.SetBuffer(0, count); + } + } + + public void Dispose() + { + Socket.Close(); + ReadBuffer.Dispose(); + WriteBuffer.Dispose(); + } + } + } +} diff --git a/src/Coap/CoAP.NET/Channel/UDPChannel.cs b/src/Coap/CoAP.NET/Channel/UDPChannel.cs new file mode 100644 index 000000000..8533570cc --- /dev/null +++ b/src/Coap/CoAP.NET/Channel/UDPChannel.cs @@ -0,0 +1,323 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; +using System.Collections.Concurrent; +using System.Net; +using System.Net.Sockets; + +namespace CoAP.Channel +{ + /// + /// Channel via UDP protocol. + /// + public partial class UDPChannel : IChannel + { + /// + /// Default size of buffer for receiving packet. + /// + public const Int32 DefaultReceivePacketSize = 4096; + private Int32 _receiveBufferSize; + private Int32 _sendBufferSize; + private Int32 _receivePacketSize = DefaultReceivePacketSize; + private Int32 _port; + private System.Net.EndPoint _localEP; + private UDPSocket _socket; + private UDPSocket _socketBackup; + private Int32 _running; + private Int32 _writing; + private readonly ConcurrentQueue _sendingQueue = new ConcurrentQueue(); + + /// + public event EventHandler DataReceived; + + /// + /// Initializes a UDP channel with a random port. + /// + public UDPChannel() + : this(0) + { + } + + /// + /// Initializes a UDP channel with the given port, both on IPv4 and IPv6. + /// + public UDPChannel(Int32 port) + { + _port = port; + } + + /// + /// Initializes a UDP channel with the specific endpoint. + /// + public UDPChannel(System.Net.EndPoint localEP) + { + _localEP = localEP; + } + + /// + public System.Net.EndPoint LocalEndPoint + { + get + { + return _socket == null + ? (_localEP ?? new IPEndPoint(IPAddress.IPv6Any, _port)) + : _socket.Socket.LocalEndPoint; + } + } + + /// + /// Gets or sets the . + /// + public Int32 ReceiveBufferSize + { + get { return _receiveBufferSize; } + set { _receiveBufferSize = value; } + } + + /// + /// Gets or sets the . + /// + public Int32 SendBufferSize + { + get { return _sendBufferSize; } + set { _sendBufferSize = value; } + } + + /// + /// Gets or sets the size of buffer for receiving packet. + /// The default value is . + /// + public Int32 ReceivePacketSize + { + get { return _receivePacketSize; } + set { _receivePacketSize = value; } + } + + /// + public void Start() + { + if (System.Threading.Interlocked.CompareExchange(ref _running, 1, 0) > 0) + return; + + if (_localEP == null) + { + try + { + _socket = SetupUDPSocket(AddressFamily.InterNetworkV6, _receivePacketSize + 1); // +1 to check for > ReceivePacketSize + } + catch (SocketException e) + { + if (e.SocketErrorCode == SocketError.AddressFamilyNotSupported) + _socket = null; + else + throw e; + } + + if (_socket == null) + { + // IPv6 is not supported, use IPv4 instead + _socket = SetupUDPSocket(AddressFamily.InterNetwork, _receivePacketSize + 1); + _socket.Socket.Bind(new IPEndPoint(IPAddress.Any, _port)); + } + else + { + try + { + // Enable IPv4-mapped IPv6 addresses to accept both IPv6 and IPv4 connections in a same socket. + _socket.Socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0); + } + catch + { + // IPv4-mapped address seems not to be supported, set up a separated socket of IPv4. + _socketBackup = SetupUDPSocket(AddressFamily.InterNetwork, _receivePacketSize + 1); + } + + _socket.Socket.Bind(new IPEndPoint(IPAddress.IPv6Any, _port)); + if (_socketBackup != null) + _socketBackup.Socket.Bind(new IPEndPoint(IPAddress.Any, _port)); + } + } + else + { + _socket = SetupUDPSocket(_localEP.AddressFamily, _receivePacketSize + 1); + _socket.Socket.Bind(_localEP); + } + + if (_receiveBufferSize > 0) + { + _socket.Socket.ReceiveBufferSize = _receiveBufferSize; + if (_socketBackup != null) + _socketBackup.Socket.ReceiveBufferSize = _receiveBufferSize; + } + if (_sendBufferSize > 0) + { + _socket.Socket.SendBufferSize = _sendBufferSize; + if (_socketBackup != null) + _socketBackup.Socket.SendBufferSize = _sendBufferSize; + } + + BeginReceive(); + } + + /// + public void Stop() + { + if (System.Threading.Interlocked.Exchange(ref _running, 0) == 0) + return; + + if (_socket != null) + { + _socket.Dispose(); + _socket = null; + } + if (_socketBackup != null) + { + _socketBackup.Dispose(); + _socketBackup = null; + } + } + + /// + public void Send(Byte[] data, System.Net.EndPoint ep) + { + RawData raw = new RawData(); + raw.Data = data; + raw.EndPoint = ep; + _sendingQueue.Enqueue(raw); + if (System.Threading.Interlocked.CompareExchange(ref _writing, 1, 0) > 0) + return; + BeginSend(); + } + + /// + public void Dispose() + { + Stop(); + } + + private void BeginReceive() + { + if (_running > 0) + { + BeginReceive(_socket); + + if (_socketBackup != null) + BeginReceive(_socketBackup); + } + } + + private void EndReceive(UDPSocket socket, Byte[] buffer, Int32 offset, Int32 count, System.Net.EndPoint ep) + { + if (count > 0) + { + Byte[] bytes = new Byte[count]; + Buffer.BlockCopy(buffer, 0, bytes, 0, count); + + if (ep.AddressFamily == AddressFamily.InterNetworkV6) + { + IPEndPoint ipep = (IPEndPoint)ep; + if (IPAddressExtensions.IsIPv4MappedToIPv6(ipep.Address)) + ep = new IPEndPoint(IPAddressExtensions.MapToIPv4(ipep.Address), ipep.Port); + } + + FireDataReceived(bytes, ep); + } + + BeginReceive(socket); + } + + private void EndReceive(UDPSocket socket, Exception ex) + { + // TODO may log exception? + BeginReceive(socket); + } + + private void FireDataReceived(Byte[] data, System.Net.EndPoint ep) + { + EventHandler h = DataReceived; + if (h != null) + h(this, new DataReceivedEventArgs(data, ep)); + } + + private void BeginSend() + { + if (_running == 0) + return; + + RawData raw; + if (!_sendingQueue.TryDequeue(out raw)) + { + System.Threading.Interlocked.Exchange(ref _writing, 0); + return; + } + + UDPSocket socket = _socket; + IPEndPoint remoteEP = (IPEndPoint)raw.EndPoint; + + if (remoteEP.AddressFamily == AddressFamily.InterNetwork) + { + if (_socketBackup != null) + { + // use the separated socket of IPv4 to deal with IPv4 conversions. + socket = _socketBackup; + } + else if (_socket.Socket.AddressFamily == AddressFamily.InterNetworkV6) + { + remoteEP = new IPEndPoint(IPAddressExtensions.MapToIPv6(remoteEP.Address), remoteEP.Port); + } + } + + BeginSend(socket, raw.Data, remoteEP); + } + + private void EndSend(UDPSocket socket, Int32 bytesTransferred) + { + BeginSend(); + } + + private void EndSend(UDPSocket socket, Exception ex) + { + // TODO may log exception? + BeginSend(); + } + + private UDPSocket SetupUDPSocket(AddressFamily addressFamily, Int32 bufferSize) + { + UDPSocket socket = NewUDPSocket(addressFamily, bufferSize); + + // do not throw SocketError.ConnectionReset by ignoring ICMP Port Unreachable + const Int32 SIO_UDP_CONNRESET = -1744830452; + try + { + socket.Socket.IOControl(SIO_UDP_CONNRESET, new Byte[] { 0 }, null); + } + catch (Exception e) + { + // ignore + } + return socket; + } + + partial class UDPSocket : IDisposable + { + public readonly Socket Socket; + + + } + + class RawData + { + public Byte[] Data; + public System.Net.EndPoint EndPoint; + } + } +} diff --git a/src/Coap/CoAP.NET/CoAP.NET.csproj b/src/Coap/CoAP.NET/CoAP.NET.csproj new file mode 100644 index 000000000..dd61b57ad --- /dev/null +++ b/src/Coap/CoAP.NET/CoAP.NET.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + diff --git a/src/Coap/CoAP.NET/CoapClient.cs b/src/Coap/CoAP.NET/CoapClient.cs new file mode 100644 index 000000000..99501c6b3 --- /dev/null +++ b/src/Coap/CoAP.NET/CoapClient.cs @@ -0,0 +1,555 @@ +/* + * Copyright (c) 2011-2015, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using CoAP.Net; +using CoAP.Observe; +using Microsoft.Extensions.Logging; +using Surging.Core.CPlatform.Utilities; + +namespace CoAP +{ + /// + /// Provides convenient methods for accessing CoAP resources. + /// + public class CoapClient + { + private readonly ILogger log; + private static readonly IEnumerable EmptyLinks = new WebLink[0]; + private Uri _uri; + private ICoapConfig _config; + private IEndPoint _endpoint; + private MessageType _type = MessageType.CON; + private Int32 _blockwise; + private Int32 _timeout = System.Threading.Timeout.Infinite; + + /// + /// Occurs when a response has arrived. + /// + public event EventHandler Respond; + /// + /// Occurs if an exception is thrown while executing a request. + /// + public event EventHandler Error; + + /// + /// Instantiates with default config. + /// + public CoapClient() + : this(null, null) + { } + + /// + /// Instantiates with default config. + /// + /// the Uri of remote resource + public CoapClient(Uri uri) + : this(uri, null) + { } + + /// + /// Instantiates. + /// + /// the config + public CoapClient(ICoapConfig config) + : this(null, config) + { } + + /// + /// Instantiates. + /// + /// the Uri of remote resource + /// the config + public CoapClient(Uri uri, ICoapConfig config) + { + log = ServiceLocator.GetService>(); + _uri = uri; + _config = config ?? CoapConfig.Default; + } + + /// + /// Gets or sets the destination URI of this client. + /// + public Uri Uri + { + get { return _uri; } + set { _uri = value; } + } + + /// + /// Gets or sets the endpoint this client is supposed to use. + /// + public IEndPoint EndPoint + { + get { return _endpoint; } + set { _endpoint = value; } + } + + /// + /// Gets or sets the timeout how long synchronous method calls will wait + /// until they give up and return anyways. The default value is . + /// + public Int32 Timeout + { + get { return _timeout; } + set { _timeout = value; } + } + + /// + /// Let the client use Confirmable requests. + /// + public CoapClient UseCONs() + { + _type = MessageType.CON; + return this; + } + + /// + /// Let the client use Non-Confirmable requests. + /// + public CoapClient UseNONs() + { + _type = MessageType.NON; + return this; + } + + /// + /// Let the client use early negotiation for the blocksize + /// (16, 32, 64, 128, 256, 512, or 1024). Other values will + /// be matched to the closest logarithm dualis. + /// + public CoapClient UseEarlyNegotiation(Int32 size) + { + _blockwise = size; + return this; + } + + /// + /// Let the client use late negotiation for the block size (default). + /// + public CoapClient UseLateNegotiation() + { + _blockwise = 0; + return this; + } + + /// + /// Performs a CoAP ping. + /// + /// success of the ping + public Boolean Ping() + { + return Ping(_timeout); + } + + /// + /// Performs a CoAP ping and gives up after the given number of milliseconds. + /// + /// the time to wait for a pong in milliseconds + /// success of the ping + public Boolean Ping(Int32 timeout) + { + try + { + Request request = new Request(Code.Empty, true); + request.Token = CoapConstants.EmptyToken; + request.URI = Uri; + request.Send().WaitForResponse(timeout); + return request.IsRejected; + } + catch (System.Threading.ThreadInterruptedException) + { + /* ignore */ + } + return false; + } + + /// + /// Discovers remote resources. + /// + /// the descoverd representing remote resources, or null if no response + public IEnumerable Discover() + { + return Discover(null); + } + + /// + /// Discovers remote resources. + /// + /// the query to filter resources + /// the descoverd representing remote resources, or null if no response + public IEnumerable Discover(String query) + { + Request discover = Prepare(Request.NewGet()); + discover.ClearUriPath().ClearUriQuery().UriPath = CoapConstants.DefaultWellKnownURI; + if (!String.IsNullOrEmpty(query)) + discover.UriQuery = query; + Response links = discover.Send().WaitForResponse(_timeout); + if (links == null) + // if no response, return null (e.g., timeout) + return null; + else if (links.ContentFormat != MediaType.ApplicationLinkFormat) + return EmptyLinks; + else + return LinkFormat.Parse(links.PayloadString); + } + + /// + /// Sends a GET request and blocks until the response is available. + /// + /// the CoAP response + public Response Get() + { + return Send(Request.NewGet()); + } + + /// + /// Sends a GET request with the specified Accept option and blocks + /// until the response is available. + /// + /// the Accept option + /// the CoAP response + public Response Get(Int32 accept) + { + return Send(Accept(Request.NewGet(), accept)); + } + + /// + /// Sends a GET request asynchronizely. + /// + /// the callback when a response arrives + /// the callback when an error occurs + public void GetAsync(Action done = null, Action fail = null) + { + SendAsync(Request.NewGet(), done, fail); + } + + /// + /// Sends a GET request with the specified Accept option asynchronizely. + /// + /// the Accept option + /// the callback when a response arrives + /// the callback when an error occurs + public void GetAsync(Int32 accept, Action done = null, Action fail = null) + { + SendAsync(Accept(Request.NewGet(), accept), done, fail); + } + + public Response Post(String payload, Int32 format = MediaType.TextPlain) + { + return Send((Request)Request.NewPost().SetPayload(payload, format)); + } + + public Response Post(String payload, Int32 format, Int32 accept) + { + return Send(Accept((Request)Request.NewPost().SetPayload(payload, format), accept)); + } + + public Response Post(Byte[] payload, Int32 format) + { + return Send((Request)Request.NewPost().SetPayload(payload, format)); + } + + public Response Post(Byte[] payload, Int32 format, Int32 accept) + { + return Send(Accept((Request)Request.NewPost().SetPayload(payload, format), accept)); + } + + public void PostAsync(String payload, + Action done = null, Action fail = null) + { + PostAsync(payload, MediaType.TextPlain, done, fail); + } + + public void PostAsync(String payload, Int32 format, + Action done = null, Action fail = null) + { + SendAsync((Request)Request.NewPost().SetPayload(payload, format), done, fail); + } + + public void PostAsync(String payload, Int32 format, Int32 accept, + Action done = null, Action fail = null) + { + SendAsync(Accept((Request)Request.NewPost().SetPayload(payload, format), accept), done, fail); + } + + public void PostAsync(Byte[] payload, Int32 format, + Action done = null, Action fail = null) + { + SendAsync((Request)Request.NewPost().SetPayload(payload, format), done, fail); + } + + public void PostAsync(Byte[] payload, Int32 format, Int32 accept, + Action done = null, Action fail = null) + { + SendAsync(Accept((Request)Request.NewPost().SetPayload(payload, format), accept), done, fail); + } + + public Response Put(String payload, Int32 format = MediaType.TextPlain) + { + return Send((Request)Request.NewPut().SetPayload(payload, format)); + } + + public Response Put(Byte[] payload, Int32 format, Int32 accept) + { + return Send(Accept((Request)Request.NewPut().SetPayload(payload, format), accept)); + } + + public Response PutIfMatch(String payload, Int32 format, params Byte[][] etags) + { + return Send(IfMatch((Request)Request.NewPut().SetPayload(payload, format), etags)); + } + + public Response PutIfMatch(Byte[] payload, Int32 format, params Byte[][] etags) + { + return Send(IfMatch((Request)Request.NewPut().SetPayload(payload, format), etags)); + } + + public Response PutIfNoneMatch(String payload, Int32 format) + { + return Send(IfNoneMatch((Request)Request.NewPut().SetPayload(payload, format))); + } + + public Response PutIfNoneMatch(Byte[] payload, Int32 format) + { + return Send(IfNoneMatch((Request)Request.NewPut().SetPayload(payload, format))); + } + + public void PutAsync(String payload, + Action done = null, Action fail = null) + { + PutAsync(payload, MediaType.TextPlain, done, fail); + } + + public void PutAsync(String payload, Int32 format, + Action done = null, Action fail = null) + { + SendAsync((Request)Request.NewPut().SetPayload(payload, format), done, fail); + } + + public void PutAsync(Byte[] payload, Int32 format, Int32 accept, + Action done = null, Action fail = null) + { + SendAsync(Accept((Request)Request.NewPut().SetPayload(payload, format), accept), done, fail); + } + + /// + /// Sends a DELETE request and waits for the response. + /// + /// the CoAP response + public Response Delete() + { + return Send(Request.NewDelete()); + } + + /// + /// Sends a DELETE request asynchronizely. + /// + /// the callback when a response arrives + /// the callback when an error occurs + public void DeleteAsync(Action done = null, Action fail = null) + { + SendAsync(Request.NewDelete(), done, fail); + } + + public Response Validate(params Byte[][] etags) + { + return Send(ETags(Request.NewGet(), etags)); + } + + public CoapObserveRelation Observe(Action notify = null, Action error = null) + { + return Observe(Request.NewGet().MarkObserve(), notify, error); + } + + public CoapObserveRelation Observe(Int32 accept, Action notify = null, Action error = null) + { + return Observe(Accept(Request.NewGet().MarkObserve(), accept), notify, error); + } + + public CoapObserveRelation ObserveAsync(Action notify = null, Action error = null) + { + return ObserveAsync(Request.NewGet().MarkObserve(), notify, error); + } + + public CoapObserveRelation ObserveAsync(Int32 accept, Action notify = null, Action error = null) + { + return ObserveAsync(Accept(Request.NewGet().MarkObserve(), accept), notify, error); + } + + public Response Send(Request request) + { + return Prepare(request).Send().WaitForResponse(_timeout); + } + + public void SendAsync(Request request, Action done = null, Action fail = null) + { + request.Respond += (o, e) => Deliver(done, e); + request.Rejected += (o, e) => Fail(fail, FailReason.Rejected); + request.TimedOut += (o, e) => Fail(fail, FailReason.TimedOut); + + Prepare(request).Send(); + } + + protected Request Prepare(Request request) + { + return Prepare(request, GetEffectiveEndpoint(request)); + } + + protected Request Prepare(Request request, IEndPoint endpoint) + { + request.Type = _type; + request.URI = _uri; + + if (_blockwise != 0) + request.SetBlock2(BlockOption.EncodeSZX(_blockwise), false, 0); + + if (endpoint != null) + request.EndPoint = endpoint; + + return request; + } + + /// + /// Gets the effective endpoint that the specified request + /// is supposed to be sent over. + /// + protected IEndPoint GetEffectiveEndpoint(Request request) + { + if (_endpoint != null) + return _endpoint; + else + return EndPointManager.Default; + // TODO secure coap + } + + private CoapObserveRelation Observe(Request request, Action notify, Action error) + { + CoapObserveRelation relation = ObserveAsync(request, notify, error); + Response response = relation.Request.WaitForResponse(_timeout); + if (response == null || !response.HasOption(OptionType.Observe)) + relation.Canceled = true; + relation.Current = response; + return relation; + } + + private CoapObserveRelation ObserveAsync(Request request, Action notify, Action error) + { + IEndPoint endpoint = GetEffectiveEndpoint(request); + CoapObserveRelation relation = new CoapObserveRelation(request, endpoint, _config); + + request.Respond += (o, e) => + { + Response resp = e.Response; + lock (relation) + { + if (relation.Orderer.IsNew(resp)) + { + relation.Current = resp; + Deliver(notify, e); + } + else + { + log.LogDebug("Dropping old notification: " + resp); + } + } + }; + Action fail = r => + { + relation.Canceled = true; + Fail(error, r); + }; + request.Rejected += (o, e) => fail(FailReason.Rejected); + request.TimedOut += (o, e) => fail(FailReason.TimedOut); + + Prepare(request, endpoint).Send(); + return relation; + } + + private void Deliver(Action act, ResponseEventArgs e) + { + if (act != null) + act(e.Response); + EventHandler h = Respond; + if (h != null) + h(this, e); + } + + private void Fail(Action fail, FailReason reason) + { + if (fail != null) + fail(reason); + EventHandler h = Error; + if (h != null) + h(this, new ErrorEventArgs(reason)); + } + + static Request Accept(Request request, Int32 accept) + { + request.Accept = accept; + return request; + } + + static Request IfMatch(Request request, params Byte[][] etags) + { + foreach (Byte[] etag in etags) + { + request.AddIfMatch(etag); + } + return request; + } + + static Request IfNoneMatch(Request request) + { + request.IfNoneMatch = true; + return request; + } + + static Request ETags(Request request, params Byte[][] etags) + { + foreach (Byte[] etag in etags) + { + request.AddETag(etag); + } + return request; + } + + /// + /// Provides details about errors. + /// + public enum FailReason + { + /// + /// The request has been rejected. + /// + Rejected, + /// + /// The request has been timed out. + /// + TimedOut + } + + /// + /// Provides event args for errors. + /// + public class ErrorEventArgs : EventArgs + { + internal ErrorEventArgs(FailReason reason) + { + this.Reason = reason; + } + + /// + /// Gets the reason why failed. + /// + public FailReason Reason { get; private set; } + } + } +} diff --git a/src/Coap/CoAP.NET/CoapConfig.cs b/src/Coap/CoAP.NET/CoapConfig.cs new file mode 100644 index 000000000..a9d01f0de --- /dev/null +++ b/src/Coap/CoAP.NET/CoapConfig.cs @@ -0,0 +1,517 @@ +/* + * Copyright (c) 2011-2015, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; +using System.Collections.Specialized; +using System.ComponentModel; +using System.IO; + +namespace CoAP +{ + /// + /// Default implementation of . + /// + public partial class CoapConfig : ICoapConfig + { + private static ICoapConfig _default; + + public static ICoapConfig Default + { + get + { + if (_default == null) + { + lock (typeof(CoapConfig)) + { + if (_default == null) + _default = LoadConfig(); + } + } + return _default; + } + } + + private Int32 _port; + private Int32 _securePort = CoapConstants.DefaultSecurePort; + private Int32 _httpPort = 8080; + private Int32 _ackTimeout = CoapConstants.AckTimeout; + private Double _ackRandomFactor = CoapConstants.AckRandomFactor; + private Double _ackTimeoutScale = 2D; + private Int32 _maxRetransmit = CoapConstants.MaxRetransmit; + private Int32 _maxMessageSize = 1024; + private Int32 _defaultBlockSize = CoapConstants.DefaultBlockSize; + private Int32 _blockwiseStatusLifetime = 10 * 60 * 1000; // ms + private Boolean _useRandomIDStart = true; + private Boolean _useRandomTokenStart = true; + private String _deduplicator = CoAP.Deduplication.DeduplicatorFactory.MarkAndSweepDeduplicator; + private Int32 _cropRotationPeriod = 2000; // ms + private Int32 _exchangeLifetime = 247 * 1000; // ms + private Int64 _markAndSweepInterval = 10 * 1000; // ms + private Int64 _notificationMaxAge = 128 * 1000; // ms + private Int64 _notificationCheckIntervalTime = 24 * 60 * 60 * 1000; // ms + private Int32 _notificationCheckIntervalCount = 100; // ms + private Int32 _notificationReregistrationBackoff = 2000; // ms + private Int32 _channelReceiveBufferSize; + private Int32 _channelSendBufferSize; + private Int32 _channelReceivePacketSize = 2048; + + /// + /// Instantiate. + /// + public CoapConfig() + { + _port = Spec.DefaultPort; + } + + /// + public String Version + { + get { return Spec.Name; } + } + + /// + public Int32 DefaultPort + { + get { return _port; } + set + { + if (_port != value) + { + _port = value; + NotifyPropertyChanged("DefaultPort"); + } + } + } + + /// + public Int32 DefaultSecurePort + { + get { return _securePort; } + set + { + if (_securePort != value) + { + _securePort = value; + NotifyPropertyChanged("DefaultSecurePort"); + } + } + } + + /// + public Int32 HttpPort + { + get { return _httpPort; } + set + { + if (_httpPort != value) + { + _httpPort = value; + NotifyPropertyChanged("HttpPort"); + } + } + } + + /// + public Int32 AckTimeout + { + get { return _ackTimeout; } + set + { + if (_ackTimeout != value) + { + _ackTimeout = value; + NotifyPropertyChanged("AckTimeout"); + } + } + } + + /// + public Double AckRandomFactor + { + get { return _ackRandomFactor; } + set + { + if (_ackRandomFactor != value) + { + _ackRandomFactor = value; + NotifyPropertyChanged("AckRandomFactor"); + } + } + } + + /// + public Double AckTimeoutScale + { + get { return _ackTimeoutScale; } + set + { + if (_ackTimeoutScale != value) + { + _ackTimeoutScale = value; + NotifyPropertyChanged("AckTimeoutScale"); + } + } + } + + /// + public Int32 MaxRetransmit + { + get { return _maxRetransmit; } + set + { + if (_maxRetransmit != value) + { + _maxRetransmit = value; + NotifyPropertyChanged("MaxRetransmit"); + } + } + } + + /// + public Int32 MaxMessageSize + { + get { return _maxMessageSize; } + set + { + if (_maxMessageSize != value) + { + _maxMessageSize = value; + NotifyPropertyChanged("MaxMessageSize"); + } + } + } + + /// + public Int32 DefaultBlockSize + { + get { return _defaultBlockSize; } + set + { + if (_defaultBlockSize != value) + { + _defaultBlockSize = value; + NotifyPropertyChanged("DefaultBlockSize"); + } + } + } + + /// + public Int32 BlockwiseStatusLifetime + { + get { return _blockwiseStatusLifetime; } + set + { + if (_blockwiseStatusLifetime != value) + { + _blockwiseStatusLifetime = value; + NotifyPropertyChanged("BlockwiseStatusLifetime"); + } + } + } + + /// + public Boolean UseRandomIDStart + { + get { return _useRandomIDStart; } + set + { + if (_useRandomIDStart != value) + { + _useRandomIDStart = value; + NotifyPropertyChanged("UseRandomIDStart"); + } + } + } + + /// + public Boolean UseRandomTokenStart + { + get { return _useRandomTokenStart; } + set + { + if (_useRandomTokenStart != value) + { + _useRandomTokenStart = value; + NotifyPropertyChanged("UseRandomTokenStart"); + } + } + } + + /// + public String Deduplicator + { + get { return _deduplicator; } + set + { + if (_deduplicator != value) + { + _deduplicator = value; + NotifyPropertyChanged("Deduplicator"); + } + } + } + + /// + public Int32 CropRotationPeriod + { + get { return _cropRotationPeriod; } + set + { + if (_cropRotationPeriod != value) + { + _cropRotationPeriod = value; + NotifyPropertyChanged("CropRotationPeriod"); + } + } + } + + /// + public Int32 ExchangeLifetime + { + get { return _exchangeLifetime; } + set + { + if (_exchangeLifetime != value) + { + _exchangeLifetime = value; + NotifyPropertyChanged("ExchangeLifetime"); + } + } + } + + /// + public Int64 MarkAndSweepInterval + { + get { return _markAndSweepInterval; } + set + { + if (_markAndSweepInterval != value) + { + _markAndSweepInterval = value; + NotifyPropertyChanged("MarkAndSweepInterval"); + } + } + } + + /// + public Int64 NotificationMaxAge + { + get { return _notificationMaxAge; } + set + { + if (_notificationMaxAge != value) + { + _notificationMaxAge = value; + NotifyPropertyChanged("NotificationMaxAge"); + } + } + } + + /// + public Int64 NotificationCheckIntervalTime + { + get { return _notificationCheckIntervalTime; } + set + { + if (_notificationCheckIntervalTime != value) + { + _notificationCheckIntervalTime = value; + NotifyPropertyChanged("NotificationCheckIntervalTime"); + } + } + } + + /// + public Int32 NotificationCheckIntervalCount + { + get { return _notificationCheckIntervalCount; } + set + { + if (_notificationCheckIntervalCount != value) + { + _notificationCheckIntervalCount = value; + NotifyPropertyChanged("NotificationCheckIntervalCount"); + } + } + } + + /// + public Int32 NotificationReregistrationBackoff + { + get { return _notificationReregistrationBackoff; } + set + { + if (_notificationReregistrationBackoff != value) + { + _notificationReregistrationBackoff = value; + NotifyPropertyChanged("NotificationReregistrationBackoff"); + } + } + } + + /// + public Int32 ChannelReceiveBufferSize + { + get { return _channelReceiveBufferSize; } + set + { + if (_channelReceiveBufferSize != value) + { + _channelReceiveBufferSize = value; + NotifyPropertyChanged("ChannelReceiveBufferSize"); + } + } + } + + /// + public Int32 ChannelSendBufferSize + { + get { return _channelSendBufferSize; } + set + { + if (_channelSendBufferSize != value) + { + _channelSendBufferSize = value; + NotifyPropertyChanged("ChannelSendBufferSize"); + } + } + } + + /// + public Int32 ChannelReceivePacketSize + { + get { return _channelReceivePacketSize; } + set + { + if (_channelReceivePacketSize != value) + { + _channelReceivePacketSize = value; + NotifyPropertyChanged("ChannelReceivePacketSize"); + } + } + } + + /// + public void Load(String configFile) + { + String[] lines = File.ReadAllLines(configFile); + NameValueCollection nvc = new NameValueCollection(lines.Length, StringComparer.OrdinalIgnoreCase); + foreach (String line in lines) + { + String[] tmp = line.Split(new Char[] { '=' }, 2); + if (tmp.Length == 2) + nvc[tmp[0]] = tmp[1]; + } + + DefaultPort = GetInt32(nvc, "DefaultPort", "DEFAULT_COAP_PORT", DefaultPort); + DefaultSecurePort = GetInt32(nvc, "DefaultSecurePort", "DEFAULT_COAPS_PORT", DefaultSecurePort); + HttpPort = GetInt32(nvc, "HttpPort", "HTTP_PORT", HttpPort); + AckTimeout = GetInt32(nvc, "AckTimeout", "ACK_TIMEOUT", AckTimeout); + AckRandomFactor = GetDouble(nvc, "AckRandomFactor", "ACK_RANDOM_FACTOR", AckRandomFactor); + AckTimeoutScale = GetDouble(nvc, "AckTimeoutScale", "ACK_TIMEOUT_SCALE", AckTimeoutScale); + MaxRetransmit = GetInt32(nvc, "MaxRetransmit", "MAX_RETRANSMIT", MaxRetransmit); + MaxMessageSize = GetInt32(nvc, "MaxMessageSize", "MAX_MESSAGE_SIZE", MaxMessageSize); + DefaultBlockSize = GetInt32(nvc, "DefaultBlockSize", "DEFAULT_BLOCK_SIZE", DefaultBlockSize); + UseRandomIDStart = GetBoolean(nvc, "UseRandomIDStart", "USE_RANDOM_MID_START", UseRandomIDStart); + UseRandomTokenStart = GetBoolean(nvc, "UseRandomTokenStart", "USE_RANDOM_TOKEN_START", UseRandomTokenStart); + Deduplicator = GetString(nvc, "Deduplicator", "DEDUPLICATOR", Deduplicator); + CropRotationPeriod = GetInt32(nvc, "CropRotationPeriod", "CROP_ROTATION_PERIOD", CropRotationPeriod); + ExchangeLifetime = GetInt32(nvc, "ExchangeLifetime", "EXCHANGE_LIFETIME", ExchangeLifetime); + MarkAndSweepInterval = GetInt64(nvc, "MarkAndSweepInterval", "MARK_AND_SWEEP_INTERVAL", MarkAndSweepInterval); + NotificationMaxAge = GetInt64(nvc, "NotificationMaxAge", "NOTIFICATION_MAX_AGE", NotificationMaxAge); + NotificationCheckIntervalTime = GetInt64(nvc, "NotificationCheckIntervalTime", "NOTIFICATION_CHECK_INTERVAL", NotificationCheckIntervalTime); + NotificationCheckIntervalCount = GetInt32(nvc, "NotificationCheckIntervalCount", "NOTIFICATION_CHECK_INTERVAL_COUNT", NotificationCheckIntervalCount); + NotificationReregistrationBackoff = GetInt32(nvc, "NotificationReregistrationBackoff", "NOTIFICATION_REREGISTRATION_BACKOFF", NotificationReregistrationBackoff); + ChannelReceiveBufferSize = GetInt32(nvc, "ChannelReceiveBufferSize", "UDP_CONNECTOR_RECEIVE_BUFFER", ChannelReceiveBufferSize); + ChannelSendBufferSize = GetInt32(nvc, "ChannelSendBufferSize", "UDP_CONNECTOR_SEND_BUFFER", ChannelSendBufferSize); + ChannelReceivePacketSize = GetInt32(nvc, "ChannelReceivePacketSize", "UDP_CONNECTOR_DATAGRAM_SIZE", ChannelReceivePacketSize); + } + + /// + public void Store(String configFile) + { + using (StreamWriter w = new StreamWriter(configFile)) + { + w.Write("DefaultPort="); w.WriteLine(DefaultPort); + w.Write("DefaultSecurePort="); w.WriteLine(DefaultSecurePort); + w.Write("HttpPort="); w.WriteLine(HttpPort); + w.Write("AckTimeout="); w.WriteLine(AckTimeout); + w.Write("AckRandomFactor="); w.WriteLine(AckRandomFactor); + w.Write("AckTimeoutScale="); w.WriteLine(AckTimeoutScale); + w.Write("MaxRetransmit="); w.WriteLine(MaxRetransmit); + w.Write("MaxMessageSize="); w.WriteLine(MaxMessageSize); + w.Write("DefaultBlockSize="); w.WriteLine(DefaultBlockSize); + w.Write("UseRandomIDStart="); w.WriteLine(UseRandomIDStart); + w.Write("UseRandomTokenStart="); w.WriteLine(UseRandomTokenStart); + w.Write("Deduplicator="); w.WriteLine(Deduplicator); + w.Write("CropRotationPeriod="); w.WriteLine(CropRotationPeriod); + w.Write("ExchangeLifetime="); w.WriteLine(ExchangeLifetime); + w.Write("MarkAndSweepInterval="); w.WriteLine(MarkAndSweepInterval); + w.Write("NotificationMaxAge="); w.WriteLine(NotificationMaxAge); + w.Write("NotificationCheckIntervalTime="); w.WriteLine(NotificationCheckIntervalTime); + w.Write("NotificationCheckIntervalCount="); w.WriteLine(NotificationCheckIntervalCount); + w.Write("NotificationReregistrationBackoff="); w.WriteLine(NotificationReregistrationBackoff); + w.Write("ChannelReceiveBufferSize="); w.WriteLine(ChannelReceiveBufferSize); + w.Write("ChannelSendBufferSize="); w.WriteLine(ChannelSendBufferSize); + w.Write("ChannelReceivePacketSize="); w.WriteLine(ChannelReceivePacketSize); + } + } + + private static String GetString(NameValueCollection nvc, String key1, String key2, String defaultValue) + { + return nvc[key1] ?? nvc[key2] ?? defaultValue; + } + + private static Int32 GetInt32(NameValueCollection nvc, String key1, String key2, Int32 defaultValue) + { + String value = GetString(nvc, key1, key2, null); + Int32 result; + return !String.IsNullOrEmpty(value) && Int32.TryParse(value, out result) ? result : defaultValue; + } + + private static Int64 GetInt64(NameValueCollection nvc, String key1, String key2, Int64 defaultValue) + { + String value = GetString(nvc, key1, key2, null); + Int64 result; + return !String.IsNullOrEmpty(value) && Int64.TryParse(value, out result) ? result : defaultValue; + } + + private static Double GetDouble(NameValueCollection nvc, String key1, String key2, Double defaultValue) + { + String value = GetString(nvc, key1, key2, null); + Double result; + return !String.IsNullOrEmpty(value) && Double.TryParse(value, out result) ? result : defaultValue; + } + + private static Boolean GetBoolean(NameValueCollection nvc, String key1, String key2, Boolean defaultValue) + { + String value = GetString(nvc, key1, key2, null); + Boolean result; + return !String.IsNullOrEmpty(value) && Boolean.TryParse(value, out result) ? result : defaultValue; + } + + private static ICoapConfig LoadConfig() + { + // TODO may have configuration file here + return new CoapConfig(); + } + + /// + public event PropertyChangedEventHandler PropertyChanged; + + private void NotifyPropertyChanged(String propertyName) + { + PropertyChangedEventHandler handler = PropertyChanged; + if (handler != null) + handler(this, new PropertyChangedEventArgs(propertyName)); + } + } +} diff --git a/src/Coap/CoAP.NET/CoapConstants.cs b/src/Coap/CoAP.NET/CoapConstants.cs new file mode 100644 index 000000000..fdf8b3af6 --- /dev/null +++ b/src/Coap/CoAP.NET/CoapConstants.cs @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2011-2012, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP +{ + /// + /// Constants defined for CoAP protocol + /// + public static class CoapConstants + { + /// + /// RFC 7252 CoAP version. + /// + public const Int32 Version = 0x01; + /// + /// The CoAP URI scheme. + /// + public const String UriScheme = "coap"; + /// + /// The CoAPS URI scheme. + /// + public const String SecureUriScheme = "coaps"; + /// + /// The default CoAP port for normal CoAP communication (not secure). + /// + public const Int32 DefaultPort = 5683; + /// + /// The default CoAP port for secure CoAP communication (coaps). + /// + public const Int32 DefaultSecurePort = 5684; + /// + /// The initial time (ms) for a CoAP message + /// + public const Int32 AckTimeout = 2000; + /// + /// The initial timeout is set + /// to a random number between RESPONSE_TIMEOUT and (RESPONSE_TIMEOUT * + /// RESPONSE_RANDOM_FACTOR) + /// + public const Double AckRandomFactor = 1.5D; + /// + /// The max time that a message would be retransmitted + /// + public const Int32 MaxRetransmit = 4; + /// + /// Default block size used for block-wise transfers + /// + public const Int32 DefaultBlockSize = 512; + public const Int32 MessageCacheSize = 32; + public const Int32 ReceiveBufferSize = 4096; + public const Int32 DefaultOverallTimeout = 100000; + /// + /// Default URI for wellknown resource + /// + public const String DefaultWellKnownURI = "/.well-known/core"; + public const Int32 TokenLength = 8; + public const Int32 DefaultMaxAge = 60; + /// + /// The number of notifications until a CON notification will be used. + /// + public const Int32 ObservingRefreshInterval = 10; + + public static readonly Byte[] EmptyToken = new Byte[0]; + + /// + /// The lowest value of a request code. + /// + public const Int32 RequestCodeLowerBound = 1; + + /// + /// The highest value of a request code. + /// + public const Int32 RequestCodeUpperBound = 31; + + /// + /// The lowest value of a response code. + /// + public const Int32 ResponseCodeLowerBound = 64; + + /// + /// The highest value of a response code. + /// + public const Int32 ResponseCodeUpperBound = 191; + } +} diff --git a/src/Coap/CoAP.NET/CoapObserveRelation.cs b/src/Coap/CoAP.NET/CoapObserveRelation.cs new file mode 100644 index 000000000..df3a48d33 --- /dev/null +++ b/src/Coap/CoAP.NET/CoapObserveRelation.cs @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2011-2015, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; +using CoAP.Net; +using CoAP.Observe; + +namespace CoAP +{ + /// + /// Represents a CoAP observe relation between a CoAP client and a resource on a server. + /// Provides a simple API to check whether a relation has successfully established and + /// to cancel or refresh the relation. + /// + public class CoapObserveRelation + { + readonly ICoapConfig _config; + readonly Request _request; + readonly IEndPoint _endpoint; + private Boolean _canceled; + private Response _current; + private ObserveNotificationOrderer _orderer; + + public CoapObserveRelation(Request request, IEndPoint endpoint, ICoapConfig config) + { + _config = config; + _request = request; + _endpoint = endpoint; + _orderer = new ObserveNotificationOrderer(config); + + request.Reregistering += OnReregister; + } + + public Request Request + { + get { return _request; } + } + + public Response Current + { + get { return _current; } + set { _current = value; } + } + + public ObserveNotificationOrderer Orderer + { + get { return _orderer; } + } + + public Boolean Canceled + { + get { return _canceled; } + set { _canceled = value; } + } + + public void ReactiveCancel() + { + _request.IsCancelled = true; + _canceled = true; + } + + public void ProactiveCancel() + { + Request cancel = Request.NewGet(); + // copy options, but set Observe to cancel + cancel.SetOptions(_request.GetOptions()); + cancel.MarkObserveCancel(); + // use same Token + cancel.Token = _request.Token; + cancel.Destination = _request.Destination; + + // dispatch final response to the same message observers + cancel.CopyEventHandler(_request); + + cancel.Send(_endpoint); + // cancel old ongoing request + _request.IsCancelled = true; + _canceled = true; + } + + private void OnReregister(Object sender, ReregisterEventArgs e) + { + // TODO: update request in observe handle for correct cancellation? + //_request = e.RefreshRequest; + + // reset orderer to accept any sequence number since server might have rebooted + _orderer = new ObserveNotificationOrderer(_config); + } + } +} diff --git a/src/Coap/CoAP.NET/Code.cs b/src/Coap/CoAP.NET/Code.cs new file mode 100644 index 000000000..1be9f2c8d --- /dev/null +++ b/src/Coap/CoAP.NET/Code.cs @@ -0,0 +1,400 @@ +/* + * Copyright (c) 2011-2015, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP +{ + /// + /// This class describes the CoAP Code Registry as defined in + /// draft-ietf-core-coap-08, section 11.1 + /// + public class Code + { + public const Int32 Empty = 0; + + public const Int32 SuccessCode = 2; + public const Int32 ClientErrorCode = 4; + public const Int32 ServerErrorCode = 5; + + #region Method Codes + + /// + /// The GET method + /// + public const Int32 GET = 1; + /// + /// The POST method + /// + public const Int32 POST = 2; + /// + /// The PUT method + /// + public const Int32 PUT = 3; + /// + /// The DELETE method + /// + public const Int32 DELETE = 4; + + #endregion + + #region Response Codes + + /// + /// 2.01 Created + /// + public const Int32 Created = 65; + /// + /// 2.02 Deleted + /// + public const Int32 Deleted = 66; + /// + /// 2.03 Valid + /// + public const Int32 Valid = 67; + /// + /// 2.04 Changed + /// + public const Int32 Changed = 68; + /// + /// 2.05 Content + /// + public const Int32 Content = 69; + /// + /// 2.?? Continue + /// + public const Int32 Continue = 95; + /// + /// 4.00 Bad Request + /// + public const Int32 BadRequest = 128; + /// + /// 4.01 Unauthorized + /// + public const Int32 Unauthorized = 129; + /// + /// 4.02 Bad Option + /// + public const Int32 BadOption = 130; + /// + /// 4.03 Forbidden + /// + public const Int32 Forbidden = 131; + /// + /// 4.04 Not Found + /// + public const Int32 NotFound = 132; + /// + /// 4.05 Method Not Allowed + /// + public const Int32 MethodNotAllowed = 133; + /// + /// 4.06 Not Acceptable + /// + public const Int32 NotAcceptable = 134; + /// + /// 4.08 Request Entity Incomplete (draft-ietf-core-block) + /// + public const Int32 RequestEntityIncomplete = 136; + /// + /// + /// + public const Int32 PreconditionFailed = 140; + /// + /// 4.13 Request Entity Too Large + /// + public const Int32 RequestEntityTooLarge = 141; + /// + /// 4.15 Unsupported Media Type + /// + public const Int32 UnsupportedMediaType = 143; + /// + /// 5.00 Internal Server Error + /// + public const Int32 InternalServerError = 160; + /// + /// 5.01 Not Implemented + /// + public const Int32 NotImplemented = 161; + /// + /// 5.02 Bad Gateway + /// + public const Int32 BadGateway = 162; + /// + /// 5.03 Service Unavailable + /// + public const Int32 ServiceUnavailable = 163; + /// + /// 5.04 Gateway Timeout + /// + public const Int32 GatewayTimeout = 164; + /// + /// 5.05 Proxying Not Supported + /// + public const Int32 ProxyingNotSupported = 165; + + #endregion + + public static Int32 GetResponseClass(Int32 code) + { + return (code >> 5) & 0x7; + } + + /// + /// Checks whether a code indicates a request + /// + /// The code to be checked + /// True iff the code indicates a request + public static Boolean IsRequest(Int32 code) + { + return (code >= 1) && (code <= 31); + } + + /// + /// Checks whether a code indicates a response + /// + /// The code to be checked + /// True iff the code indicates a response + public static Boolean IsResponse(Int32 code) + { + return (code >= 64) && (code <= 191); + } + + /// + /// Checks whether a code represents a success code. + /// + public static Boolean IsSuccess(Int32 code) + { + return code >= 64 && code < 96; + } + + /// + /// Checks whether a code is valid + /// + /// The code to be checked + /// True iff the code is valid + public static Boolean IsValid(Int32 code) + { + // allow unknown custom codes + return (code >= 0) && (code <= 255); + } + + /// + /// Returns a string representation of the code + /// + /// The code to be described + /// A string describing the code + public static String ToString(Int32 code) + { + switch (code) + { + case Empty: + return "Empty Message"; + case GET: + return "GET"; + case POST: + return "POST"; + case PUT: + return "PUT"; + case DELETE: + return "DELETE"; + case Created: + return "2.01 Created"; + case Deleted: + return "2.02 Deleted"; + case Valid: + return "2.03 Valid"; + case Changed: + return "2.04 Changed"; + case Content: + return "2.05 Content"; + case BadRequest: + return "4.00 Bad Request"; + case Unauthorized: + return "4.01 Unauthorized"; + case BadOption: + return "4.02 Bad Option"; + case Forbidden: + return "4.03 Forbidden"; + case NotFound: + return "4.04 Not Found"; + case MethodNotAllowed: + return "4.05 Method Not Allowed"; + case NotAcceptable: + return "4.06 Not Acceptable"; + case RequestEntityIncomplete: + return "4.08 Request Entity Incomplete"; + case PreconditionFailed: + return "4.12 Precondition Failed"; + case RequestEntityTooLarge: + return "4.13 Request Entity Too Large"; + case UnsupportedMediaType: + return "4.15 Unsupported Media Type"; + case InternalServerError: + return "5.00 Internal Server Error"; + case NotImplemented: + return "5.01 Not Implemented"; + case BadGateway: + return "5.02 Bad Gateway"; + case ServiceUnavailable: + return "5.03 Service Unavailable"; + case GatewayTimeout: + return "5.04 Gateway Timeout"; + case ProxyingNotSupported: + return "5.05 Proxying Not Supported"; + default: + break; + } + + if (IsValid(code)) + { + if (IsRequest(code)) + { + return String.Format("Unknown Request [code {0}]", code); + } + else if (IsResponse(code)) + { + return String.Format("Unknown Response [code {0}]", code); + } + else + { + return String.Format("Reserved [code {0}]", code); + } + } + else + { + return String.Format("Invalid Message [code {0}]", code); + } + } + } + + /// + /// Methods of request + /// + public enum Method + { + /// + /// GET method + /// + GET = 1, + /// + /// POST method + /// + POST = 2, + /// + /// PUT method + /// + PUT = 3, + /// + /// DELETE method + /// + DELETE = 4 + } + + /// + /// Response status codes. + /// + public enum StatusCode + { + /// + /// 2.01 Created + /// + Created = 65, + /// + /// 2.02 Deleted + /// + Deleted = 66, + /// + /// 2.03 Valid + /// + Valid = 67, + /// + /// 2.04 Changed + /// + Changed = 68, + /// + /// 2.05 Content + /// + Content = 69, + /// + /// 2.?? Continue + /// + Continue = 95, + /// + /// 4.00 Bad Request + /// + BadRequest = 128, + /// + /// 4.01 Unauthorized + /// + Unauthorized = 129, + /// + /// 4.02 Bad Option + /// + BadOption = 130, + /// + /// 4.03 Forbidden + /// + Forbidden = 131, + /// + /// 4.04 Not Found + /// + NotFound = 132, + /// + /// 4.05 Method Not Allowed + /// + MethodNotAllowed = 133, + /// + /// 4.06 Not Acceptable + /// + NotAcceptable = 134, + /// + /// 4.08 Request Entity Incomplete (draft-ietf-core-block) + /// + RequestEntityIncomplete = 136, + /// + /// + /// + PreconditionFailed = 140, + /// + /// 4.13 Request Entity Too Large + /// + RequestEntityTooLarge = 141, + /// + /// 4.15 Unsupported Media Type + /// + UnsupportedMediaType = 143, + /// + /// 5.00 Internal Server Error + /// + InternalServerError = 160, + /// + /// 5.01 Not Implemented + /// + NotImplemented = 161, + /// + /// 5.02 Bad Gateway + /// + BadGateway = 162, + /// + /// 5.03 Service Unavailable + /// + ServiceUnavailable = 163, + /// + /// 5.04 Gateway Timeout + /// + GatewayTimeout = 164, + /// + /// 5.05 Proxying Not Supported + /// + ProxyingNotSupported = 165 + } +} diff --git a/src/Coap/CoAP.NET/Codec/DatagramReader.cs b/src/Coap/CoAP.NET/Codec/DatagramReader.cs new file mode 100644 index 000000000..6b335835a --- /dev/null +++ b/src/Coap/CoAP.NET/Codec/DatagramReader.cs @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; +using System.IO; + +namespace CoAP.Codec +{ + /// + /// This class describes the functionality to read raw network-ordered datagrams on bit-level. + /// + public class DatagramReader + { + private MemoryStream _stream; + private Byte _currentByte; + private Int32 _currentBitIndex; + + /// + /// Initializes a new DatagramReader object + /// + /// The byte array to read from + public DatagramReader(Byte[] buffer) + { + _stream = new MemoryStream(buffer, false); + _currentByte = 0; + _currentBitIndex = -1; + } + + /// + /// Reads a sequence of bits from the stream + /// + /// The number of bits to read + /// An integer containing the bits read + public Int32 Read(Int32 numBits) + { + Int32 bits = 0; // initialize all bits to zero + for (Int32 i = numBits - 1; i >= 0; i--) + { + // check whether new byte needs to be read + if (_currentBitIndex < 0) + { + ReadCurrentByte(); + } + + // test current bit + Boolean bit = (_currentByte >> _currentBitIndex & 1) != 0; + if (bit) + { + // set bit at i-th position + bits |= (1 << i); + } + + // decrease current bit index + --_currentBitIndex; + } + return bits; + } + + /// + /// Reads a sequence of bytes from the stream + /// + /// The number of bytes to read + /// The sequence of bytes read from the stream + public Byte[] ReadBytes(Int32 count) + { + // for negative count values, read all bytes left + if (count < 0) + count = (Int32)(_stream.Length - _stream.Position); + + Byte[] bytes = new Byte[count]; + + // are there bits left to read in buffer? + if (_currentBitIndex >= 0) + { + for (Int32 i = 0; i < count; i++) + { + bytes[i] = (Byte)Read(8); + } + } + else + { + _stream.Read(bytes, 0, bytes.Length); + } + + return bytes; + } + + /// + /// Reads the next byte from the stream. + /// + public Byte ReadNextByte() + { + return ReadBytes(1)[0]; + } + + /// + /// Reads the complete sequence of bytes left in the stream + /// + /// The sequence of bytes left in the stream + public Byte[] ReadBytesLeft() + { + return ReadBytes(-1); + } + + /// + /// Checks if there are remaining bytes to read. + /// + public Boolean BytesAvailable + { + get { return _stream.Length - _stream.Position > 0; } + } + + private void ReadCurrentByte() + { + Int32 val = _stream.ReadByte(); + + if (val >= 0) + _currentByte = (Byte)val; + else + // EOF + _currentByte = 0; + + // reset current bit index + _currentBitIndex = 7; + } + } +} diff --git a/src/Coap/CoAP.NET/Codec/DatagramWriter.cs b/src/Coap/CoAP.NET/Codec/DatagramWriter.cs new file mode 100644 index 000000000..cc6834a17 --- /dev/null +++ b/src/Coap/CoAP.NET/Codec/DatagramWriter.cs @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using Microsoft.Extensions.Logging; +using Surging.Core.CPlatform.Utilities; + +namespace CoAP.Codec +{ + /// + /// This class describes the functionality to write raw network-ordered datagrams on bit-level. + /// + public class DatagramWriter + { + private readonly ILogger log ; + + private MemoryStream _stream; + private Byte _currentByte; + private Int32 _currentBitIndex; + + /// + /// Initializes a new DatagramWriter object + /// + public DatagramWriter() + { + log=ServiceLocator.GetService>(); + _stream = new MemoryStream(); + _currentByte = 0; + _currentBitIndex = 7; + } + + /// + /// Writes a sequence of bits to the stream + /// + /// An integer containing the bits to write + /// The number of bits to write + public void Write(Int32 data, Int32 numBits) + { + if (numBits < 32 && data >= (1 << numBits)) + { + if (log.IsEnabled(LogLevel.Warning)) + log.LogWarning(String.Format("Truncating value {0} to {1}-bit integer", data, numBits)); + } + + for (Int32 i = numBits - 1; i >= 0; i--) + { + // test bit + Boolean bit = (data >> i & 1) != 0; + if (bit) + { + // set bit in current byte + _currentByte |= (Byte)(1 << _currentBitIndex); + } + + // decrease current bit index + --_currentBitIndex; + + // check if current byte can be written + if (_currentBitIndex < 0) + { + WriteCurrentByte(); + } + } + } + + /// + /// Writes a sequence of bytes to the stream + /// + /// The sequence of bytes to write + public void WriteBytes(Byte[] bytes) + { + // check if anything to do at all + if (bytes == null) + return; + + // are there bits left to write in buffer? + if (_currentBitIndex < 7) + { + for (int i = 0; i < bytes.Length; i++) + { + Write(bytes[i], 8); + } + } + else + { + // if bit buffer is empty, call can be delegated + // to byte stream to increase + _stream.Write(bytes, 0, bytes.Length); + } + } + + /// + /// Writes one byte to the stream. + /// + public void WriteByte(Byte b) + { + WriteBytes(new Byte[] { b }); + } + + /// + /// Returns a byte array containing the sequence of bits written + /// + /// The byte array containing the written bits + public Byte[] ToByteArray() + { + WriteCurrentByte(); + Byte[] byteArray = _stream.ToArray(); + _stream.Position = 0; + return byteArray; + } + + private void WriteCurrentByte() + { + if (_currentBitIndex < 7) + { + _stream.WriteByte(_currentByte); + _currentByte = 0; + _currentBitIndex = 7; + } + } + } +} diff --git a/src/Coap/CoAP.NET/Codec/IMessageDecoder.cs b/src/Coap/CoAP.NET/Codec/IMessageDecoder.cs new file mode 100644 index 000000000..7d760cfda --- /dev/null +++ b/src/Coap/CoAP.NET/Codec/IMessageDecoder.cs @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP.Codec +{ + /// + /// Provides methods to parse incoming byte arrays to messages. + /// + public interface IMessageDecoder + { + /// + /// Checks if the decoding message is wellformed. + /// + Boolean IsWellFormed { get; } + /// + /// Checks if the decoding message is a reply. + /// + Boolean IsReply { get; } + /// + /// Checks if the decoding message is a request. + /// + Boolean IsRequest { get; } + /// + /// Checks if the decoding message is a response. + /// + Boolean IsResponse { get; } + /// + /// Checks if the decoding message is an empty message. + /// + Boolean IsEmpty { get; } + /// + /// Gets the version of the decoding message. + /// + Int32 Version { get; } + /// + /// Gets the id of the decoding message. + /// + Int32 ID { get; } + /// + /// Decodes as a . + /// + /// the decoded request + Request DecodeRequest(); + /// + /// Decodes as a . + /// + /// the decoded response + Response DecodeResponse(); + /// + /// Decodes as a . + /// + /// the decoded empty message + EmptyMessage DecodeEmptyMessage(); + /// + /// Decodes as a CoAP message. + /// + /// the decoded message, or null if not be recognized. + Message Decode(); + } +} diff --git a/src/Coap/CoAP.NET/Codec/IMessageEncoder.cs b/src/Coap/CoAP.NET/Codec/IMessageEncoder.cs new file mode 100644 index 000000000..6a3bbdcda --- /dev/null +++ b/src/Coap/CoAP.NET/Codec/IMessageEncoder.cs @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP.Codec +{ + /// + /// Provides methods to serialize outgoing messages to byte arrays. + /// + public interface IMessageEncoder + { + /// + /// Encodes a request into a bytes array. + /// + /// the request to encode + /// the encoded bytes + Byte[] Encode(Request request); + /// + /// Encodes a response into a bytes array. + /// + /// the response to encode + /// the encoded bytes + Byte[] Encode(Response response); + /// + /// Encodes an empty message into a bytes array. + /// + /// the empty message to encode + /// the encoded bytes + Byte[] Encode(EmptyMessage message); + /// + /// Encodes a CoAP message into a bytes array. + /// + /// the message to encode + /// + /// the encoded bytes, or null if the message can not be encoded, + /// i.e. the message is not a , a or an . + /// + Byte[] Encode(Message message); + } +} diff --git a/src/Coap/CoAP.NET/Codec/MessageDecoder.cs b/src/Coap/CoAP.NET/Codec/MessageDecoder.cs new file mode 100644 index 000000000..f86ce2c6d --- /dev/null +++ b/src/Coap/CoAP.NET/Codec/MessageDecoder.cs @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP.Codec +{ + /// + /// Base class for message decoders. + /// + public abstract class MessageDecoder : IMessageDecoder + { + /// + /// the bytes reader + /// + protected DatagramReader m_reader; + /// + /// the version of the decoding message + /// + protected Int32 m_version; + /// + /// the type of the decoding message + /// + protected MessageType m_type; + /// + /// the length of token + /// + protected Int32 m_tokenLength; + /// + /// the code of the decoding message + /// + protected Int32 m_code; + /// + /// the id of the decoding message + /// + protected Int32 m_id; + + /// + /// Instantiates. + /// + /// the bytes array to decode + public MessageDecoder(Byte[] data) + { + m_reader = new DatagramReader(data); + } + + /// + /// Reads protocol headers. + /// + protected abstract void ReadProtocol(); + + /// + public abstract Boolean IsWellFormed { get; } + + /// + public Boolean IsReply + { + get { return m_type == MessageType.ACK || m_type == MessageType.RST; } + } + + /// + public virtual Boolean IsRequest + { + get + { + return m_code >= CoapConstants.RequestCodeLowerBound && + m_code <= CoapConstants.RequestCodeUpperBound; + } + } + + /// + public virtual Boolean IsResponse + { + get + { + return m_code >= CoapConstants.ResponseCodeLowerBound && + m_code <= CoapConstants.ResponseCodeUpperBound; + } + } + + /// + public Boolean IsEmpty + { + get { return m_code == Code.Empty; } + } + + /// + public Int32 Version + { + get { return m_version; } + } + + /// + public Int32 ID + { + get { return m_id; } + } + + /// + public Request DecodeRequest() + { + System.Diagnostics.Debug.Assert(IsRequest); + Request request = new Request((Method)m_code); + request.Type = m_type; + request.ID = m_id; + ParseMessage(request); + return request; + } + + /// + public Response DecodeResponse() + { + System.Diagnostics.Debug.Assert(IsResponse); + Response response = new Response((StatusCode)m_code); + response.Type = m_type; + response.ID = m_id; + ParseMessage(response); + return response; + } + + /// + public EmptyMessage DecodeEmptyMessage() + { + System.Diagnostics.Debug.Assert(!IsRequest && !IsResponse); + EmptyMessage message = new EmptyMessage(m_type); + message.Type = m_type; + message.ID = m_id; + ParseMessage(message); + return message; + } + + /// + public Message Decode() + { + if (IsRequest) + return DecodeRequest(); + else if (IsResponse) + return DecodeResponse(); + else if (IsEmpty) + return DecodeEmptyMessage(); + else + return null; + } + + /// + /// Parses the rest data other than protocol headers into the given message. + /// + /// + protected abstract void ParseMessage(Message message); + } +} diff --git a/src/Coap/CoAP.NET/Codec/MessageEncoder.cs b/src/Coap/CoAP.NET/Codec/MessageEncoder.cs new file mode 100644 index 000000000..539a1e25a --- /dev/null +++ b/src/Coap/CoAP.NET/Codec/MessageEncoder.cs @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP.Codec +{ + /// + /// Base class for message encoders. + /// + public abstract class MessageEncoder : IMessageEncoder + { + /// + public Byte[] Encode(Request request) + { + DatagramWriter writer = new DatagramWriter(); + Serialize(writer, request, request.Code); + return writer.ToByteArray(); + } + + /// + public Byte[] Encode(Response response) + { + DatagramWriter writer = new DatagramWriter(); + Serialize(writer, response, response.Code); + return writer.ToByteArray(); + } + + /// + public Byte[] Encode(EmptyMessage message) + { + DatagramWriter writer = new DatagramWriter(); + Serialize(writer, message, Code.Empty); + return writer.ToByteArray(); + } + + /// + public Byte[] Encode(Message message) + { + if (message.IsRequest) + return Encode((Request)message); + else if (message.IsResponse) + return Encode((Response)message); + else if (message is EmptyMessage) + return Encode((EmptyMessage)message); + else + return null; + } + + /// + /// Serializes a message. + /// + /// the writer + /// the message to write + /// the code + protected abstract void Serialize(DatagramWriter writer, Message message, Int32 code); + } +} diff --git a/src/Coap/CoAP.NET/Deduplication/CropRotation.cs b/src/Coap/CoAP.NET/Deduplication/CropRotation.cs new file mode 100644 index 000000000..e404a2b4f --- /dev/null +++ b/src/Coap/CoAP.NET/Deduplication/CropRotation.cs @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; +using System.Collections.Concurrent; +using System.Timers; +using CoAP.Net; + +namespace CoAP.Deduplication +{ + class CropRotation : IDeduplicator, IDisposable + { + private ConcurrentDictionary[] _maps; + private Int32 _first; + private Int32 _second; + private System.Timers.Timer _timer; + + public CropRotation(ICoapConfig config) + { + _maps = new ConcurrentDictionary[3]; + _maps[0] = new ConcurrentDictionary(); + _maps[1] = new ConcurrentDictionary(); + _maps[2] = new ConcurrentDictionary(); + _first = 0; + _second = 1; + _timer = new System.Timers.Timer(config.CropRotationPeriod); + _timer.Elapsed += Rotation; + } + + private void Rotation(Object sender, ElapsedEventArgs e) + { + Int32 third = _first; + _first = _second; + _second = (_second + 1) % 3; + _maps[third].Clear(); + } + + /// + public void Start() + { + _timer.Start(); + } + + /// + public void Stop() + { + _timer.Stop(); + Clear(); + } + + /// + public void Clear() + { + _maps[0].Clear(); + _maps[1].Clear(); + _maps[2].Clear(); + } + + /// + public Exchange FindPrevious(Exchange.KeyID key, Exchange exchange) + { + Int32 f = _first, s = _second; + Exchange prev = null; + + _maps[f].AddOrUpdate(key, exchange, (k, v) => + { + prev = v; + return exchange; + }); + if (prev != null || f == s) + return prev; + + prev = _maps[s].AddOrUpdate(key, exchange, (k, v) => + { + prev = v; + return exchange; + }); + return prev; + } + + /// + public Exchange Find(Exchange.KeyID key) + { + Int32 f = _first, s = _second; + Exchange prev; + if (_maps[f].TryGetValue(key, out prev) || f == s) + return prev; + _maps[s].TryGetValue(key, out prev); + return prev; + } + + /// + public void Dispose() + { + _timer.Dispose(); + } + } +} diff --git a/src/Coap/CoAP.NET/Deduplication/DeduplicatorFactory.cs b/src/Coap/CoAP.NET/Deduplication/DeduplicatorFactory.cs new file mode 100644 index 000000000..a4cc43421 --- /dev/null +++ b/src/Coap/CoAP.NET/Deduplication/DeduplicatorFactory.cs @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using Microsoft.Extensions.Logging; +using Surging.Core.CPlatform.Utilities; + +namespace CoAP.Deduplication +{ + static class DeduplicatorFactory + { + public const String MarkAndSweepDeduplicator = "MarkAndSweep"; + public const String CropRotationDeduplicator = "CropRotation"; + public const String NoopDeduplicator = "Noop"; + + public static IDeduplicator CreateDeduplicator(ICoapConfig config) + { + String type = config.Deduplicator; + if (String.Equals(MarkAndSweepDeduplicator, type, StringComparison.OrdinalIgnoreCase) + || String.Equals("DEDUPLICATOR_MARK_AND_SWEEP", type, StringComparison.OrdinalIgnoreCase)) + return new SweepDeduplicator(config); + else if (String.Equals(CropRotationDeduplicator, type, StringComparison.OrdinalIgnoreCase) + || String.Equals("DEDUPLICATOR_CROP_ROTATIO", type, StringComparison.OrdinalIgnoreCase)) + return new CropRotation(config); + else if (!String.Equals(NoopDeduplicator, type, StringComparison.OrdinalIgnoreCase) + && !String.Equals("NO_DEDUPLICATOR", type, StringComparison.OrdinalIgnoreCase)) + { + } + return new NoopDeduplicator(); + } + } +} diff --git a/src/Coap/CoAP.NET/Deduplication/IDeduplicator.cs b/src/Coap/CoAP.NET/Deduplication/IDeduplicator.cs new file mode 100644 index 000000000..c016988d9 --- /dev/null +++ b/src/Coap/CoAP.NET/Deduplication/IDeduplicator.cs @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using CoAP.Net; + +namespace CoAP.Deduplication +{ + /// + /// Provides methods to detect duplicates. + /// Notice that CONs and NONs can be duplicates. + /// + public interface IDeduplicator + { + /// + /// Starts. + /// + void Start(); + /// + /// Stops. + /// + void Stop(); + /// + /// Clears the state of this deduplicator. + /// + void Clear(); + /// + /// Checks if the specified key is already associated with a previous + /// exchange and otherwise associates the key with the exchange specified. + /// + /// + /// + /// the previous exchange associated with the specified key, + /// or null if there was no mapping for the key + Exchange FindPrevious(Exchange.KeyID key, Exchange exchange); + Exchange Find(Exchange.KeyID key); + } +} diff --git a/src/Coap/CoAP.NET/Deduplication/NoopDeduplicator.cs b/src/Coap/CoAP.NET/Deduplication/NoopDeduplicator.cs new file mode 100644 index 000000000..6bb697a04 --- /dev/null +++ b/src/Coap/CoAP.NET/Deduplication/NoopDeduplicator.cs @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using CoAP.Net; + +namespace CoAP.Deduplication +{ + /// + /// A dummy implementation that does no deduplication. + /// + class NoopDeduplicator : IDeduplicator + { + /// + public void Start() + { + // do nothing + } + + /// + public void Stop() + { + // do nothing + } + + /// + public void Clear() + { + // do nothing + } + + /// + public Exchange FindPrevious(Exchange.KeyID key, Exchange exchange) + { + return null; + } + + /// + public Exchange Find(Exchange.KeyID key) + { + return null; + } + } +} diff --git a/src/Coap/CoAP.NET/Deduplication/SweepDeduplicator.cs b/src/Coap/CoAP.NET/Deduplication/SweepDeduplicator.cs new file mode 100644 index 000000000..903a3e6a7 --- /dev/null +++ b/src/Coap/CoAP.NET/Deduplication/SweepDeduplicator.cs @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; +using System.Collections.Concurrent; +using System.Timers; +using CoAP.Net; +using Microsoft.Extensions.Logging; +using Surging.Core.CPlatform.Utilities; + +namespace CoAP.Deduplication +{ + class SweepDeduplicator : IDeduplicator + { + private readonly ILogger log; + + private ConcurrentDictionary _incommingMessages + = new ConcurrentDictionary(); + private System.Timers.Timer _timer; + private ICoapConfig _config; + + public SweepDeduplicator(ICoapConfig config) + { + log=ServiceLocator.GetService>(); + _config = config; + _timer = new System.Timers.Timer(config.MarkAndSweepInterval); + _timer.Elapsed += Sweep; + } + + private void Sweep(Object sender, ElapsedEventArgs e) + { + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("Start Mark-And-Sweep with " + _incommingMessages.Count + " entries"); + + DateTime oldestAllowed = DateTime.Now.AddMilliseconds(-_config.ExchangeLifetime); + List keysToRemove = new List(); + foreach (KeyValuePair pair in _incommingMessages) + { + if (pair.Value.Timestamp < oldestAllowed) + { + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("Mark-And-Sweep removes " + pair.Key); + keysToRemove.Add(pair.Key); + } + } + if (keysToRemove.Count > 0) + { + Exchange ex; + foreach (Exchange.KeyID key in keysToRemove) + { + _incommingMessages.TryRemove(key, out ex); + } + } + } + + /// + public void Start() + { + _timer.Start(); + } + + /// + public void Stop() + { + _timer.Stop(); + Clear(); + } + + /// + public void Clear() + { + _incommingMessages.Clear(); + } + + /// + public Exchange FindPrevious(Exchange.KeyID key, Exchange exchange) + { + Exchange prev = null; + _incommingMessages.AddOrUpdate(key, exchange, (k, v) => + { + prev = v; + return exchange; + }); + return prev; + } + + /// + public Exchange Find(Exchange.KeyID key) + { + Exchange prev; + _incommingMessages.TryGetValue(key, out prev); + return prev; + } + + /// + public void Dispose() + { + _timer.Dispose(); + } + } +} diff --git a/src/Coap/CoAP.NET/EmptyMessage.cs b/src/Coap/CoAP.NET/EmptyMessage.cs new file mode 100644 index 000000000..83966f329 --- /dev/null +++ b/src/Coap/CoAP.NET/EmptyMessage.cs @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP +{ + /// + /// Represents an empty CoAP message. An empty message has either + /// the ACK or RST. + /// + public class EmptyMessage : Message + { + /// + /// Instantiates a new empty message. + /// + public EmptyMessage(MessageType type) + : base(type, CoAP.Code.Empty) + { } + + /// + /// Create a new acknowledgment for the specified message. + /// + /// the message to acknowledge + /// the acknowledgment + public static EmptyMessage NewACK(Message message) + { + EmptyMessage ack = new EmptyMessage(MessageType.ACK); + ack.ID = message.ID; + ack.Token = CoapConstants.EmptyToken; + ack.Destination = message.Source; + return ack; + } + + /// + /// Create a new reset message for the specified message. + /// + /// the message to reject + /// the reset + public static EmptyMessage NewRST(Message message) + { + EmptyMessage rst = new EmptyMessage(MessageType.RST); + rst.ID = message.ID; + rst.Token = CoapConstants.EmptyToken; + rst.Destination = message.Source; + return rst; + } + } +} diff --git a/src/Coap/CoAP.NET/EndPoint/Resources/RemoteResource.cs b/src/Coap/CoAP.NET/EndPoint/Resources/RemoteResource.cs new file mode 100644 index 000000000..28aecb887 --- /dev/null +++ b/src/Coap/CoAP.NET/EndPoint/Resources/RemoteResource.cs @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011-2012, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP.EndPoint.Resources +{ + public class RemoteResource : Resource + { + public RemoteResource(String resourceIdentifier) + : base(resourceIdentifier) + { } + + public static RemoteResource NewRoot(String linkFormat) + { + return LinkFormat.Deserialize(linkFormat); + } + + /// + /// Creates a resouce instance with proper subtype. + /// + /// + protected override Resource CreateInstance(String name) + { + return new RemoteResource(name); + } + + protected override void DoCreateSubResource(Request request, String newIdentifier) + { + } + } +} diff --git a/src/Coap/CoAP.NET/EndPoint/Resources/Resource.cs b/src/Coap/CoAP.NET/EndPoint/Resources/Resource.cs new file mode 100644 index 000000000..40cd40121 --- /dev/null +++ b/src/Coap/CoAP.NET/EndPoint/Resources/Resource.cs @@ -0,0 +1,526 @@ +/* + * Copyright (c) 2011-2012, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using CoAP.Util; +using Microsoft.Extensions.Logging; +using Surging.Core.CPlatform.Utilities; + +namespace CoAP.EndPoint.Resources +{ + /// + /// This class describes the functionality of a CoAP resource. + /// + public abstract class Resource : IComparable + { + private readonly ILogger log; + + private Int32 _totalSubResourceCount; + private String _resourceIdentifier; + private HashSet _attributes; + private Resource _parent; + private SortedDictionary _subResources; + private Boolean _hidden; + + /// + /// Initialize a resource. + /// + /// The identifier of this resource + public Resource(String resourceIdentifier) : this(resourceIdentifier, false) { } + + /// + /// Initialize a resource. + /// + /// The identifier of this resource + /// True if this resource is hidden + public Resource(String resourceIdentifier, Boolean hidden) + { + log=ServiceLocator.GetService>(); + this._resourceIdentifier = resourceIdentifier; + this._hidden = hidden; + this._attributes = new HashSet(); + } + + /// + /// Gets the URI of this resource. + /// + public String Path + { + get + { + StringBuilder sb = new StringBuilder(); + sb.Append(Name); + if (_parent == null) + sb.Append("/"); + else + { + Resource res = _parent; + while (res != null) + { + sb.Insert(0, "/"); + sb.Insert(0, res.Name); + res = res._parent; + } + } + return sb.ToString(); + } + } + + public String Name + { + get { return _resourceIdentifier; } + set { _resourceIdentifier = value; } + } + + public ICollection Attributes + { + get { return _attributes; } + } + + public IList GetAttributes(String name) + { + List list = new List(); + foreach (LinkAttribute attr in Attributes) + { + if (attr.Name.Equals(name)) + list.Add(attr); + } + return list.AsReadOnly(); + } + + public Boolean SetAttribute(LinkAttribute attr) + { + // Adds depending on the Link Format rules + return LinkFormat.AddAttribute(Attributes, attr); + } + + public Boolean ClearAttribute(String name) + { + Boolean cleared = false; + foreach (LinkAttribute attr in GetAttributes(name)) + { + cleared |= _attributes.Remove(attr); + } + return cleared; + } + + public Boolean Hidden + { + get { return _hidden; } + set { _hidden = value; } + } + + public IList ResourceTypes + { + get + { + return GetStringValues(GetAttributes(LinkFormat.ResourceType)); + } + } + + /// + /// Gets or sets the type attribute of this resource. + /// + public String ResourceType + { + get + { + IList attrs = GetAttributes(LinkFormat.ResourceType); + return attrs.Count == 0 ? null : attrs[0].StringValue; + } + set + { + SetAttribute(new LinkAttribute(LinkFormat.ResourceType, value)); + } + } + + /// + /// Gets or sets the title attribute of this resource. + /// + public String Title + { + get + { + IList attrs = GetAttributes(LinkFormat.Title); + return attrs.Count == 0 ? null : attrs[0].StringValue; + } + set + { + ClearAttribute(LinkFormat.Title); + SetAttribute(new LinkAttribute(LinkFormat.Title, value)); + } + } + + public IList InterfaceDescriptions + { + get + { + return GetStringValues(GetAttributes(LinkFormat.InterfaceDescription)); + } + } + + /// + /// Gets or sets the interface description attribute of this resource. + /// + public String InterfaceDescription + { + get + { + IList attrs = GetAttributes(LinkFormat.InterfaceDescription); + return attrs.Count == 0 ? null : attrs[0].StringValue; + } + set + { + SetAttribute(new LinkAttribute(LinkFormat.InterfaceDescription, value)); + } + } + + public IList GetContentTypeCodes + { + get + { + return GetIntValues(GetAttributes(LinkFormat.ContentType)); + } + } + + /// + /// Gets or sets the content type code attribute of this resource. + /// + public Int32 ContentTypeCode + { + get + { + IList attrs = GetAttributes(LinkFormat.ContentType); + return attrs.Count == 0 ? 0 : attrs[0].IntValue; + } + set + { + SetAttribute(new LinkAttribute(LinkFormat.ContentType, value)); + } + } + + /// + /// Gets or sets the maximum size estimate attribute of this resource. + /// + public Int32 MaximumSizeEstimate + { + get + { + IList attrs = GetAttributes(LinkFormat.MaxSizeEstimate); + return attrs.Count == 0 ? -1 : attrs[0].IntValue; + } + set + { + SetAttribute(new LinkAttribute(LinkFormat.MaxSizeEstimate, value)); + } + } + + /// + /// Gets or sets the observable attribute of this resource. + /// + public Boolean Observable + { + get + { + return GetAttributes(LinkFormat.Observable).Count > 0; + } + set + { + if (value) + SetAttribute(new LinkAttribute(LinkFormat.Observable, value)); + else + ClearAttribute(LinkFormat.Observable); + } + } + + /// + /// Gets the total count of sub-resources, including children and children's children... + /// + public Int32 TotalSubResourceCount + { + get { return _totalSubResourceCount; } + } + + /// + /// Gets the count of sub-resources of this resource. + /// + public Int32 SubResourceCount + { + get { return null == _subResources ? 0 : _subResources.Count; } + } + + /// + /// Removes this resource from its parent. + /// + public void Remove() + { + if (_parent != null) + _parent.RemoveSubResource(this); + } + + /// + /// Gets sub-resources of this resource. + /// + /// + public Resource[] GetSubResources() + { + if (null == _subResources) + return new Resource[0]; + + Resource[] resources = new Resource[_subResources.Count]; + this._subResources.Values.CopyTo(resources, 0); + return resources; + } + + public Resource GetResource(String path) + { + return GetResource(path, false); + } + + public Resource GetResource(String path, Boolean last) + { + if (String.IsNullOrEmpty(path)) + return this; + + // find root for absolute path + if (path.StartsWith("/")) + { + Resource root = this; + while (root._parent != null) + root = root._parent; + path = path.Equals("/") ? null : path.Substring(1); + return root.GetResource(path); + } + + Int32 pos = path.IndexOf('/'); + String head = null, tail = null; + + // note: "some/resource/" addresses a resource "" under "resource" + if (pos == -1) + { + head = path; + } + else + { + head = path.Substring(0, pos); + tail = path.Substring(pos + 1); + } + + if (SubResources.ContainsKey(head)) + return SubResources[head].GetResource(tail, last); + else if (last) + return this; + else + return null; + } + + private SortedDictionary SubResources + { + get + { + if (_subResources == null) + _subResources = new SortedDictionary(); + return _subResources; + } + } + + /// + /// Adds a resource as a sub-resource of this resource. + /// + /// The sub-resource to be added + public void AddSubResource(Resource resource) + { + if (null == resource) + throw new ArgumentNullException("resource"); + + // no absolute paths allowed, use root directly + while (resource.Name.StartsWith("/")) + { + if (_parent != null) + { + if (log.IsEnabled(LogLevel.Warning)) + log.LogWarning("Adding absolute path only allowed for root: made relative " + resource.Name); + } + resource.Name = resource.Name.Substring(1); + } + + // get last existing resource along path + Resource baseRes = GetResource(resource.Name, true); + + String path = this.Path; + if (!path.EndsWith("/")) + path += "/"; + path += resource.Name; + + path = path.Substring(baseRes.Path.Length); + if (path.StartsWith("/")) + path = path.Substring(1); + + if (path.Length == 0) + { + // resource replaces base + if (log.IsEnabled(LogLevel.Information)) + log.LogInformation("Replacing resource " + baseRes.Path); + foreach (Resource sub in baseRes.GetSubResources()) + { + sub._parent = resource; + resource.SubResources[sub.Name] = sub; + } + resource._parent = baseRes._parent; + baseRes._parent.SubResources[baseRes.Name] = resource; + } + else + { + // resource is added to base + + String[] segments = path.Split('/'); + if (segments.Length > 1) + { + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("Splitting up compound resource " + resource.Name); + resource.Name = segments[segments.Length - 1]; + + // insert middle segments + Resource sub = null; + for (Int32 i = 0; i < segments.Length - 1; i++) + { + sub = baseRes.CreateInstance(segments[i]); + sub.Hidden = true; + baseRes.AddSubResource(sub); + baseRes = sub; + } + } + else + resource.Name = path; + + resource._parent = baseRes; + baseRes.SubResources[resource.Name] = resource; + + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("Add resource " + resource.Name); + } + + // update number of sub-resources in the tree + Resource p = resource._parent; + while (p != null) + { + p._totalSubResourceCount++; + p = p._parent; + } + } + + /// + /// Removes a sub-resource from this resource by its identifier. + /// + /// the path of the sub-resource to remove + public void RemoveSubResource(String resourcePath) + { + RemoveSubResource(GetResource(resourcePath)); + } + + /// + /// Removes a sub-resource from this resource. + /// + /// the sub-resource to remove + public void RemoveSubResource(Resource resource) + { + if (null == resource) + return; + + if (SubResources.Remove(resource._resourceIdentifier)) + { + Resource p = resource._parent; + while (p != null) + { + p._totalSubResourceCount--; + p = p._parent; + } + + resource._parent = null; + } + } + + public void CreateSubResource(Request request, String newIdentifier) + { + DoCreateSubResource(request, newIdentifier); + } + + public Int32 CompareTo(Resource other) + { + return Path.CompareTo(other.Path); + } + + public override String ToString() + { + StringBuilder sb = new StringBuilder(); + Print(sb, 0); + return sb.ToString(); + } + + private void Print(StringBuilder sb, Int32 indent) + { + for (Int32 i = 0; i < indent; i++) + sb.Append(" "); + sb.AppendFormat("+[{0}]",_resourceIdentifier); + + String title = Title; + if (title != null) + sb.AppendFormat(" {0}", title); + sb.AppendLine(); + + foreach (LinkAttribute attr in Attributes) + { + if (attr.Name.Equals(LinkFormat.Title)) + continue; + for (Int32 i = 0; i < indent + 3; i++) + sb.Append(" "); + sb.AppendFormat("- "); + attr.Serialize(sb); + sb.AppendLine(); + } + + if (_subResources != null) + foreach (Resource sub in _subResources.Values) + { + sub.Print(sb, indent + 2); + } + } + + /// + /// Creates a resouce instance with proper subtype. + /// + /// + protected abstract Resource CreateInstance(String name); + protected abstract void DoCreateSubResource(Request request, String newIdentifier); + + private static IList GetStringValues(IEnumerable attributes) + { + List list = new List(); + foreach (LinkAttribute attr in attributes) + { + list.Add(attr.StringValue); + } + return list; + } + + private static IList GetIntValues(IEnumerable attributes) + { + List list = new List(); + foreach (LinkAttribute attr in attributes) + { + list.Add(attr.IntValue); + } + return list; + } + } +} diff --git a/src/Coap/CoAP.NET/ICoapConfig.cs b/src/Coap/CoAP.NET/ICoapConfig.cs new file mode 100644 index 000000000..35efc9a5b --- /dev/null +++ b/src/Coap/CoAP.NET/ICoapConfig.cs @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2011-2015, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; + +namespace CoAP +{ + /// + /// Provides configuration for CoAP communication. + /// + public partial interface ICoapConfig : System.ComponentModel.INotifyPropertyChanged + { + /// + /// Gets the version of CoAP protocol. + /// + String Version { get; } + /// + /// Gets the default CoAP port for normal CoAP communication (not secure). + /// + Int32 DefaultPort { get; } + /// + /// Gets the default CoAP port for secure CoAP communication (coaps). + /// + Int32 DefaultSecurePort { get; } + /// + /// Gets the port which HTTP proxy is on. + /// + Int32 HttpPort { get; } + + Int32 AckTimeout { get; } + Double AckRandomFactor { get; } + Double AckTimeoutScale { get; } + Int32 MaxRetransmit { get; } + + Int32 MaxMessageSize { get; } + /// + /// Gets the default preferred size of block in blockwise transfer. + /// + Int32 DefaultBlockSize { get; } + Int32 BlockwiseStatusLifetime { get; } + Boolean UseRandomIDStart { get; } + Boolean UseRandomTokenStart { get; } + + Int64 NotificationMaxAge { get; } + Int64 NotificationCheckIntervalTime { get; } + Int32 NotificationCheckIntervalCount { get; } + Int32 NotificationReregistrationBackoff { get; } + + String Deduplicator { get; } + Int32 CropRotationPeriod { get; } + Int32 ExchangeLifetime { get; } + Int64 MarkAndSweepInterval { get; } + + Int32 ChannelReceiveBufferSize { get; } + Int32 ChannelSendBufferSize { get; } + Int32 ChannelReceivePacketSize { get; } + + /// + /// Loads configuration from a config properties file. + /// + void Load(String configFile); + + /// + /// Stores the configuration in a config properties file. + /// + void Store(String configFile); + } +} diff --git a/src/Coap/CoAP.NET/LinkAttribute.cs b/src/Coap/CoAP.NET/LinkAttribute.cs new file mode 100644 index 000000000..07c887008 --- /dev/null +++ b/src/Coap/CoAP.NET/LinkAttribute.cs @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2011-2013, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; +using System.Text; +using Microsoft.Extensions.Logging; +using Surging.Core.CPlatform.Utilities; + +namespace CoAP +{ + /// + /// Class for linkformat attributes. + /// + public class LinkAttribute : IComparable + { + private readonly ILogger log ; + + private String _name; + private Object _value; + + /// + /// Initializes an attribute. + /// + public LinkAttribute(String name, Object value) + { + log = ServiceLocator.GetService>(); + _name = name; + _value = value; + } + + /// + /// Gets the name of this attribute. + /// + public String Name + { + get { return _name; } + } + + /// + /// Gets the value of this attribute. + /// + public Object Value + { + get { return _value; } + } + + /// + /// Gets the int value of this attribute. + /// + public Int32 IntValue + { + get { return (_value is Int32) ? (Int32)_value : -1; } + } + + /// + /// Gets the string value of this attribute. + /// + public String StringValue + { + get { return (_value is String) ? (String)_value : null; } + } + + /// + /// Serializes this attribute into its string representation. + /// + /// + public void Serialize(StringBuilder builder) + { + // check if there's something to write + if (_name != null && _value != null) + { + if (_value is Boolean) + { + // flag attribute + if ((Boolean)_value) + builder.Append(_name); + } + else + { + // name-value-pair + builder.Append(_name); + builder.Append('='); + if (_value is String) + { + builder.Append('"'); + builder.Append((String)_value); + builder.Append('"'); + } + else if (_value is Int32) + { + builder.Append(((Int32)_value)); + } + else + { + if (log.IsEnabled(LogLevel.Error)) + log.LogError(String.Format("Serializing attribute of unexpected type: {0} ({1})", _name, _value.GetType().Name)); + } + } + } + } + + /// + public override String ToString() + { + return String.Format("name: {0} value: {1}", _name, _value); + } + + /// + public Int32 CompareTo(LinkAttribute other) + { + Int32 ret = _name.CompareTo(other.Name); + if (ret == 0) + { + if (_value is String) + return StringValue.CompareTo(other.StringValue); + else if (_value is Int32) + return IntValue.CompareTo(other.IntValue); + } + return ret; + } + } +} diff --git a/src/Coap/CoAP.NET/LinkFormat.cs b/src/Coap/CoAP.NET/LinkFormat.cs new file mode 100644 index 000000000..bccef4a0a --- /dev/null +++ b/src/Coap/CoAP.NET/LinkFormat.cs @@ -0,0 +1,490 @@ +/* + * Copyright (c) 2011-2014, Longxiang He , + * SmeshLink Technology Co. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * This file is part of the CoAP.NET, a CoAP framework in C#. + * Please see README for more information. + */ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; +using CoAP.EndPoint.Resources; +using CoAP.Server.Resources; +using CoAP.Util; +using Microsoft.Extensions.Logging; +using Resource = CoAP.EndPoint.Resources.Resource; + +namespace CoAP +{ + /// + /// This class provides link format definitions as specified in + /// draft-ietf-core-link-format-06 + /// + public static class LinkFormat + { + /// + /// Name of the attribute Resource Type + /// + public static readonly String ResourceType = "rt"; + /// + /// Name of the attribute Interface Description + /// + public static readonly String InterfaceDescription = "if"; + /// + /// Name of the attribute Content Type + /// + public static readonly String ContentType = "ct"; + /// + /// Name of the attribute Max Size Estimate + /// + public static readonly String MaxSizeEstimate = "sz"; + /// + /// Name of the attribute Title + /// + public static readonly String Title = "title"; + /// + /// Name of the attribute Observable + /// + public static readonly String Observable = "obs"; + /// + /// Name of the attribute link + /// + public static readonly String Link = "href"; + + /// + /// The string as the delimiter between resources + /// + public static readonly String Delimiter = ","; + /// + /// The string to separate attributes + /// + public static readonly String Separator = ";"; + + public static readonly Regex DelimiterRegex = new Regex("\\s*" + Delimiter + "+\\s*"); + public static readonly Regex SeparatorRegex = new Regex("\\s*" + Separator + "+\\s*"); + + public static readonly Regex ResourceNameRegex = new Regex("<[^>]*>"); + public static readonly Regex WordRegex = new Regex("\\w+"); + public static readonly Regex QuotedString = new Regex("\\G\".*?\""); + public static readonly Regex Cardinal = new Regex("\\G\\d+"); + static readonly Regex EqualRegex = new Regex("="); + static readonly Regex BlankRegex = new Regex("\\s"); + + public static String Serialize(IResource root) + { + return Serialize(root, null); + } + + public static String Serialize(IResource root, IEnumerable queries) + { + StringBuilder linkFormat = new StringBuilder(); + + foreach (IResource child in root.Children) + { + SerializeTree(child, queries, linkFormat); + } + + if (linkFormat.Length > 1) + linkFormat.Remove(linkFormat.Length - 1, 1); + + return linkFormat.ToString(); + } + + public static IEnumerable Parse(String linkFormat) + { + if (!String.IsNullOrEmpty(linkFormat)) + { + Scanner scanner = new Scanner(linkFormat); + String path = null; + while ((path = scanner.Find(ResourceNameRegex)) != null) + { + path = path.Substring(1, path.Length - 2); + WebLink link = new WebLink(path); + + String attr = null; + while (scanner.Find(DelimiterRegex, 1) == null && + (attr = scanner.Find(WordRegex)) != null) + { + if (scanner.Find(EqualRegex, 1) == null) + { + // flag attribute without value + link.Attributes.Add(attr); + } + else + { + String value = null; + if ((value = scanner.Find(QuotedString)) != null) + { + // trim " " + value = value.Substring(1, value.Length - 2); + if (Title.Equals(attr)) + link.Attributes.Add(attr, value); + else + foreach (String part in BlankRegex.Split(value)) + link.Attributes.Add(attr, part); + } + else if ((value = scanner.Find(WordRegex)) != null) + { + link.Attributes.Set(attr, value); + } + else if ((value = scanner.Find(Cardinal)) != null) + { + link.Attributes.Set(attr, value); + } + } + } + + yield return link; + } + } + + yield break; + } + + private static void SerializeTree(IResource resource, IEnumerable queries, StringBuilder sb) + { + if (resource.Visible && Matches(resource, queries)) + { + SerializeResource(resource, sb); + sb.Append(","); + } + + // sort by resource name + List childrens = new List(resource.Children); + childrens.Sort(delegate(IResource r1, IResource r2) { return String.Compare(r1.Name, r2.Name); }); + + foreach (IResource child in childrens) + { + SerializeTree(child, queries, sb); + } + } + + private static void SerializeResource(IResource resource, StringBuilder sb) + { + sb.Append("<") + .Append(resource.Path) + .Append(resource.Name) + .Append(">"); + SerializeAttributes(resource.Attributes, sb); + } + + private static void SerializeAttributes(ResourceAttributes attributes, StringBuilder sb) + { + List keys = new List(attributes.Keys); + keys.Sort(); + foreach (String name in keys) + { + List values = new List(attributes.GetValues(name)); + if (values.Count == 0) + continue; + sb.Append(Separator); + SerializeAttribute(name, values, sb); + } + } + + private static void SerializeAttribute(String name, IEnumerable values, StringBuilder sb) + { + String delimiter = "="; + Boolean quotes = false; + + sb.Append(name); + + using (IEnumerator it = values.GetEnumerator()) + { + if (!it.MoveNext() || String.IsNullOrEmpty(it.Current)) + return; + + sb.Append(delimiter); + + String first = it.Current; + Boolean more = it.MoveNext(); + if (more || !IsNumber(first)) + { + sb.Append('"'); + quotes = true; + } + + sb.Append(first); + while (more) + { + sb.Append(' '); + sb.Append(it.Current); + more = it.MoveNext(); + } + + if (quotes) + sb.Append('"'); + } + } + + private static Boolean IsNumber(String value) + { + if (String.IsNullOrEmpty(value)) + return false; + foreach (Char c in value) + { + if (!Char.IsNumber(c)) + return false; + } + return true; + } + + public static String Serialize(Resource resource, IEnumerable