初始化CRICS
This commit is contained in:
66
Common/AliyunSMSHelper.cs
Normal file
66
Common/AliyunSMSHelper.cs
Normal 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
61
Common/AppUtils.cs
Normal 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
44
Common/BLWMQTT.cs
Normal 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
34
Common/CPUData.cs
Normal 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;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
356
Common/CSRedisCacheHelper.cs
Normal file
356
Common/CSRedisCacheHelper.cs
Normal 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
196
Common/Common.csproj
Normal 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>
|
||||
6
Common/Common.csproj.user
Normal file
6
Common/Common.csproj.user
Normal 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
83
Common/DuiOperation.cs
Normal 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
2302
Common/DynamicLibrary.cs
Normal file
File diff suppressed because it is too large
Load Diff
42
Common/EnumDescription.cs
Normal file
42
Common/EnumDescription.cs
Normal 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
203
Common/ExcelHelper.cs
Normal 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
167
Common/FreeGoOperation.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
143
Common/FrequencyControler.cs
Normal file
143
Common/FrequencyControler.cs
Normal 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
32
Common/GlobalCache.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
}
|
||||
219
Common/HttpWebRequestHelper.cs
Normal file
219
Common/HttpWebRequestHelper.cs
Normal 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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
53
Common/IQueryOverExtension.cs
Normal file
53
Common/IQueryOverExtension.cs
Normal 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
137
Common/MemoryCacheHelper.cs
Normal 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
156
Common/MemoryCacheUtil.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
42
Common/MemoryStreamPool.cs
Normal file
42
Common/MemoryStreamPool.cs
Normal 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
283
Common/MyDes.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
27
Common/NPOIMemoryStream.cs
Normal file
27
Common/NPOIMemoryStream.cs
Normal 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
17
Common/OnOffLineData.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
36
Common/Properties/AssemblyInfo.cs
Normal file
36
Common/Properties/AssemblyInfo.cs
Normal 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")]
|
||||
10
Common/Properties/DataSources/System.Data.DataSet.datasource
Normal file
10
Common/Properties/DataSources/System.Data.DataSet.datasource
Normal 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
311
Common/ProtocalData.cs
Normal 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,全局属性A3,V80复位开关A4,配置数据版本号A5,485调光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
51
Common/RateLimiter.cs
Normal 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
64
Common/RokidOperation.cs
Normal 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
103
Common/SQLHelper.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
30
Common/SimpleMemoryStreamPool.cs
Normal file
30
Common/SimpleMemoryStreamPool.cs
Normal 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
87
Common/StructConverter.cs
Normal 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
158
Common/SyncRoomStatus.cs
Normal 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
419
Common/TFTPclient.cs
Normal 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
101
Common/TVOperation.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
63
Common/TianMaoOperation.cs
Normal file
63
Common/TianMaoOperation.cs
Normal 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
70
Common/TimeHelper.cs
Normal 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
849
Common/Tools.cs
Normal 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
33
Common/UDPPackageCount.cs
Normal 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
123
Common/UdplogServer.cs
Normal 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
14
Common/ValidatePattern.cs
Normal 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
105
Common/WeiXinHelper.cs
Normal 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 + "×tamp=" + 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
151
Common/XidaoDuOperation.cs
Normal 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("×tamp=" + TimeHelper.GetCurrentTimestamp(false));
|
||||
sb.Append("&v=2.0");
|
||||
sb.Append("&source=baidu");
|
||||
sb.Append("¶mJson=" + 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
144
Common/XuanZhuOperation.cs
Normal 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
11
Common/app.config
Normal 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>
|
||||
Reference in New Issue
Block a user