初始化CRICS

This commit is contained in:
2025-12-11 09:17:16 +08:00
commit 83247ec0a2
2735 changed files with 787765 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
/WebSite/obj
/WebSite/Bin
/Service/bin
/Service/obj
/RenWu/obj
/RenWu/bin
/CommonEntity/bin
/Common/bin
/WebSite/obj/Release/Package/PackageTmp/bin
/RCUHost/bin
/MissionSystem/obj/Debug/Package/PackageTmp/bin
/MissionSystem/bin
/Domain/bin
/Dao/bin
/Domain/obj
/Dao/obj
/CommonEntity/obj
/Common/obj
/RCUHost/obj
/MissionSystem/obj
.fake
/WebSite/WebSite.Publish.xml
/WebSite/WebSite.csproj.user

0
.tgitconfig Normal file
View File

View File

@@ -0,0 +1,12 @@
{
"Version": 1,
"WorkspaceRootPath": "E:\\tian\\chongxin\\CRICS_V3_1124\\",
"Documents": [],
"DocumentGroupContainers": [
{
"Orientation": 0,
"VerticalTabListWidth": 256,
"DocumentGroups": []
}
]
}

View File

@@ -0,0 +1,23 @@
{
"Version": 1,
"WorkspaceRootPath": "E:\\tian\\chongxin\\CRICS_V3_1124\\",
"Documents": [],
"DocumentGroupContainers": [
{
"Orientation": 0,
"VerticalTabListWidth": 256,
"DocumentGroups": [
{
"DockedWidth": 200,
"SelectedChildIndex": -1,
"Children": [
{
"$type": "Bookmark",
"Name": "ST:0:0:{aa2115a1-9712-457b-9047-dbb71ca2cdd2}"
}
]
}
]
}
]
}

Binary file not shown.

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"dotnet.preferCSharpExtension": true
}

View File

@@ -0,0 +1 @@
HP6vcqAL58UjczRRQ7SpqppM9wczrgOic0weey1QcnOwxYcvTnrjb2iqkBsCPfbOxOYezdzkDroujE752nqi5UkychJq0szAj70/q3C0tG5fzXspn9ih9W67FbPxy50NTFAQd97KmH9k0bLIUdgv8rG3zicIc8yKZBkungptRjF8u7TWygG7BU/TuQqWd7xnzwjgIiqu/38AwpbY22XWlTLlsR89SrM682uO41AKBP2NqlUv16f/sfXpsLhJ9wec0dPGjspdpmpbWYIHhETbSzjiBIBI6+ik6fI563PT9HuwSloHJcH7eUan+SBArY4Nr7B+I/mRP+bdSTqBW9OuJgRPtxqDUkfngqkwORHmsA4GNBNDavZAQQ==

186
CRICS_V3_1124.sln Normal file
View File

@@ -0,0 +1,186 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebSite", "WebSite\WebSite.csproj", "{36E8D929-8643-4C4C-9D1A-912617A69646}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Domain", "Domain\Domain.csproj", "{A42D287A-8EF4-48F6-B14C-7F9CA834F786}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dao", "Dao\Dao.csproj", "{DC017E1A-8853-4267-932E-30CB3BCF8CF5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Service", "Service\Service.csproj", "{BAFCD632-06A1-4EDC-9B14-0897E001572A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csproj", "{B3F29715-E925-4E56-9248-580F06C3BC11}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RCUHost", "RCUHost\RCUHost.csproj", "{3AF4C628-0B47-412C-950A-DBC0161F2A7F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommonEntity", "CommonEntity\CommonEntity.csproj", "{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApplication1", "ConsoleApplication1\ConsoleApplication1.csproj", "{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApplication2", "ConsoleApplication2\ConsoleApplication2.csproj", "{4646F920-6D41-4519-8E03-5528B64EC7FE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApplication3", "ConsoleApplication3\ConsoleApplication3.csproj", "{29658931-8503-4AF6-8145-D432FB554A2C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApplication666", "ConsoleApplication666\ConsoleApplication666.csproj", "{E5890D7A-EB40-4864-B6D8-5B74A443A3F2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "test\test.csproj", "{C51B044F-6F86-4119-AFBA-9496690BC8CD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyIPY", "MyIPY\MyIPY.csproj", "{C2CD5BD8-784F-4B5F-961D-F609EBCFA126}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "testwebservice", "testwebservice\testwebservice.csproj", "{AAD98780-C51C-4498-BD90-45E37C435080}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{36E8D929-8643-4C4C-9D1A-912617A69646}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{36E8D929-8643-4C4C-9D1A-912617A69646}.Debug|Any CPU.Build.0 = Debug|Any CPU
{36E8D929-8643-4C4C-9D1A-912617A69646}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{36E8D929-8643-4C4C-9D1A-912617A69646}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{36E8D929-8643-4C4C-9D1A-912617A69646}.Debug|x86.ActiveCfg = Debug|Any CPU
{36E8D929-8643-4C4C-9D1A-912617A69646}.Release|Any CPU.ActiveCfg = Release|Any CPU
{36E8D929-8643-4C4C-9D1A-912617A69646}.Release|Any CPU.Build.0 = Release|Any CPU
{36E8D929-8643-4C4C-9D1A-912617A69646}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{36E8D929-8643-4C4C-9D1A-912617A69646}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{36E8D929-8643-4C4C-9D1A-912617A69646}.Release|x86.ActiveCfg = Release|Any CPU
{A42D287A-8EF4-48F6-B14C-7F9CA834F786}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A42D287A-8EF4-48F6-B14C-7F9CA834F786}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A42D287A-8EF4-48F6-B14C-7F9CA834F786}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{A42D287A-8EF4-48F6-B14C-7F9CA834F786}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{A42D287A-8EF4-48F6-B14C-7F9CA834F786}.Debug|x86.ActiveCfg = Debug|Any CPU
{A42D287A-8EF4-48F6-B14C-7F9CA834F786}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A42D287A-8EF4-48F6-B14C-7F9CA834F786}.Release|Any CPU.Build.0 = Release|Any CPU
{A42D287A-8EF4-48F6-B14C-7F9CA834F786}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{A42D287A-8EF4-48F6-B14C-7F9CA834F786}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{A42D287A-8EF4-48F6-B14C-7F9CA834F786}.Release|x86.ActiveCfg = Release|Any CPU
{DC017E1A-8853-4267-932E-30CB3BCF8CF5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DC017E1A-8853-4267-932E-30CB3BCF8CF5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DC017E1A-8853-4267-932E-30CB3BCF8CF5}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{DC017E1A-8853-4267-932E-30CB3BCF8CF5}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{DC017E1A-8853-4267-932E-30CB3BCF8CF5}.Debug|x86.ActiveCfg = Debug|Any CPU
{DC017E1A-8853-4267-932E-30CB3BCF8CF5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DC017E1A-8853-4267-932E-30CB3BCF8CF5}.Release|Any CPU.Build.0 = Release|Any CPU
{DC017E1A-8853-4267-932E-30CB3BCF8CF5}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{DC017E1A-8853-4267-932E-30CB3BCF8CF5}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{DC017E1A-8853-4267-932E-30CB3BCF8CF5}.Release|x86.ActiveCfg = Release|Any CPU
{BAFCD632-06A1-4EDC-9B14-0897E001572A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BAFCD632-06A1-4EDC-9B14-0897E001572A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BAFCD632-06A1-4EDC-9B14-0897E001572A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{BAFCD632-06A1-4EDC-9B14-0897E001572A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{BAFCD632-06A1-4EDC-9B14-0897E001572A}.Debug|x86.ActiveCfg = Debug|Any CPU
{BAFCD632-06A1-4EDC-9B14-0897E001572A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BAFCD632-06A1-4EDC-9B14-0897E001572A}.Release|Any CPU.Build.0 = Release|Any CPU
{BAFCD632-06A1-4EDC-9B14-0897E001572A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{BAFCD632-06A1-4EDC-9B14-0897E001572A}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{BAFCD632-06A1-4EDC-9B14-0897E001572A}.Release|x86.ActiveCfg = Release|Any CPU
{B3F29715-E925-4E56-9248-580F06C3BC11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B3F29715-E925-4E56-9248-580F06C3BC11}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3F29715-E925-4E56-9248-580F06C3BC11}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{B3F29715-E925-4E56-9248-580F06C3BC11}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{B3F29715-E925-4E56-9248-580F06C3BC11}.Debug|x86.ActiveCfg = Debug|Any CPU
{B3F29715-E925-4E56-9248-580F06C3BC11}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3F29715-E925-4E56-9248-580F06C3BC11}.Release|Any CPU.Build.0 = Release|Any CPU
{B3F29715-E925-4E56-9248-580F06C3BC11}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{B3F29715-E925-4E56-9248-580F06C3BC11}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{B3F29715-E925-4E56-9248-580F06C3BC11}.Release|x86.ActiveCfg = Release|Any CPU
{3AF4C628-0B47-412C-950A-DBC0161F2A7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3AF4C628-0B47-412C-950A-DBC0161F2A7F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3AF4C628-0B47-412C-950A-DBC0161F2A7F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{3AF4C628-0B47-412C-950A-DBC0161F2A7F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{3AF4C628-0B47-412C-950A-DBC0161F2A7F}.Debug|x86.ActiveCfg = Debug|Any CPU
{3AF4C628-0B47-412C-950A-DBC0161F2A7F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3AF4C628-0B47-412C-950A-DBC0161F2A7F}.Release|Any CPU.Build.0 = Release|Any CPU
{3AF4C628-0B47-412C-950A-DBC0161F2A7F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{3AF4C628-0B47-412C-950A-DBC0161F2A7F}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{3AF4C628-0B47-412C-950A-DBC0161F2A7F}.Release|x86.ActiveCfg = Release|Any CPU
{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}.Debug|x86.ActiveCfg = Debug|Any CPU
{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}.Release|Any CPU.Build.0 = Release|Any CPU
{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}.Release|x86.ActiveCfg = Release|Any CPU
{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}.Debug|Any CPU.ActiveCfg = Debug|x86
{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}.Debug|Mixed Platforms.Build.0 = Debug|x86
{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}.Debug|x86.ActiveCfg = Debug|x86
{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}.Debug|x86.Build.0 = Debug|x86
{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}.Release|Any CPU.ActiveCfg = Release|x86
{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}.Release|Mixed Platforms.ActiveCfg = Release|x86
{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}.Release|Mixed Platforms.Build.0 = Release|x86
{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}.Release|x86.ActiveCfg = Release|x86
{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}.Release|x86.Build.0 = Release|x86
{4646F920-6D41-4519-8E03-5528B64EC7FE}.Debug|Any CPU.ActiveCfg = Debug|x86
{4646F920-6D41-4519-8E03-5528B64EC7FE}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{4646F920-6D41-4519-8E03-5528B64EC7FE}.Debug|Mixed Platforms.Build.0 = Debug|x86
{4646F920-6D41-4519-8E03-5528B64EC7FE}.Debug|x86.ActiveCfg = Debug|x86
{4646F920-6D41-4519-8E03-5528B64EC7FE}.Debug|x86.Build.0 = Debug|x86
{4646F920-6D41-4519-8E03-5528B64EC7FE}.Release|Any CPU.ActiveCfg = Release|x86
{4646F920-6D41-4519-8E03-5528B64EC7FE}.Release|Mixed Platforms.ActiveCfg = Release|x86
{4646F920-6D41-4519-8E03-5528B64EC7FE}.Release|Mixed Platforms.Build.0 = Release|x86
{4646F920-6D41-4519-8E03-5528B64EC7FE}.Release|x86.ActiveCfg = Release|x86
{4646F920-6D41-4519-8E03-5528B64EC7FE}.Release|x86.Build.0 = Release|x86
{29658931-8503-4AF6-8145-D432FB554A2C}.Debug|Any CPU.ActiveCfg = Debug|x86
{29658931-8503-4AF6-8145-D432FB554A2C}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{29658931-8503-4AF6-8145-D432FB554A2C}.Debug|Mixed Platforms.Build.0 = Debug|x86
{29658931-8503-4AF6-8145-D432FB554A2C}.Debug|x86.ActiveCfg = Debug|x86
{29658931-8503-4AF6-8145-D432FB554A2C}.Debug|x86.Build.0 = Debug|x86
{29658931-8503-4AF6-8145-D432FB554A2C}.Release|Any CPU.ActiveCfg = Release|x86
{29658931-8503-4AF6-8145-D432FB554A2C}.Release|Mixed Platforms.ActiveCfg = Release|x86
{29658931-8503-4AF6-8145-D432FB554A2C}.Release|Mixed Platforms.Build.0 = Release|x86
{29658931-8503-4AF6-8145-D432FB554A2C}.Release|x86.ActiveCfg = Release|x86
{29658931-8503-4AF6-8145-D432FB554A2C}.Release|x86.Build.0 = Release|x86
{E5890D7A-EB40-4864-B6D8-5B74A443A3F2}.Debug|Any CPU.ActiveCfg = Debug|x86
{E5890D7A-EB40-4864-B6D8-5B74A443A3F2}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{E5890D7A-EB40-4864-B6D8-5B74A443A3F2}.Debug|Mixed Platforms.Build.0 = Debug|x86
{E5890D7A-EB40-4864-B6D8-5B74A443A3F2}.Debug|x86.ActiveCfg = Debug|x86
{E5890D7A-EB40-4864-B6D8-5B74A443A3F2}.Debug|x86.Build.0 = Debug|x86
{E5890D7A-EB40-4864-B6D8-5B74A443A3F2}.Release|Any CPU.ActiveCfg = Release|x86
{E5890D7A-EB40-4864-B6D8-5B74A443A3F2}.Release|Mixed Platforms.ActiveCfg = Release|x86
{E5890D7A-EB40-4864-B6D8-5B74A443A3F2}.Release|Mixed Platforms.Build.0 = Release|x86
{E5890D7A-EB40-4864-B6D8-5B74A443A3F2}.Release|x86.ActiveCfg = Release|x86
{E5890D7A-EB40-4864-B6D8-5B74A443A3F2}.Release|x86.Build.0 = Release|x86
{C51B044F-6F86-4119-AFBA-9496690BC8CD}.Debug|Any CPU.ActiveCfg = Debug|x86
{C51B044F-6F86-4119-AFBA-9496690BC8CD}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{C51B044F-6F86-4119-AFBA-9496690BC8CD}.Debug|Mixed Platforms.Build.0 = Debug|x86
{C51B044F-6F86-4119-AFBA-9496690BC8CD}.Debug|x86.ActiveCfg = Debug|x86
{C51B044F-6F86-4119-AFBA-9496690BC8CD}.Debug|x86.Build.0 = Debug|x86
{C51B044F-6F86-4119-AFBA-9496690BC8CD}.Release|Any CPU.ActiveCfg = Release|x86
{C51B044F-6F86-4119-AFBA-9496690BC8CD}.Release|Mixed Platforms.ActiveCfg = Release|x86
{C51B044F-6F86-4119-AFBA-9496690BC8CD}.Release|Mixed Platforms.Build.0 = Release|x86
{C51B044F-6F86-4119-AFBA-9496690BC8CD}.Release|x86.ActiveCfg = Release|x86
{C51B044F-6F86-4119-AFBA-9496690BC8CD}.Release|x86.Build.0 = Release|x86
{C2CD5BD8-784F-4B5F-961D-F609EBCFA126}.Debug|Any CPU.ActiveCfg = Debug|x86
{C2CD5BD8-784F-4B5F-961D-F609EBCFA126}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{C2CD5BD8-784F-4B5F-961D-F609EBCFA126}.Debug|Mixed Platforms.Build.0 = Debug|x86
{C2CD5BD8-784F-4B5F-961D-F609EBCFA126}.Debug|x86.ActiveCfg = Debug|x86
{C2CD5BD8-784F-4B5F-961D-F609EBCFA126}.Debug|x86.Build.0 = Debug|x86
{C2CD5BD8-784F-4B5F-961D-F609EBCFA126}.Release|Any CPU.ActiveCfg = Release|x86
{C2CD5BD8-784F-4B5F-961D-F609EBCFA126}.Release|Mixed Platforms.ActiveCfg = Release|x86
{C2CD5BD8-784F-4B5F-961D-F609EBCFA126}.Release|Mixed Platforms.Build.0 = Release|x86
{C2CD5BD8-784F-4B5F-961D-F609EBCFA126}.Release|x86.ActiveCfg = Release|x86
{C2CD5BD8-784F-4B5F-961D-F609EBCFA126}.Release|x86.Build.0 = Release|x86
{AAD98780-C51C-4498-BD90-45E37C435080}.Debug|Any CPU.ActiveCfg = Debug|x86
{AAD98780-C51C-4498-BD90-45E37C435080}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{AAD98780-C51C-4498-BD90-45E37C435080}.Debug|Mixed Platforms.Build.0 = Debug|x86
{AAD98780-C51C-4498-BD90-45E37C435080}.Debug|x86.ActiveCfg = Debug|x86
{AAD98780-C51C-4498-BD90-45E37C435080}.Debug|x86.Build.0 = Debug|x86
{AAD98780-C51C-4498-BD90-45E37C435080}.Release|Any CPU.ActiveCfg = Release|x86
{AAD98780-C51C-4498-BD90-45E37C435080}.Release|Mixed Platforms.ActiveCfg = Release|x86
{AAD98780-C51C-4498-BD90-45E37C435080}.Release|Mixed Platforms.Build.0 = Release|x86
{AAD98780-C51C-4498-BD90-45E37C435080}.Release|x86.ActiveCfg = Release|x86
{AAD98780-C51C-4498-BD90-45E37C435080}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

BIN
CRICS_V3_1124.suo Normal file

Binary file not shown.

66
Common/AliyunSMSHelper.cs Normal file
View File

@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
namespace Common
{
public static class AliyunSMSHelper
{
/// <summary>
/// 发送验证码
/// </summary>
/// <param name="recNum">接收号码,多个号码可以逗号分隔</param>
/// <param name="code">验证码</param>
public static void SendVerifySMS(string recNum, string code)
{
SendSMS(recNum, "{'code':'" + code + "'}");
}
/// <summary>
/// 发送验证码
/// </summary>
/// <param name="recNum">接收号码,多个号码可以逗号分隔</param>
/// <param name="paramString">短信模板中的变量数字需要转换为字符串个人用户每个变量长度必须小于15个字符。</param>
/// <returns></returns>
private static void SendSMS(string recNum, string paramString)
{
//IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", "LTAICuIny2zJSSjm", "uguZzmshKPtT0fW87E8sP1TXe7Kwc9");
IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", "8NjAZd7btOhDFPBB", "UVgzyUqW1p0dYY7nMDYG5CkJdVwzUY");
//IAcsClient client = new DefaultAcsClient(profile);
//SingleSendSmsRequest request = new SingleSendSmsRequest();
DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");//短信API产品名称,短信API产品域名
IAcsClient acsClient = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
try
{
//必填:待发送手机号。支持以逗号分隔的形式进行批量调用批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
request.PhoneNumbers = recNum;
//必填:短信签名-可在短信控制台中找到
//request.SignName = "小威提示";;
request.SignName = "宝来威";
//必填:短信模板-可在短信控制台中找到
//request.TemplateCode = "SMS_95095011";
request.TemplateCode = "SMS_199310216";
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
request.TemplateParam = paramString;// "{\"customer\":\"123\"}";
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
//request.OutId = "21212121211";
//请求失败这里会抛ClientException异常
//SendSmsResponse sendSmsResponse =
acsClient.GetAcsResponse(request);
}
catch (ServerException e)
{
throw e;
}
catch (ClientException e)
{
throw e;
}
}
}
}

61
Common/AppUtils.cs Normal file
View File

@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
public sealed class AppUtils
{
/// <summary>
/// 获取数据库连接字符串
/// </summary>
/// <returns></returns>
private static string GetConnectingString()
{
var databaseSettings = ConfigurationManager.GetSection("databaseSettings") as NameValueCollection;
return databaseSettings["connectionString"];
}
/// <summary>
/// 重置回路当天开启时长
/// </summary>
public static void ResetHostModalTime()
{
Task.Factory.StartNew(() =>
{
using (IDbConnection connection = new SqlConnection(GetConnectingString()))
{
using (IDbCommand command = connection.CreateCommand())
{
connection.Open();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UpdateHostModalRecords";
command.ExecuteNonQuery();
}
}
});
}
/// <summary>
/// 统计回路能耗
/// </summary>
public static void StatisticHostModalEnergy()
{
using (IDbConnection connection = new SqlConnection(GetConnectingString()))
{
using (IDbCommand command = connection.CreateCommand())
{
connection.Open();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "QueryRoomTypeModal_Power";
command.ExecuteNonQuery();
}
}
}
}
}

44
Common/BLWMQTT.cs Normal file
View File

@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using System.Net;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace Common
{
public class BLWMQTT
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(BLWMQTT));
public static MqttClient MqttClientGlobal { get; set; }
public static void StartMqtt()
{
try
{
// create client instance
MqttClientGlobal = new MqttClient(IPAddress.Parse("120.24.73.62"));
string clientId = Guid.NewGuid().ToString();
MqttClientGlobal.Connect(clientId, "admin", "blw@1234");
}
catch (Exception ex)
{
logger.Error("mqtt:" + ex.Message);
}
}
public static void MQTTPublishData(string topic, string payload)
{
try
{
if (MqttClientGlobal.IsConnected)
{
MqttClientGlobal.Publish(topic, Encoding.UTF8.GetBytes(payload), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
}
}
catch (Exception)
{
}
}
}
}

34
Common/CPUData.cs Normal file
View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Common
{
public class CPUData
{
public static PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
public static double GetCPU()
{
cpuCounter.NextValue(); // 初始化计数器,让它开始计数
System.Threading.Thread.Sleep(1000); // 等待一秒
double cpuUsage = cpuCounter.NextValue(); // 获取CPU使用率
return cpuUsage;
}
[DllImport("kernel32.dll")]
private static extern void GetSystemTimePreciseAsFileTime(out long fileTime);
// 将 FILETIME (long) 转换为 DateTime
public static DateTime GetNowPrecise()
{
long fileTime;
GetSystemTimePreciseAsFileTime(out fileTime);
DateTime localTime = DateTime.FromFileTimeUtc(fileTime).ToLocalTime();
return localTime;
}
}
}

View File

@@ -0,0 +1,356 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using CSRedis;
using NHibernate.Cache;
namespace Common
{
/// <summary>
/// Redis缓存辅助类
/// </summary>
public class CSRedisCacheHelper
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(CSRedisCacheHelper));
public static CSRedisClient redis;
public static CSRedisClient redis1;
public static CSRedisClient redis2;
public static CSRedisClient redis3;
public static CSRedisClient redis4;
public static CSRedisClient redis5;
//private static readonly string[] redisHosts = null;
private static int SessionExpireMinutes = int.Parse(ConfigurationManager.AppSettings["session_expire_minutes"]);
private static int MonitorLogExpireMinutes = int.Parse(ConfigurationManager.AppSettings["monitor_log_expire_minutes"]);
//过期时间60个小时
private static int DeviceStatusExpireMinutes = 60;
//private static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);
//private static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);
//private const string ip = "127.0.0.1";
//private const string port = "6379";
//private const string preheat = "100"; // 设置预热连接数
//private const string connectTimeout = "100"; // 设置连接超时时间
//private const string tryit = "1"; // 设置重试次数
//private const string prefix = "CSRedisTest."; // 设置前缀
//private static readonly string _connectString = $"{ip}:{port},preheat={preheat},connectTimeout={connectTimeout},tryit={tryit},prefix={prefix}";
public static string HeartBeatPrefix = "HeartBeatMonitor";
static CSRedisCacheHelper()
{
var redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];
if (!string.IsNullOrEmpty(redisHostStr))
{
redis = new CSRedisClient(redisHostStr);//+ ",password=,defaultDatabase=0,poolsize=500,ssl=false,writeBuffer=10240,prefix=");
//RedisHelper.Initialization(redis);
//redis = new CSRedisClient[2];
//redis[0] = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=0");
//redis[1] = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=1");
redis1 = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=1");
redis2 = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=2");
redis3 = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=3");
redis4 = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=4");
redis5 = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=5");
//Native subscribe
string channel = "__keyevent@0__:expired";
var QQQ = new ValueTuple<string, Action<CSRedisClient.SubscribeMessageEventArgs>>(channel, (msg) =>
{
//string Key = CacheKey.UPGradeProgressBar + "_" + id;
try
{
if (!msg.Body.StartsWith("UPProgressBar"))
{
bool containsHyphen = msg.Body.Contains("-");
bool isNumeric = msg.Body.All(char.IsDigit);
if (containsHyphen == false && isNumeric)
{
string hotelcode = Tools.HostNumberToHotelCode(msg.Body).ToString();
OnOffLineData o = new OnOffLineData();
o.HotelCode = hotelcode;
o.HostNumber = msg.Body;
o.CurrentStatus = "off";
o.CurrentTime = DateTime.Now;
//新来的数据
string str = Newtonsoft.Json.JsonConvert.SerializeObject(o);
CSRedisCacheHelper.redis3.Publish("redis-on_off_line", str);
//redis4.Set(HeartBeatPrefix + "_" + msg.Body, 1, 5 * 60);
}
}
}
catch (Exception ex)
{
logger.Error("RedisYiChu: " + msg.Body);
logger.Error(ex.Message);
}
});
redis.Subscribe(QQQ);
//RedisHelper.PSubscribe(new[] { "test*", "*test001", "test*002" }, msg =>
//{
// Console.WriteLine("");
//});
}
}
/// <summary>
/// 添加缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public static void Set<T>(string key, T value)
{
redis.Set(key, value, SessionExpireMinutes * 60);
}
public static T Get<T>(string key)
{
return redis.Get<T>(key);
}
public static void Del(string[] key)
{
redis.Del(key.ToArray());
}
public static void Del_Partition(string key, int SliceNo = 2)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
client.Del(key);
}
public static T ForeverGet<T>(string key)
{
return redis1.Get<T>(key);
}
public static void Forever<T>(string key, T value)
{
redis1.Set(key, value, MonitorLogExpireMinutes * 24 * 60 * 60);
}
public static T Get_Partition<T>(string key, int SliceNo = 2)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
return client.Get<T>(key);
}
public static void Set_Partition<T>(string key, T value, int SliceNo = 2)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
client.Set(key, value, DeviceStatusExpireMinutes * 60 * 60);
}
/// <summary>
/// 设置过期时间
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="ExpireTime_Minutes"></param>
/// <param name="SliceNo"></param>
public static void Set_PartitionWithTime<T>(string key, T value, int ExpireTime_Minutes, int SliceNo = 2)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
client.Set(key, value, ExpireTime_Minutes * 60);
}
public static void Set_PartitionWithForever<T>(string key, T value, int SliceNo = 2)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
client.Set(key, value, -1);
}
public static void Del_Partition(string[] key, int SliceNo = 2)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
client.Del(key);
}
public static bool Contains_Partition(string key, int SliceNo = 2)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
bool result = client.Exists(key);
return result;
}
private static CSRedisClient WhitchRedisSlice(int SliceNo)
{
CSRedisClient client = null;
if (SliceNo == 1)
{
client = redis1;
}
else if (SliceNo == 2)
{
client = redis2;
}
else if (SliceNo == 3)
{
client = redis3;
}
else if (SliceNo == 4)
{
client = redis4;
}
else if (SliceNo == 5)
{
client = redis5;
}
else
{
client = redis;
}
return client;
}
public static long GetForever_ExpireMinutes<T>(string key)
{
return redis.Ttl(key);
}
/// <summary>
/// 获取
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T Get<T>(string key, string mac)
{
T obj = redis.Get<T>(mac);
if (obj == null)
{
return redis.Get<T>(key);
}
return obj;
}
/// <summary>
/// 判断是否存在
/// </summary>
/// <param name="key"></param>
/// <param name="mac"></param>
/// <returns></returns>
public static bool Contains(string key, string mac)
{
bool result = redis.Exists(mac);
if (!result)
{
result = redis.Exists(key);
}
return result;
}
public static bool Contains(string key)
{
bool result = redis.Exists(key);
return result;
}
public static void Publish(string Topic, string Payload)
{
CSRedisCacheHelper.redis3.Publish(Topic, Payload);
}
/// <summary>
/// 添加Hash缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public static void HMSet(int SliceNo, string key, params object[] value)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
client.HMSet(key, value);
}
public static void HMSet(int SliceNo, int ExpireTime_M, string key, params object[] value)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
client.HMSet(key, value);
client.Expire(key, new TimeSpan(0, ExpireTime_M, 0));
}
/// <summary>
/// 获取Hash缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T[] HMGet<T>(int SliceNo, string key, string KeyV)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
return client.HMGet<T>(key, KeyV);
}
public static Dictionary<string, string> HMGetAll(int SliceNo, string key)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
return client.HGetAll(key);
}
/// <summary>
/// 获取 某个hash值的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static int GetHMCount(string key)
{
return redis5.HGetAll(key).Count;
}
/// <summary>
/// 删除Hash缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static long HDelAll<T>(int SliceNo, string key)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
return client.HDel(key);
}
public static long HDel(int SliceNo, string key, string key1)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
return client.HDel(key, key1);
}
public static void ListAdd(int SliceNo, string key, params object[] obj)
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
client.LPush(key, obj);
}
public static int MaxLen = 500000;
public static void StreamAdd(int SliceNo, string key, string Value)
{
try
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
// 添加简单消息
client.XAdd(key, MaxLen, "*", new ValueTuple<string, string>("__data", Value));
}
catch (Exception)
{
}
}
public static void StreamConsume(int SliceNo, string key, string group = "UDPData", string consumer = "Crics1")
{
CSRedisClient client = WhitchRedisSlice(SliceNo);
var data = redis.XReadGroup(group, consumer, 100, 10, new ValueTuple<string, string>(key, ">"));
if (data != null)
{
//检查pending表的长度
//消费确认前pending 应该等于2
var pending = redis.XPending(key, group);
foreach (var item in data)
{
var idarray = item.Item2;
foreach (var SerializeNo in idarray)
{
var id1 = SerializeNo.Item1;
redis.XAck(key, group, id1);
redis.XDel(key, id1);
}
}
}
}
}
}

196
Common/Common.csproj Normal file
View File

@@ -0,0 +1,196 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{B3F29715-E925-4E56-9248-580F06C3BC11}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Common</RootNamespace>
<AssemblyName>Common</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\WebSite\Bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Reference Include="AipSdk">
<HintPath>..\lib\AipSdk.dll</HintPath>
</Reference>
<Reference Include="aliyun-net-sdk-core">
<HintPath>..\lib\aliyun-net-sdk-core.dll</HintPath>
</Reference>
<Reference Include="aliyun-net-sdk-dysmsapi">
<HintPath>..\lib\aliyun-net-sdk-dysmsapi.dll</HintPath>
</Reference>
<Reference Include="Antlr3.Runtime, Version=3.1.3.42154, Culture=neutral, PublicKeyToken=3a9cab8f8d22bfb7, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NHibernate\Antlr3.Runtime.dll</HintPath>
</Reference>
<Reference Include="Bamboo.Prevalence, Version=1.4.4.4, Culture=neutral, PublicKeyToken=0edf2245780ab2d7">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NHibernate\Bamboo.Prevalence.dll</HintPath>
</Reference>
<Reference Include="Bamboo.Prevalence.Util, Version=1.4.4.4, Culture=neutral, PublicKeyToken=0edf2245780ab2d7">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NHibernate\Bamboo.Prevalence.Util.dll</HintPath>
</Reference>
<Reference Include="CacheManager.Core">
<HintPath>..\lib\CacheManager.Core.0.7.4\lib\net40\CacheManager.Core.dll</HintPath>
</Reference>
<Reference Include="CacheManager.Memcached">
<HintPath>..\lib\CacheManager.Memcached.0.7.4\lib\net40\CacheManager.Memcached.dll</HintPath>
</Reference>
<Reference Include="CacheManager.SystemRuntimeCaching">
<HintPath>..\lib\CacheManager.SystemRuntimeCaching.0.7.4\lib\net40\CacheManager.SystemRuntimeCaching.dll</HintPath>
</Reference>
<Reference Include="CSRedisCore">
<HintPath>..\lib\Redis\CSRedisCore.dll</HintPath>
</Reference>
<Reference Include="Enyim.Caching">
<HintPath>..\lib\EnyimMemcached.2.13\lib\net35\Enyim.Caching.dll</HintPath>
</Reference>
<Reference Include="HibernatingRhinos.Profiler.Appender, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0774796e73ebf640, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NHibernate\HibernatingRhinos.Profiler.Appender.dll</HintPath>
</Reference>
<Reference Include="Iesi.Collections, Version=1.0.1.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NHibernate\Iesi.Collections.dll</HintPath>
</Reference>
<Reference Include="LinFu.DynamicProxy, Version=1.0.4.18998, Culture=neutral, PublicKeyToken=62a6874124340d6e, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NHibernate\LinFu.DynamicProxy.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\log4net\log4net.dll</HintPath>
</Reference>
<Reference Include="M2Mqtt.Net, Version=4.3.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\M2Mqtt.Net\M2Mqtt.Net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="NHibernate, Version=3.0.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NHibernate\NHibernate.dll</HintPath>
</Reference>
<Reference Include="NHibernate.ByteCode.LinFu, Version=3.0.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NHibernate\NHibernate.ByteCode.LinFu.dll</HintPath>
</Reference>
<Reference Include="NHibernate.Caches.Prevalence, Version=3.0.0.4000, Culture=neutral, PublicKeyToken=6876f2ea66c9f443, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NHibernate\NHibernate.Caches.Prevalence.dll</HintPath>
</Reference>
<Reference Include="NPOI, Version=2.1.3.1, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NPOI\dotnet4\NPOI.dll</HintPath>
</Reference>
<Reference Include="NPOI.OOXML, Version=2.1.3.1, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NPOI\dotnet4\NPOI.OOXML.dll</HintPath>
</Reference>
<Reference Include="NPOI.OpenXml4Net, Version=2.1.3.1, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NPOI\dotnet4\NPOI.OpenXml4Net.dll</HintPath>
</Reference>
<Reference Include="NPOI.OpenXmlFormats, Version=2.1.3.1, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NPOI\dotnet4\NPOI.OpenXmlFormats.dll</HintPath>
</Reference>
<Reference Include="Remotion.Data.Linq, Version=1.13.41.2, Culture=neutral, PublicKeyToken=cab60358ab4081ea, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\NHibernate\Remotion.Data.Linq.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Management" />
<Reference Include="System.Runtime.Caching" />
<Reference Include="System.ValueTuple">
<HintPath>..\lib\Redis\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AliyunSMSHelper.cs" />
<Compile Include="AppUtils.cs" />
<Compile Include="BLWMQTT.cs" />
<Compile Include="CPUData.cs" />
<Compile Include="ExcelHelper.cs" />
<Compile Include="MemoryStreamPool.cs" />
<Compile Include="OnOffLineData.cs" />
<Compile Include="RateLimiter.cs" />
<Compile Include="CSRedisCacheHelper.cs" />
<Compile Include="DynamicLibrary.cs" />
<Compile Include="EnumDescription.cs" />
<Compile Include="FreeGoOperation.cs" />
<Compile Include="GlobalCache.cs" />
<Compile Include="HttpWebRequestHelper.cs" />
<Compile Include="IQueryOverExtension.cs" />
<Compile Include="MemoryCacheHelper.cs" />
<Compile Include="MemoryCacheUtil.cs" />
<Compile Include="MyDes.cs" />
<Compile Include="NPOIMemoryStream.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ProtocalData.cs" />
<Compile Include="SimpleMemoryStreamPool.cs" />
<Compile Include="SQLHelper.cs" />
<Compile Include="StructConverter.cs" />
<Compile Include="TFTPclient.cs" />
<Compile Include="TimeHelper.cs" />
<Compile Include="Tools.cs" />
<Compile Include="TVOperation.cs" />
<Compile Include="UDPLogServer.cs" />
<Compile Include="UDPPackageCount.cs" />
<Compile Include="ValidatePattern.cs" />
<Compile Include="WeiXinHelper.cs" />
<Compile Include="SyncRoomStatus.cs" />
<Compile Include="RokidOperation.cs" />
<Compile Include="XidaoDuOperation.cs" />
<Compile Include="DuiOperation.cs" />
<Compile Include="XuanZhuOperation.cs" />
<Compile Include="FrequencyControler.cs" />
<Compile Include="TianMaoOperation.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectView>ProjectFiles</ProjectView>
</PropertyGroup>
</Project>

83
Common/DuiOperation.cs Normal file
View File

@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common
{
public static class DuiOperation
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(DuiOperation));
private static readonly string _uploadURL = "https://gw.duiopen.com";
/// <summary>
/// 开启设备更新上报
/// </summary>
/// <returns></returns>
public static bool OpenUploadApplianceSwitch()
{
StringBuilder sb = new StringBuilder();
sb.Append(_uploadURL);
sb.Append("/dcas/v1/uploadApplianceSwitch");
sb.Append("?apikey=b4b4c81c01e446b4b40f85b196c6aaec");
sb.Append("&skillId=2020120900000014");
try
{
string result = HttpWebRequestHelper.PutWebRequest(sb.ToString(), "{'status':1}");
DuiResult duiResult = Newtonsoft.Json.JsonConvert.DeserializeObject<DuiResult>(result);
if (duiResult.errId != 0)
{
logger.Error(string.Format("DUI开启设备更新上报失败url:{0},errId:{1}", sb.ToString(), duiResult.errId));
return false;
}
return true;
}
catch (Exception ex)
{
logger.Error(string.Format("DUI开启设备更新上报失败url:{0},原因:{1}", sb.ToString(), ex));
}
return false;
}
/// <summary>
/// 通知更新技能
/// </summary>
/// <param name="hotelName"></param>
/// <param name="roomNumber"></param>
/// <param name="accessToken"></param>
/// <returns></returns>
public static bool UploadDeviceFun(string hotelName, string roomNumber, string accessToken)
{
StringBuilder sb = new StringBuilder();
sb.Append(_uploadURL);
sb.Append("/dcas/v1/uploadAppliance");
sb.Append("?apikey=b4b4c81c01e446b4b40f85b196c6aaec");
sb.Append("&skillId=2020120900000014");
//sb.Append("&productId=2020120900000014");
sb.Append("&accessToken=" + accessToken);
sb.Append("&group=" + roomNumber);
sb.Append("&type=notify");
try
{
string result = HttpWebRequestHelper.PutWebRequest(sb.ToString(), "");
DuiResult duiResult = Newtonsoft.Json.JsonConvert.DeserializeObject<DuiResult>(result);
if (duiResult.errId != 0)
{
logger.Error(string.Format("DUI酒店({0})客房({1})同步技能失败。errId:{2}", hotelName, roomNumber, duiResult.errId));
return false;
}
//logger.Error(string.Format("DUI酒店({0})客房({1})已通知同步技能。", hotelName, roomNumber));
return true;
}
catch (Exception ex)
{
logger.Error(string.Format("DUI酒店({0})客房({1})调用DUI接口({2})失败:{3}", hotelName, roomNumber, _uploadURL, ex));
}
return false;
}
}
internal class DuiResult
{
public int errId { get; set; }
public int status { get; set; }
}
}

2302
Common/DynamicLibrary.cs Normal file

File diff suppressed because it is too large Load Diff

42
Common/EnumDescription.cs Normal file
View File

@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Common
{
public class EnumDescription
{
public static string GetDescription(Enum enumValue)
{
if (enumValue == null)
{
return String.Empty;
}
string strValue = enumValue.ToString();
Type enumType = enumValue.GetType();
FieldInfo fieldInfo = enumType.GetField(strValue);
Object[] attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
return (attributes[0] as DescriptionAttribute).Description;
}
return strValue;
}
public static Dictionary<string, object> GetNameValueList(Type enumType)
{
Dictionary<string, object> nameValueList = new Dictionary<string, object>();
return nameValueList;
}
}
}

203
Common/ExcelHelper.cs Normal file
View File

@@ -0,0 +1,203 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Data;
namespace Common
{
/// <summary>
/// NPOI读写Excel操作类
/// </summary>
public class ExcelHelper : IDisposable
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed;
public ExcelHelper(string fileName)
{
this.fileName = fileName;
disposed = false;
}
/// <summary>
/// 将DataTable数据导入到excel中
/// </summary>
/// <param name="data">要导入的数据</param>
/// <param name="isColumnWritten">DataTable的列名是否要导入</param>
/// <param name="sheetName">要导入的excel的sheet的名称</param>
/// <returns>导入数据行数(包含列名那一行)</returns>
public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook();
try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
workbook.Write(fs); //写入到excel
return count;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="fileStream">文档流,空的话取文件路径</param>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(Stream fileStream, string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
if (fileStream != null)
{
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fileStream);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fileStream);
}
else
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
}
if (string.IsNullOrEmpty(sheetName))
{
sheet = workbook.GetSheetAt(0);
}
else
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt(0);
}
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null       
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
throw ex;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (fs != null)
fs.Close();
}
fs = null;
disposed = true;
}
}
}
}

167
Common/FreeGoOperation.cs Normal file
View File

@@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Web.Routing;
namespace Common
{
/// <summary>
/// FreeGo对接
/// </summary>
public static class FreeGoOperation
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(FreeGoOperation));
private static string freego_url = System.Configuration.ConfigurationManager.AppSettings["freego_url"];
private static string freego_codes = System.Configuration.ConfigurationManager.AppSettings["freego_codes"];
private static string freego_appid = System.Configuration.ConfigurationManager.AppSettings["freego_appid"];
private static string freego_appsecret = System.Configuration.ConfigurationManager.AppSettings["freego_appsecret"];
/// <summary>
/// 调用freego获取设备密钥等信息
/// </summary>
/// <param name="mac">主机mac地址如34-D0-00-00-00-01格式</param>
/// <returns></returns>
public static DeviceRegisterResult DeviceRegister(string mac)
{
string deviceName = mac.Replace("-", "").ToUpper();
DeviceRegisterPostData postData = new DeviceRegisterPostData()
{
appid = freego_appid,
timestamp = TimeHelper.DateTimeToStamp(DateTime.Now).ToString(),
nonce_str = Guid.NewGuid().ToString(),
device_name = deviceName
};
var dic = new RouteValueDictionary();
dic["appid"] = postData.appid;
dic["timestamp"] = postData.timestamp;
dic["nonce_str"] = postData.nonce_str;
dic["device_name"] = postData.device_name;
postData.sign = HttpWebRequestHelper.GetFreeGoSignature(dic, freego_appsecret);
try
{
string result = HttpWebRequestHelper.PostWebRequest(freego_url, Newtonsoft.Json.JsonConvert.SerializeObject(postData));
return JsonConvert.DeserializeObject<DeviceRegisterResult>(result);
}
catch (Exception ex)
{
logger.Error("调用FreeGo接口失败" + ex.ToString());
return new DeviceRegisterResult() { errcode = "-1", msg = ex.Message }; ;
}
}
/// <summary>
/// 给FreeGo福瑞狗上报SOS和DND状态
/// </summary>
/// <param name="hotelCode"></param>
/// <param name="roomNumber"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public static void UploadService(string hotelCode, string roomNumber, string key, string value)
{
foreach (string freego_code in freego_codes.Split(','))
{
if (freego_code == hotelCode)
{
UploadServicePostData postData = new UploadServicePostData()
{
appid = freego_appid,
appsecret = freego_appsecret,
code = freego_code,
room_number = roomNumber,
timestamp = TimeHelper.DateTimeToStamp(DateTime.Now).ToString(),
key = key,
value = value
};
try
{
HttpWebRequestHelper.PostWebRequest(freego_url, Newtonsoft.Json.JsonConvert.SerializeObject(postData));
}
catch (Exception ex)
{
logger.Error("调用FreeGo接口失败" + ex.ToString());
}
break;
}
}
}
}
internal class DeviceRegisterPostData
{
/// <summary>
/// 分配的请求id
/// </summary>
public string appid { get; set; }
/// <summary>
/// 当前unix时间戳
/// </summary>
public string timestamp { get; set; }
/// <summary>
/// 随机字符串
/// </summary>
public string nonce_str { get; set; }
/// <summary>
/// 设备名称
/// </summary>
public string device_name { get; set; }
/// <summary>
/// 签名
/// </summary>
public string sign { get; set; }
}
public class DeviceRegisterResult
{
/// <summary>
/// 错误代码0表示成功
/// </summary>
public string errcode { get; set; }
/// <summary>
/// 设备名称
/// </summary>
public string device_name { get; set; }
/// <summary>
/// 设备密钥
/// </summary>
public string device_secret { get; set; }
/// <summary>
/// 阿里云物联网id
/// </summary>
public string iot_id { get; set; }
/// <summary>
/// 产品key
/// </summary>
public string product_key { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string msg { get; set; }
}
internal class UploadServicePostData
{
public string appid { get; set; }
public string appsecret { get; set; }
/// <summary>
/// 酒店编码
/// </summary>
public string code { get; set; }
/// <summary>
/// 房号
/// </summary>
public string room_number { get; set; }
/// <summary>
/// 当前unix时间戳
/// </summary>
public string timestamp { get; set; }
/// <summary>
/// SOS/DND
/// </summary>
public string key { get; set; }
/// <summary>
/// 当前服务值
/// </summary>
public string value { get; set; }
}
}

View File

@@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Web;
namespace Common
{
/// <summary>
/// 记录每次(总次数设定上限,超过要求的频率即可)访问的时间,比较当前访问时间与向前指定次数那次的访问时间,如果时间短于规定的时长,则表示已经超过规定时长内访问次数了,即访问过于频繁了。
/// 如public static FrequencyControler DoFrequency = new FrequencyControler("act", 10, 3);//定义访问控制器允许10秒内3次请求
/// DoFrequency.IsTooFrequently(true)//访问过于频繁!
/// </summary>
public class FrequencyControler
{
/// <summary>
/// 访问控制器名称,用于区分其它控制器,支持多个控制器
/// </summary>
private string Name { get; set; }
/// <summary>
/// 限定时长
/// </summary>
private int Seconds { get; set; }
/// <summary>
/// 限定次数
/// </summary>
private int Times { get; set; }
public readonly int MAX_TIMES = 100;
#region
private string SessionNameDatelist
{
get { return String.Format("fc.{0}.datelist", Name); }
}
private string SessionNameDatepos
{
get { return String.Format("fc.{0}.datepos", Name); }
}
/// <summary>
/// 取得用于保存每次访问时间点的数组(做队列用)
/// </summary>
/// <returns></returns>
private long[] GetDateList()
{
if (HttpContext.Current.Session[SessionNameDatelist] == null)
{
HttpContext.Current.Session[SessionNameDatelist] = new long[MAX_TIMES];
}
return (long[])HttpContext.Current.Session[SessionNameDatelist];
}
/// <summary>
/// 获取时间记录位置,相当于当前队列位置
/// </summary>
/// <returns></returns>
private int GetDatepos()
{
if (HttpContext.Current.Session[SessionNameDatepos] == null)
{
HttpContext.Current.Session[SessionNameDatepos] = 0;
}
return (int)HttpContext.Current.Session[SessionNameDatepos];
}
/// <summary>
/// 设置时间记录位置,相当于当前队列位置
/// </summary>
/// <param name="pos"></param>
private void SetDatepos(int pos)
{
HttpContext.Current.Session[SessionNameDatepos] = pos;
}
#endregion
/// <summary>
/// 构造访问检测器,限定指定时间内最多请求次数
/// </summary>
/// <param name="name">名称</param>
/// <param name="seconds">限定时间范围(秒数)</param>
/// <param name="times">限定次数</param>
public FrequencyControler(string name, int seconds, int times)
{
Name = name;
Seconds = seconds;
Times = times;
if (times > MAX_TIMES) throw new Exception("限定次数设置值超出上限!");
}
/// <summary>
/// 记录一次访问,在时间点数组的下一个位置(按最大长度循环覆盖存储)
/// </summary>
public void Record()
{
long[] ds = GetDateList();
int pos = GetDatepos();
pos = (pos + 1) % ds.Length;
ds[pos] = DateTime.Now.Ticks;
SetDatepos(pos);
}
/// <summary>
/// 判断是否达到访问限制(并默认记录一次请求)
/// </summary>
/// <returns></returns>
public bool IsTooFrequently()
{
return IsTooFrequently(true);
}
/// <summary>
/// 判断是否达到访问限制(主要外部使用功能)
/// </summary>
/// <param name="isRecord">是否包含本次请求为true时会先记录一次请求再判断</param>
/// <returns></returns>
public bool IsTooFrequently(bool isRecord)
{
if (isRecord) Record();
long[] ds = GetDateList();
int pos = GetDatepos();
// 取得之前 限定次数 位置的时间点与最后的时间点比较,
// 如果之前的访问次数还没有达到限定次数则忽略
int pre_pos = (pos + ds.Length - Times + 1) % ds.Length;
long pre_ticks = ds[pre_pos];
long now_ticks = ds[pos];
// 如果访问的次烤都还没有达到限定次数pre_ticks 必定为0所以大于0时才进行比较
if (pre_ticks > 0)
{
TimeSpan span = new TimeSpan(now_ticks - pre_ticks);
if (span.TotalSeconds <= Seconds)
{
return true;
}
}
return false;
}
}
}

32
Common/GlobalCache.cs Normal file
View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CacheManager.Core;
namespace Common
{
public class GlobalCache
{
private static ICacheManager<object> cacheManager { get; set; }
private static readonly object locker = new object();
static GlobalCache()
{
if (cacheManager == null)
{
lock (locker)
{
//cacheManager = CacheFactory.Build("memcached", settings => settings.WithMemcachedCacheHandle("enyim.com/memcached"));
cacheManager = CacheFactory.FromConfiguration<object>("myCache");
}
}
}
public static ICacheManager<object> CacheManager
{
get { return cacheManager; }
}
}
}

View File

@@ -0,0 +1,219 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Routing;
using System.Security.Cryptography;
using System.Web;
using System.Reflection;
using System.Collections.Specialized;
namespace Common
{
public static class HttpWebRequestHelper
{
/// <summary>
/// Get数据接口
/// </summary>
/// <param name="url">接口地址(带参数)</param>
/// <returns></returns>
public static string GetWebRequest(string url)
{
string responseContent = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//在这里对接收到的页面内容进行处理
using (Stream resStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8))
{
responseContent = reader.ReadToEnd();
}
}
return responseContent;
}
public static string PutWebRequest(string url, string postData)
{
string result = string.Empty;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "PUT";
//req.Timeout = 10000;//设置请求超时时间,单位为毫秒
req.ContentType = "application/json";
byte[] data = Encoding.UTF8.GetBytes(postData);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
using (Stream stream = resp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();//获取响应内容
}
}
return result;
}
/// <summary>
/// post数据接口
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="method">post和put默认post</param>
/// <returns></returns>
public static string PostWebRequest(string url, string postData)
{
if (url.ToLower().StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;//设置这个安全协议必须在创建请求之前!
}
string result = string.Empty;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
//req.Timeout = 10000;//设置请求超时时间,单位为毫秒
req.ContentType = "application/json";
byte[] data = Encoding.UTF8.GetBytes(postData);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
using (Stream stream = resp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();//获取响应内容
}
}
return result;
}
/// <summary>
/// post数据接口
/// </summary>
/// <param name="url"></param>
/// <param name="headerAuthorization"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string PostWebRequest(string url, string headerAuthorization, string postData)
{
if (url.ToLower().StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;//设置这个安全协议必须在创建请求之前!
}
string result = string.Empty;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add("Authorization", headerAuthorization);
byte[] data = Encoding.UTF8.GetBytes(postData);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
using (Stream stream = resp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();//获取响应内容
}
}
return result;
}
/// <summary>
/// post数据接口
/// </summary>
/// <param name="url"></param>
/// <param name="headerAuthorization"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string PostAliOpenApi(string url, string headerAuthorization, string postData)
{
string result = string.Empty;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.Host = "openapi.aligenie.com";
req.Headers.Add("Authorization", headerAuthorization);
req.Headers.Add("x-acs-action", "ImportHotelConfig");
req.Headers.Add("x-acs-version", "ip_1.0");
req.Headers.Add("x-acs-date", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"));
req.Headers.Add("x-acs-signature-nonce", "bf0a025c-8b91-4f46-9a95-8a15421223a016891516640081");
//req.Headers.Add("x-acs-content-sha256", "fdbc85c3630ae25fd7724f95d3b0029021a6433783226b90af76670e72cc4b23");
byte[] data = Encoding.UTF8.GetBytes(postData);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
using (Stream stream = resp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();//获取响应内容
}
}
return result;
}
/// <summary>
/// 获取阿里云签名结果串
/// </summary>
/// <param name="dic"></param>
/// <param name="accessKeySecret"></param>
/// <returns></returns>
public static string GetAliyunSignature(RouteValueDictionary dic, string accessKeySecret)
{
var canonicalizedQueryString = string.Join("&",
dic.OrderBy(x => x.Key)
.Select(x => PercentEncode(x.Key) + "=" + PercentEncode(x.Value.ToString())));
var stringToSign = "GET&%2F&" + PercentEncode(canonicalizedQueryString);
var keyBytes = Encoding.UTF8.GetBytes(accessKeySecret + "&");
var hmac = new HMACSHA1(keyBytes);
var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
return Convert.ToBase64String(hashBytes);
}
/// <summary>
/// freego签名
/// </summary>
/// <param name="dic"></param>
/// <param name="accessKeySecret"></param>
/// <returns></returns>
public static string GetFreeGoSignature(RouteValueDictionary dic, string accessKeySecret)
{
var canonicalizedQueryString = string.Join("&", dic.OrderBy(x => x.Key)
.Select(x => PercentEncode(x.Key) + "=" + PercentEncode(x.Value.ToString())));
canonicalizedQueryString += "&key=" + accessKeySecret;
return Tools.MD5Encrypt(canonicalizedQueryString);
}
private static string PercentEncode(string value)
{
return UpperCaseUrlEncode(value)
.Replace("+", "%20")
.Replace("*", "%2A")
.Replace("%7E", "~");
}
private static string UpperCaseUrlEncode(string s)
{
char[] temp = HttpUtility.UrlEncode(s).ToCharArray();
for (int i = 0; i < temp.Length - 2; i++)
{
if (temp[i] == '%')
{
temp[i + 1] = char.ToUpper(temp[i + 1]);
temp[i + 2] = char.ToUpper(temp[i + 2]);
}
}
return new string(temp);
}
}
}

View File

@@ -0,0 +1,53 @@
using System;
using System.Linq;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Criterion.Lambda;
namespace Common
{
/// <summary>
/// 扩展 IQueryOver
/// </summary>
public static class IQueryOverExtension
{
/// <summary>
/// 扩展 IQueryOver.OrderBy
/// </summary>
/// <typeparam name="TRoot"></typeparam>
/// <typeparam name="TSubType"></typeparam>
/// <param name="source"></param>
/// <param name="sort"></param>
/// <param name="order"></param>
/// <returns></returns>
public static IQueryOver<TRoot, TSubType> OrderBy<TRoot, TSubType>(this IQueryOver<TRoot, TSubType> source, string sort, string order)
{
if (String.IsNullOrEmpty(sort)) {
throw new ArgumentNullException("sort");
}
Type type = typeof(TRoot);
if (type.GetProperties().Count(r => r.Name == sort) == 0) {
throw new ArgumentException(String.Format("无效的参数值,{0}不是{1}的属性。", sort, type.Name), "sort");
}
if (String.IsNullOrEmpty(order)) {
throw new ArgumentNullException("order");
}
bool ascending = true;
if (String.Equals(order, "asc", StringComparison.OrdinalIgnoreCase)) {
ascending = true;
} else if (String.Equals(order, "desc", StringComparison.OrdinalIgnoreCase)) {
ascending = false;
} else {
throw new ArgumentException("无效的参数值,取值范围 asc 或 desc 。", "order");
}
IQueryOverOrderBuilder<TRoot, TSubType> orderBuilder = source.OrderBy(Projections.Property(sort));
return ascending ? orderBuilder.Asc : orderBuilder.Desc;
}
}
}

137
Common/MemoryCacheHelper.cs Normal file
View File

@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Collections.Concurrent;
namespace Common
{
/// <summary>
/// 基于MemoryCache的缓存辅助类
/// </summary>
public static class MemoryCacheHelper
{
private static readonly Object _locker = new object();
public readonly static MemoryCache _cache = MemoryCache.Default;
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MemoryCacheHelper));
/// <summary>
/// 缓存数据默认2分钟后过期
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public static void Set(string key, object value)
{
if (value != null)
{
CacheItemPolicy policy = new CacheItemPolicy(); //创建缓存项策略
policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(10)); //设定某个时间过后将逐出缓存
Set(key, value, policy);
}
}
public static void Delete(string key)
{
lock (_locker)
{
_cache.Remove(key);
}
}
public static void SlideSet(string key, object value)
{
CacheItemPolicy policy = new CacheItemPolicy(); //创建缓存项策略
policy.SlidingExpiration = new TimeSpan(0, 20, 0); //如果20分钟内使用还使用这个数据
Set(key, value, policy);
}
public static void SlideSet(string key, object value, TimeSpan span)
{
CacheItemPolicy policy = new CacheItemPolicy(); //创建缓存项策略
policy.SlidingExpiration = span; //如果20分钟内使用还使用这个数据
Set(key, value, policy);
}
/// <summary>
/// 缓存数据,指定过期时间
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expiration"></param>
public static void Set(string key, object value, DateTimeOffset expiration)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = expiration;
//policy.RemovedCallback = new CacheEntryRemovedCallback((arguments) =>
//{
// try
// {
// //第一版本的代码,先废弃掉
// string KKK = arguments.CacheItem.Key;
// if (KKK.StartsWith("UDPPackage_"))
// {
// object VVV = arguments.CacheItem.Value;
// string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
// string nnn = Newtonsoft.Json.JsonConvert.SerializeObject(VVV);
// UDPPackageCount t = (UDPPackageCount)VVV;
// UDPPackage u = new UDPPackage();
// u.CommandType = KKK;
// u.TotalCount = t.Count;
// u.RemoveTime = ti;
// string mns = Newtonsoft.Json.JsonConvert.SerializeObject(u);
// logger.Error(ti + ",UDP Package" + KKK + "," + nnn);
// CSRedisCacheHelper.redis3.Publish("redis-udppackage", mns);
// }
// }
// catch (Exception ex)
// {
// logger.Info("数量统计error" + ex.Message);
// }
//});
Set(key, value, policy);
}
private static void Set(string key, object value, CacheItemPolicy policy)
{
if (value != null)
{
_cache.Set(key, value, policy);
}
}
public static object Get(string key)
{
object result = _cache.Get(key);
return result;
}
///// <summary>
///// 获取缓存对象主机的IP地址和端口优先使用mac地址匹配
///// </summary>
///// <param name="key">主机编码</param>
///// <param name="mac">mac地址</param>
///// <returns></returns>
//public static string Get(string key, string mac)
//{
// object result = _cache.Get(mac);
// if (null == result)
// {
// result = _cache.Get(key);
// }
// return result == null ? "" : result.ToString();
//}
/// <summary>
/// 判断主机是否在缓存里优先使用mac地址匹配
/// </summary>
/// <param name="key">主机编码</param>
/// <param name="mac">mac地址</param>
/// <returns></returns>
public static bool Contains(string key, string mac)
{
bool result = _cache.Contains(mac);
if (!result)
{
return _cache.Contains(key);
}
return result;
}
}
}

156
Common/MemoryCacheUtil.cs Normal file
View File

@@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
public static class MemoryCacheUtil
{
private static readonly Object _locker = new object(), _locker2 = new object();
/// <summary>
/// 取缓存项,如果不存在则返回空
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T GetCacheItem<T>(String key)
{
try
{
return (T)MemoryCache.Default[key];
}
catch
{
return default(T);
}
}
/// <summary>
/// 是否包含指定键的缓存项
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Contains(string key)
{
return MemoryCache.Default.Contains(key);
}
/// <summary>
/// 取缓存项,如果不存在则新增缓存项
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="cachePopulate"></param>
/// <param name="slidingExpiration"></param>
/// <param name="absoluteExpiration"></param>
/// <returns></returns>
public static T GetOrAddCacheItem<T>(String key, Func<T> cachePopulate, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null)
{
if (String.IsNullOrWhiteSpace(key)) throw new ArgumentException("Invalid cache key");
if (cachePopulate == null) throw new ArgumentNullException("cachePopulate");
if (slidingExpiration == null && absoluteExpiration == null) throw new ArgumentException("Either a sliding expiration or absolute must be provided");
if (MemoryCache.Default[key] == null)
{
lock (_locker)
{
if (MemoryCache.Default[key] == null)
{
T cacheValue = cachePopulate();
if (!typeof(T).IsValueType && ((object)cacheValue) == null) //如果是引用类型且为NULL则不存缓存
{
return cacheValue;
}
var item = new CacheItem(key, cacheValue);
var policy = CreatePolicy(slidingExpiration, absoluteExpiration);
MemoryCache.Default.Add(item, policy);
}
}
}
return (T)MemoryCache.Default[key];
}
/// <summary>
/// 取缓存项,如果不存在则新增缓存项
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="cachePopulate"></param>
/// <param name="dependencyFilePath"></param>
/// <returns></returns>
public static T GetOrAddCacheItem<T>(String key, Func<T> cachePopulate, string dependencyFilePath)
{
if (String.IsNullOrWhiteSpace(key)) throw new ArgumentException("Invalid cache key");
if (cachePopulate == null) throw new ArgumentNullException("cachePopulate");
if (MemoryCache.Default[key] == null)
{
lock (_locker2)
{
if (MemoryCache.Default[key] == null)
{
T cacheValue = cachePopulate();
if (!typeof(T).IsValueType && ((object)cacheValue) == null) //如果是引用类型且为NULL则不存缓存
{
return cacheValue;
}
var item = new CacheItem(key, cacheValue);
var policy = CreatePolicy(dependencyFilePath);
MemoryCache.Default.Add(item, policy);
}
}
}
return (T)MemoryCache.Default[key];
}
/// <summary>
/// 移除指定键的缓存项
/// </summary>
/// <param name="key"></param>
public static void RemoveCacheItem(string key)
{
try
{
MemoryCache.Default.Remove(key);
}
catch
{ }
}
private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
{
var policy = new CacheItemPolicy();
if (absoluteExpiration.HasValue)
{
policy.AbsoluteExpiration = absoluteExpiration.Value;
}
else if (slidingExpiration.HasValue)
{
policy.SlidingExpiration = slidingExpiration.Value;
}
policy.Priority = CacheItemPriority.Default;
return policy;
}
private static CacheItemPolicy CreatePolicy(string filePath)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string>() { filePath }));
policy.Priority = CacheItemPriority.Default;
return policy;
}
}
}

View File

@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.IO;
namespace Common
{
/// <summary>
/// MemoryStream对象池用于高并发场景减少GC压力
/// </summary>
internal static class MemoryStreamPool
{
private static readonly ConcurrentBag<MemoryStream> pool = new ConcurrentBag<MemoryStream>();
private const int MaxPoolSize = 100;
private const int MaxStreamCapacity = 10240; // 10KB超过此大小的流不放回池中
public static MemoryStream Rent()
{
MemoryStream stream = null;
if (pool.TryTake(out stream))
{
stream.Position = 0;
stream.SetLength(0);
return stream;
}
return new MemoryStream();
}
public static void Return(MemoryStream stream)
{
if (stream != null && stream.Capacity <= MaxStreamCapacity && pool.Count < MaxPoolSize)
{
stream.Position = 0;
stream.SetLength(0);
pool.Add(stream);
}
}
}
}

283
Common/MyDes.cs Normal file
View File

@@ -0,0 +1,283 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
namespace Common
{
public static class MyDes
{
public const string AuthorizationCode = "D7CD0C3660F6A658C9668233516A5397";
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MyDes));
private static System.Security.Cryptography.DES mydes = new DESCryptoServiceProvider();
private static string m_key = "szblw_license";
private static string m_iv = "szblw_license";
private static object _lock = new object();
private static byte[] GetLegalKey()
{
string sTemp = m_key;
mydes.GenerateKey();
byte[] bytTemp = mydes.Key;
int KeyLength = bytTemp.Length;
if (sTemp.Length > KeyLength)
sTemp = sTemp.Substring(0, KeyLength);
else if (sTemp.Length < KeyLength)
sTemp = sTemp.PadRight(KeyLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
private static byte[] GetLegalIV()
{
string sTemp = m_iv;
mydes.GenerateIV();
byte[] bytTemp = mydes.IV;
int IVLength = bytTemp.Length;
if (sTemp.Length > IVLength)
sTemp = sTemp.Substring(0, IVLength);
else if (sTemp.Length < IVLength)
sTemp = sTemp.PadRight(IVLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
#region License
/// <summary>
/// 解密文件
/// </summary>
/// <param name="inFileName"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool DecodeFromFile(string inFileName, ref string result)
{
return Decode(File.ReadAllText(inFileName), ref result);
}
/// <summary>
/// 解密文件
/// </summary>
/// <param name="inFileName"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool DecodeFromStream(Stream stream, ref string result)
{
using (StreamReader reader = new StreamReader(stream))
{
return Decode(reader.ReadToEnd(), ref result);
}
}
/// <summary>
/// 解密文件
/// </summary>
/// <param name="base64License"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool Decode(string base64License, ref string result)
{
try
{
mydes.IV = GetLegalIV();
mydes.Key = GetLegalKey();
byte[] btFile = Convert.FromBase64String(base64License);
ICryptoTransform encrypto = mydes.CreateDecryptor();
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream encStream = new CryptoStream(mStream, encrypto, CryptoStreamMode.Write))
{
encStream.Write(btFile, 0, btFile.Length);
encStream.FlushFinalBlock();
result = Encoding.UTF8.GetString(mStream.ToArray());
}
}
}
catch (Exception ex)
{
result = "解密文件失败!原因:" + ex.Message;
if (logger.IsErrorEnabled)
{
logger.Error(result, ex);
}
return false;
}
return true;
}
#endregion
#region License
/// <summary>
/// 每次登录验证验证成功时修改License文件的最后写入时间
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
public static bool Validate(ref string result)
{
string file = GetLicensePath();
if (!System.IO.File.Exists(file))
{
result = "授权文件不存在!";
return false;
}
string strLicense = "";
if (!DecodeFromFile(file, ref strLicense))
{
result = "无效的授权文件!";
return false;
}
bool ret = Validate(strLicense, ref result);
if (ret)
{
File.SetLastWriteTime(file, DateTime.Now);
}
return ret;
}
/// <summary>
/// 导入授权文件验证
/// </summary>
/// <param name="licenseStream"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool ImportValidate(Stream licenseStream, ref string result)
{
string strLicense = "";
if (!Common.MyDes.DecodeFromStream(licenseStream, ref strLicense))
{
result = "无效的授权文件!";
return false;
}
return Validate(strLicense, ref result);
}
/// <summary>
/// 验证 License文件
/// </summary>
/// <param name="strLicense"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool Validate(string strLicense, ref string result)
{
License license = ReadLicense(strLicense);
if (license == null)
{
result = "无效的授权文件!";
return false;
}
if (license.SystemTypeID != 0)
{
result = "授权文件不匹配本系统!";
return false;
}
//判断授权文件上的机器码是否符合当前电脑的机器码如机器码是12个0不做校验
if (license.MAC != Tools.GetMachineCode())
{
result = "机器码与授权文件不匹配!";
return false;
}
DateTime now = GetServerDate();
if (now < license.StartDate || now > license.EndDate)
{
result = "授权到期!";
return false;
}
result = "验证成功!";
return true;
}
private static DateTime GetServerDate()
{
DateTime nowDate = DateTime.Now.Date;
string file = GetLicensePath();
if (!File.Exists(file))
{
return nowDate;
}
DateTime fileTime = File.GetLastWriteTime(file);
if (fileTime > DateTime.Now)
{
return fileTime.Date;
}
return nowDate;
}
#endregion
public static License GetLicense()
{
string result = "";
if (DecodeFromFile(GetLicensePath(), ref result))
{
return ReadLicense(result);
}
return null;
}
public static string GetLicensePath()
{
return Tools.GetApplicationPath() + @"License\blw-t3s.lic";
}
public static License ReadLicense(string strLicense)
{
try
{
lock (_lock)
{
if (strLicense.Contains("<?"))
{
strLicense = strLicense.Substring(strLicense.IndexOf('>') + 1);//去掉xml header
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(strLicense);
XmlNode data = doc.DocumentElement.GetElementsByTagName("data")[0];
License license = new License()
{
ID = data.Attributes["id"].Value,
CustomerID = data.Attributes["customerid"].Value,
Customer = data.Attributes["customer"].Value,
SN = data.Attributes["sn"].Value,
Key = data.Attributes["key"].Value,
MAC = data.Attributes["mac"].Value,
Limit = Convert.ToInt32(data.Attributes["limit"].Value),
StartDate = Convert.ToDateTime(data.Attributes["start"].Value),
EndDate = Convert.ToDateTime(data.Attributes["end"].Value),
SystemTypeID = Convert.ToInt32(data.Attributes["systemtypeid"].Value)
};
data = null;
doc = null;
GC.Collect();
return license;
}
}
catch (Exception ex)
{
logger.Error(string.Format("读取license失败{0}", ex.ToString()));
return null;
}
}
}
public class License
{
public string ID { get; set; }
public string CustomerID { get; set; }
public string Customer { get; set; }
public string SN { get; set; }
public string Key { get; set; }
public string MAC { get; set; }
public int Limit { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int SystemTypeID { get; set; }
}
}

View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Common
{
public class NPOIMemoryStream : MemoryStream
{
public NPOIMemoryStream()
{
AllowClose = true;
}
public bool AllowClose { get; set; }
public override void Close()
{
if (AllowClose)
{
base.Close();
}
}
}
}

17
Common/OnOffLineData.cs Normal file
View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common
{
public class OnOffLineData
{
public string HotelCode { get; set; }
public string MAC { get; set; }
public string HostNumber { get; set; }
public string EndPoint { get; set; }
public string CurrentStatus { get; set; }
public DateTime CurrentTime { get; set; }
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Common")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("35ffd210-94b7-4b20-a729-7cb77962cfaa")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="DataSet" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>System.Data.DataSet, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</TypeInfo>
</GenericObjectDataSource>

311
Common/ProtocalData.cs Normal file
View File

@@ -0,0 +1,311 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace Common
{
public static class ProtocalData
{
/// <summary>
/// 获取子群数据
/// </summary>
/// <param name="subGroupNode"></param>
/// <returns></returns>
public static List<List<byte>> GetSubgroupSendData(XmlNode subGroupNode)
{
List<List<byte>> sendDatas = new List<List<byte>>();
int totalFrame = subGroupNode.ChildNodes.Count + 3;//补上配置xml文件版本号、配置数据版本号和全局属性数据
List<object> textData;
//=============1、新增配置xml文件版本号=======================
sendDatas.Add(GetSendData(GetVersionSendData(subGroupNode.Attributes["SettingVersion"].Value), 0xA9, totalFrame, 1));
//=============2、配置数据版本号===========================
sendDatas.Add(GetSendData(GetVersionSendData(subGroupNode.Attributes["Version"].Value), 0xA5, totalFrame, 2));
//=============3、全局属性数据=================================
sendDatas.Add(GetSendData(GetGlobalSendData(subGroupNode), 0xA3, totalFrame, 3));
//=============4、设备和动作数据=============================
for (int i = 0; i < subGroupNode.ChildNodes.Count; i++)
{
XmlNode detailNode = subGroupNode.ChildNodes[i];
textData = new List<object>();
textData.Add(detailNode.Attributes["Type"].Value);//类型
int paramCount = Convert.ToInt16(detailNode.Attributes["ParamCount"].Value);
switch (Convert.ToInt16(detailNode.Attributes["Type"].Value))
{
case 0://设备
textData.Add(detailNode.Attributes["DeviceAddress"].Value.Split('.')[0]);//设备地址第一位
textData.Add(detailNode.Attributes["DeviceAddress"].Value.Split('.')[1]);//设备地址第二位
textData.Add(detailNode.Attributes["DeviceAddress"].Value.Split('.')[2]);//设备地址第三位
for (int j = 1; j <= paramCount; j++)
{
//设备类型、输入回路数,输出回路数为两位字节
switch (j)
{
case 7:
case 8:
textData.Add("DeviceAddr");//标记一下,为了转为两位字节
textData.Add(detailNode.Attributes["Param" + j.ToString()].Value);
break;
default:
textData.Add(detailNode.Attributes["Param" + j.ToString()].Value);
break;
}
}
break;
case 1://动作
textData.Add(detailNode.Attributes["DeviceAddress"].Value.Split('.')[0]);//设备地址第一位
textData.Add(detailNode.Attributes["DeviceAddress"].Value.Split('.')[1]);//设备地址第二位
textData.Add(detailNode.Attributes["DeviceAddress"].Value.Split('.')[2]);//设备地址第三位
for (int j = 1; j <= paramCount; j++)
{
//设备类型、输入地址为两位字节
switch (j)
{
case 4:
textData.Add("DeviceAddr");//标记一下,为了转为两位字节
textData.Add(detailNode.Attributes["Param" + j.ToString()].Value);
break;
default:
textData.Add(detailNode.Attributes["Param" + j.ToString()].Value);
break;
}
}
//扩展属性
foreach (XmlNode expandNode in detailNode.ChildNodes)
{
paramCount = Convert.ToInt16(expandNode.Attributes["ParamCount"].Value);
for (int j = 1; j <= paramCount; j++)
{
switch (j)
{
case 1:
case 2:
case 4://延时执行内容
case 5://延时执行单位
textData.Add(expandNode.Attributes["Param" + j.ToString()].Value);
break;
default:
//扩展属性都为两位字节
textData.Add("DeviceAddr");//标记一下,为了转为两位字节
textData.Add(expandNode.Attributes["Param" + j.ToString()].Value);
break;
}
}
//扩展属性的输出类型
int outTypeParamCount = Convert.ToInt16(expandNode.Attributes["OutTypeParamCount"].Value);
switch (outTypeParamCount)
{
case 1:
textData.Add("DeviceAddr");//标记一下,为了转为两位字节
textData.Add(expandNode.Attributes["Param" + (paramCount + 1).ToString()].Value);
break;
case 2:
textData.Add(expandNode.Attributes["Param" + (paramCount + 1).ToString()].Value);
textData.Add(expandNode.Attributes["Param" + (paramCount + 2).ToString()].Value);
break;
case 3://背景音乐
textData.Add("DeviceAddr");//标记一下,为了转为两位字节
textData.Add((Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 1).ToString()].Value) << 0) +
(Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 2).ToString()].Value) << 12) +
(Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 3).ToString()].Value) << 8));
break;
case 4://地暖
textData.Add("DeviceAddr");//标记一下,为了转为两位字节
textData.Add((Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 1).ToString()].Value) << 12) +
(Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 2).ToString()].Value) << 8) +
(Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 3).ToString()].Value) << 6) +
Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 4).ToString()].Value));
break;
case 5://空调
textData.Add("DeviceAddr");//标记一下,为了转为两位字节
textData.Add((Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 1).ToString()].Value) << 14) +
(Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 2).ToString()].Value) << 12) +
(Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 3).ToString()].Value) << 10) +
(Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 4).ToString()].Value) << 8) +
Convert.ToInt16(expandNode.Attributes["Param" + (paramCount + 5).ToString()].Value));
break;
}
}
break;
case 2://MQTT映射去掉组地址、设备地址增加别名长度20
string deviceType2 = detailNode.Attributes["DeviceType"].Value;
textData.Add(deviceType2);
textData.Add(detailNode.Attributes["Param1"].Value);
if ("0" == deviceType2)
{
textData.Add(0x00);
textData.Add(detailNode.Attributes["Param2"].Value);
}
else
{
textData.Add("DeviceAddr");//标记一下,为了转为两位字节
textData.Add(detailNode.Attributes["Param2"].Value);
}
//paramCount = Convert.ToInt16(detailNode.Attributes["ParamCount"].Value);
//for (int j = 1; j <= paramCount; j++)
//{
// textData.Add(detailNode.Attributes["Param" + j.ToString()].Value);
//}
byte[] nameBGK = Encoding.GetEncoding("GBK").GetBytes(detailNode.Attributes["Name"].Value);
foreach (byte b in nameBGK)
{
textData.Add(b);
}
for (int j = nameBGK.Length; j < 20; j++)//不足20位补0
{
textData.Add(0x00);
}
break;
case 3://BLW映射
textData.Add(detailNode.Attributes["GroupAddress"].Value);
textData.Add(detailNode.Attributes["DeviceAddress"].Value);
string deviceType3 = detailNode.Attributes["DeviceType"].Value;
textData.Add(deviceType3);
textData.Add(detailNode.Attributes["Param1"].Value);
if ("0" == deviceType3)
{
textData.Add(0x00);
textData.Add(detailNode.Attributes["Param2"].Value);
}
else
{
textData.Add("DeviceAddr");//标记一下,为了转为两位字节
textData.Add(detailNode.Attributes["Param2"].Value);
}
//textData.Add(detailNode.Attributes["DeviceType"].Value);
//paramCount = Convert.ToInt16(detailNode.Attributes["ParamCount"].Value);
//for (int j = 1; j <= paramCount; j++)
//{
// textData.Add(detailNode.Attributes["Param" + j.ToString()].Value);
//}
break;
}
//每一组设备地址发送数据加入集合
sendDatas.Add(GetSendData(textData, 0xA2, totalFrame, (i + 4)));//组地址等属性
}
return sendDatas;
}
/// <summary>
/// 按所定义的格式获取与RCU主机通讯的数据
/// </summary>
/// <param name="textData">数据内容</param>
/// <param name="mode">模式:时间同步A0组地址调试A1子群发布A2全局属性A3V80复位开关A4配置数据版本号A5485调光A6网络设置A7</param>
/// <param name="totalFrame">数据总帧数</param>
/// <param name="currentFrame">当前帧数</param>
/// <returns></returns>
private static List<byte> GetSendData(List<object> textData, byte mode, Int32 totalFrame, Int32 currentFrame)
{
//发送数据
//byte[] demoData = new byte[] {
// 0xF0, 0x0F, //数据头
// 0xA1, //调试模式
// 0x00, 0x2C, //数据总长度
// 0x00, 0x01, //数据总帧数
// 0x00, 0x01, //当前帧数
// 0x54, 0x33, 0x53, 0x41, //识别码T3SA
// 0x01, 0x01, 0x02, //组地址属性
// 0x01, 0x00, 0x23, 0x01, 0x00, 0x00, 0x00, 0x02, //弱电输入
// 0x01, 0x01, 0x09, 0x01, 0xFF, 0x03, 0x00, 0x00, 0xFF, //弱电输出
// 0x01, 0x02, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, //强电输出
// 0x57, 0xDA //CRC16校验
//};
List<byte> sendData = new List<byte>();
sendData.Add(0xF0);//数据头
sendData.Add(0x0F);//数据头
sendData.Add(mode);//调试模式
//数据总长度除了前面2位数据头其他都算
byte[] dataLen = Tools.Int32ToByte(textData.Count + 13);
foreach (byte b in dataLen)
{
sendData.Add(b);
}
//数据总帧数
dataLen = Tools.Int32ToByte(totalFrame);
foreach (byte b in dataLen)
{
sendData.Add(b);
}
//当前帧数
dataLen = Tools.Int32ToByte(currentFrame);
foreach (byte b in dataLen)
{
sendData.Add(b);
}
sendData.Add(0x54);//识别码T3SA
sendData.Add(0x33);//识别码T3SA
sendData.Add(0x53);//识别码T3SA
sendData.Add(0x41);//识别码T3SA
bool isToByte = false;
foreach (object obj in textData)
{
//遇到“DeviceAddr”标记则改成2个byte
if (Convert.ToString(obj) == "DeviceAddr")
{
isToByte = true;
}
else
{
if (isToByte)
{
dataLen = Tools.Int32ToByte2(Convert.ToInt32(obj));//小端
foreach (byte b in dataLen)
{
sendData.Add(b);
}
isToByte = false;
}
else
{
sendData.Add(byte.Parse(obj.ToString()));
}
}
}
ushort crc = Tools.CRC16(sendData.ToArray(), sendData.Count);
sendData.Add(Convert.ToByte(crc & 0xFF));//CRC16校验
sendData.Add(Convert.ToByte((crc >> 8) & 0xFF));//CRC16校验
return sendData;
}
/// <summary>
/// 获取配置数据版本号发送数据version为空时提供默认值FF,FF,FF
/// </summary>
/// <param name="version"></param>
/// <returns></returns>
private static List<object> GetVersionSendData(string version)
{
List<object> textData = new List<object>();
if (string.IsNullOrEmpty(version))
{
textData.Add(0xFF);
textData.Add(0xFF);
textData.Add(0xFF);
}
else
{
textData.Add(version.Split('.')[0]);
textData.Add(version.Split('.')[1]);
textData.Add(version.Split('.')[2]);
}
return textData;
}
/// <summary>
/// 获取子群全局属性发送数据
/// </summary>
/// <param name="projectGroupAddrID">子群ID</param>
/// <param name="projectID">项目ID</param>
/// <returns></returns>
private static List<object> GetGlobalSendData(XmlNode subGroupNode)
{
List<object> textData = new List<object>();
int paramCount = Convert.ToInt16(subGroupNode.Attributes["ParamCount"].Value);
for (int j = 1; j <= paramCount; j++)
{
textData.Add(subGroupNode.Attributes["Param" + j.ToString()].Value);
}
return textData;
}
}
}

51
Common/RateLimiter.cs Normal file
View File

@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Threading;
namespace Common
{
public class RateLimiter
{
private static readonly object lockObject = new object();
private static readonly int requestsPerSecond = 5;//每秒允许请求5次
private static int remainingRequests;//剩余请求次数
private static long lastRequestTime;//上次请求时间
/// <summary>
/// 实现速率限制。它根据指定的每秒请求数量来控制请求是否被允许
/// </summary>
static RateLimiter()
{
remainingRequests = requestsPerSecond;
lastRequestTime = DateTime.UtcNow.Ticks;
}
/// <summary>
/// 实现速率限制默认每秒允许请求5次
/// </summary>
/// <returns></returns>
public static bool TryRequest()
{
lock (lockObject)
{
long currentTime = DateTime.UtcNow.Ticks;//当前请求时间
long elapsedTicks = currentTime - lastRequestTime;
double elapsedSeconds = elapsedTicks / TimeSpan.TicksPerSecond;
remainingRequests += (int)(elapsedSeconds * requestsPerSecond);
if (remainingRequests > requestsPerSecond)
{
remainingRequests = requestsPerSecond;
}
if (remainingRequests > 0)
{
remainingRequests--;
lastRequestTime = currentTime;
return true;
}
return false;
}
}
}
}

64
Common/RokidOperation.cs Normal file
View File

@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common
{
/// <summary>
/// 若琪对接
/// </summary>
public static class RokidOperation
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(RokidOperation));
//private static string rokid_url = "https://homebase.rokid.com/trigger/with/4GoVytuQZ";
/// <summary>
/// 通知若琪播报欢迎词
/// </summary>
/// <param name="hotelName"></param>
/// <param name="roomNumber"></param>
/// <param name="webhookUrl"></param>
/// <param name="message"></param>
public static void UploadWebhook(string hotelName, string roomNumber, string webhookUrl, string message)
{
if (!string.IsNullOrEmpty(webhookUrl) && !string.IsNullOrEmpty(message))
{
RokidWebhook postData = new RokidWebhook()
{
type = "tts",
devices = new DeviceQuery() { roomName = roomNumber },
data = new RokidObject() { text = message }
};
try
{
string param = Newtonsoft.Json.JsonConvert.SerializeObject(postData);
string result = HttpWebRequestHelper.PostWebRequest(webhookUrl, param);
}
catch (Exception ex)
{
logger.Error(string.Format("酒店({0})客房({1})调用若琪接口({2})失败:{3}", hotelName, roomNumber, webhookUrl, ex));
}
}
}
}
internal class RokidWebhook
{
public string type { get; set; }
public DeviceQuery devices { get; set; }
public RokidObject data { get; set; }
}
internal class DeviceQuery
{
//public string sn { get; set; }
public string roomName { get; set; }
//public string tag { get; set; }
//public bool isAll { get; set; }
}
internal class RokidObject
{
public string text { get; set; }
}
}

103
Common/SQLHelper.cs Normal file
View File

@@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace Common
{
public static class SqlHelper
{
//连接字符串
private static readonly string connStr = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
/// <summary>
/// 1.执行增、删、改的方法ExecuteNonQuery
/// </summary>
/// <param name="sql"></param>
/// <param name="pms"></param>
/// <returns></returns>
public static int ExecuteNonQuery(string sql, params SqlParameter[] pms)
{
using (SqlConnection con = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// 2.封装一个执行返回单个对象的方法ExecuteScalar()
/// </summary>
/// <param name="sql"></param>
/// <param name="pms"></param>
/// <returns></returns>
public static object ExecuteScalar(string sql, params SqlParameter[] pms)
{
using (SqlConnection con = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteScalar();
}
}
}
/// <summary>
/// 3.执行查询多行多列的数据的方法ExecuteReader
/// </summary>
/// <param name="sql"></param>
/// <param name="pms"></param>
/// <returns></returns>
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms)
{
SqlConnection con = new SqlConnection(connStr);
using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
try
{
con.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception)
{
con.Close();
con.Dispose();
throw;
}
}
}
/// <summary>
/// 4.执行返回DataTable的方法
/// </summary>
/// <param name="sql"></param>
/// <param name="pms"></param>
/// <returns></returns>
public static DataTable ExecuteDataTable(string sql, params SqlParameter[] pms)
{
DataTable dt = new DataTable();
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, connStr))
{
if (pms != null)
{
adapter.SelectCommand.Parameters.AddRange(pms);
}
adapter.Fill(dt);
}
return dt;
}
}
}

View File

@@ -0,0 +1,30 @@
// 简易对象池
using System.Collections.Concurrent;
using System.IO;
public class SimpleMemoryStreamPool
{
private static readonly ConcurrentBag<MemoryStream> _pool = new ConcurrentBag<MemoryStream>();
private const int MaxPoolSize = 50;
public static MemoryStream Rent(int capacity = 1024)
{
MemoryStream stream;
if (_pool.TryTake(out stream))
{
stream.SetLength(0);
stream.Position = 0;
return stream;
}
return new MemoryStream(capacity);
}
public static void Return(MemoryStream stream)
{
if (stream != null && _pool.Count < MaxPoolSize)
{
stream.SetLength(0);
stream.Position = 0;
_pool.Add(stream);
}
}
}

87
Common/StructConverter.cs Normal file
View File

@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Common
{
public sealed class StructConverter
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(StructConverter));
public static int SizeOf(object structObj)
{
unsafe { return Marshal.SizeOf(structObj); }
}
public static int SizeOf(Type type)
{
return Marshal.SizeOf(type);
}
public static int SizeOf<T>()
{
return Marshal.SizeOf(typeof(T));
}
/// <summary>
/// 结构体转成字节数组
/// </summary>
/// <param name="structObj"></param>
/// <returns></returns>
public static byte[] StructToBytes(object structObj)
{
int size = SizeOf(structObj);
byte[] bytes = new byte[size];
IntPtr structPtr = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structObj, structPtr, false);
Marshal.Copy(structPtr, bytes, 0, size);
}
finally
{
Marshal.FreeHGlobal(structPtr);
}
return bytes;
}
/// <summary>
/// 字节数组转成结构体
/// </summary>
/// <param name="bytes"></param>
/// <param name="type"></param>
/// <returns></returns>
public static object BytesToStruct(byte[] bytes, Type type)
{
return BytesToStruct(bytes, 0, type);
}
/// <summary>
/// 字节数组转成结构体
/// </summary>
/// <param name="bytes"></param>
/// <param name="startIndex"></param>
/// <param name="type"></param>
/// <returns></returns>
public static object BytesToStruct(byte[] bytes, int startIndex, Type type)
{
object structObj = null;
int size = Marshal.SizeOf(type);
if (startIndex < 0 || startIndex >= bytes.Length || size > bytes.Length)
{
return null;
}
IntPtr structPtr = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, startIndex, structPtr, size);
structObj = Marshal.PtrToStructure(structPtr, type);
}
finally
{
Marshal.FreeHGlobal(structPtr);
}
return structObj;
}
}
}

158
Common/SyncRoomStatus.cs Normal file
View File

@@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace Common
{
public sealed class SyncRoomStatus
{
//private static object _lock = new object();
///// <summary>
///// 重置回路当天开启时长
///// </summary>
//public static void SyncRoomStatus(string codes)
//{
// //using (IDbConnection connection = new SqlConnection(AppUtils.GetConnectingString()))
// //using (IDbCommand command = connection.CreateCommand())
// //{
// // connection.Open();
// // //command.CommandType = CommandType.Text;
// // //command.CommandText = "UPDATE tb_HostModal SET [Time]=0,UpdateTime=GETDATE()";
// // command.CommandType = CommandType.StoredProcedure;
// // command.CommandText = "UpdateHostModalRecords";
// // command.ExecuteNonQuery();
// //}
// lock (_lock)
// {
// foreach (string code in codes.Split(','))//遍历多家酒店需要与PMS同步房态
// {
// //DataTable dtHotel = _client.GetHotelByCode(code);
// DataSet ds = _client.GetCheckInOrOutRecord(code);
// if (ds != null && ds.Tables.Count > 2)
// {
// int hotelID = Convert.ToInt16(ds.Tables[3].Rows[0]["HotelID"].ToString());//与PMS同步接口所配置的HotelID
// using (IDbConnection connection = new SqlConnection(AppUtils.GetConnectingString()))
// using (IDbCommand command = connection.CreateCommand())
// {
// connection.Open();
// command.CommandType = System.Data.CommandType.Text;
// //新开房记录
// foreach (DataRow dr in ds.Tables[0].Rows)
// {
// //更新RICS房态出租2
// SyncRoomStatus(hotelID, command, dr, 2, 0);
// }
// //新退房记录
// foreach (DataRow dr in ds.Tables[1].Rows)
// {
// //更新RICS房态退房8
// SyncRoomStatus(hotelID, command, dr, 8, 1);
// }
// //新待租记录
// foreach (DataRow dr in ds.Tables[2].Rows)
// {
// //更新RICS房态待租4
// SyncRoomStatus(hotelID, command, dr, 4, 2);
// }
// }
// }
// }
// //判断已插卡取电但尚未开房5分钟后上报报警数据给金天鹅PMS
// //Group group = GroupManager.Load(21);
// //IList<Host> hosts = HostManager.LoadAll(group);
// //foreach (Host host in hosts)
// //{
// // IList<HostRoomCard> hostRoomCards = HostRoomCardManager.LoadAll(host.RoomNumber, "");
// // if (hostRoomCards != null && hostRoomCards.Count > 0)
// // {
// // XmlDocument xmlDoc = new XmlDocument();
// // xmlDoc.LoadXml(_client1.GethHotelcode("宝来客控对接酒店"));
// // XmlElement element = xmlDoc.DocumentElement;
// // string hotelCode = element.GetElementsByTagName("Body")[0].ChildNodes[0].ChildNodes[0].InnerText;//"HOTEL1489374686";
// // xmlDoc = new XmlDocument();
// // XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");//创建类型声明节点
// // xmlDoc.AppendChild(node);
// // XmlNode root = xmlDoc.CreateElement("request");
// // xmlDoc.AppendChild(root);
// // XmlNode card = xmlDoc.CreateElement("Alarm");
// // root.AppendChild(card);
// // XmlNode data = xmlDoc.CreateNode(XmlNodeType.Element, "hotelCode", null);
// // data.InnerText = hotelCode;//酒店代码
// // card.AppendChild(data);
// // data = xmlDoc.CreateNode(XmlNodeType.Element, "roomno", null);
// // data.InnerText = host.RoomNumber;//房间号
// // card.AppendChild(data);
// // data = xmlDoc.CreateNode(XmlNodeType.Element, "remark", null);
// // data.InnerText = "";//备注
// // card.AppendChild(data);
// // data = xmlDoc.CreateNode(XmlNodeType.Element, "state", null);
// // HostRoomCard hostRoomCard = hostRoomCards[hostRoomCards.Count - 1];
// // if (host.RoomStatus.ID != 2 && host.RoomCard != null)
// // {
// // if ((hostRoomCard.IsAlarm == null || hostRoomCard.IsAlarm == false) &&
// // Convert.ToDateTime(hostRoomCard.InCardTime).AddMinutes(5) <= DateTime.Now)
// // {
// // data.InnerText = "1";//报警
// // card.AppendChild(data);
// // data = xmlDoc.CreateNode(XmlNodeType.Element, "key", null);
// // data.InnerText = "Wide_Third";//授权码
// // card.AppendChild(data);
// // //string result = _client1.send(xmlDoc.InnerXml);
// // logger.Error(xmlDoc.InnerXml);//result + Environment.NewLine +
// // hostRoomCard.IsAlarm = true;
// // HostRoomCardManager.Update(hostRoomCard);
// // }
// // }
// // else if (hostRoomCard.IsAlarm == true)
// // {
// // data.InnerText = "0";//取消报警
// // card.AppendChild(data);
// // data = xmlDoc.CreateNode(XmlNodeType.Element, "key", null);
// // data.InnerText = "Wide_Third";//授权码
// // card.AppendChild(data);
// // //string result = _client1.send(xmlDoc.InnerXml);
// // logger.Error(xmlDoc.InnerXml);//result + Environment.NewLine +
// // hostRoomCard.IsAlarm = false;
// // HostRoomCardManager.Update(hostRoomCard);
// // }
// // }
// //}
// }
//}
///// <summary>
///// 同步房态
///// </summary>
///// <param name="hotelID">酒店ID</param>
///// <param name="command"></param>
///// <param name="dr"></param>
///// <param name="roomStatusID">房态ID</param>
///// <param name="flag">更新字段标记</param>
//private static void SyncRoomStatus(int hotelID, IDbCommand command, DataRow dr, int roomStatusID, int flag)
//{
// _client.UpdateCheckInOrOutRecord(dr["Code"].ToString(), Convert.ToInt64(dr["ID"]), flag);//更新已同步状态
// string sql = "select id from tb_Hosts where HotelID=" + hotelID + " + and RoomNumber='" + dr["RoomNumber"].ToString() + "'";
// command.CommandText = sql;
// using (IDataReader reader = command.ExecuteReader())
// {
// reader.Read();
// if (reader[0] != null)
// {
// Host host = HostManager.Get(reader[0]);
// RoomStatus roomStatus = RoomStatusManager.Get(roomStatusID);
// HostManager.ChangeRoomStatus(host, roomStatus);
// }
// }
//}
}
}

419
Common/TFTPclient.cs Normal file
View File

@@ -0,0 +1,419 @@
#region COPYRIGHT (c) 2007 by Matthias Fischer
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//
// This material may not be duplicated in whole or in part, except for
// personal use, without the express written consent of the author.
//
// Autor: Matthais Fischer
// Email: mfischer@comzept.de
//
// Copyright (C) 2007 Matthias Fischer. All Rights Reserved.
#endregion
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Comzept.Genesis.NetworkTools
{
/// <summary>
/// Implementation of Basic TFTP Client Functions
/// </summary>
public class TFTPClient
{
#region -=[ Declarations ]=-
/// <summary>
/// TFTP opcodes
/// </summary>
public enum Opcodes
{
Unknown = 0,
Read = 1,
Write = 2,
Data = 3,
Ack = 4,
Error = 5
}
/// <summary>
/// TFTP modes
/// </summary>
public enum Modes
{
Unknown = 0,
NetAscii = 1,
Octet = 2,
Mail = 3
}
/// <summary>
/// <20><><EFBFBD><EFBFBD><E6B4AB><EFBFBD><EFBFBD><EFBFBD>ɽ<EFBFBD><C9BD><EFBFBD><EFBFBD>¼<EFBFBD>ί<EFBFBD><CEAF>
/// </summary>
/// <param name="completedBlock"><3E><><EFBFBD><EFBFBD><EFBFBD>ɴ<EFBFBD><C9B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD></param>
/// <param name="totalBlock"><3E>ܿ<EFBFBD><DCBF><EFBFBD></param>
public delegate void ReportCompletedProgressEventDelegate(string remoteIP, int completedBlock, int totalBlock);
/// <summary>
/// A TFTP Exception
/// </summary>
public class TFTPException : Exception
{
public string ErrorMessage = "";
public int ErrorCode = -1;
/// <summary>
/// Initializes a new instance of the <see cref="TFTPException"/> class.
/// </summary>
/// <param name="errCode">The err code.</param>
/// <param name="errMsg">The err MSG.</param>
public TFTPException(int errCode, string errMsg)
{
ErrorCode = errCode;
ErrorMessage = errMsg;
}
/// <summary>
/// Creates and returns a string representation of the current exception.
/// </summary>
/// <returns>
/// A string representation of the current exception.
/// </returns>
/// <filterPriority>1</filterPriority>
/// <permissionSet class="System.Security.permissionSet" version="1">
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" PathDiscovery="*AllFiles*"/>
/// </permissionSet>
public override string ToString()
{
return String.Format("TFTPException: ErrorCode: {0} Message: {1}", ErrorCode, ErrorMessage);
}
}
private int tftpPort;
private string tftpServer = "";
private int blockSize = 512;
#endregion
#region -=[ Ctor ]=-
/// <summary>
/// Initializes a new instance of the <see cref="TFTPClient"/> class.
/// </summary>
/// <param name="server">The server.</param>
public TFTPClient(string server)
: this(server, 69)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TFTPClient"/> class.
/// </summary>
/// <param name="server">The server.</param>
/// <param name="port">The port.</param>
public TFTPClient(string server, int port)
{
Server = server;
Port = port;
}
#endregion
#region -=[ Public Properties ]=-
/// <summary>
/// Gets the port.
/// </summary>
/// <value>The port.</value>
public int Port
{
get { return tftpPort; }
private set { tftpPort = value; }
}
/// <summary>
/// Gets the server.
/// </summary>
/// <value>The server.</value>
public string Server
{
get { return tftpServer; }
private set { tftpServer = value; }
}
/// <summary>
/// <20><><EFBFBD><EFBFBD>С
/// </summary>
public int BlockSize
{
get { return this.blockSize; }
private set { this.blockSize = value; }
}
#endregion
#region -=[ Events ]=-
public event ReportCompletedProgressEventDelegate ReportCompletedProgress;
#endregion
#region -=[ Public Member ]=-
/// <summary>
/// Gets the specified remote file.
/// </summary>
/// <param name="remoteFile">The remote file.</param>
/// <param name="localFile">The local file.</param>
public void Get(string remoteFile, string localFile)
{
Get(remoteFile, localFile, Modes.Octet);
}
/// <summary>
/// Gets the specified remote file.
/// </summary>
/// <param name="remoteFile">The remote file.</param>
/// <param name="localFile">The local file.</param>
/// <param name="tftpMode">The TFTP mode.</param>
public void Get(string remoteFile, string localFile, Modes tftpMode)
{
int len = 0;
int packetNr = 1;
byte[] sndBuffer = CreateRequestPacket(Opcodes.Read, remoteFile, tftpMode);
byte[] rcvBuffer = new byte[516];
BinaryWriter fileStream = new BinaryWriter(new FileStream(localFile, FileMode.Create, FileAccess.Write, FileShare.Read));
//IPHostEntry hostEntry = Dns.GetHostEntry(tftpServer);
//IPEndPoint serverEP = new IPEndPoint(hostEntry.AddressList[0], tftpPort);
IPEndPoint serverEP = new IPEndPoint(IPAddress.Parse(tftpServer), tftpPort);
EndPoint dataEP = (EndPoint)serverEP;
Socket tftpSocket = new Socket(serverEP.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
// Request and Receive first Data Packet From TFTP Server
tftpSocket.SendTo(sndBuffer, sndBuffer.Length, SocketFlags.None, serverEP);
tftpSocket.ReceiveTimeout = 10000;
len = tftpSocket.ReceiveFrom(rcvBuffer, ref dataEP);
// keep track of the TID
serverEP.Port = ((IPEndPoint)dataEP).Port;
while (true)
{
// handle any kind of error
if (((Opcodes)rcvBuffer[1]) == Opcodes.Error)
{
fileStream.Close();
tftpSocket.Close();
throw new TFTPException(((rcvBuffer[2] << 8) & 0xff00) | rcvBuffer[3], Encoding.ASCII.GetString(rcvBuffer, 4, rcvBuffer.Length - 5).Trim('\0'));
}
// expect the next packet
if ((((rcvBuffer[2] << 8) & 0xff00) | rcvBuffer[3]) == packetNr)
{
// Store to local file
fileStream.Write(rcvBuffer, 4, len - 4);
// Send Ack Packet to TFTP Server
sndBuffer = CreateAckPacket(packetNr++);
tftpSocket.SendTo(sndBuffer, sndBuffer.Length, SocketFlags.None, serverEP);
}
// Was ist the last packet ?
if (len < 516)
{
break;
}
else
{
// Receive Next Data Packet From TFTP Server
len = tftpSocket.ReceiveFrom(rcvBuffer, ref dataEP);
}
}
// Close Socket and release resources
tftpSocket.Close();
fileStream.Close();
}
/// <summary>
/// Puts the specified remote file.
/// </summary>
/// <param name="remoteFile">The remote file.</param>
/// <param name="localFile">The local file.</param>
public void Put(string remoteFile, string localFile)
{
Put(remoteFile, localFile, Modes.Octet);
}
/// <summary>
/// Puts the specified remote file.
/// </summary>
/// <param name="remoteFile">The remote file.</param>
/// <param name="localFile">The local file.</param>
/// <param name="tftpMode">The TFTP mode.</param>
/// <remarks>What if the ack does not come !</remarks>
public void Put(string remoteFile, string localFile, Modes tftpMode)
{
int len = 0;
byte[] sndBuffer = CreateRequestPacket(Opcodes.Write, remoteFile, tftpMode);
byte[] rcvBuffer = new byte[516];
BinaryReader fileStreamReader = new BinaryReader(new FileStream(localFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
//IPHostEntry hostEntry = Dns.GetHostEntry(tftpServer);
//IPEndPoint serverEP = new IPEndPoint(hostEntry.AddressList[0], tftpPort);
IPEndPoint serverEP = new IPEndPoint(IPAddress.Parse(tftpServer), tftpPort);
EndPoint dataEP = (EndPoint)serverEP;
Socket tftpSocket = new Socket(serverEP.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
// Request Writing to TFTP Server
tftpSocket.SendTo(sndBuffer, sndBuffer.Length, SocketFlags.None, serverEP);
len = tftpSocket.ReceiveFrom(rcvBuffer, ref dataEP);
tftpSocket.ReceiveTimeout = 5000;
// keep track of the TID
serverEP.Port = ((IPEndPoint)dataEP).Port;
int tryCount = 5;
int packetTl = (int)Math.Ceiling((double)fileStreamReader.BaseStream.Length / this.blockSize);
for (int packetNr = 1; packetNr <= packetTl; packetNr++)
{
// handle any kind of error
if (((Opcodes)rcvBuffer[1]) == Opcodes.Error)
{
fileStreamReader.Close();
tftpSocket.Close();
throw new TFTPException(((rcvBuffer[2] << 8) & 0xff00) | rcvBuffer[3], Encoding.ASCII.GetString(rcvBuffer, 4, rcvBuffer.Length - 5).Trim('\0'));
}
// expect the next packet ack
if ((((Opcodes)rcvBuffer[1]) == Opcodes.Ack) &&
(((rcvBuffer[2] << 8) & 0xff00) | rcvBuffer[3]) == (packetNr - 1))
{
fileStreamReader.BaseStream.Seek((packetNr - 1) * blockSize, SeekOrigin.Begin);
sndBuffer = CreateDataPacket(packetNr, fileStreamReader.ReadBytes(512));
tftpSocket.SendTo(sndBuffer, sndBuffer.Length, SocketFlags.None, serverEP);
}
if (ReportCompletedProgress != null)
{
ReportCompletedProgress.Invoke(serverEP.Address.ToString(), packetNr, packetTl);
}
try
{
len = tftpSocket.ReceiveFrom(rcvBuffer, ref dataEP);
tryCount = 5;
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.TimedOut && tryCount >= 0)
{
tryCount--;
packetNr = (packetNr <= 0 ? 0 : --packetNr);
}
else
{
throw ex;
}
}
}
// Close Socket and release resources
tftpSocket.Close();
fileStreamReader.Close();
}
#endregion
#region -=[ Private Member ]=-
/// <summary>
/// Creates the request packet.
/// </summary>
/// <param name="opCode">The op code.</param>
/// <param name="remoteFile">The remote file.</param>
/// <param name="tftpMode">The TFTP mode.</param>
/// <returns>the ack packet</returns>
private byte[] CreateRequestPacket(Opcodes opCode, string remoteFile, Modes tftpMode)
{
// Create new Byte array to hold Initial
// Read Request Packet
int pos = 0;
string modeAscii = tftpMode.ToString().ToLowerInvariant();
byte[] ret = new byte[modeAscii.Length + remoteFile.Length + 4];
// Set first Opcode of packet to indicate
// if this is a read request or write request
ret[pos++] = 0;
ret[pos++] = (byte)opCode;
// Convert Filename to a char array
pos += Encoding.ASCII.GetBytes(remoteFile, 0, remoteFile.Length, ret, pos);
ret[pos++] = 0;
pos += Encoding.ASCII.GetBytes(modeAscii, 0, modeAscii.Length, ret, pos);
ret[pos] = 0;
return ret;
}
/// <summary>
/// Creates the data packet.
/// </summary>
/// <param name="packetNr">The packet nr.</param>
/// <param name="data">The data.</param>
/// <returns>the data packet</returns>
private byte[] CreateDataPacket(int blockNr, byte[] data)
{
// Create Byte array to hold ack packet
byte[] ret = new byte[4 + data.Length];
// Set first Opcode of packet to TFTP_ACK
ret[0] = 0;
ret[1] = (byte)Opcodes.Data;
ret[2] = (byte)((blockNr >> 8) & 0xff);
ret[3] = (byte)(blockNr & 0xff);
Array.Copy(data, 0, ret, 4, data.Length);
return ret;
}
/// <summary>
/// Creates the ack packet.
/// </summary>
/// <param name="blockNr">The block nr.</param>
/// <returns>the ack packet</returns>
private byte[] CreateAckPacket(int blockNr)
{
// Create Byte array to hold ack packet
byte[] ret = new byte[4];
// Set first Opcode of packet to TFTP_ACK
ret[0] = 0;
ret[1] = (byte)Opcodes.Ack;
// Insert block number into packet array
ret[2] = (byte)((blockNr >> 8) & 0xff);
ret[3] = (byte)(blockNr & 0xff);
return ret;
}
#endregion
}
}

101
Common/TVOperation.cs Normal file
View File

@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace Common
{
/// <summary>
/// 与第三方TV云端对接将语音文字上报
/// </summary>
public static class TVOperation
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(TVOperation));
//private static readonly string _iptvURL = "http://iot.gooorun.com:8282/uis/smartVoiceSkill/commonSmartPreInterceptor";
//http://192.168.1.210:8888/epg/api/audioControl/control
//private static readonly string _tclURL = "";
//private static readonly string _tclAppKey = "4a4b4c125608";
//private static readonly string _tclAppSecret = "4a4b4c125608";
/// <summary>
/// 远程控制IPTV
/// </summary>
/// <param name="tvControlToken"></param>
/// <param name="tvControlUrl">控制地址</param>
/// <param name="hotelCode"></param>
/// <param name="roomNumber"></param>
/// <param name="value"></param>
public static bool ReportIPTV(string tvControlToken, string tvControlUrl, string hotelCode, string roomNumber, string value)
{
if (!string.IsNullOrEmpty(tvControlUrl))
{
try
{
if (string.IsNullOrEmpty(tvControlToken))
{
tvControlToken = "DEFAULT_TOKEN";
}
IPTVPostData postData = new IPTVPostData()
{
token = tvControlToken,
hotelId = "",//hotelCode
roomId = roomNumber,
value = value
};
string param = Newtonsoft.Json.JsonConvert.SerializeObject(postData);
string result = HttpWebRequestHelper.PostWebRequest(tvControlUrl, param);
IPTVPostDataResult returnResult = JsonConvert.DeserializeObject<IPTVPostDataResult>(result);
if (returnResult.retCode == "1")
{
return true;
}
logger.Error(string.Format("酒店({0})客房({1})调用iptv接口({2})失败:{3}", hotelCode, roomNumber, tvControlUrl, returnResult.retMsg));
return false;
}
catch (Exception ex)
{
logger.Error(string.Format("酒店({0})客房({1})调用iptv接口({2})失败:{3}", hotelCode, roomNumber, tvControlUrl, ex));
return false;
}
}
logger.Error(string.Format("酒店({0})客房({1})调用iptv接口({2})失败", hotelCode, roomNumber, tvControlUrl));
return false;
}
}
/// <summary>
/// 发送数据
/// </summary>
internal class IPTVPostData
{
/// <summary>
/// 机顶盒序列号
/// </summary>
public string token { get; set; }
/// <summary>
/// 酒店ID
/// </summary>
public string hotelId { get; set; }
/// <summary>
/// 房间ID
/// </summary>
public string roomId { get; set; }
/// <summary>
/// 用户语句
/// </summary>
public string value { get; set; }
}
/// <summary>
/// 返回
/// </summary>
internal class IPTVPostDataResult
{
/// <summary>
/// 返回码
/// </summary>
public string retCode { get; set; }
/// <summary>
/// 返回描述
/// </summary>
public string retMsg { get; set; }
}
}

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common
{
public static class TianMaoOperation
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(TianMaoOperation));
private const string apiURL = "http://pms.boonlive-rcu.com:90/home/";
private const string accessKeyId = "5d36d736c7866d47600d87d6a881adaa";
private const string accessKeySecret = "b4f94f725b2417dfbc4703dd457087f9";
/// <summary>
///
/// </summary>
/// <param name="method">方法名PostCustomScene</param>
/// <param name="jsonData"></param>
/// <param name="hotelCode"></param>
/// <param name="roomNumber"></param>
public static void PostWebRequestToTianMao(string method, string jsonData, string hotelCode, string roomNumber)
{
try
{
var QQQ =
Newtonsoft.Json.JsonConvert.SerializeObject(new
{
accessKeyId = accessKeyId,
accessKeySecret = accessKeySecret,
jsonData = jsonData
});
//logger.Error("天猫精灵调用的JSON:"+QQQ);
string result = Common.HttpWebRequestHelper.PostWebRequest(apiURL + method, QQQ);
APIResultEntity apiResult = Newtonsoft.Json.JsonConvert.DeserializeObject<APIResultEntity>(result);
if (!apiResult.result)
{
logger.Error(string.Format("酒店({0})客房({1})上报天猫精灵接口({2}),结果:{3},数据:{4}", hotelCode, roomNumber, method, result, Newtonsoft.Json.JsonConvert.SerializeObject(jsonData)));
}
}
catch (Exception ex)
{
logger.Error(string.Format("酒店({0})客房({1})上报天猫精灵接口({2})失败:{3},数据:{4}", hotelCode, roomNumber, method, ex.ToString(), Newtonsoft.Json.JsonConvert.SerializeObject(jsonData)));
}
}
}
public class APIResultEntity
{
/// <summary>
/// 结果true成功false失败
/// </summary>
public bool result { get; set; }
/// <summary>
/// 提示信息
/// </summary>
public string msg { get; set; }
/// <summary>
/// 返回数据
/// </summary>
public string data { get; set; }
}
}

70
Common/TimeHelper.cs Normal file
View File

@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common
{
public static class TimeHelper
{
/// <summary>
/// 时间转unix时间戳
/// </summary>
/// <param name="now"></param>
/// <returns></returns>
public static long DateTimeToStamp(DateTime now)
{
return (now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}
/// <summary>
/// 获取当前时间戳
/// </summary>
/// <param name="millisecond">精度(毫秒)设置 true则生成13位的时间戳精度设置为 false则生成10位的时间戳默认为 true </param>
/// <returns></returns>
public static string GetCurrentTimestamp(bool millisecond = true)
{
return DateTime.Now.ToTimestamp(millisecond);
}
/// <summary>
/// 转换指定时间得到对应的时间戳
/// </summary>
/// <param name="dateTime"></param>
/// <param name="millisecond">精度(毫秒)设置 true则生成13位的时间戳精度设置为 false则生成10位的时间戳默认为 true </param>
/// <returns>返回对应的时间戳</returns>
public static string ToTimestamp(this DateTime dateTime, bool millisecond = true)
{
return dateTime.ToTimestampLong(millisecond).ToString();
}
/// <summary>
/// 转换指定时间得到对应的时间戳
/// </summary>
/// <param name="dateTime"></param>
/// <param name="millisecond">精度(毫秒)设置 true则生成13位的时间戳精度设置为 false则生成10位的时间戳默认为 true </param>
/// <returns>返回对应的时间戳</returns>
public static long ToTimestampLong(this DateTime dateTime, bool millisecond = true)
{
var ts = dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return millisecond ? Convert.ToInt64(ts.TotalMilliseconds) : Convert.ToInt64(ts.TotalSeconds);
}
/// <summary>
/// 转换指定时间戳到对应的时间(同时增加八个小时)
/// </summary>
/// <param name="timestamp">10位或13位时间戳</param>
/// <returns>返回对应的时间</returns>
public static DateTime ToDateTime(this long timestamp)
{
var tz = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
if (timestamp.ToString().Length == 13)
{
return tz.AddMilliseconds(Convert.ToInt64(timestamp));
}
else
{
return tz.AddSeconds(Convert.ToInt64(timestamp));
}
}
}
}

849
Common/Tools.cs Normal file
View File

@@ -0,0 +1,849 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Security.Cryptography;
using System.Web;
using System.Net.NetworkInformation;
using System.Management;
using System.ComponentModel;
using System.Diagnostics;
using System.Collections;
using System.Text.RegularExpressions;
namespace Common
{
public static class Tools
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Tools));
/// <summary>
/// 获取机器码
/// </summary>
/// <returns></returns>
public static string GetMachineCode()
{
StringBuilder result = new StringBuilder();
String[] macAddress = GetMacAddressByNetworkInformation("-").Split('-');
//String motherBoardSerialNumber = GetMotherBoardSerialNumber();
String diskModel = GetDiskModel();
if (diskModel.Length < 10)
{
diskModel = "PIUHOUHZUW";
}
result.Append(macAddress[0] + diskModel.Substring(0, 2).Replace(" ", "z"));// + motherBoardSerialNumber.Substring(0, 2)).Replace(" ", "a");
result.Append(macAddress[1] + diskModel.Substring(2, 2).Replace(" ", "x"));// + motherBoardSerialNumber.Substring(2, 2).Replace(" ", "s"));
result.Append(macAddress[2] + diskModel.Substring(4, 2).Replace(" ", "c"));// + motherBoardSerialNumber.Substring(4, 2).Replace(" ", "d"));
result.Append(macAddress[3] + diskModel.Substring(6, 2).Replace(" ", "v"));// + motherBoardSerialNumber.Substring(6, 2).Replace(" ", "f"));
result.Append(macAddress[4] + diskModel.Substring(8, 2).Replace(" ", "b"));// + motherBoardSerialNumber.Substring(8, 2).Replace(" ", "g"));
result.Append(macAddress[5]);
return result.ToString();
}
/// <summary>
/// 获取mac地址
/// </summary>
/// <param name="separatedFlag"></param>
/// <returns></returns>
public static String GetMacAddressByNetworkInformation(string separatedFlag = "")
{
string macAddress = "";
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
adapter.Description.ToUpper().IndexOf("WIRELESS") == -1 && adapter.Description.ToUpper().IndexOf("3G") == -1 &&
adapter.Description.ToUpper().IndexOf("VIRTUAL") == -1 && adapter.Description.ToUpper().IndexOf("VPN") == -1)
{
macAddress = adapter.GetPhysicalAddress().ToString();
if (!string.IsNullOrEmpty(separatedFlag))
{
for (int i = 1; i < 6; i++)
{
macAddress = macAddress.Insert(3 * i - 1, separatedFlag);
}
}
break;
}
}
return macAddress;
}
/// <summary>
/// 获取硬盘序列号
/// </summary>
/// <returns></returns>
public static String GetDiskModel()
{
using (ManagementClass mc = new ManagementClass("Win32_DiskDrive"))
{
using (ManagementObjectCollection moc = mc.GetInstances())
{
string Model = "";
foreach (ManagementObject mo in moc)
{
Model = mo["Model"].ToString().Trim();
break;
}
return Model;
}
}
}
public static string GetClientIP(HttpRequestBase request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
string ip = null;
if (!string.IsNullOrEmpty(request.ServerVariables["HTTP_VIA"]))
{
ip = Convert.ToString(request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
}
if (string.IsNullOrEmpty(ip))
{
ip = Convert.ToString(request.ServerVariables["REMOTE_ADDR"]);
}
return ip;
}
public static string GetClientIP()
{
string userIP;
HttpRequest request = System.Web.HttpContext.Current.Request; // 如果使用代理获取真实IP
if (request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
userIP = request.ServerVariables["REMOTE_ADDR"];
else
userIP = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (userIP == null || userIP == "")
userIP = request.UserHostAddress;
return userIP;
}
/// <summary>
/// 获取本地IP地址
/// </summary>
/// <returns></returns>
public static string GetLocalIP()
{
string localIp = "";
IPAddress[] addressList = Dns.GetHostAddresses(Dns.GetHostName());//会返回所有地址包括IPv4和IPv6
foreach (IPAddress ip in addressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
localIp = ip.ToString();
break;
}
}
return localIp;
}
/// <summary>
/// 将主机名或 IP 地址解析IP地址
/// </summary>
/// <param name="domain"></param>
/// <returns></returns>
public static IPAddress GetIPByDomain(string hostNameOrAddress)
{
IPHostEntry host = Dns.GetHostEntry(hostNameOrAddress);
return host.AddressList[0];
}
/// <summary>
/// 获取本地IP地址列表
/// </summary>
/// <returns></returns>
public static IList<string> GetLocalIPList()
{
IList<string> localIpList = new List<string>();
IPAddress[] addressList = Dns.GetHostAddresses(Dns.GetHostName());//会返回所有地址包括IPv4和IPv6
foreach (IPAddress ip in addressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
localIpList.Add(ip.ToString());
}
}
return localIpList;
}
public static string GetApplicationPath()
{
return AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
}
/// <summary>
/// 获取记录访问量文件路径
/// </summary>
/// <returns></returns>
public static string GetCounterFilePath()
{
return GetApplicationPath() + @"License\counter.txt";
}
/// <summary>
/// 生成CRC16校验
/// </summary>
/// <param name="buffer"></param>
/// <param name="len"></param>
/// <returns></returns>
public static ushort CRC16(byte[] buffer, int len)
{
uint xda, xdapoly;
byte xdabit;
xda = 0xFFFF;
xdapoly = 0xA001; // (X**16 + X**15 + X**2 + 1)
for (int i = 0; i < len; i++)
{
xda ^= buffer[i];
for (int j = 0; j < 8; j++)
{
xdabit = (byte)(xda & 0x01);
xda >>= 1;
if (xdabit == 1)
{
xda ^= xdapoly;
}
}
}
return Convert.ToUInt16(xda & 0xffff);
}
/// <summary>
/// 计算文件的MD5值
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static byte[] MD5(string file)
{
using (Stream stream = File.Open(file, FileMode.Open))
{
return MD5(stream);
}
}
/// <summary>
/// 计算流的MD5值
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static byte[] MD5(Stream stream)
{
using (MD5 md5 = new MD5CryptoServiceProvider())
{
return md5.ComputeHash(stream);
}
}
/// <summary>
/// 计算文件MD5
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static string ComputeFileHash(Stream stream)
{
byte[] retVal = Tools.MD5(stream);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
/// <summary>
/// 将MD5字符串转换成整型数组表示
/// </summary>
/// <param name="md5"></param>
/// <returns></returns>
public static uint[] MD5StringToUIntArray(string md5)
{
if (String.IsNullOrWhiteSpace(md5))
{
throw new ArgumentException("参数不能为空。", "md5");
}
try
{
uint[] md5Arr = new uint[4] { 0, 0, 0, 0 };
md5Arr[0] = Convert.ToUInt32(md5.Substring(0, 8), 16);
md5Arr[1] = Convert.ToUInt32(md5.Substring(8, 8), 16);
md5Arr[2] = Convert.ToUInt32(md5.Substring(16, 8), 16);
md5Arr[3] = Convert.ToUInt32(md5.Substring(24, 8), 16);
return md5Arr;
}
catch (Exception ex)
{
throw new ApplicationException("转换MD5出错。", ex);
}
}
/// <summary>
/// 用MD5加密字符串
/// </summary>
/// <param name="str">待加密的字符串</param>
/// <returns></returns>
public static string MD5Encrypt(string str)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] hashedDataBytes;
hashedDataBytes = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(str));
StringBuilder tmp = new StringBuilder();
foreach (byte i in hashedDataBytes)
{
tmp.Append(i.ToString("x2"));
}
return tmp.ToString();
}
/// <summary>
/// 获取指定长的的字符串对应的16进制字节码如果长度不够末位自动补0
/// </summary>
/// <param name="s"></param>
/// <param name="length"></param>
/// <returns></returns>
public static byte[] GetBytes(String str, int length)
{
byte[] s = System.Text.Encoding.GetEncoding("gb2312").GetBytes(str);
int fixLength = length - s.Length;
if (s.Length < length)
{
byte[] S_bytes = new byte[length];
Array.Copy(s, 0, S_bytes, 0, s.Length);
for (int x = length - fixLength; x < length; x++)
{
S_bytes[x] = 0x00;
}
return S_bytes;
}
return s;
}
public static string CreateValidateNumber(int length)
{
int[] randMembers = new int[length];
int[] validateNums = new int[length];
System.Text.StringBuilder validateNumberStr = new System.Text.StringBuilder();
//生成起始序列值
int seekSeek = unchecked((int)DateTime.Now.Ticks);
Random seekRand = new Random(seekSeek);
int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);
int[] seeks = new int[length];
for (int i = 0; i < length; i++)
{
beginSeek += 10000;
seeks[i] = beginSeek;
}
//生成随机数字
for (int i = 0; i < length; i++)
{
Random rand = new Random(seeks[i]);
int pownum = 1 * (int)Math.Pow(10, length);
randMembers[i] = rand.Next(pownum, Int32.MaxValue);
}
//抽取随机数字
for (int i = 0; i < length; i++)
{
string numStr = randMembers[i].ToString();
int numLength = numStr.Length;
Random rand = new Random();
int numPosition = rand.Next(0, numLength - 1);
validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
}
//生成验证码
for (int i = 0; i < length; i++)
{
validateNumberStr.Append(validateNums[i].ToString());
}
return validateNumberStr.ToString();
}
public static byte[] CreateValidateGraphic(string validateNum)
{
using (Bitmap image = new Bitmap((int)Math.Ceiling(validateNum.Length * 12.5), 22))
{
using (Graphics g = Graphics.FromImage(image))
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的干扰线
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
using (Font font = new Font("Arial", 14, (FontStyle.Bold | FontStyle.Italic)))
{
using (LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.2f, true))
{
g.DrawString(validateNum, font, brush, 3, 2);
}
}
//画图片的前景干扰点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
//保存图片数据
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, ImageFormat.Jpeg);
return stream.ToArray();
}
}
}
}
/// <summary>
/// 获取一个随机数组
/// </summary>
/// <param name="num">数组个数</param>
/// <param name="minValue"></param>
/// <param name="maxValue"></param>
/// <returns></returns>
public static int[] GetRandomNum(int num, int minValue, int maxValue)
{
Random ra = new Random(unchecked((int)DateTime.Now.Ticks));
int[] arrNum = new int[num];
int tmp = 0;
for (int i = 0; i <= num - 1; i++)
{
tmp = ra.Next(minValue, maxValue); //随机取数
arrNum[i] = tmp;
}
return arrNum;
}
/// <summary>
/// 解决下载名称在IE下中文乱码
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static String ToUtf8String(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (c >= 0 && c <= 255)
{
sb.Append(c);
}
else
{
byte[] b;
try
{
b = Encoding.UTF8.GetBytes(c.ToString());
}
catch (Exception)
{
b = new byte[0];
}
for (int j = 0; j < b.Length; j++)
{
int k = b[j];
if (k < 0) k += 256;
sb.Append("%" + Convert.ToString(k, 16).ToUpper());
}
}
}
return sb.ToString();
}
/// <summary>
/// 字节内容转换为字符串
/// </summary>
/// <param name="bytesData"></param>
/// <returns></returns>
public static string ByteToString(byte[] bytesData)
{
StringBuilder result = new StringBuilder();
foreach (byte r in bytesData)
{
result.Append(r.ToString("X2") + " ");
}
return result.ToString();
}
/// <summary>
/// 把int32类型的数据转存到2个字节的byte数组中
/// </summary>
/// <param name="m">int32类型的数据</param>
/// <param name="arry">2个字节大小的byte数组</param>
/// <returns></returns>
public static byte[] Int32ToByte(Int32 data)
{
byte[] arry = new byte[2];
arry[0] = (byte)((data & 0xFF00) >> 8);
arry[1] = (byte)(data & 0xFF);
return arry;
}
/// <summary>
/// 把int32类型的数据转存到2个字节的byte数组中小端
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] Int32ToByte2(Int32 data)
{
byte[] arry = new byte[2];
arry[0] = (byte)(data & 0xFF);
arry[1] = (byte)((data & 0xFF00) >> 8);
//arry[2] = (byte)((data & 0xFF0000) >> 16);
//arry[3] = (byte)((data >> 24) & 0xFF);
return arry;
}
/// <summary>
/// 2位byte转换为int类型
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static int ByteToInt(byte[] data)
{
return (data[1] & 0xFF) << 8 | data[0];
}
/// <summary>
/// 4位byte转换为long类型
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static long Byte4ToLong(byte[] data)
{
return (data[3] << 24) & 0xFF | (data[2] & 0xFF00) << 16 | (data[1] & 0xFF) << 8 | data[0];
}
/// <summary>
/// long类型转换为4位byte
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] LongToByte4(long data)
{
byte[] arry = new byte[4];
arry[0] = (byte)(data & 0xFF);
arry[1] = (byte)((data & 0xFF00) >> 8);
arry[2] = (byte)((data & 0xFF0000) >> 16);
arry[3] = (byte)((data >> 24) & 0xFF);
return arry;
}
/// <summary>
/// 在指定时间过后执行指定的表达式
/// </summary>
/// <param name="interval">事件之间经过的时间(以毫秒为单位)</param>
/// <param name="action">要执行的表达式</param>
public static void SetTimeout(double interval, Action action)
{
System.Timers.Timer timer = new System.Timers.Timer(interval);
timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
{
timer.Enabled = false;
action();
};
timer.Enabled = true;
}
/// <summary>
/// 得到字符串的长度一个汉字算2个字符
/// </summary>
/// <param name="str">字符串</param>
/// <returns>返回字符串长度</returns>
public static int GetLength(string str)
{
if (str.Length == 0) return 0;
ASCIIEncoding ascii = new ASCIIEncoding();
int tempLen = 0;
byte[] s = ascii.GetBytes(str);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
{
tempLen += 2;
}
else
{
tempLen += 1;
}
}
return tempLen;
}
/// <summary>
/// 获取枚举描述
/// </summary>
/// <param name="en">枚举</param>
/// <returns>返回枚举的描述 </returns>
public static string GetDescription(Enum en)
{
Type type = en.GetType();//获取类型
MemberInfo[] memberInfos = type.GetMember(en.ToString()); //获取成员
if (memberInfos != null && memberInfos.Length > 0)
{
DescriptionAttribute[] attrs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; //获取描述特性
if (attrs != null && attrs.Length > 0)
{
return attrs[0].Description; //返回当前描述
}
}
return en.ToString();
}
/// <summary>
/// 显示消息提示对话框,并进行页面跳转
/// </summary>
/// <param name="page">当前页面指针一般为this</param>
/// <param name="msg">提示信息</param>
/// <param name="url">跳转的目标URL</param>
/// <param name="isTop">指定是否为框架内跳转(True表示跳出框架外)</param>
public static void ShowAndRedirect(System.Web.UI.Page page, string msg, string url, bool isTop)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script language='javascript' defer>");
sb.AppendFormat("alert('{0}');", msg);
if (isTop == true)
{
sb.AppendFormat("top.location.href='{0}'", url);
}
else
{
sb.AppendFormat("location.href='{0}'", url);
}
sb.Append("</script>");
page.ClientScript.RegisterStartupScript(page.GetType(), "message" + System.Guid.NewGuid().ToString(), sb.ToString());
}
/// <summary>
/// stream to reader
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static string StreamToString(Stream stream)
{
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
/// <summary>
/// HEX编码转换为——>ASCII编码
/// </summary>
/// <param name="Msg"></param>
/// <returns></returns>
public static string HexToASCII(string Msg)
{
byte[] buff = new byte[Msg.Length / 2];
string Message = "";
for (int i = 0; i < buff.Length; i++)
{
buff[i] = byte.Parse(Msg.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
}
System.Text.Encoding chs = System.Text.Encoding.ASCII;
Message = chs.GetString(buff);
return Message;
}
/// <summary>
/// HEX编码转换为——>字符串
/// </summary>
/// <param name="Msg"></param>
/// <returns></returns>
public static string HexToStr(string Msg)
{
byte[] buff = new byte[Msg.Length / 2];
string Message = "";
for (int i = 0; i < buff.Length; i++)
{
buff[i] = byte.Parse(Msg.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
}
System.Text.Encoding chs = System.Text.Encoding.GetEncoding("gb2312");
Message = chs.GetString(buff);
return Message;
}
/// <summary>
/// 字符串转化为——>HEX编码
/// </summary>
/// <param name="Msg"></param>
/// <returns></returns>
public static string StrToHex(string Msg)
{
byte[] bytes = System.Text.Encoding.Default.GetBytes(Msg);//转换为字节(十进制)
string str = "";
for (int i = 0; i < bytes.Length; i++)
{
str += string.Format("{0:X}", bytes[i]); //转换为十六进制
}
return str;
}
/// <summary>
/// Hex文件解释
/// </summary>
/// <param name="filepath"></param>
public static void HexFileRead(string filepath)//从指定文件目录读取HEX文件并解析放入缓存数组buffer中
{
string szLine;
int startAdr;
int endAdr = 0; //用于判断hex地址是否连续不连续补充0xFF
byte[] buffer = new byte[1024 * 1024 * 5]; // 打开文件hex to bin缓存
int bufferAdr = 0;// 打开文件hex to bin缓存指针用于计算bin的长度
if (filepath == "")
{
return;
}
FileStream fsRead = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Read);
StreamReader HexReader = new StreamReader(fsRead); //读取数据流
while (true)
{
szLine = HexReader.ReadLine(); //读取Hex中一行
if (szLine == null) { break; } //读取完毕,退出
if (szLine.Substring(0, 1) == ":") //判断首字符是”:”
{
if (szLine.Substring(1, 8) == "00000001") { break; } //文件结束标识
if ((szLine.Substring(8, 1) == "0") || (szLine.Substring(8, 1) == "1"))//直接解析数据类型标识为 : 00 和 01 的格式
{
int lineLenth;
string hexString;
hexString = szLine.Substring(1, 2);
lineLenth = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber); // 获取一行的数据个数值
hexString = szLine.Substring(3, 4);
startAdr = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber); // 获取地址值
for (int i = 0; i < startAdr - endAdr; i++) // 补空位置
{
hexString = "FF";
byte value = byte.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
buffer[bufferAdr] = value;
bufferAdr++;
}
for (int i = 0; i < lineLenth; i++) // hex转换为byte
{
hexString = szLine.Substring(i * 2 + 9, 2);
byte value = byte.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
buffer[bufferAdr] = value;
bufferAdr++;
}
endAdr = startAdr + lineLenth;
}
}
}
}
/// <summary>
/// 将url参数转成json
/// </summary>
/// <param name="urlParams"></param>
/// <returns></returns>
public static string UrlParamsToJson(string urlParams)
{
var nameValueCollection = HttpUtility.ParseQueryString(urlParams);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(nameValueCollection.AllKeys.ToDictionary(k => k, k => nameValueCollection[k]));
return json;
}
//public static string GetUrl(string url)
//{
// ComputeSignature();
// return "http://"+ url + "/?" +
// string.Join("&", _parameters.Select(x => x.Key + "=" + HttpUtility.UrlEncode(x.Value)));
//}
public static long GetCurrentTimeStamp(DateTime dt)
{
TimeSpan ts = dt - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local);
long current_timestamp = Convert.ToInt64(ts.TotalSeconds);
return current_timestamp;
}
public static DateTime GetCurrentDateTime(long timestampMilliseconds)
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
DateTime utcTime = epoch.AddSeconds(timestampMilliseconds);
return utcTime;
}
/// <summary>
/// 格林尼治时间
/// </summary>
/// <returns></returns>
public static long GetUnixTime()
{
DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long unixTimestampMillisecondsManual = (long)(DateTime.UtcNow - unixEpoch).TotalSeconds;
return unixTimestampMillisecondsManual;
}
public static DateTime GetTimeFromUnixTime(long timestampSeconds)
{
// Unix 时间戳的起始时间1970-01-01 00:00:00 UTC
DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
// 加上 Unix 时间戳的秒数
return unixEpoch.AddSeconds(timestampSeconds);
}
public static byte CombineBitsToByte(bool bit0, bool bit1, bool bit2, bool bit3)
{
byte result = (byte)((bit0 ? 1 : 0) << 3); // 将bit0移到第4位高位
result |= (byte)((bit1 ? 1 : 0) << 2); // 将bit1移到第3位
result |= (byte)((bit2 ? 1 : 0) << 1); // 将bit2移到第2位
result |= (byte)(bit3 ? 1 : 0); // 将bit3移到第1位低位
return result;
}
/// <summary>
/// 16进制字符串转换成 字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] GetBytesFromString(string hexString)
{
byte[] bytes = new byte[hexString.Length / 2]; // 计算字节数组的长度
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); // 每次取两个字符转换为字节
}
return bytes;
}
/// <summary>
/// 替换掉空白字符
/// </summary>
/// <param name="originalString"></param>
/// <returns></returns>
public static string DeleteSpaceChar(string originalString)
{
string result = Regex.Replace(originalString, @"\s", "");
return result;
}
public static short HostNumberToHotelCode(string wer)
{
var v1 = wer.Substring(0, 3);
var v2 = wer.Substring(3, 3);
byte b12 = byte.Parse(v1);
byte b13 = byte.Parse(v2);
byte[] vva1 = new byte[] { b12, b13 };
var usa = BitConverter.ToInt16(vva1, 0);
return usa;
}
}
}

33
Common/UDPPackageCount.cs Normal file
View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
namespace Common
{
public class YUANZI_TongJi
{
public static long TotalReceiveCount = 0;
public static long TotalErrorPackageReceiveCount = 0;
}
public class UDPPackageCount
{
public long Count { get; set; }
public ConcurrentDictionary<string, long> FenLei { get; set; }
}
public class UDPPackage
{
public string CommandType { get; set; }
public long TotalCount { get; set; }
public ConcurrentDictionary<string, long> FenLei { get; set; }
public ConcurrentDictionary<string, string> ExtraData { get; set; }
public string RemoveTime { get; set; }
}
public class Block_NameList
{
public string HotelCode { get; set; }
public List<string> HostNumberList;
}
}

123
Common/UdplogServer.cs Normal file
View File

@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading.Tasks;
public class UDPLogServer
{
private static DateTime Sendtime = DateTime.Now;
private static UdpClient udpClient;
//private static IPEndPoint endPoint;
private static Object _lock = new Object();
public static void Init()
{
//endPoint = new IPEndPoint(IPAddress.Parse("122.152.232.170"), 45000);
if (null != udpClient)
{
udpClient.Close();
udpClient = null;
}
udpClient = new UdpClient("122.152.232.170", 45000);
}
/// <summary>
/// AddMessage 添加数据
/// </summary>
public static void AddMessage(long custom, int type, string body)
{
if (null == udpClient)
{
return;
}
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
List<byte> data = new List<byte>();
data.Add(0xAA);//head
data.AddRange(uint16tobyte((new MessagesData()).Id));// 添加id 2个字节
// 添加时间 8个字节
TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
data.AddRange(BitConverter.GetBytes(ts.TotalMilliseconds));
// 自定义 只取 3 Byte
var bCustom = uint32tobyte(custom);
data.Add(bCustom[1]);
data.Add(bCustom[2]);
data.Add(bCustom[3]);
data.Add((byte)type);
var body_str = System.Text.Encoding.UTF8.GetBytes(body);
data.AddRange(uint16tobyte(body_str.Length));// 添加长度 2 个字节
data.AddRange(body_str);// 添加内容
data.Add(0x55);//end
byte[] sendData = data.ToArray();
//udpClient.BeginSend(sendData, sendData.Length, new AsyncCallback(SendCallback), null);
lock (_lock)
{
udpClient.Send(sendData, sendData.Length);
}
}, System.Threading.CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
private static void SendCallback(IAsyncResult ar)
{
if (ar.IsCompleted)
{
udpClient.EndSend(ar);
}
}
private static byte[] uint16tobyte(int data)
{
byte[] res = new byte[2];
res[0] = byte.Parse((data / 0x100).ToString());
res[1] = byte.Parse((data % 0x100).ToString());
return res;
}
private static byte[] uint32tobyte(long data)
{
byte[] res = new byte[4];
long temp_data = data;
// int temp_2 = 0;
res[0] = byte.Parse((temp_data / 0x1000000).ToString());
temp_data = temp_data % 0x1000000;
res[1] = byte.Parse((temp_data / 0x10000).ToString());
//temp_2 = int.Parse( (temp_data % 0x10000 ).ToString());
temp_data = temp_data % 0x10000;
res[2] = byte.Parse((temp_data / 0x100).ToString());
temp_data = temp_data % 0x100;
res[3] = byte.Parse((temp_data % 0x100).ToString());
return res;
}
}
public class MessagesData
{
static object locks = new object();
public MessagesData()
{
lock (locks)
{
MAX_Id++;
if (MAX_Id > 65535)
{
MAX_Id = 1;
}
}
this.Id = MAX_Id;
}
internal static int MAX_Id = 0;
internal int Id = MAX_Id;
public int type = 1;
public DateTime time = DateTime.Now;
public string body = "";
public int about_id = 0;
public long custom = 0;
}

14
Common/ValidatePattern.cs Normal file
View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common
{
public sealed class ValidatePattern
{
public const string MAC = @"^([0-9a-fA-F]{2})((-[0-9a-fA-F]{2}){5})$";
public const string IPAddress = @"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))";
}
}

105
Common/WeiXinHelper.cs Normal file
View File

@@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Configuration;
using Newtonsoft.Json;
namespace Common
{
public sealed class WeiXinHelper
{
public static string AppId
{
get { return ConfigurationManager.AppSettings["WeiXinAppId"]; }
}
public static string AppSecret
{
get { return ConfigurationManager.AppSettings["WeiXinAppSecret"]; }
}
public static WeiXinAccessToken GetAccessToken()
{
string accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppId + "&secret=" + AppSecret;
using (WebClient client = new WebClient())
{
string result = client.DownloadString(accessTokenUrl);
return JsonConvert.DeserializeObject<WeiXinAccessToken>(result);
}
}
public static WeiXinJsApiTicket GetJsApiTicket(string accessToken)
{
string jsApiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
using (WebClient client = new WebClient())
{
string result = client.DownloadString(jsApiTicketUrl);
return JsonConvert.DeserializeObject<WeiXinJsApiTicket>(result);
}
}
public static string CreateJsApiSignature(string jsApiTicket, string noncestr, int timestamp, string url)
{
string str = "jsapi_ticket=" + jsApiTicket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
byte[] data = Encoding.Default.GetBytes(str);
byte[] hashcode = System.Security.Cryptography.SHA1.Create().ComputeHash(data);
return BitConverter.ToString(hashcode).Replace("-", "").ToLower();
}
public static string CreateNonceStr(uint length = 16)
{
string noncestr = "";
string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random rand = new Random((int)DateTime.Now.Ticks);
for (int i = 0; i < length; i++)
{
noncestr += chars[rand.Next(chars.Length - 1)];
}
return noncestr;
}
public static int GetCurrentTimeStamp()
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(DateTime.Now - startTime).TotalSeconds;
}
}
public class WeiXinResult
{
[JsonProperty("errcode")]
public int ErrorCode { get; set; }
[JsonProperty("errmsg")]
public string ErrorMsg { get; set; }
}
public class WeiXinAccessToken : WeiXinResult
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
}
public class WeiXinJsApiTicket : WeiXinResult
{
[JsonProperty("ticket")]
public string Ticket { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
}
}

151
Common/XidaoDuOperation.cs Normal file
View File

@@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common
{
public static class XiaoDuOperation
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(XiaoDuOperation));
private static readonly string _welcomeURL = "https://dueros.baidu.com/business/open/restful";
/// <summary>
/// 获取AccessToken
/// </summary>
/// <returns></returns>
public static XiaoDuError GetXiaoDuAccessToken()
{
try
{
StringBuilder sbURL = new StringBuilder();
sbURL.Append("https://dueros.baidu.com/business/oauth/v2/token");
sbURL.Append("?grant_type=client_credentials");
sbURL.Append("&app_id=vG6mcOYY7kBvGv8GGhqLe36t9wAWQHjH");
sbURL.Append("&app_secret=c7ulEmnWSATaEBLXjV35Oj3onxRmhuNQ");
string result = HttpWebRequestHelper.GetWebRequest(sbURL.ToString());
XiaoDuError error = Newtonsoft.Json.JsonConvert.DeserializeObject<XiaoDuError>(result);
if (error.errno > 0)
{
logger.Error(string.Format("获取小度accessToken失败。errno:{0},errmsg:{1}", error.errno, error.errmsg));
}
return error;
}
catch (Exception ex)
{
logger.Error(string.Format("获取小度accessToken失败{0}", ex.Message));
}
return null;
}
/// <summary>
/// 发送命令给小度
/// </summary>
/// <param name="accessToken"></param>
/// <param name="cuid"></param>
/// <param name="paramJson"></param>
/// <param name="hotelCode"></param>
/// <param name="roomNumber"></param>
/// <returns></returns>
public static void PostWebRequestToXiaoDu(string accessToken, string cuid, XiaoDuParamJson paramJson, string hotelCode, string roomNumber)
{
if (!string.IsNullOrEmpty(accessToken) && !string.IsNullOrEmpty(cuid))
{
StringBuilder sb = new StringBuilder();
sb.Append("cuid=" + cuid);
sb.Append("&timestamp=" + TimeHelper.GetCurrentTimestamp(false));
sb.Append("&v=2.0");
sb.Append("&source=baidu");
sb.Append("&paramJson=" + Newtonsoft.Json.JsonConvert.SerializeObject(paramJson));
HttpWebRequestHelper.PostWebRequest(_welcomeURL, "Bearer " + accessToken, sb.ToString());
//string result = HttpWebRequestHelper.PostWebRequest(_welcomeURL, "Bearer " + accessToken, sb.ToString());
//XiaoDuError error = Newtonsoft.Json.JsonConvert.DeserializeObject<XiaoDuError>(result);
//if (error.errno > 0)
//{
// logger.Error(string.Format("酒店({0})客房({1})调用小度接口失败。cuid:{2}, method:{3}, errmsg:{4}, error:{5}", hotelCode, roomNumber, cuid, paramJson.method, error.errmsg, result));
//}
}
//else
//{
// logger.Error(string.Format("酒店({0})客房({1})调用小度接口失败。cuid:{2}, accessToken:{3}", hotelCode, roomNumber, cuid, accessToken));
//}
}
/// <summary>
/// 通知小度播报欢迎词
/// </summary>
/// <param name="hotelCode"></param>
/// <param name="roomNumber"></param>
/// <param name="webhookUrl"></param>
/// <param name="message"></param>
public static void UploadWebhook(string accessToken, string cuids, string message, string hotelCode, string roomNumber)
{
try
{
foreach (string cuid in cuids.Split(','))//多个小度英文逗号隔开
{
XiaoDuParamJson paramJson = new XiaoDuParamJson()
{
method = "welcome",
cuid = cuid,
outputSpeechText = message,
cardContent = message,
backgroundMusic = "http://www.abc.com"
};
PostWebRequestToXiaoDu(accessToken, cuid, paramJson, hotelCode, roomNumber);
}
}
catch (Exception ex)
{
logger.Error(string.Format("酒店({0})客房({1})调用小度接口({2})失败。原因:{3}", hotelCode, roomNumber, _welcomeURL, ex.Message));
}
}
/// <summary>
/// 同步设备技能
/// </summary>
/// <param name="hotelName"></param>
/// <param name="roomNumber"></param>
/// <param name="cuids"></param>
/// <param name="accessToken"></param>
/// <returns></returns>
//public static bool UploadDeviceFun(string hotelName, string roomNumber, string cuids, string accessToken)
//{
// try
// {
// XiaoDuParamJson paramJson = new XiaoDuParamJson() { method = "deviceSync", isNoBlocked = 1 };
// foreach (string cuid in cuids.Split(','))//多个小度英文逗号隔开
// {
// PostWebRequestToXiaoDu(accessToken, cuid, paramJson);
// }
// return true;
// }
// catch (Exception ex)
// {
// logger.Error(string.Format("酒店({0})客房({1})调用小度接口({2})失败:{3}", hotelName, roomNumber, _welcomeURL, ex));
// }
// return false;
//}
}
public class XiaoDuParamJson
{
public string method { get; set; }
public string cuid { get; set; }
public string outputSpeechText { get; set; }
public string cardContent { get; set; }
public string backgroundMusic { get; set; }
public int isNoBlocked { get; set; }
}
public class XiaoDuError
{
public int errno { get; set; }
public string errmsg { get; set; }
public XiaoDuErrorData data { get; set; }
}
public class XiaoDuErrorData
{
public string access_token { get; set; }
public int expires_in { get; set; }
public int deadline { get; set; }
public string refresh_token { get; set; }
}
}

144
Common/XuanZhuOperation.cs Normal file
View File

@@ -0,0 +1,144 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Net;
namespace Common
{
/// <summary>
/// 与第三方选住云端对接:将相关服务信息推送过去
/// </summary>
public static class XuanZhuOperation
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(XuanZhuOperation));
//private static readonly string _postURL = "http://111.231.106.196:19230/hogood/report";
//###
//POST http://111.231.106.196:19230/hogood/report
//Content-Type: application/json; charset=UTF-8
//{
// "code": "1094",//酒店编码
// "roomNumber": "8888",//房号
// "address": "001001001",//回路地址
// "name": "廊灯",//回路名称
// "status":"1" //状态1开2关
//}
//### 返回
//{
// "retCode": 1, //0代表成功 其他代表失败
// "retMsg": "[003]非法访问",
// "retData": null
//}
//###
/// <summary>
/// 上报设备或服务状态信息
/// </summary>
/// <param name="url"></param>
/// <param name="resp"></param>
/// <returns></returns>
public static bool ReportService(string url, XuanZhuResponse resp)
{
string param = Newtonsoft.Json.JsonConvert.SerializeObject(resp);
try
{
var A = (SecurityProtocolType)48;
var B = (SecurityProtocolType)192;
var C = (SecurityProtocolType)768;
var D = (SecurityProtocolType)3072;
var E = (SecurityProtocolType)12288;
ServicePointManager.SecurityProtocol = A | B | C | D | E;
string result = HttpWebRequestHelper.PostWebRequest(url, param);
if (resp.code.Equals("1003"))
{
logger.Error(resp.roomNumber + " Params:"+param+" Result:" + result);
}
XuanZhuResult returnResult = JsonConvert.DeserializeObject<XuanZhuResult>(result);
//if (returnResult.retCode == "0")//0代表成功 其他代表失败
//{
// return true;
//}
//logger.Error(string.Format("酒店({0})客房({1})调用设备状态推送接口({2})结果:{3}", hotelCode, roomNumber, url, returnResult.retMsg));
//return false;
return true;
}
catch (Exception ex)
{
logger.Error(string.Format("酒店({0})客房({1})调用设备状态或异常推送接口({2})失败:{3},数据:{4}", resp.code, resp.roomNumber, url, ex.Message, param));
return false;
}
}
}
public class XuanZhuResponse
{
/// <summary>
/// 酒店编码
/// </summary>
public string code { get; set; }
/// <summary>
/// 房号
/// </summary>
public string roomNumber { get; set; }
/// <summary>
/// 回路地址
/// </summary>
public string address { get; set; }
/// <summary>
/// 回路名称
/// </summary>
public string name { get; set; }
/// <summary>
/// 状态
/// </summary>
public int status { get; set; }
/// <summary>
/// 异常类型
/// </summary>
public int faultType { get; set; }
/// <summary>
/// 异常值
/// </summary>
public int faultData { get; set; }
/// <summary>
/// 亮度
/// </summary>
public int brightness { get; set; }
/// <summary>
/// 当前温度
/// </summary>
public int currentTemp { get; set; }
/// <summary>
/// 设定温度
/// </summary>
public int settingTemp { get; set; }
/// <summary>
/// 风速
/// </summary>
public int fanSpeed { get; set; }
/// <summary>
/// 模式
/// </summary>
public int mode { get; set; }
/// <summary>
/// 阀门
/// </summary>
public int valve { get; set; }
}
internal class XuanZhuResult
{
/// <summary>
/// 返回码
/// </summary>
public string retCode { get; set; }
/// <summary>
/// 返回描述
/// </summary>
public string retMsg { get; set; }
/// <summary>
/// 返回描述
/// </summary>
public string retData { get; set; }
}
}

11
Common/app.config Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

21
CommonEntity/CacheDTO.cs Normal file
View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class Host_DTO
{
public string HostId { get; set; }
public string RoomTypeId { get; set; }
public string RoomNumber { get; set; }
public string HotelId { get; set; }
public string HotelCode { get; set; }
public string XiaoDuCUID { get; set; }
public string TianMaoCUID { get; set; }
public string SysHotel_WelcomeSpeech { get; set; }
public string SysHotel_IsPowerOffResetXiaoDu { get; set; }
public string SysHotel_DeviceStatusPushURL { get; set; }
}
}

130
CommonEntity/CacheKey.cs Normal file
View File

@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class CacheKey
{
public static string HostInfo_ByHostNumber = "HostInfo_ByHostNumber";
public static string NewVersionDeviceStatus = "NewVersionDeviceStatus";
public static string Key = "monitor_host";
public static string IOTKey = "iot_monitor_host";
public static string MonitorLogPrefix = "AllLogKey";
public static string CarbonVIP_Prefix = "CarbonVIP";
public static string HostModalStatus_Prefix = "HostModalStatusReceiver";
public static string HostModalStatus_Prefix_ByHostNumber = "HostModalStatus_Prefix_ByHostNumber";
public static string HostModalStatus_BoolFilterPrefix = "HostModalBoolFilter";
public static string RoomStatus_Prefix = "RoomStatusReceiver";
public static string AllReadyDealWith0E_Prefix = "SAME_0E";
public static string AllReadyDealWith01_Prefix = "SAME_01";
//C#自身缓存
/// <summary>
/// string KKK1 = CacheKey.HostInfo_Key_MAC + hhotelcode + "_" + mac;
/// </summary>
public static string HostInfo_Key_MAC = "HostInfo_Key_MAC";
//通过 host_numbe 来存储
public static string HostInfo_Key_HostNumber = "HostInfo_Key_HostNumber";
//通过hotelcode
public static string HotelInfo_Key_Code = "HotelInfo_Key_Code";
/// <summary>
/// 这个主要是结合 hotelid 和room_number来使用
/// </summary>
public static string WebAPIGetRCUStatus = "WebAPIGetRCUStatus";
public static string FCSToken = "FCS_Security_Authenticate";
public static string TCLToken = "TCL_Security_Authenticate";
/// <summary>
/// 升级进度
/// </summary>
public static string UPGradeProgressBar = "UPProgressBar";
/// <summary>
///
/// </summary>
public static string SendDataRepeatKey = "SendDataRepeatKey";
public static string LieECOKey = "LieECOKey";
/// <summary>
/// 省电模式,小坑用户
/// </summary>
public static string LieECOTask = "LieECOTask";
/// <summary>
/// 2025-08-05 开会08 0E 如果超过2秒钟不再处理
/// </summary>
public static string TimeIntercept = "TimeIntercept";
public static string SyncTimeIntercept = "SyncTimeIntercept";
public static string RCUOnLine = "RCUOnLine";
public static string TakeCardOnLine = "TakeCardOnLine";
/// <summary>
/// 天猫精灵
/// </summary>
public static string TianMaoJingLing = "TianMaoJingLing";
public static string TianMaoJingLingQuerryAll = "TianMaoJingLingQuerryAll";
/// <summary>
/// 小度语音
/// </summary>
public static string XiaoDuYuYin = "XiaoDuYuYin";
public static string TCLYuYin = "TCLYuYin";
public static string PublicKeyboard = "PublicKeyboard";
public static string HostFrameNo = "HostFrameNo";
public static string PowerSupply = "PowerSupply";
public static string LockVoltage = "LockVoltage";
public static string HostTemp = "HostTemp";
public static string NengHao = "NengHao";
public static string SyncRoomStatus = "SyncRoommStatus";
public static string ServiceInfoOther = "ServiceInfoOther";
public static string InvokeHttpInterface = "redis-invoke_httpinterface";
public static string XiaoDuCacheUpdate = "XiaoDuCacheUpdate";
public static string TouChuanKey = "TouChuanKey";
public static string HostId_HostNumber = "HostId_HostNumber";
public static string RoomNumber_HostNumber = "RoomNumber_HostNumber";
public static string DingShiReportData = "TimerReportData";
/// <summary>
/// 空调凌晨定时控制
/// </summary>
public static string KT_Timer_Controller = "KT_Timer_Controller";
/// <summary>
/// 清理 在开的状态下3分钟之内只能触发一次
/// </summary>
public static string CleanFCS_TriggerCount = "CleanFCS_TriggerCount";
public static string FCSOrder = "FCSOrder";
public static string FCSRoom_Mapping_Order = "FCS_R_M_O";
}
public class ChangLiangValue
{
public static string CommandType_FCS = "FCS";
public static string TCL = "TCL";
public static string SkyWorth = "SkyWorth";
public static string TianMao = "TianMao";
public static string XiaoDu = "XiaoDu";
}
}

View File

@@ -0,0 +1,108 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CommonEntity</RootNamespace>
<AssemblyName>CommonEntity</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="jose-jwt">
<HintPath>..\lib\jwt\jose-jwt.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\log4net\log4net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="RestSharp">
<HintPath>..\lib\RestSharp\RestSharp.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CacheDTO.cs" />
<Compile Include="CacheKey.cs" />
<Compile Include="DataTongJi.cs" />
<Compile Include="FCS.cs" />
<Compile Include="ForkSystem.cs" />
<Compile Include="GaiXie.cs" />
<Compile Include="GetHostIDByNumber.cs" />
<Compile Include="HisenseData.cs" />
<Compile Include="HiWei.cs" />
<Compile Include="HostMappingData.cs" />
<Compile Include="HostModal_Cache.cs" />
<Compile Include="HostNumber_CacheData.cs" />
<Compile Include="HostSearchEntity.cs" />
<Compile Include="JWTData.cs" />
<Compile Include="KongQi.cs" />
<Compile Include="LieECOTaskExtra.cs" />
<Compile Include="LingChenECO.cs" />
<Compile Include="LogRecorrd.cs" />
<Compile Include="LostData.cs" />
<Compile Include="MissionRequestData.cs" />
<Compile Include="MonitorLog.cs" />
<Compile Include="MyHttp.cs" />
<Compile Include="NewDataSQL.cs" />
<Compile Include="NewRoomStatusPush.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RedisTakeCardStatus.cs" />
<Compile Include="RedisTongJiData.cs" />
<Compile Include="RoomStatusRequest.cs" />
<Compile Include="SkyWorth.cs" />
<Compile Include="SmartVoiceData.cs" />
<Compile Include="TCLToken.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{B3F29715-E925-4E56-9248-580F06C3BC11}</Project>
<Name>Common</Name>
</ProjectReference>
<ProjectReference Include="..\Domain\Domain.csproj">
<Project>{A42D287A-8EF4-48F6-B14C-7F9CA834F786}</Project>
<Name>Domain</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

338
CommonEntity/DataTongJi.cs Normal file
View File

@@ -0,0 +1,338 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
using System.Collections.Concurrent;
using System.Threading;
namespace CommonEntity
{
public class DataTongJi
{
public static ConcurrentDictionary<string, UDPPackageCount> TotalCount = new ConcurrentDictionary<string, UDPPackageCount>();
public static ConcurrentBag<double> CPU_Data = new ConcurrentBag<double>();
/// <summary>
/// 下位机黑名单
/// </summary>
//public static UDPPackageBlockFilter BlockLowerMachineList = new UDPPackageBlockFilter();
public static ConcurrentDictionary<string, ConcurrentBag<string>> BlockLowerMachineList = new ConcurrentDictionary<string, ConcurrentBag<string>>();
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(DataTongJi));
/// <summary>
/// 0x19数据
/// </summary>
public static ConcurrentBag<string> ZeroX19_PassHotelCode = new ConcurrentBag<string>();
/// <summary>
/// RCU在线数量
/// </summary>
public static ConcurrentDictionary<string, RCUOnLineExtra> ONLINERCU = new ConcurrentDictionary<string, RCUOnLineExtra>();
/// <summary>
/// 取电开关
/// </summary>
public static ConcurrentDictionary<string, MTakeCardData> TakeCardOnLine = new ConcurrentDictionary<string, MTakeCardData>();
/// <summary>
/// 在线用户
/// </summary>
public static ConcurrentDictionary<string, OnLineUser> OnLineUserList_IP = new ConcurrentDictionary<string, OnLineUser>();
//public static ConcurrentDictionary<string, OnLineUser> OnLineUserList_Account = new ConcurrentDictionary<string, OnLineUser>();
public class MTakeCardData
{
public string HostNUMBER { get; set; }
public string HotelCode { get; set; }
public byte Status { get; set; }
public DateTime LastUpdateTime { get; set; }
}
public class OtherServiceInfo
{
public string HotelCode { get; set; }
public string HostNumber { get; set; }
public string Address { get; set; }
public ushort StatusReceiver { get; set; }
public DateTime LastUpdateTime { get; set; }
}
public static long DefineLostPackage = 0;
/// <summary>
/// 记录丢失的数据
/// </summary>
public static long RecordLostPackage = 0;
public static int LostPackage_Interval = 60;
/// <summary>
/// 判断 A数组是否包含B数组
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="subsequence"></param>
/// <returns></returns>
public static bool ContainsSubsequence<T>(List<T> source, List<T> subsequence)
{
if (subsequence.Count == 0) return true;
if (source.Count < subsequence.Count) return false;
for (int i = 0; i <= source.Count - subsequence.Count; i++)
{
var subList = source.GetRange(i, subsequence.Count);
if (subList.SequenceEqual(subsequence))
return true;
}
return false;
}
public static void CeShi()
{
List<byte> A = new List<byte> { 0x01, 0x02, 0x04, 0x00, 0x01, 0xff, 0xff, 0xff, 0x04, 0x00, 0x01, 0xAA, 0xBB, 0xCC, 0x04, 0x00, 0x01, 0xCC, 0xDD, 0x01 };
List<byte> target = new List<byte> { 0x04, 0x00, 0x01 };
// 查找所有匹配的位置
List<int> matchIndices = FindAllMatches(A, target);
if (matchIndices.Count > 0)
{
Console.WriteLine("找到匹配的序列:");
foreach (int index in matchIndices)
{
// 提取匹配序列及其后两个字节
int start = index;
int end = Math.Min(index + target.Count + 3, A.Count);
List<byte> extracted = A.GetRange(start, end - start);
}
}
else
{
Console.WriteLine("未找到匹配的序列");
}
}
/// <summary>
/// 查找匹配的位置
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <returns></returns>
public static List<int> FindAllMatches(List<byte> source, List<byte> target)
{
List<int> indices = new List<int>();
if (target.Count == 0 || source.Count < target.Count) return indices;
for (int i = 0; i <= source.Count - target.Count; i++)
{
bool match = true;
for (int j = 0; j < target.Count; j++)
{
if (source[i + j] != target[j])
{
match = false;
break;
}
}
if (match)
{
indices.Add(i);
}
}
return indices;
}
/// <summary>
/// 给某个模块添加 调用次数统计,统计是每个小时 调用的总数
/// </summary>
/// <param name="ModuleName"></param>
public static void InvokeCount(string ModuleName)
{
try
{
DateTime DDT = DateTime.Now;
int Year = DDT.Year;
int MM = DDT.Month;
int dd = DDT.Day;
int HH = DDT.Hour;
string Key = ModuleName + Year + "-" + MM + "-" + dd + "#" + HH;
//string hotelid = Session["CurrentHotelID"].ToString();
//string HotelName = Session["CurrentHotelName"].ToString();
long data = CSRedisCacheHelper.Get_Partition<long>(Key, 1);
if (data == 0)
{
CSRedisCacheHelper.Set_PartitionWithTime<long>(Key, 1, 120, 1);
}
else
{
CSRedisCacheHelper.Set_PartitionWithTime<long>(Key, data += 1, 120, 1);
}
}
catch (Exception)
{
}
}
}
public class RCUOnLineExtra
{
public DateTime CurrentDateTime { get; set; }
public string HotelCode { get; set; }
}
public class StepInfo
{
public long EveryMessageId { get; set; }
public long Monitor_0E_01 { get; set; }
public string HotelCode { get; set; }
public string HostNumber { get; set; }
public string MessageId { get; set; }
public string TriggerTime { get; set; }
public double Step { get; set; }
public string StepDescription { get; set; }
public byte[] Content { get; set; }
}
public class OnLineUser
{
public string Account { get; set; }
public string IP { get; set; }
public string HotelCode { get; set; }
public int HotelId { get; set; }
public DateTime LastUpdateTime { get; set; }
}
public class NengHao
{
public long HotelCode { get; set; }
public string HostNumber { get; set; }
public string RoomNumber { get; set; }
public string Mac { get; set; }
public string EndPoint { get; set; }
public string Version { get; set; }
public bool IsTakeCard { get; set; }
public int CarbonVIP { get; set; }
public double V { get; set; }
public double A { get; set; }
public double P { get; set; }
public double KW_H { get; set; }
public double Sum_KW_H { get; set; }
public long CreateTime { get; set; }
public DateTime ReportTime { get; set; }
}
public class NengHao4BaoJing
{
public long HotelCode { get; set; }
public string HostNumber { get; set; }
public string RoomNumber { get; set; }
public string Mac { get; set; }
public string EndPoint { get; set; }
public string Version { get; set; }
public bool IsTakeCard { get; set; }
public int CarbonVIP { get; set; }
public double V { get; set; }
public double A { get; set; }
public double P { get; set; }
public double Energy_Consumption { get; set; }
public double Sum_Energy_Consumption { get; set; }
public long CreateTime { get; set; }
public string ReportTime { get; set; }
public List<DingShiReportDate> AllDeviceData { get; set; }
public int IdentityInfo {get;set;}
}
public class Interface3Log
{
public string HotelCode { get; set; }
public string HostNumber { get; set; }
public string RoomNumber { get; set; }
public HttpActionData ActionData { get; set; }
public DateTime TriggerTime { get; set; }
public string CommandType { get; set; }
}
public class HttpActionData
{
public double Step { get; set; }
public string RequestData { get; set; }
public string ResponseData { get; set; }
}
public class WelcomeAction
{
public string CUID { get; set; }
public string VoiceDeviceClass { get; set; }
public string CommandType { get; set; }
}
public class StepTongJi
{
/// <summary>
/// 每一条消息都有一个ID
/// </summary>
public static long EveryMessageIDNo = 0;
/// <summary>
/// 每一个01和0E的编号
/// </summary>
public static long Every_0E_01_MessageID = 0;
/// <summary>
/// 每 一条消息都有一个ID
/// </summary>
public static string EveryMessageID = "";
/// <summary>
/// 1000包抓取一包,抓包计数器
/// </summary>
public static long LookDataCounter = 0;
/// <summary>
/// 要监听的数据包编号
/// </summary>
public static string GlobalListenID = "";
public static string GlobalListenIDNo = "";
/// <summary>
/// 是否要锁定
/// </summary>
public static int IsLocked = 0;
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(StepTongJi));
/// <summary>
/// 发送Redis广播
/// </summary>
/// <param name="step"></param>
/// <param name="desc"></param>
/// <param name="context_messageid"></param>
public static void SendInfo(double step, string desc, string context_messageid, bool ismonitor)
{
try
{
if (ismonitor)
{
StepInfo s = new StepInfo();
s.MessageId = context_messageid;
s.Step = step;
s.StepDescription = desc;
//string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff");
string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
s.TriggerTime = ti;
string NNN = Newtonsoft.Json.JsonConvert.SerializeObject(s);
CSRedisCacheHelper.Publish("redis-roomstatus-monitor", NNN);
}
}
catch (Exception ex)
{
logger.Error("StepTongJi Error:" + ex.Message);
}
}
}
}

473
CommonEntity/FCS.cs Normal file
View File

@@ -0,0 +1,473 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using RestSharp;
using System.Net;
using Newtonsoft.Json.Linq;
using Common;
using Newtonsoft.Json;
namespace CommonEntity
{
public class User
{
public string username { get; set; }
public string password { get; set; }
public int oauth_id { get; set; }
}
public class FCS_ReturnInfo
{
public int success { get; set; }
public FCS_ReturnData data { get; set; }
}
// {"success": 1, "data": true, "rmsg": {"code": "s_job_orders", "param": ["JO-0001970-01"]}}
public class FCS_JobResponse
{
public int success { get; set; }
public bool data { get; set; }
//"rmsg":
//[
//{
// "code": "s_user_not_found",
// "param": []
//}
//]
public List<FCSJobResponseData> rmsg { get; set; }
}
public class FCSJobResponseData
{
public string code { get; set; }
public List<string> param { get; set; }
}
public class FCS_ReturnData
{
public bool is_authenticated { get; set; }
public string access_token { get; set; }
public string refresh_token { get; set; }
public bool show_password_expire { get; set; }
public string password_expired_date { get; set; }
public bool password_expired { get; set; }
public bool valid_license_access { get; set; }
public bool require_reset { get; set; }
public string property_config { get; set; }
public string show_pp { get; set; }
public int oauth_id { get; set; }
public bool is_ip_valid { get; set; }
public bool is_support_aliyun { get; set; }
}
public class FCS_JobRequest
{
public List<string> location_uuid { get; set; }
public List<FCS_service_items> service_items { get; set; }
public string remark { get; set; }
public string assigned_to { get; set; }
public int user_type { get; set; }
public bool get_details { get; set; }
}
public class FCS_service_items
{
public string item_uuid { get; set; }
public int quantity { get; set; }
}
public struct FCS_OrderData
{
public string LocationUUID { get; set; }
public string ItemUUID { get; set; }
public string PropertyID { get; set; }
public string ItemType { get; set; }
public string OrderUUID { get; set; }
public string OrderNo { get; set; }
public string HotelCode { get; set; }
public string RoomNUMBER { get; set; }
public string HostNUMBER { get; set; }
}
public class FCS_Response
{
public int success { get; set; }
public List<FCS_R_DataItem> data { get; set; }
public RMSG rmsg { get; set; }
}
public class FCS_R_DataItem
{
public string job_no { get; set; }
public string job_status_colour { get; set; }
public string job_uuid { get; set; }
}
public class RMSG
{
public string code { get; set; }
public List<string> param { get; set; }
}
/// <summary>
/// 查询 类
/// </summary>
public class QueryFCSOrder
{
public string filter { get; set; }
public OrderQueryItem column_filter { get; set; }
}
public class OrderQueryItem
{
public string field { get; set; }
public List<string> value { get; set; }
}
public class QueryOrderResponse
{
public string success { get; set; }
public List<Dictionary<string, string>> data { get; set; }
public object[] rmsg { get; set; }
}
public class RR
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(RR));
private static void SSLXieYi()
{
//ssl 协议不兼容
var A = (SecurityProtocolType)48;
var B = (SecurityProtocolType)192;
var C = (SecurityProtocolType)768;
var D = (SecurityProtocolType)3072;
var E = (SecurityProtocolType)12288;
ServicePointManager.SecurityProtocol = A | B | C | D | E;
}
public static void Login(string FCSLoginUrl, string FCSLoginUserName, string FCSLoginPassWord, string HotelCode, string RoomNum)
{
try
{
SSLXieYi();
var client1 = new RestClient(FCSLoginUrl);
var request1 = new RestRequest("/api/security/authenticate", Method.POST);
Dictionary<string, string> dic = new Dictionary<string, string>();
User us = new User();
us.username = FCSLoginUserName;
us.password = FCSLoginPassWord;
us.oauth_id = 1;
request1.AddJsonBody(us);
Interface3Log w1 = new Interface3Log();
w1.HotelCode = HotelCode;
w1.RoomNumber = RoomNum;
w1.TriggerTime = DateTime.Now;
w1.ActionData = new HttpActionData() { RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(dic) };
w1.CommandType = ChangLiangValue.CommandType_FCS;
var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);
var QQQ = client1.Execute(request1);
HttpStatusCode HHH = QQQ.StatusCode;
if (HHH == HttpStatusCode.Created || HHH == HttpStatusCode.OK)
{
string ddd = QQQ.Content;
Interface3Log w2 = new Interface3Log();
w2.HotelCode = HotelCode;
w2.RoomNumber = RoomNum;
w2.TriggerTime = DateTime.Now;
w2.ActionData = new HttpActionData() { ResponseData = ddd };
w2.CommandType = ChangLiangValue.CommandType_FCS;
var q2 = Newtonsoft.Json.JsonConvert.SerializeObject(w2);
CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q2);
var FFFA = Newtonsoft.Json.JsonConvert.DeserializeObject<FCS_ReturnInfo>(ddd);
string TokenKey = CacheKey.FCSToken;
CSRedisCacheHelper.Set_Partition(TokenKey, FFFA, 1);
}
}
catch (Exception ex)
{
logger.Error("FCS Login Error" + ex.Message);
logger.Error(ex.StackTrace);
}
//client1.ExecuteAsync(request1, (response) =>
//{
// Console.WriteLine(response.Content);
//});
}
public static void JobRequest(string AccessToken, string location_uuid, string item_uuid, string FCSLoginUrl, string UserName, string PassWord, string PropertyID, string code, string roomno, string remarkdata, string itemclass)
{
if (string.IsNullOrEmpty(item_uuid))
{
return;
}
SSLXieYi();
var client1 = new RestClient(FCSLoginUrl);
var request1 = new RestRequest("/api-secure/job/request", Method.POST);
FCS_JobRequest fff = new FCS_JobRequest();
fff.location_uuid = new List<string>() { location_uuid };
fff.service_items = new List<FCS_service_items>()
{
new FCS_service_items()
{
item_uuid=item_uuid,
quantity=1
}
};
fff.remark = remarkdata;
fff.assigned_to = "auto";
fff.user_type = 1;
fff.get_details = true;
string WER = Newtonsoft.Json.JsonConvert.SerializeObject(fff);
logger.Error("push data is " + WER);
logger.Error("push token is " + AccessToken);
request1.AddHeader("token", AccessToken);
//下面这个是个定值
request1.AddHeader("property", PropertyID);
request1.AddParameter("payload", WER);
Interface3Log w1 = new Interface3Log();
w1.HotelCode = code;
w1.RoomNumber = roomno;
w1.TriggerTime = DateTime.Now;
w1.ActionData = new HttpActionData() { RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(WER) };
w1.CommandType = ChangLiangValue.CommandType_FCS;
var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);
client1.ExecuteAsync(request1, (QQQ) =>
{
HttpStatusCode HHH = QQQ.StatusCode;
string FHS = QQQ.Content;
Interface3Log w2 = new Interface3Log();
w2.HotelCode = code;
w2.RoomNumber = roomno;
w2.TriggerTime = DateTime.Now;
w2.ActionData = new HttpActionData() { ResponseData = FHS };
w2.CommandType = ChangLiangValue.CommandType_FCS;
var q2 = Newtonsoft.Json.JsonConvert.SerializeObject(w2);
CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q2);
//{
// "success": 1,
// "data": [
// {
// "job_no": "JO-0004548-01",
// "job_status_colour": "#FA8C16",
// "job_uuid": "b1dcb088-6dbc-4ca5-a1c4-0a8b951113fd"
// }
// ],
// "rmsg": {
// "code": "s_job_orders",
// "param": [
// "JO-0004548-01"
// ]
// }
//}
logger.Error("PushData 返回值为:" + FHS);
logger.Error("PushData Status:" + HHH.ToString());
if (string.IsNullOrEmpty(FHS))
{
return;
}
JObject jsonObject = JObject.Parse(FHS);
var error = jsonObject.SelectToken("error");
//如果有错
if (error != null)
{
Login(FCSLoginUrl, UserName, PassWord, code, roomno);
}
else
{
if (itemclass.Equals("Clean"))
{
logger.Error("写入订单"+FHS);
//FCS_Response
var FFF = JsonConvert.DeserializeObject<FCS_Response>(FHS);
var JJJ = FFF.data.FirstOrDefault();
if (JJJ != null)
{
string orderuuid = JJJ.job_uuid;
FCS_OrderData f = new FCS_OrderData();
f.OrderUUID = orderuuid;
f.PropertyID = PropertyID;
f.ItemType = "Clean";
f.OrderNo = JJJ.job_no;
f.ItemUUID = item_uuid;
f.LocationUUID = location_uuid;
f.HotelCode = code;
f.RoomNUMBER = roomno;
string fsa = Newtonsoft.Json.JsonConvert.SerializeObject(f);
//这个是 供轮循的时候调用使用
CSRedisCacheHelper.HMSet(3, 60 * 24, CacheKey.FCSOrder, fsa);
//这个是供 取消订单的时候使用的
//这个只 支持 取消 清理
logger.Error("记录入循环:"+orderuuid);
CSRedisCacheHelper.Set_PartitionWithTime(CacheKey.FCSRoom_Mapping_Order + "_" + location_uuid, orderuuid, 24 * 60, 3);
}
}
}
if (HHH == HttpStatusCode.OK)
{
}
});
}
/// <summary>
/// FCS数据推送
/// </summary>
/// <param name="Item_UUID"></param>
public static void FCS_PushData(string Item_UUID, string location_UUID, string PropertyUUID, string LoginUrl, string UserName, string PassWord, string code, string roomno, string remarkdata = "", string HOSTNUMBER = "")
{
try
{
if (string.IsNullOrEmpty(Item_UUID))
{
return;
}
//logger.Error("FCS push data");
if (!string.IsNullOrEmpty(location_UUID))
{
string Key = CacheKey.FCSToken;
var TokenTakeOut = CSRedisCacheHelper.Get_Partition<FCS_ReturnInfo>(Key, 1);
if (TokenTakeOut == null)
{
logger.Error("FCS login");
RR.Login(LoginUrl, UserName, PassWord, code, roomno);
}
else
{
logger.Error("FCS push action data");
string ItemClass = "";
if (!string.IsNullOrEmpty(HOSTNUMBER))
{
ItemClass = "Clean";
}
logger.Error("FCS push action itemclass:" + ItemClass);
RR.JobRequest(TokenTakeOut.data.access_token, location_UUID, Item_UUID, LoginUrl, UserName, PassWord, PropertyUUID, code, roomno, remarkdata, ItemClass);
if (!string.IsNullOrEmpty(HOSTNUMBER))
{
string CleanTrigger = CacheKey.CleanFCS_TriggerCount + "_" + HOSTNUMBER;
CSRedisCacheHelper.Set_PartitionWithTime<int>(CleanTrigger, 1, 3);
}
}
}
}
catch (Exception ex)
{
logger.Error("FCS PushData Error: " + ex.Message);
}
}
/// <summary>
/// 取消Job
/// </summary>
/// <param name="AccessToken"></param>
/// <param name="location_uuid"></param>
/// <param name="item_uuid"></param>
/// <param name="FCSLoginUrl"></param>
/// <param name="UserName"></param>
/// <param name="PassWord"></param>
/// <param name="PropertyID"></param>
/// <param name="HotelCode"></param>
/// <param name="RoomNo"></param>
/// <param name="remarkdata"></param>
/// <param name="itemclass"></param>
public static void JobCancelRequest(string AccessToken, string FCSLoginUrl, string PropertyID, string HotelCode, string RoomNo, string OrderId)
{
if (string.IsNullOrEmpty(OrderId))
{
return;
}
SSLXieYi();
string RUrl = string.Format("/job/order/{0}/cancelled", OrderId);
var client1 = new RestClient(FCSLoginUrl);
var request1 = new RestRequest(RUrl, Method.POST);
logger.Error("push data is " + OrderId);
logger.Error("push token is " + AccessToken);
request1.AddHeader("token", AccessToken);
//下面这个是个定值
request1.AddHeader("property", PropertyID);
Interface3Log w1 = new Interface3Log();
w1.HotelCode = HotelCode;
w1.RoomNumber = RoomNo;
w1.TriggerTime = DateTime.Now;
w1.ActionData = new HttpActionData() { RequestData = OrderId };
w1.CommandType = ChangLiangValue.CommandType_FCS;
var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);
client1.ExecuteAsync(request1, (QQQ) =>
{
HttpStatusCode HHH = QQQ.StatusCode;
string FHS = QQQ.Content;
logger.Error("cancel PushData not data is" + FHS);
Interface3Log w2 = new Interface3Log();
w2.HotelCode = HotelCode;
w2.RoomNumber = RoomNo;
w2.TriggerTime = DateTime.Now;
w2.ActionData = new HttpActionData() { ResponseData = FHS };
w2.CommandType = ChangLiangValue.CommandType_FCS;
var q2 = Newtonsoft.Json.JsonConvert.SerializeObject(w2);
CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q2);
});
}
public static void FCS_CancelOrderJob(string location_UUID, string PropertyUUID, string LoginUrl, string UserName, string PassWord, string code, string roomno, string OrderUUID = "")
{
try
{
if (string.IsNullOrEmpty(OrderUUID))
{
return;
}
if (!string.IsNullOrEmpty(location_UUID))
{
string Key = CacheKey.FCSToken;
var TokenTakeOut = CSRedisCacheHelper.Get_Partition<FCS_ReturnInfo>(Key, 1);
if (TokenTakeOut == null)
{
logger.Error("FCS login");
RR.Login(LoginUrl, UserName, PassWord, code, roomno);
}
else
{
logger.Error("FCS cancel push action data");
RR.JobCancelRequest(TokenTakeOut.data.access_token, LoginUrl, PropertyUUID, code, roomno, OrderUUID);
}
}
}
catch (Exception ex)
{
logger.Error("FCS PushData Error: " + ex.Message);
}
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
namespace CommonEntity
{
public class ForkSystem
{
public string EndPoint { get; set; }
public byte[] Data { get; set; }
public DateTime CurrentTime { get; set; }
}
public class Fork_Function
{
public static void PublishData<T>(T f)
{
string mns2 = Newtonsoft.Json.JsonConvert.SerializeObject(f);
CSRedisCacheHelper.Publish("redis-forksystemdata", mns2);
}
}
}

13
CommonEntity/GaiXie.cs Normal file
View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public struct GaiXie
{
public byte[] Data { get; set; }
public string IPEndPoint { get; set; }
}
}

View File

@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain;
namespace CommonEntity
{
public class GetHostIDByNumber
{
public int ID { get; set; }
public string HostNumber { get; set; }
public string RoomNumber { get; set; }
public string HotelCode { get; set; }
}
public class NewVersionHexData
{
public byte CmdType { get; set; }
public string HotelCode { get; set; }
public string HostNumber { get; set; }
public string RoomNumber { get; set; }
public string RemoteEndPoint { get; set; }
public string HexData { get; set; }
public DateTime CurrentTime { get; set; }
}
/// <summary>
/// 新版本的设备状态
/// </summary>
public class NewVersionDeviceStatus
{
public string HotelCode { get; set; }
public string HostNumber { get; set; }
public string RoomNumber { get; set; }
public string DeviceAddress { get; set; }
/// <summary>
/// 当前设备是 空调 灯光
/// </summary>
public DeviceType ModalType { get; set; }
/// <summary>
/// 调光亮度
/// </summary>
public int Brightness { get; set; }
/// <summary>
/// 开关状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 空调
/// </summary>
public AirConditionData AirConditionData { get; set; }
public DateTime? UpdateTime { get; set; }
public int Time { get; set; }
}
}

39
CommonEntity/HiWei.cs Normal file
View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;
using System.Net;
namespace CommonEntity
{
public class HiWei
{
public static string BaseUrl = "tvos.hw-iot.com.cn";
public void Login()
{
try
{
var client1 = new RestClient(BaseUrl);
var request1 = new RestRequest("/api/security/authenticate", Method.POST);
Dictionary<string, string> dic = new Dictionary<string, string>();
User us = new User();
us.username = "";
us.password = "";
us.oauth_id = 1;
request1.AddJsonBody(us);
var QQQ = client1.Execute(request1);
HttpStatusCode HHH = QQQ.StatusCode;
if (HHH == HttpStatusCode.Created||HHH==HttpStatusCode.OK)
{
}
}
catch (Exception)
{
}
}
}
}

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class HaiXinData
{
public string baiduReqBody { get; set; }
public string deviceFactory { get; set; }
public string forceUpdate { get; set; }
public string deleteFlag { get; set; }
public string hotelContract { get; set; }
public List<string> macList { get; set; }
}
public class HaiXinHeader
{
public header header { get; set; }
public payload payload { get; set; }
}
public class header
{
public string @namespace { get; set; }
public string name { get; set; }
public string messageId { get; set; }
public string payloadVersion { get; set; }
}
public class payload
{
public string accessToken { get; set; }
public string openUid { get; set; }
public string cuid { get; set; }
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class HostMappingData
{
public int Id { get; set; }
public string HostNumber { get; set; }
}
public class HostRoomNumberMapping
{
public string HostNumber { get; set; }
public string RoomNumber { get; set; }
}
}

View File

@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain;
using System.Collections.Concurrent;
namespace CommonEntity
{
/// <summary>
/// 这个类是 组合 式的
///
/// 意思是 根据类型,来选取相应的字段
/// 比如说 空调只就需要使用空调的
/// 调光灯 只需要 一个亮度。
///
/// 这样修改最原来的代码是 最简单,最快的,但是不是最合理的
///
/// 如果分开写的话,设备类型太多,写不过来
/// </summary>
public class HostModal_Cache
{
public int HostID { get; set; }
/// <summary>
/// 设备的一些基础信息,如地址,名称
/// </summary>
public RoomTypeModalCache Modal { get; set; }
/// <summary>
/// 当前设备是 空调 灯光
/// </summary>
public DeviceType ModalType { get; set; }
/// <summary>
/// 调光亮度
/// </summary>
public int Brightness { get; set; }
/// <summary>
/// 开关状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 空调
/// </summary>
public AirConditionData AirConditionData { get; set; }
public DateTime? UpdateTime { get; set; }
public int Time { get; set; }
}
public class AirConditionData
{
/// <summary>
/// 开关
/// </summary>
public int AirStatus { get; set; }
/// <summary>
/// 当前温度
/// </summary>
public int CurrentTemp { get; set; }
/// <summary>
/// 设定温度
/// </summary>
public int SettingTemp { get; set; }
/// <summary>
/// 风速
/// </summary>
public int FanSpeed { get; set; }
/// <summary>
/// 模式
/// </summary>
public int Mode { get; set; }
/// <summary>
/// 阀门
/// </summary>
public int Valve { get; set; }
/// <summary>
/// 当天开启时长
/// </summary>
public int Time { get; set; }
public DateTime? UpdateTime { get; set; }
}
public class RoomTypeModalCache
{
public int ID { get; set; }
/// <summary>
/// 设备的名字
/// </summary>
public string Name { get; set; }
/// <summary>
/// 设备的地址
/// </summary>
public string ModalAddress { get; set; }
/// <summary>
/// 设备所属的房型
/// </summary>
public int RoomTypeID { get; set; }
public int Sort { get; set; }
public bool ActiveIndicator { get; set; }
}
}

View File

@@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain;
namespace CommonEntity
{
public class SomeDeviceExistsData
{
public string HostNUMBER { get; set; }
public string IP { get; set; }
public string MAC { get; set; }
public int HotelID { get; set; }
public int RoomTypeID { get; set; }
public int HostID { get; set; }
public string HotelCode { get; set; }
public string RoomNumber { get; set; }
public int FrameNo { get; set; }
/// <summary>
/// 电源锁定0正常1锁定
/// </summary>
public bool PowerSupply { get; set; }
/// <summary>
/// 门锁电量
/// </summary>
public ushort LockVoltage { get; set; }
/// <summary>
/// 主机温度
/// </summary>
public byte HostTemp { get; set; }
public string CreatDate { get; set; }
/// <summary>
/// 有的时候有用
/// </summary>
public string ModalID { get; set; }
/// <summary>
/// 房门开还是关
/// </summary>
public bool DoorLockStatus { get; set; }
/// <summary>
/// 门锁状态
/// </summary>
public int LockStatus { get; set; }
/// <summary>
/// 房态 是出租房,还是空房
/// </summary>
public RoomStatus RoomStatus { get; set; }
public string RoomCard{get;set;}
public string OutCardTime { get; set; }
public RoomCard RoomCardData { get; set; }
public string DeviceStatusPushURL { get; set; }
public string TianMaoCUID { get; set; }
public string XiaoDuCUID { get; set; }
public string WelcomeSpeech { get; set; }
public string GoodbyeSpeech { get; set; }
//断电重置智能音箱
public bool IsPowerOffResetXiaoDu { get; set; }
public string FaultPushURL { get; set; }
public string DisableStartTime { get; set; }
public string DisableEndTime { get; set; }
public bool IsWelcomeDisableTime { get; set; }
}
public class AirCondition
{
public int AirID = 0;
public int AirStatus = 2;
public string ModalAddress = "";
public int RoomTemp = 0;
public int SettingTemp = 0;
public int Mode = 0;
public int FanSpeed = 0;
public int Valve = 0;
public string ValveName; //阀门
}
}

View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class HostSearchEntity
{
public string HostNumber { get; set; }
public string RoomNumber { get; set; }
public string DNS { get; set; }
public string Version { get; set; }
public string ConfigVersion { get; set; }
public string SubnetMask { get; set; }
public string Gateway { get; set; }
public string Remark { get; set; }
public DateTime? Last_Modified_Time { get; set; }
public string IP { get; set; }
public int Port { get; set; }
public string MAC { get; set; }
public string DeviceName { get; set; }
public bool IsAutoGetKey { get; set; }
public string DeviceSecret { get; set; }
public string IotId { get; set; }
public string ProductKey { get; set; }
public bool IsPublish { get; set; }
}
}

135
CommonEntity/JWTData.cs Normal file
View File

@@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Jose;
using Common;
namespace CommonEntity
{
public class JWTData
{
/// <summary>
/// 主题
/// </summary>
public string sub { get; set; }
/// <summary>
/// 发行人
/// </summary>
public string iss { get; set; }
/// <summary>
/// 到期时间
/// </summary>
public long exp { get; set; }
/// <summary>
/// 用户
/// </summary>
public string aud { get; set; }
/// <summary>
/// 在此之前不可用
/// </summary>
public string nbf { get; set; }
/// <summary>
/// 发布时间
/// </summary>
public string iat { get; set; }
/// <summary>
///用于标识该JWT
/// </summary>
public string jti { get; set; }
public string username { get; set; }
}
public class ChuangWeiUser
{
public string UserName { get; set; }
public string Version { get; set; }
}
public class ReturnInfo
{
public int code { get; set; }
public string msg { get; set; }
public object data { get; set; }
}
public class TokenData
{
public string accessToken { get; set; }
public string refreshToken { get; set; }
}
public class SignKeyCommon
{
public readonly static string ChuangWei_JWTKey = "#这x是98一个uv永远$不可0能到的a一个数据*";
public static ReturnInfo GetTokenData(string username)
{
DateTime dt = DateTime.Now.AddMonths(6);
string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
long l = Tools.GetCurrentTimeStamp(dt);
CommonEntity.JWTData j = new CommonEntity.JWTData();
j.sub = "创维电视登录";
j.exp = l;
j.aud = "创维电视accesstoken";
j.nbf = DateTime.Now.AddMinutes(3).ToString("yyyy-MM-dd HH:mm:ss.fff");
j.iat = ti;
j.jti = Guid.NewGuid().ToString("N");
j.username = username;
var secretKey = Encoding.UTF8.GetBytes(SignKeyCommon.ChuangWei_JWTKey);
string token = Jose.JWT.Encode(j, secretKey, JwsAlgorithm.HS256);
j.aud = "创维电视refresh_token";
j.jti = Guid.NewGuid().ToString("N");
string refresh_token = Jose.JWT.Encode(j, secretKey, JwsAlgorithm.HS256);
ReturnInfo r = new ReturnInfo();
r.code = 200;
r.msg = "登录成功";
r.data = new TokenData()
{
accessToken = token,
refreshToken = refresh_token
};
return r;
}
public static bool TokenValidate(string retoken, out JWTData data, out int code, out string msg)
{
data = new JWTData();
bool isv = false;
code = 200;
msg = "sucess";
byte[] secretKey = Encoding.UTF8.GetBytes(SignKeyCommon.ChuangWei_JWTKey);
JWTData MMU = Jose.JWT.Decode<JWTData>(retoken, secretKey, JwsAlgorithm.HS256);
if (MMU != null)
{
DateTime dt = Tools.GetCurrentDateTime(MMU.exp);
string username = MMU.username;
if (dt > DateTime.Now)
{
isv = true;
data = MMU;
}
else
{
isv = false;
code = 10042;
msg = "Token值已经过期";
}
}
else
{
isv = false;
code = 10021;
msg = "非法token";
}
return isv;
}
}
}

29
CommonEntity/KongQi.cs Normal file
View File

@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class KongQi
{
public string HotelID { get; set; }
public string HotelCode { get; set; }
public string RoomNumber { get; set; }
public string CreatDate { get; set; }
}
public class KongQiReport
{
public string hotel_code { get; set; }
public string time { get; set; }
public string sign { get; set; }
public string room_no { get; set; }
public string pm25 { get; set; }
public string co2 { get; set; }
public string tvoc { get; set; }
public string humidness { get; set; }
public string temperature { get; set; }
public string methanal { get; set; }
public string pm10 { get; set; }
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class LieECOTaskExtra
{
public string MissionKey { get; set; }
public string TaskType { get; set; }
public string HostNUMBER { get; set; }
public string MAC { get; set; }
public string ModalAddress { get; set; }
public int Status { get; set; }
public int Brightness { get; set; }
public int FanSpeed { get; set; }
public int Mode { get; set; }
public int SetTemperatureValue { get; set; }
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class LingChenECO
{
public string StartTime { get; set; }
public string RelativeValue { get; set; }
public bool IsEnable { get; set; }
public string HotelCode { get; set; }
}
public class TimerECOData
{
public string Key = "HotelCode";
public List<LingChenECO> Data { get; set; }
}
}

View File

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;
using System.Configuration;
namespace CommonEntity
{
public class LogRecorrd
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(LogRecorrd));
public static readonly string LogReportUrl = ConfigurationManager.AppSettings["debug_log_report_url"];
public static void WebAPI_DataSend<T>(T t, string topic)
{
try
{
//这个是 定阅的服务器要写的
//string debug_log_report_mqtt_topic = "blw/webapi/monitor/";
string str = Newtonsoft.Json.JsonConvert.SerializeObject(t);
var client1 = new RestClient(LogReportUrl);
var request1 = new RestRequest("/", Method.POST);
//注意方法是POST
//两个参数名字必须是 topic 和payload ,区分大小写的
request1.AddParameter("topic", topic);
request1.AddParameter("payload", str);
client1.ExecuteAsync(request1, (response) => { });
}
catch (Exception ex)
{
logger.Error("SendMQTTData: " + ex.Message);
}
}
}
}

11
CommonEntity/LostData.cs Normal file
View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class LostData
{
}
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain;
namespace CommonEntity
{
public class MissionRequestData
{
public KongTiaoTimer KT { get; set; }
public int DelayTimer { get; set; }
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class MonitorLog
{
public long HotelCode{get;set;}
public int HostID{get;set;}
public string HostNumber { get; set; }
public string RoomNo{get;set;}
public string LanIP { get; set; }
public int LanPort { get; set; }
public string WWW_IP { get; set; }
public int WWW_Port { get; set; }
public string MAC{get;set;}
public string CommandType { get; set; }
public string SendOrReceive { get; set; }
public string Data { get; set; }
public string CreateTime { get; set; }
}
public class MonitorRedis:MonitorLog
{
public string RemoteEndPointIP { get; set; }
public int RemoteEndPointPort { get; set; }
}
public class Monitor_Host
{
public string HotelCode { get; set; }
public string Key_HostNumber { get; set; }
public string HostID { get; set; }
public string RoomNumber { get; set; }
public string MAC { get; set; }
public string CreateDateTime { get; set; }
}
/// <summary>
/// 语音控制监控类
/// </summary>
public class IOT_Monitor_Host
{
public string HotelCode { get; set; }
public string HotelID { get; set; }
public string RoomNumber { get; set; }
public string CreateDateTime { get; set; }
}
}

48
CommonEntity/MyHttp.cs Normal file
View File

@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;
using System.Net;
namespace CommonEntity
{
public class MyHttp
{
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MyHttp));
/// <summary>
/// 发送HTTP请求
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Url"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static string SendHttpData<T>(string Url, T obj)
{
try
{
var A = (SecurityProtocolType)48;
var B = (SecurityProtocolType)192;
var C = (SecurityProtocolType)768;
var D = (SecurityProtocolType)3072;
var E = (SecurityProtocolType)12288;
ServicePointManager.SecurityProtocol = A | B | C | D | E;
var client1 = new RestClient(Url);
var request1 = new RestRequest("", Method.POST);
var jsa= Newtonsoft.Json.JsonConvert.SerializeObject(obj);
request1.AddJsonBody(obj);
var QQQ = client1.Execute(request1);
HttpStatusCode HHH = QQQ.StatusCode;
string fanhuizhi = QQQ.Content;
return fanhuizhi;
}
catch (Exception ex)
{
logger.Error("Fault Push Error:" + ex.Message);
logger.Error("Fault Push Error:" + ex.StackTrace);
return ex.Message;
}
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;
namespace CommonEntity
{
public class NewDataSQL
{
//public static string BaseUrl = "http://localhost:5108/";
public static string BaseUrl = "http://localhost:7000/";
public static void GenericHOSTNUMBER(string HotelID,string Code)
{
//string str = Newtonsoft.Json.JsonConvert.SerializeObject("");
var client1 = new RestClient(BaseUrl);
var request1 = new RestRequest("api/Values/GenericHOSTNUMBER", Method.POST);
//注意方法是POST
request1.AddParameter("HotelID", HotelID);
request1.AddParameter("HotelCode", Code);
//request1.AddParameter("payload", str);
client1.ExecuteAsync(request1, (response) => { });
}
}
}

View File

@@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class NewRoomStatusPush
{
/// <summary>
/// 酒店编码
/// </summary>
public string code { get; set; }
public string hostnumber { get; set; }
/// <summary>
/// 房号
/// </summary>
public string roomNumber { get; set; }
/// <summary>
/// 回路地址
/// </summary>
public string address { get; set; }
/// <summary>
/// 回路名称
/// </summary>
public string name { get; set; }
/// <summary>
/// 状态
/// </summary>
public int status { get; set; }
/// <summary>
/// 亮度
/// </summary>
public int brightness { get; set; }
/// <summary>
/// 当前温度
/// </summary>
public int currentTemp { get; set; }
/// <summary>
/// 设定温度
/// </summary>
public int settingTemp { get; set; }
/// <summary>
/// 风速
/// </summary>
public int fanSpeed { get; set; }
/// <summary>
/// 模式
/// </summary>
public int mode { get; set; }
/// <summary>
/// 阀门
/// </summary>
public int valve { get; set; }
public long createtime { get; set; }
}
public class DingShiReportDate
{
/// <summary>
/// HostID
/// </summary>
public int HostID { get; set; }
/// <summary>
/// 设备类型
/// </summary>
public string DeviceType { get; set; }
/// <summary>
/// 设备地址
/// </summary>
public string Address { get; set; }
/// <summary>
/// 状态1开2关
/// </summary>
public int Status { get; set; }
/// <summary>
/// 亮度
/// </summary>
public int Brightness { get; set; }
/// <summary>
/// 当前温度
/// </summary>
public int CurrentTemp { get; set; }
/// <summary>
/// 设定温度
/// </summary>
public int SettingTemp { get; set; }
/// <summary>
/// 风速
/// </summary>
public int FanSpeed { get; set; }
/// <summary>
/// 模式
/// </summary>
public int Mode { get; set; }
/// <summary>
/// 阀门
/// </summary>
public int Valve { get; set; }
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("CommonEntity")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("CommonEntity")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("961ad106-c2d8-4768-8301-6e12a794bd64")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class RedisTakeCardStatus
{
public string HostNUMBER { get; set; }
public List<byte> OriginalDat { get; set; }
}
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class RedisTongJiData
{
public string url { get; set; }
public string cron_exp { get; set; }
public string mission_key { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain;
namespace CommonEntity
{
public class RoomStatusRequest
{
public string HostNumber { get; set; }
public string MAC { get; set; }
public RoomStatus Status { get; set; }
}
}

97
CommonEntity/SkyWorth.cs Normal file
View File

@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;
using System.Net;
using Common;
namespace CommonEntity
{
public class SkyWorth
{
private static readonly string BaseUrl = "http://localhost:9000/";
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SkyWorth));
public static void Invoke(string hotelcode, string roomnum, string authCode, int cmd_no)
{
try
{
string R_ID = System.Guid.NewGuid().ToString("N");
string tiA = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
Dictionary<string, string> RequestData = new Dictionary<string, string>();
RequestData.Add("HotelCode", hotelcode);
RequestData.Add("RoomNumber", roomnum);
RequestData.Add("RequestId", R_ID);
var R_cmd = new Dictionary<string, string>();
R_cmd.Add("room", roomnum);
R_cmd.Add("event", cmd_no.ToString());
R_cmd.Add("authCode", authCode);
var cmdstr = Newtonsoft.Json.JsonConvert.SerializeObject(R_cmd);
RequestData.Add("RequestCmd", cmdstr);
RequestData.Add("RequestTime", tiA);
//LogRecorrd.WebAPI_DataSend(RequestData, "api/skyworth");
var client1 = new RestClient(BaseUrl);
var request1 = new RestRequest("api/skyworth", Method.POST);
request1.AddParameter("room", roomnum);
request1.AddParameter("event", cmd_no);
request1.AddParameter("authCode", authCode);
logger.Error("调用子创维电视:数据为:" + authCode + " RoomNUM" + roomnum);
Interface3Log w1 = new Interface3Log();
w1.HotelCode = hotelcode;
w1.RoomNumber = roomnum;
w1.TriggerTime = DateTime.Now;
w1.ActionData = new HttpActionData() { RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(RequestData) };
w1.CommandType = ChangLiangValue.SkyWorth;
var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);
client1.ExecuteAsync(request1, (QQQ) =>
{
HttpStatusCode HHH = QQQ.StatusCode;
string FHS = QQQ.Content;
logger.Error("调用创维电视,结果为:" + FHS);
//string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
//Dictionary<string, string> ResponseData = new Dictionary<string, string>();
//ResponseData.Add("HotelCode", hotelcode);
//ResponseData.Add("RoomNumber", roomnum);
//ResponseData.Add("RequestId", R_ID);
//ResponseData.Add("ResponseMsg", FHS);
//ResponseData.Add("ResponseTime", ti);
//LogRecorrd.WebAPI_DataSend(ResponseData, "api/skyworth");
Interface3Log ww = new Interface3Log();
ww.HotelCode = hotelcode;
ww.RoomNumber = roomnum;
ww.TriggerTime = DateTime.Now;
ww.ActionData = new HttpActionData() { ResponseData = FHS };
ww.CommandType = ChangLiangValue.SkyWorth;
var qq = Newtonsoft.Json.JsonConvert.SerializeObject(ww);
CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, qq);
});
}
catch (Exception ex)
{
logger.Error("创维电视前台叫出问题了:" + ex.Message);
}
}
}
public class iotVoiceData
{
public string room { get; set; }
public string @event { get; set; }
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommonEntity
{
public class SmartVoiceData
{
//小度
public string HotelCode { get; set; }
public string RoomNumber { get; set; }
public string XiaoDuCUID { get; set; }
public string TianMaoCUID { get; set; }
public string WelcomeSpeech { get; set; }
//断电重置
public bool IsPowerOffResetXiaoDu { get; set; }
public string GoodbyeSpeech { get; set; }
}
}

158
CommonEntity/TCLToken.cs Normal file
View File

@@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;
using Common;
using System.Configuration;
namespace CommonEntity
{
public class TCLToken
{
public int errno { get; set; }
public string errmsg { get; set; }
public TCLTokenData data { get; set; }
}
public class TCLTokenData
{
public string access_token { get; set; }
public long expires_in { get; set; }
public long deadline { get; set; }
public string refresh_token { get; set; }
}
public class TCLCommon
{
public static string TCLLoginUrl = ConfigurationManager.AppSettings["TCLLoginUrl"];
public static string TCLAppId = ConfigurationManager.AppSettings["TCLAppId"];
public static string TCLAppSecret = ConfigurationManager.AppSettings["TCLAppSecret"];
private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(TCLCommon));
/// <summary>
/// 获取TCL Token
/// </summary>
public static void GetTCLTV_Token()
{
try
{
var client1 = new RestClient(TCLLoginUrl);
var request1 = new RestRequest("oauth/token", Method.GET);
request1.AddParameter("app_id", TCLAppId);
request1.AddParameter("app_secret", TCLAppSecret);
var QQQ = client1.Execute(request1);
string ddd = QQQ.Content;
var FFFA = Newtonsoft.Json.JsonConvert.DeserializeObject<TCLToken>(ddd);
string TokenKey = CacheKey.TCLToken;
CSRedisCacheHelper.Set_Partition<TCLToken>(TokenKey, FFFA, 1);
}
catch (Exception ex)
{
logger.Error("TCL Token Error" + ex.Message);
}
}
/// <summary>
/// 给TCL发送数据
/// </summary>
/// <param name="CUID"></param>
/// <param name="skillid"></param>
/// <param name="sceneCode"></param>
/// <param name="count"></param>
public static void SendData(string hotelcode, string roomnum, string CUID, string skillid, string sceneCode, int count = 0)
{
try
{
string ID = Guid.NewGuid().ToString("N");
string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
Dictionary<string, string> dicg = new Dictionary<string, string>();
dicg.Add("Step", "1");
dicg.Add("HotelCode", hotelcode);
dicg.Add("RoomNumber", roomnum);
dicg.Add("RequestTime", roomnum);
dicg.Add("CmdType", sceneCode);
dicg.Add("RequestId", ID);
var dic1 = new Dictionary<string, string>();
dic1.Add("cuid", roomnum);
dic1.Add("sceneCode", sceneCode);
dic1.Add("botId", skillid);
logger.Error("TCL send data");
string TokenKey = CacheKey.TCLToken;
var T = CSRedisCacheHelper.Get_Partition<TCLToken>(TokenKey, 1);
if (T != null)
{
logger.Equals("TCL Token是" + T.data.access_token);
dic1.Add("token", T.data.access_token);
var jsondic = Newtonsoft.Json.JsonConvert.SerializeObject(dic1);
dicg.Add("RequestCmd", jsondic);
//LogRecorrd.WebAPI_DataSend(dicg, "api/tcl_tv");
Interface3Log w1 = new Interface3Log();
w1.HotelCode = hotelcode;
w1.RoomNumber = roomnum;
w1.TriggerTime = DateTime.Now;
w1.ActionData = new HttpActionData() { RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(dicg) };
w1.CommandType = ChangLiangValue.TCL;
var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);
var client1 = new RestClient(TCLLoginUrl);
var request1 = new RestRequest("open/countercontrol/scene_trigger", Method.POST);
request1.AddHeader("Authorization", "Bearer " + T.data.access_token);
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("cuid", CUID);
dic.Add("sceneCode", sceneCode);
dic.Add("botId", skillid);
request1.AddJsonBody(dic);
var QQQ = client1.Execute(request1);
string ddd = QQQ.Content;
//string ti1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
//Dictionary<string, string> dicg1 = new Dictionary<string, string>();
//dicg1.Add("HotelCode", hotelcode);
//dicg1.Add("RoomNumber", roomnum);
//dicg1.Add("RequestId", ID);
//dicg1.Add("ResponseMsg", ddd);
//dicg1.Add("ResponseTime", ti1);
//LogRecorrd.WebAPI_DataSend(dicg1, "api/tcl_tv");
logger.Error("TCL 电视触发了 情景。返回数据为:" + ddd);
Interface3Log ww = new Interface3Log();
ww.HotelCode = hotelcode;
ww.RoomNumber = roomnum;
ww.TriggerTime = DateTime.Now;
ww.ActionData = new HttpActionData() { ResponseData = ddd };
ww.CommandType = ChangLiangValue.TCL;
var qq = Newtonsoft.Json.JsonConvert.SerializeObject(ww);
CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, qq);
}
else
{
logger.Equals("TCL Token 为空");
if (count == 0)
{
GetTCLTV_Token();
count = count + 1;
SendData(hotelcode, roomnum, CUID, skillid, sceneCode, count++);
}
}
}
catch (Exception ex)
{
logger.Error("TCL SenData" + ex.Message);
}
}
}
}

View File

@@ -0,0 +1,128 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{BE0C3821-67F3-4FF5-B688-E727BD4C90AE}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ConsoleApplication1</RootNamespace>
<AssemblyName>ConsoleApplication1</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="C5">
<HintPath>..\..\..\..\lib\Quart\quartznet-2.3.3\quartznet-2.3.3\build\4.0\Debug\Quartz\C5.dll</HintPath>
</Reference>
<Reference Include="CacheManager.Core, Version=0.7.4.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\CacheManager.Core.0.7.4\lib\net40\CacheManager.Core.dll</HintPath>
</Reference>
<Reference Include="CacheManager.Memcached">
<HintPath>..\lib\CacheManager.Memcached.0.7.4\lib\net40\CacheManager.Memcached.dll</HintPath>
</Reference>
<Reference Include="CacheManager.SystemRuntimeCaching">
<HintPath>..\lib\CacheManager.SystemRuntimeCaching.0.7.4\lib\net40\CacheManager.SystemRuntimeCaching.dll</HintPath>
</Reference>
<Reference Include="Common.Logging, Version=1.2.0.0, Culture=neutral, PublicKeyToken=af08829b84f0328e">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\lib\Quart\quartznet-2.3.3\quartznet-2.3.3\build\4.0\Debug\Quartz\Common.Logging.dll</HintPath>
</Reference>
<Reference Include="Common.Logging.Core">
<HintPath>..\..\..\..\lib\Quart\quartznet-2.3.3\quartznet-2.3.3\build\4.0\Debug\Quartz\Common.Logging.Core.dll</HintPath>
</Reference>
<Reference Include="CSRedisCore, Version=3.8.670.0, Culture=neutral, PublicKeyToken=9aa6a3079358d437, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\Redis\CSRedisCore.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="Quartz">
<HintPath>..\..\..\..\lib\Quart\quartznet-2.3.3\quartznet-2.3.3\build\4.0\Debug\Quartz\Quartz.dll</HintPath>
</Reference>
<Reference Include="RestSharp">
<HintPath>..\lib\RestSharp\RestSharp.dll</HintPath>
</Reference>
<Reference Include="ServiceStack.Common">
<HintPath>..\lib\Redis\ServiceStack.Common.dll</HintPath>
</Reference>
<Reference Include="ServiceStack.Interfaces">
<HintPath>..\lib\Redis\ServiceStack.Interfaces.dll</HintPath>
</Reference>
<Reference Include="ServiceStack.Redis">
<HintPath>..\lib\Redis\ServiceStack.Redis.dll</HintPath>
</Reference>
<Reference Include="ServiceStack.Text">
<HintPath>..\lib\Redis\ServiceStack.Text.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.ValueTuple">
<HintPath>..\lib\Redis\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CommonEntity\CommonEntity.csproj">
<Project>{1D7073B2-4CC3-49F5-9F37-50A21D74A39D}</Project>
<Name>CommonEntity</Name>
</ProjectReference>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{B3F29715-E925-4E56-9248-580F06C3BC11}</Project>
<Name>Common</Name>
</ProjectReference>
<ProjectReference Include="..\Domain\Domain.csproj">
<Project>{A42D287A-8EF4-48F6-B14C-7F9CA834F786}</Project>
<Name>Domain</Name>
</ProjectReference>
<ProjectReference Include="..\RCUHost\RCUHost.csproj">
<Project>{3AF4C628-0B47-412C-950A-DBC0161F2A7F}</Project>
<Name>RCUHost</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ConsoleApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApplication1")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("294a52c2-b3d2-4af1-a63e-358eb085073d")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,18 @@
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="TCLLoginUrl" value="https://ai.tclyun.cn/"/>
<add key="TCLAppId" value="3fc1fe5560bdf2efda50a8dc23521d8a"/>
<add key="TCLAppSecret" value="48c30d8fcca4e14ab4842e9bfd54c082"/>
<!-- redis Start -->
<add key="session_expire_minutes" value="5" />
<add key="redis_server_session" value="127.0.0.1:6379" />
<add key="redis_max_read_pool" value="1000" />
<add key="redis_max_write_pool" value="1000" />
<add key="monitor_log_expire_minutes" value="30" />
<!--redis end-->
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

View File

@@ -0,0 +1,327 @@
{
"1462": [],
"1472": [],
"1402": [],
"1412": [],
"1567": [],
"1432": [],
"1246": [],
"1256": [],
"1323": [],
"1286": [],
"1100": [],
"1120": [],
"1180": [],
"65535": [],
"1906": [],
"1936": [],
"1268": [],
"1208": [],
"1840": [],
"1870": [],
"1800": [],
"1830": [],
"1453": [],
"1463": [],
"1473": [],
"1403": [],
"1413": [],
"1433": [],
"1247": [],
"1277": [],
"1207": [],
"1217": [],
"1362": [],
"1302": [],
"1287": [],
"1297": [],
"1147": [],
"1392": [],
"1260": [],
"1137": [],
"1210": [],
"1220": [],
"1230": [],
"1858": [],
"1063": [],
"1073": [],
"1818": [],
"1955": [],
"1828": [],
"1838": [],
"1033": [],
"1915": [],
"1259": [],
"1279": [],
"1995": [],
"1871": [],
"1078": [],
"1008": [],
"1028": [],
"1038": [],
"1891": [],
"1098": [],
"1156": [],
"1241": [],
"1251": [],
"1201": [],
"1763": [],
"1186": [],
"1196": [],
"1859": [],
"1040": [],
"1733": [],
"1070": [],
"1944": [],
"1291": [],
"1964": [],
"1020": [],
"1030": [],
"1904": [],
"1647": [],
"1924": [],
"1889": [],
"1667": [],
"1899": [],
"1080": [],
"1984": [],
"1637": [],
"1856": [],
"1069": [],
"1079": [],
"1943": [],
"1019": [],
"1826": [],
"1973": [],
"1913": [],
"1648": [],
"1658": [],
"1886": [],
"1089": [],
"1608": [],
"1618": [],
"1983": [],
"1638": [],
"1698": [],
"1165": [],
"1762": [],
"1031": [],
"1792": [],
"1670": [],
"1755": [],
"1630": [],
"1775": [],
"1715": [],
"1680": [],
"1690": [],
"1817": [],
"1506": [],
"1795": [],
"1649": [],
"1516": [],
"1659": [],
"1526": [],
"1536": [],
"1679": [],
"1897": [],
"1629": [],
"1586": [],
"1596": [],
"1448": [],
"1458": [],
"1689": [],
"1498": [],
"1661": [],
"1611": [],
"1621": [],
"1774": [],
"1704": [],
"1714": [],
"1470": [],
"1430": [],
"1565": [],
"1575": [],
"1535": [],
"1305": [],
"1585": [],
"1469": [],
"1395": [],
"1439": [],
"1642": [],
"1602": [],
"1471": [],
"1682": [],
"1421": [],
"1514": [],
"1481": [],
"1344": [],
"1491": [],
"1334": [],
"1466": [],
"1416": [],
"1222": [],
"1232": [],
"1282": [],
"1292": [],
"1942": [],
"1952": [],
"1902": [],
"1992": [],
"1347": [],
"1357": [],
"1457": [],
"1477": [],
"1397": [],
"1134": [],
"1263": [],
"1213": [],
"1233": [],
"1194": [],
"1056": [],
"1066": [],
"1076": [],
"1293": [],
"1016": [],
"1026": [],
"1173": [],
"1103": [],
"1113": [],
"1123": [],
"1096": [],
"1379": [],
"1319": [],
"1874": [],
"1814": [],
"1951": [],
"1389": [],
"1911": [],
"1884": [],
"1931": [],
"1894": [],
"1981": [],
"1346": [],
"1356": [],
"1376": [],
"1306": [],
"1336": [],
"1274": [],
"1361": [],
"1047": [],
"1057": [],
"1959": [],
"1017": [],
"1909": [],
"1102": [],
"1939": [],
"1747": [],
"1999": [],
"1182": [],
"1192": [],
"1845": [],
"1855": [],
"1737": [],
"1940": [],
"1950": [],
"1149": [],
"1960": [],
"1797": [],
"1179": [],
"1910": [],
"1920": [],
"1119": [],
"1930": [],
"1129": [],
"1885": [],
"1990": [],
"1199": [],
"1852": [],
"1802": [],
"1812": [],
"1892": [],
"1215": [],
"1044": [],
"1064": [],
"1004": [],
"1014": [],
"1024": [],
"1978": [],
"1171": [],
"1101": [],
"1643": [],
"1121": [],
"1663": [],
"1938": [],
"1084": [],
"1131": [],
"1756": [],
"1766": [],
"1191": [],
"1706": [],
"1716": [],
"1726": [],
"1683": [],
"1148": [],
"1957": [],
"1553": [],
"1158": [],
"1786": [],
"1917": [],
"1513": [],
"1118": [],
"1927": [],
"1523": [],
"1533": [],
"1604": [],
"1583": [],
"1593": [],
"1709": [],
"1853": [],
"1719": [],
"1694": [],
"1803": [],
"1813": [],
"1015": [],
"1025": [],
"1035": [],
"1095": [],
"1771": [],
"1042": [],
"1721": [],
"1072": [],
"1012": [],
"1022": [],
"1562": [],
"1032": [],
"1791": [],
"1512": [],
"1665": [],
"1675": [],
"1092": [],
"1625": [],
"1592": [],
"1579": [],
"1539": [],
"1484": [],
"1494": [],
"1589": [],
"1599": [],
"1358": [],
"1328": [],
"1338": [],
"1398": [],
"1710": [],
"1720": [],
"1541": [],
"1551": [],
"1511": [],
"1656": [],
"1521": [],
"1666": [],
"1581": [],
"1578": [],
"1508": [],
"1495": [],
"1370": [],
"1300": [],
"1330": []
}

View File

@@ -0,0 +1,260 @@
17:30
17:30
17:30
23:00
23:00
23:00
17:30
23:00
17:30
23:00
17:30
23:00
17:30
23:00
17:30
23:00
17:30
23:00
17:30
23:00
00:00
00:30
01:00
01:30
02:00
02:30
03:00
03:30
04:00
04:30
05:00
05:30
06:00
06:30
07:00
07:30
08:00
08:30
09:00
09:30
10:00
10:30
11:00
11:30
12:00
12:30
13:00
13:30
14:00
14:30
15:00
15:30
16:00
16:30
17:00
17:30
18:00
18:30
19:00
19:30
20:00
20:30
21:00
21:30
22:00
22:30
23:00
23:30
00:30
01:00
01:30
02:00
02:30
03:00
03:30
04:00
04:30
05:00
05:30
06:00
06:30
07:00
07:30
08:00
08:30
09:00
09:30
10:00
10:30
11:00
11:30
12:00
12:30
13:00
13:30
14:00
14:30
15:00
15:30
16:00
16:30
17:00
17:30
18:00
18:30
19:00
19:30
20:00
20:30
21:00
21:30
22:00
22:30
23:00
23:30
23:59
00:30
01:00
01:30
02:00
02:30
03:00
03:30
04:00
04:30
05:00
05:30
06:00
06:30
07:00
07:30
08:00
08:30
09:00
09:30
10:00
10:30
11:00
11:30
12:00
12:30
13:00
13:30
14:00
14:30
15:00
15:30
16:00
16:30
17:00
17:30
18:00
18:30
19:00
19:30
20:00
20:30
21:00
21:30
22:00
22:30
23:00
23:30
23:59
00:30
01:00
01:30
02:00
02:30
03:00
03:30
04:00
04:30
05:00
05:30
06:00
06:30
07:00
07:30
08:00
08:30
09:00
09:30
10:00
11:00
11:30
12:00
12:30
13:00
13:30
14:00
14:30
15:00
15:30
16:00
16:30
17:00
17:30
18:00
18:30
19:00
19:30
20:00
20:30
21:00
21:30
22:00
22:30
23:00
23:30
00:00
00:30
01:00
01:30
02:00
02:30
03:00
03:30
04:00
04:30
05:00
05:30
06:00
06:30
07:00
07:30
08:00
08:30
09:00
09:30
10:00
10:30
11:00
11:30
12:00
12:30
13:00
13:30
14:00
14:30
15:00
15:30
16:00
16:30
17:00
17:30
18:00
18:30
19:00
19:30
20:00
20:30
21:00
21:30
22:00
22:30
23:00
23:30
00:00
00:00,00:15,00:30,00:45,01:00,01:15,01:30,01:45,02:00,02:15,02:30,02:45,03:00,03:15,03:30,03:45,04:00,04:15,04:30,04:45,05:00,05:15,05:30,05:45,06:00,06:15,06:30,06:45,07:00,07:15,07:30,07:45,08:00,08:15,08:30,08:45,09:00,09:15,09:30,09:45,10:00,10:15,10:30,10:45,11:00,11:15,11:30,11:45,12:00,12:15,12:30,12:45,13:00,13:15,13:30,13:45,14:00,14:15,14:30,14:45,15:00,15:15,15:30,15:45,16:00,16:15,16:30,16:45,17:00,17:15,17:30,17:45,18:00,18:15,18:30,18:45,19:00,19:15,19:30,19:45,20:00,20:15,20:30,20:45,21:00,21:15,21:30,21:45,22:00,22:15,22:30,22:45,23:00,23:15,23:30,23:45
1 17:30
2 17:30
3 17:30
4 23:00
5 23:00
6 23:00
7 17:30
8 23:00
9 17:30
10 23:00
11 17:30
12 23:00
13 17:30
14 23:00
15 17:30
16 23:00
17 17:30
18 23:00
19 17:30
20 23:00
21 00:00
22 00:30
23 01:00
24 01:30
25 02:00
26 02:30
27 03:00
28 03:30
29 04:00
30 04:30
31 05:00
32 05:30
33 06:00
34 06:30
35 07:00
36 07:30
37 08:00
38 08:30
39 09:00
40 09:30
41 10:00
42 10:30
43 11:00
44 11:30
45 12:00
46 12:30
47 13:00
48 13:30
49 14:00
50 14:30
51 15:00
52 15:30
53 16:00
54 16:30
55 17:00
56 17:30
57 18:00
58 18:30
59 19:00
60 19:30
61 20:00
62 20:30
63 21:00
64 21:30
65 22:00
66 22:30
67 23:00
68 23:30
69 00:30
70 01:00
71 01:30
72 02:00
73 02:30
74 03:00
75 03:30
76 04:00
77 04:30
78 05:00
79 05:30
80 06:00
81 06:30
82 07:00
83 07:30
84 08:00
85 08:30
86 09:00
87 09:30
88 10:00
89 10:30
90 11:00
91 11:30
92 12:00
93 12:30
94 13:00
95 13:30
96 14:00
97 14:30
98 15:00
99 15:30
100 16:00
101 16:30
102 17:00
103 17:30
104 18:00
105 18:30
106 19:00
107 19:30
108 20:00
109 20:30
110 21:00
111 21:30
112 22:00
113 22:30
114 23:00
115 23:30
116 23:59
117 00:30
118 01:00
119 01:30
120 02:00
121 02:30
122 03:00
123 03:30
124 04:00
125 04:30
126 05:00
127 05:30
128 06:00
129 06:30
130 07:00
131 07:30
132 08:00
133 08:30
134 09:00
135 09:30
136 10:00
137 10:30
138 11:00
139 11:30
140 12:00
141 12:30
142 13:00
143 13:30
144 14:00
145 14:30
146 15:00
147 15:30
148 16:00
149 16:30
150 17:00
151 17:30
152 18:00
153 18:30
154 19:00
155 19:30
156 20:00
157 20:30
158 21:00
159 21:30
160 22:00
161 22:30
162 23:00
163 23:30
164 23:59
165 00:30
166 01:00
167 01:30
168 02:00
169 02:30
170 03:00
171 03:30
172 04:00
173 04:30
174 05:00
175 05:30
176 06:00
177 06:30
178 07:00
179 07:30
180 08:00
181 08:30
182 09:00
183 09:30
184 10:00
185 11:00
186 11:30
187 12:00
188 12:30
189 13:00
190 13:30
191 14:00
192 14:30
193 15:00
194 15:30
195 16:00
196 16:30
197 17:00
198 17:30
199 18:00
200 18:30
201 19:00
202 19:30
203 20:00
204 20:30
205 21:00
206 21:30
207 22:00
208 22:30
209 23:00
210 23:30
211 00:00
212 00:30
213 01:00
214 01:30
215 02:00
216 02:30
217 03:00
218 03:30
219 04:00
220 04:30
221 05:00
222 05:30
223 06:00
224 06:30
225 07:00
226 07:30
227 08:00
228 08:30
229 09:00
230 09:30
231 10:00
232 10:30
233 11:00
234 11:30
235 12:00
236 12:30
237 13:00
238 13:30
239 14:00
240 14:30
241 15:00
242 15:30
243 16:00
244 16:30
245 17:00
246 17:30
247 18:00
248 18:30
249 19:00
250 19:30
251 20:00
252 20:30
253 21:00
254 21:30
255 22:00
256 22:30
257 23:00
258 23:30
259 00:00
260 00:00 00:15 00:30 00:45 01:00 01:15 01:30 01:45 02:00 02:15 02:30 02:45 03:00 03:15 03:30 03:45 04:00 04:15 04:30 04:45 05:00 05:15 05:30 05:45 06:00 06:15 06:30 06:45 07:00 07:15 07:30 07:45 08:00 08:15 08:30 08:45 09:00 09:15 09:30 09:45 10:00 10:15 10:30 10:45 11:00 11:15 11:30 11:45 12:00 12:15 12:30 12:45 13:00 13:15 13:30 13:45 14:00 14:15 14:30 14:45 15:00 15:15 15:30 15:45 16:00 16:15 16:30 16:45 17:00 17:15 17:30 17:45 18:00 18:15 18:30 18:45 19:00 19:15 19:30 19:45 20:00 20:15 20:30 20:45 21:00 21:15 21:30 21:45 22:00 22:15 22:30 22:45 23:00 23:15 23:30 23:45

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,189 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>CacheManager.Memcached</name>
</assembly>
<members>
<member name="T:CacheManager.Core.ConfigurationBuilderExtensions">
<summary>
Extensions for the configuration builder specific to the memcached cache handle.
</summary>
</member>
<member name="M:CacheManager.Core.ConfigurationBuilderExtensions.WithMemcachedCacheHandle(CacheManager.Core.ConfigurationBuilderCachePart,System.String)">
<summary>
Adds a <see cref="T:CacheManager.Memcached.MemcachedCacheHandle`1"/>. The <paramref name="configurationName"/> must match with cache configured via enyim configuration section.
</summary>
<param name="part">The builder part.</param>
<param name="configurationName">The configuration name.</param>
<returns>The part.</returns>
<exception cref="T:System.ArgumentNullException">Thrown if handleName is null.</exception>
</member>
<member name="M:CacheManager.Core.ConfigurationBuilderExtensions.WithMemcachedCacheHandle(CacheManager.Core.ConfigurationBuilderCachePart,System.String,System.Boolean)">
<summary>
Adds a <see cref="T:CacheManager.Memcached.MemcachedCacheHandle`1"/>. The <paramref name="configurationName"/> must match with cache configured via enyim configuration section.
</summary>
<param name="part">The builder part.</param>
<param name="configurationName">The configuration name.</param>
<param name="isBackPlateSource">
Set this to true if this cache handle should be the source of the back plate.
<para>This setting will be ignored if no back plate is configured.</para>
</param>
<returns>The part.</returns>
<exception cref="T:System.ArgumentNullException">
Thrown if handleName or handleType are null.
</exception>
</member>
<member name="T:CacheManager.Memcached.MemcachedCacheHandle`1">
<summary>
Cache handle implementation based on the Enyim memcached client.
</summary>
<typeparam name="TCacheValue">The type of the cache value.</typeparam>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.#ctor(CacheManager.Core.CacheManagerConfiguration,CacheManager.Core.CacheHandleConfiguration,CacheManager.Core.Logging.ILoggerFactory)">
<summary>
Initializes a new instance of the <see cref="T:CacheManager.Memcached.MemcachedCacheHandle`1"/> class.
</summary>
<param name="managerConfiguration">The manager configuration.</param>
<param name="configuration">The cache handle configuration.</param>
<param name="loggerFactory">The logger factory.</param>
<exception cref="T:System.ArgumentNullException">
If <paramref name="configuration"/> or <paramref name="loggerFactory"/> is null.
</exception>
<exception cref="T:System.InvalidOperationException">
The cache value type is not serializable or if the enyim configuration section could not
be initialized.
</exception>
</member>
<member name="P:CacheManager.Memcached.MemcachedCacheHandle`1.Count">
<summary>
Gets the number of items the cache handle currently maintains.
</summary>
<value>The count.</value>
</member>
<member name="P:CacheManager.Memcached.MemcachedCacheHandle`1.GetMemcachedClientConfiguration">
<summary>
Gets the get memcached client configuration.
</summary>
<value>The get memcached client configuration.</value>
</member>
<member name="P:CacheManager.Memcached.MemcachedCacheHandle`1.ServerItemCount">
<summary>
Gets the total number of items per server.
</summary>
<value>The total number of items per server.</value>
</member>
<member name="P:CacheManager.Memcached.MemcachedCacheHandle`1.Servers">
<summary>
Gets the servers.
</summary>
<value>The servers.</value>
</member>
<member name="P:CacheManager.Memcached.MemcachedCacheHandle`1.Cache">
<summary>
Gets or sets the cache.
</summary>
<value>The cache.</value>
</member>
<member name="P:CacheManager.Memcached.MemcachedCacheHandle`1.Logger">
<inheritdoc />
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.Clear">
<summary>
Clears this cache, removing all items in the base cache and all regions.
</summary>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.ClearRegion(System.String)">
<summary>
Clears the cache region, removing all items from the specified <paramref name="region"/> only.
</summary>
<param name="region">The cache region.</param>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.Update(System.String,System.Func{`0,`0},System.Int32)">
<inheritdoc />
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.Update(System.String,System.String,System.Func{`0,`0},System.Int32)">
<inheritdoc />
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.AddInternalPrepared(CacheManager.Core.CacheItem{`0})">
<summary>
Adds a value to the cache.
</summary>
<param name="item">The <c>CacheItem</c> to be added to the cache.</param>
<returns>
<c>true</c> if the key was not already added to the cache, <c>false</c> otherwise.
</returns>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.Dispose(System.Boolean)">
<summary>
Performs application-defined tasks associated with freeing, releasing, or resetting
unmanaged resources.
</summary>
<param name="disposeManaged">Indicator if managed resources should be released.</param>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.GetCacheItemInternal(System.String)">
<summary>
Gets a <c>CacheItem</c> for the specified key.
</summary>
<param name="key">The key being used to identify the item within the cache.</param>
<returns>The <c>CacheItem</c>.</returns>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.GetCacheItemInternal(System.String,System.String)">
<summary>
Gets a <c>CacheItem</c> for the specified key.
</summary>
<param name="key">The key being used to identify the item within the cache.</param>
<param name="region">The cache region.</param>
<returns>The <c>CacheItem</c>.</returns>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.PutInternalPrepared(CacheManager.Core.CacheItem{`0})">
<summary>
Puts the <paramref name="item"/> into the cache. If the item exists it will get updated
with the new value. If the item doesn't exist, the item will be added to the cache.
</summary>
<param name="item">The <c>CacheItem</c> to be added to the cache.</param>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.RemoveInternal(System.String)">
<summary>
Removes a value from the cache for the specified key.
</summary>
<param name="key">The key being used to identify the item within the cache.</param>
<returns>
<c>true</c> if the key was found and removed from the cache, <c>false</c> otherwise.
</returns>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.RemoveInternal(System.String,System.String)">
<summary>
Removes a value from the cache for the specified key.
</summary>
<param name="key">The key being used to identify the item within the cache.</param>
<param name="region">The cache region.</param>
<returns>
<c>true</c> if the key was found and removed from the cache, <c>false</c> otherwise.
</returns>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.Store(Enyim.Caching.Memcached.StoreMode,CacheManager.Core.CacheItem{`0})">
<summary>
Stores the item with the specified mode.
</summary>
<param name="mode">The mode.</param>
<param name="item">The item.</param>
<returns>The result.</returns>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.GetEnyimSectionName(System.String)">
<summary>
Gets the name of the enyim section.
</summary>
<param name="handleName">Name of the handle.</param>
<returns>The section name.</returns>
</member>
<member name="M:CacheManager.Memcached.MemcachedCacheHandle`1.GetSection">
<summary>
Gets the section.
</summary>
<returns>The client configuration.</returns>
<exception cref="T:System.Configuration.ConfigurationErrorsException">
If memcached client section was not found or there are no servers defined for memcached.
</exception>
</member>
</members>
</doc>

Some files were not shown because too many files have changed in this diff Show More