using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
using System.Data;
using System.Net;
using System.Net.Security;
using System.Web.Mail;
using System.Configuration;
using System.Globalization;
using Wuqi.Webdiyer;
using System.Web;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Excel = Microsoft.Office.Interop.Excel;
using System.Text.RegularExpressions;
using System.Management;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Xml;
using System.Web.Script.Serialization;
using System.Threading.Tasks;
using Shell32;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Sms.V20190711;
using TencentCloud.Sms.V20190711.Models;
using NPinyin;
using Microsoft.International.Converters.PinYinConverter;
namespace Mtxfw.Utility
{
public class Common
{
#region 汉字转化为拼音首字母
private static Encoding gb2312 = Encoding.GetEncoding("utf-8");
///
/// 汉字转全拼
///
///
///
public static string ConvertToAllSpell(string strChinese)
{
try
{
if (strChinese.Length != 0)
{
StringBuilder fullSpell = new StringBuilder();
for (int i = 0; i < strChinese.Length; i++)
{
var chr = strChinese[i];
fullSpell.Append(GetSpell(chr));
}
return fullSpell.ToString().ToUpper();
}
}
catch (Exception e)
{
Console.WriteLine("全拼转化出错!" + e.Message);
}
return string.Empty;
}
///
/// 汉字转首字母
///
///
///
public static string GetFirstSpell(string strChinese)
{
//NPinyin.Pinyin.GetInitials(strChinese) 有Bug 洺无法识别
//return NPinyin.Pinyin.GetInitials(strChinese);
string strfullSpell = "";
try
{
if (strChinese.Length != 0)
{
StringBuilder fullSpell = new StringBuilder();
var chr = strChinese[0];
fullSpell.Append(GetSpell(chr)[0]);
strfullSpell = fullSpell.ToString().ToUpper();
}
}
catch (Exception e)
{
strfullSpell = "首";
Console.WriteLine("首字母转化出错!" + e.Message);
}
return strfullSpell;
}
private static string GetSpell(char chr)
{
var coverchr = NPinyin.Pinyin.GetPinyin(chr);
bool isChineses = ChineseChar.IsValidChar(coverchr[0]);
if (isChineses)
{
ChineseChar chineseChar = new ChineseChar(coverchr[0]);
foreach (string value in chineseChar.Pinyins)
{
if (!string.IsNullOrEmpty(value))
{
return value.Remove(value.Length - 1, 1);
}
}
}
return coverchr;
}
#endregion
#region 转换输出聊天内容
///
/// 转换输出聊天内容
///
/// 需要输出内容
public static string ccontent(int t, string content, emojiconsConfig econfig)
{
if (t == 1)
{
string html = "";//
return html;
}
else if (t == 2)
{
string html = "
";
return html;
}
else if (t == 3)
{
string html = "";
return html;
}
else if (t == 4)
{
string html = "";
return html;
}
else
{
string pattern2 = @"\[(.*?)\]";
Regex R2 = new Regex(pattern2);
Match M2 = R2.Match(content);
while (M2.Success)
{
string group = M2.Groups[1].ToString();
string gdata = econfig.getData("[" + group + "]");
if (group != "" && gdata != "")
{
content = content.Replace("[" + group + "]", "
");
}
M2 = M2.NextMatch();
}
return content;
}
}
#endregion
#region 用ShellClass获取音频文件时长
///
/// 如果添加引用编译提示"不能引用嵌入式接口之类的错误",把引用属性里的嵌入式***,设为false;
/// asp.net 环境下测试未通过,c#未测试;
///
/// 文件路径
///
public static int GetDurationByShellClass(string filePath)
{
ShellClass sh = new ShellClass();
Folder dir = sh.NameSpace(Path.GetDirectoryName(filePath));
FolderItem item = dir.ParseName(Path.GetFileName(filePath));
string str = dir.GetDetailsOf(item, 27); // 获取歌曲时长。
if (str != "")
{
var matchs = Regex.Match(str, @"(\d{2}):(\d{2}):(\d{2})");
var hour = Convert.ToInt32(matchs.Groups[1].Value);
var minute = Convert.ToInt32(matchs.Groups[2].Value);
var second = Convert.ToInt32(matchs.Groups[3].Value);
var len = hour * 3600 + minute * 60 + second;
return len;
}
else
{
return 0;
}
return 0;
}
#endregion
#region 转换输出手机号码
///
/// 转换输出手机号码
///
/// 需要输出内容
public static string cphone(string phone)
{
if (phone.Length == 11)
{
return phone.Substring(0, 3) + "****" + phone.Substring(7, 4);
}
else
{
return phone;
}
}
#endregion
#region 转换输出中奖号码
///
/// 转换输出中奖号码
///
/// 转换输出中奖号码
public static string czjhm(string zjhm)
{
if (zjhm == "1")
{
return "一";
}
else if (zjhm == "2")
{
return "二";
}
else if (zjhm == "3")
{
return "三";
}
else if (zjhm == "4")
{
return "四";
}
else if (zjhm == "5")
{
return "五";
}
else
{
return "五";
}
}
#endregion
#region 转换输出购买类型
///
/// 转换输出购买类型
///
/// 转换输出购买类型
public static string cutype(string utype)
{
switch (utype)
{
case "0":
utype = "生活区";
break;
case "1":
utype = "流量包";
break;
case "2":
utype = "生态区";
break;
case "3":
utype = "";
break;
case "4":
utype = "创客区";
break;
case "5":
utype = "流量区";
break;
case "8":
utype = "事业联盟";
break;
}
return utype;
}
#endregion
#region 打印输出
///
/// Json打印输出
///
/// HttpContext
/// 需要输出内容
public static void WriteJson(HttpContext context, string data)
{
context.Response.Clear();
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.ContentType = "application/json";
context.Response.Write(data);
try
{
context.Response.Flush();
}
catch
{
}
finally
{
context.ApplicationInstance.CompleteRequest();
}
}
#endregion
#region 获取某一日期是该年中的第几周
///
/// 获取某一日期是该年中的第几周
///
/// 日期
/// 该日期在该年中的周数
public static int GetWeekOfYear(DateTime dt)
{
GregorianCalendar gc = new GregorianCalendar();
return gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
}
#endregion
#region 获取一周第一天的DateTime
public static DateTime GetWeekStart(DateTime datePoint)//函数作用是接受某一天,然后返回该日期所处星期的第一天
{
//新建要返回的变量
DateTime result = new DateTime();
//其实到此为止。。就已经判断完所处本周中哪一天了。 C#自带了这个方法,只不过DayOfWeek不是一个基本类型,需要用string取出来。
//转换为我们可以判断操作的string类型
DayOfWeek day = datePoint.DayOfWeek;
string dayString = day.ToString().ToLower();
//switch判断
switch (dayString)
{
case "sunday":
result = datePoint.Date;
break;
case "monday":
//若就是星期一,那本周开头一天就是这个传进来的变量
result = datePoint.Date.AddDays(-1);
break;
case "tuesday":
//以此类推
result = datePoint.Date.AddDays(-2);
break;
case "wednesday":
result = datePoint.Date.AddDays(-3);
break;
case "thursday":
result = datePoint.Date.AddDays(-4);
break;
case "friday":
result = datePoint.Date.AddDays(-5);
break;
case "saturday":
result = datePoint.Date.AddDays(-6);
break;
}
//switch
return result;
}
#endregion
#region 获取一周最后一天的DateTime
public static DateTime GetWeekEnd(DateTime datePoint)//函数作用是接受某一天,然后返回该日期所处星期的最后一天
{
//新建要返回的变量
DateTime result = new DateTime();
//其实到此为止。。就已经判断完所处本周中哪一天了。 C#自带了这个方法,只不过DayOfWeek不是一个基本类型,需要用string取出来。
//转换为我们可以判断操作的string类型
DayOfWeek day = datePoint.DayOfWeek;
string dayString = day.ToString().ToLower();
//switch判断
switch (dayString)
{
case "sunday":
result = datePoint.Date.AddDays(6);
break;
case "monday":
//若就是星期一,那本周开头一天就是这个传进来的变量
result = datePoint.Date.AddDays(5);
break;
case "tuesday":
//以此类推
result = datePoint.Date.AddDays(4);
break;
case "wednesday":
result = datePoint.Date.AddDays(3);
break;
case "thursday":
result = datePoint.Date.AddDays(2);
break;
case "friday":
result = datePoint.Date.AddDays(1);
break;
case "saturday":
result = datePoint.Date;
break;
}
//switch
return result;
}
#endregion
#region 获取本月最后一天的DateTime
public static DateTime GetMonthEnd(DateTime datePoint)//函数作用是接受某一天,然后返回该日期所处星期的最后一天
{
DateTime s = DateTime.Parse(datePoint.ToString("yyyy-MM-dd") + " 23:59:59");
DateTime ss = s.AddDays(1 - s.Day);
DateTime result = ss.AddMonths(1).AddDays(-1);
return result;
}
#endregion
#region 判断上传的文件类型是否是允许的
///
/// 判断上传的文件类型是否是允许的
///
public static bool hasType(string[] array, string type)
{
bool isType = false;
foreach (string str in array)
{
if (type.IndexOf(str) != -1)
{
isType = true;
//如果上传的文件类型是允许的则跳出循环
break;
}
}
return isType;
}
#endregion
#region 获取access_token
public static string getaccess_token(HttpContext context, string appKey, string appSecret, Mtxfw.Utility.Config config)
{
string straccess_token = "";
if (config.webaccess_token == "" || config.webaccess_token_time == "")
{
string str = Mtxfw.Utility.Common.getPage2("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appKey + "&secret=" + appSecret, "", "utf-8");
str = str.Replace("\n", "").Replace("\040", "").Replace("{\"access_token\":\"", "");
str = str.Replace("\",\"expires_in\":7199}", "");
str = str.Replace("\",\"expires_in\":7200}", "");
straccess_token = str;
config.webaccess_token = str;
config.webaccess_token_time = DateTime.Now.ToString();
config.Save();
}
else
{
try
{
bool b = true;
DateTime dt = Convert.ToDateTime(config.webaccess_token_time);
DateTime dt1 = DateTime.Now;
DateTime dt2 = dt.AddSeconds(7000);
if (DateTime.Compare(dt2, dt1) < 0)
{
b = false;
}
if (b)
{
straccess_token = config.webaccess_token;
}
else
{
string str = Mtxfw.Utility.Common.getPage2("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appKey + "&secret=" + appSecret, "", "utf-8");
str = str.Replace("\n", "").Replace("\040", "").Replace("{\"access_token\":\"", "");
str = str.Replace("\",\"expires_in\":7199}", "");
str = str.Replace("\",\"expires_in\":7200}", "");
straccess_token = str;
config.webaccess_token = str;
config.webaccess_token_time = DateTime.Now.ToString();
config.Save();
}
}
catch
{
string str = Mtxfw.Utility.Common.getPage2("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appKey + "&secret=" + appSecret, "", "utf-8");
str = str.Replace("\n", "").Replace("\040", "").Replace("{\"access_token\":\"", "");
str = str.Replace("\",\"expires_in\":7199}", "");
str = str.Replace("\",\"expires_in\":7200}", "");
straccess_token = str;
config.webaccess_token = str;
config.webaccess_token_time = DateTime.Now.ToString();
config.Save();
}
}
return straccess_token;
}
#endregion
#region 获取jsapi_ticket
public static string getjsapi_ticket(HttpContext context, string appKey, string appSecret, Mtxfw.Utility.Config config)
{
string strticket = "";
if (config.webjsapi_ticket == "" || config.webjsapi_ticket_time == "")
{
string ticket = Mtxfw.Utility.Common.getPage2("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getaccess_token(context, appKey, appSecret, config) + "&type=jsapi", "", "utf-8");
ticket = ticket.Replace("\n", "").Replace("\040", "");
ticket = ticket.Replace("{\"errcode\":0,\"errmsg\":\"ok\",\"ticket\":\"", "");
ticket = ticket.Replace("\",\"expires_in\":7199}", "");
ticket = ticket.Replace("\",\"expires_in\":7200}", "");
strticket = ticket;
config.webjsapi_ticket = ticket;
config.webjsapi_ticket_time = DateTime.Now.ToString();
config.Save();
}
else
{
try
{
bool b = true;
DateTime dt = Convert.ToDateTime(config.webjsapi_ticket_time);
DateTime dt1 = DateTime.Now;
DateTime dt2 = dt.AddSeconds(7000);
if (DateTime.Compare(dt2, dt1) < 0)
{
b = false;
}
if (b)
{
strticket = config.webjsapi_ticket;
}
else
{
string ticket = Mtxfw.Utility.Common.getPage2("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getaccess_token(context, appKey, appSecret, config) + "&type=jsapi", "", "utf-8");
ticket = ticket.Replace("\n", "").Replace("\040", "");
ticket = ticket.Replace("{\"errcode\":0,\"errmsg\":\"ok\",\"ticket\":\"", "");
ticket = ticket.Replace("\",\"expires_in\":7199}", "");
ticket = ticket.Replace("\",\"expires_in\":7200}", "");
strticket = ticket;
config.webjsapi_ticket = ticket;
config.webjsapi_ticket_time = DateTime.Now.ToString();
config.Save();
}
}
catch
{
string ticket = Mtxfw.Utility.Common.getPage2("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getaccess_token(context, appKey, appSecret, config) + "&type=jsapi", "", "utf-8");
ticket = ticket.Replace("\n", "").Replace("\040", "");
ticket = ticket.Replace("{\"errcode\":0,\"errmsg\":\"ok\",\"ticket\":\"", "");
ticket = ticket.Replace("\",\"expires_in\":7199}", "");
ticket = ticket.Replace("\",\"expires_in\":7200}", "");
strticket = ticket;
config.webjsapi_ticket = ticket;
config.webjsapi_ticket_time = DateTime.Now.ToString();
config.Save();
}
}
return strticket;
}
#endregion
#region 获取小程序access_token
public static WXaccess_token getxaccess_token(string appID, string appSecret)
{
WXaccess_token ac = null;
string str = Mtxfw.Utility.Common.getPage2("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSecret + "", "", "utf-8");
//Mtxfw.Utility.Common.WriteHtml("/weixin/str0.txt", str);
if (str.IndexOf("access_token") != -1)
{
ac = (WXaccess_token)Fromaccess_token(str);
}
return ac;
}
public static object Fromaccess_token(string json)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Deserialize(json);
}
#endregion
#region 获取hjpay_returns0
public static object Fromhjpay_returnsJson0(string json)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Deserialize(json);
}
#endregion
#region 创建随机字符串
private static string[] strs = new string[]
{
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
};
///
/// 创建随机字符串
///
///
public static string CreatenNonce_str()
{
Random r = new Random();
var sb = new StringBuilder();
var length = strs.Length;
for (int i = 0; i < 15; i++)
{
sb.Append(strs[r.Next(length - 1)]);
}
return sb.ToString();
}
///
/// 生成指定位数的随机数
///
/// 参数是随机数的位数
/// 返回一个随机数字符串
public static string RandNum(int VcodeNum)
{
Random random = new Random();
if (VcodeNum == 6)
{
return (random.Next(100000, 999999).ToString());
}
else
{
return (random.Next(1000, 9999).ToString());
}
}
#endregion
#region 创建时间戳
///
/// 创建时间戳
///
///
public static long CreatenTimestamp(DateTime dt)
{
return (dt.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}
public static string timeStamp()
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); // 当地时区
DateTime localNow = DateTime.Now;
long timeStamp = (long)((localNow - startTime).TotalSeconds);
return "" + timeStamp;
}
#endregion
#region 将时间戳转换为时间
///
/// 将时间戳转换为时间
///
///
public static DateTime ToDateTime(long TimeStamps)
{
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0);
long tt = dt.Ticks + TimeStamps * 10000000;
return new DateTime(tt);
}
///
/// 将时间戳转换为13位时间
///
///
public static DateTime To13DateTime(long TimeStamps)
{
var date = new DateTime(1970, 1, 1).AddMilliseconds(TimeStamps);
//new DateTime().AddMilliseconds(621355968000000000/10000).AddMilliseconds(TimeStamps);//效果同上
return date;
}
#endregion
#region 签名算法如下
///
/// 签名算法 ///本代码来自开源微信SDK项目:https://github.com/night-king/weixinSDK
///
/// jsapi_ticket
/// 随机字符串(必须与wx.config中的nonceStr相同)
/// 时间戳(必须与wx.config中的timestamp相同)
/// 当前网页的URL,不包含#及其后面部分(必须是调用JS接口页面的完整URL)
///
public static string GetSignature(string jsapi_ticket, string noncestr, string timestamp, string url, out string string1)
{
var string1Builder = new StringBuilder();
string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")
.Append("noncestr=").Append(noncestr).Append("&")
.Append("timestamp=").Append(timestamp).Append("&")
.Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
string1 = string1Builder.ToString();
return Sha1(string1);
}
#endregion
#region Hash算法
public static string Sha1(string orgStr, string encode = "UTF-8")
{
var sha1 = new SHA1Managed();
var sha1bytes = System.Text.Encoding.GetEncoding(encode).GetBytes(orgStr);
byte[] resultHash = sha1.ComputeHash(sha1bytes);
string sha1String = BitConverter.ToString(resultHash).ToLower();
sha1String = sha1String.Replace("-", "");
return sha1String;
}
#endregion
#region 区块算法
///
/// 校验 Hash 是否有效
///
/// Hash 值
/// 难度
///
public static bool IsHashValid(string hashStr, int difficulty)
{
var bytes = Enumerable.Range(0, hashStr.Length)
.Where(n => n % 2 == 0)
.Select(n => Convert.ToByte(hashStr.Substring(n, 2), 16))
.ToArray();
var bits = new BitArray(bytes);
for (var i = 0; i < difficulty; i++)
{
if (bits[i]) return false;
}
return true;
}
///
/// 计算区块 HASH 值
///
/// 区块实例
/// 计算完成的区块散列值
public static string CalculateHash(Block block)
{
string calculationStr = "{block.Index}{block.TimeStamp}{block.BPM}{block.PrevHash}{block.Nonce}";
SHA256 sha256Generator = SHA256.Create();
byte[] sha256HashBytes = sha256Generator.ComputeHash(Encoding.UTF8.GetBytes(calculationStr));
StringBuilder sha256StrBuilder = new StringBuilder();
foreach (byte @byte in sha256HashBytes)
{
sha256StrBuilder.Append(@byte.ToString("x2"));
}
return sha256StrBuilder.ToString();
}
///
/// 计算当前时间的 UTC 表示格式
///
/// UTC 时间字符串
public static string CalculateCurrentTimeUTC()
{
DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
DateTime nowTime = DateTime.Now;
long unixTime = (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);
return unixTime.ToString();
}
///
/// 生成新的区块
///
/// 旧的区块数据
/// 心率
/// 下一个区块生成难度
/// 新的区块
public static Block GenerateBlock(Block oldBlock, int BPM, int Difficulty)
{
Block newBlock = new Block()
{
Index = oldBlock.Index + 1,
TimeStamp = CalculateCurrentTimeUTC(),
BPM = BPM,
PrevHash = oldBlock.Hash,
Difficulty = Difficulty
};
// 挖矿 ing...
for (int i = 0; ; i++)
{
newBlock.Nonce = i.ToString("x2");
if (!IsHashValid(CalculateHash(newBlock), Difficulty))
{
Console.WriteLine("目前结果:{CalculateHash(newBlock)} ,正在计算中...");
System.Threading.Thread.Sleep(5000);
continue;
}
else
{
Console.WriteLine("目前结果:{CalculateHash(newBlock)} ,计算完毕...");
newBlock.Hash = CalculateHash(newBlock);
break;
}
}
// 原有代码
// newBlock.Hash = CalculateHash(newBlock);
return newBlock;
}
#endregion
#region 判断是否是手机浏览
static string[] mobileTag = { "iphone", "ios", "ipad", "android", "mobile" };
public static bool IsMobile(string userAgent)
{
bool result = false;
userAgent = userAgent.ToLower();
foreach (string sTmp in mobileTag)
{
if (userAgent.Contains(sTmp))
{
result = true;
break;
}
}
return result;
}
#endregion
#region 计算时间差
//计算时间差
public static int DateDiff(DateTime DateTime1, DateTime DateTime2)
{
int dateDiff = 0;
TimeSpan ts = DateTime1.Subtract(DateTime2).Duration();
dateDiff = ts.Days;
return dateDiff;
}
#endregion
#region 转换输出星期几
///
/// 转换输出星期几
///
/// 转换输出星期几
public static string cweek(string utype)
{
string strweek = "";
if (utype.IndexOf("monday") != -1)
{
strweek = "星期一";
}
if (utype.IndexOf("tuesday") != -1)
{
if (strweek != "")
{
strweek += ",星期二";
}
else
{
strweek += "星期二";
}
}
if (utype.IndexOf("wednesday") != -1)
{
if (strweek != "")
{
strweek += ",星期三";
}
else
{
strweek += "星期三";
}
}
if (utype.IndexOf("thursday") != -1)
{
if (strweek != "")
{
strweek += ",星期四";
}
else
{
strweek += "星期四";
}
}
if (utype.IndexOf("friday") != -1)
{
if (strweek != "")
{
strweek += ",星期五";
}
else
{
strweek += "星期五";
}
}
if (utype.IndexOf("saturday") != -1)
{
if (strweek != "")
{
strweek += ",星期六";
}
else
{
strweek += "星期六";
}
}
if (utype.IndexOf("sunday") != -1)
{
if (strweek != "")
{
strweek += ",星期日";
}
else
{
strweek += "星期日";
}
}
return strweek;
}
#endregion
#region 转换输出周几
///
/// 转换输出周几
///
/// 转换输出周几
public static string cweek0(string utype)
{
string strweek = "";
if (utype=="monday")
{
strweek = "周一";
}
if (utype=="tuesday")
{
strweek = "周二";
}
if (utype=="wednesday")
{
strweek = "周三";
}
if (utype=="thursday")
{
strweek = "周四";
}
if (utype=="friday")
{
strweek = "周五";
}
if (utype=="saturday")
{
strweek = "周六";
}
if (utype == "sunday")
{
strweek = "周日";
}
return strweek;
}
#endregion
#region 替换部分字符串
///
/// 替换部分字符串
///
/// 需要替换的字符串
///
public static string ReplaceString(string JsonString)
{
if (JsonString == null) { return JsonString; }
//JsonString = Regex.Replace(JsonString, "style=\"(.*?)\"", "");
if (JsonString.Contains("\\"))
{
JsonString = JsonString.Replace("\\", "\\\\");
}
if (JsonString.Contains("\'"))
{
JsonString = JsonString.Replace("\'", "\\\'");
}
if (JsonString.Contains("\""))
{
JsonString = JsonString.Replace("\"", "\\\"");
}
//去掉字符串的回车换行符
JsonString = Regex.Replace(JsonString, @"[\n\r\t]", "");
JsonString = JsonString.Trim();
return JsonString;
}
#endregion
#region 获取推流地址
///
/// 获取推流地址
///
/// 您用来推流的域名
/// 您用来区别不同推流地址的唯一流名称
/// 安全密钥
/// 过期时间
///
public static string getPushUrl(string domain, string streamName, string liveKey, DateTime time)
{
StringBuilder sb = new StringBuilder(32);
string TimeStamp = GetTimeStamp16(time, false);
MD5 md5 = new MD5CryptoServiceProvider();
//string strkey = "/agapp/" + streamName + "-" + TimeStamp + "-0-0-" + liveKey;
string strkey = liveKey + streamName + TimeStamp;
byte[] t = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(strkey));
for (int i = 0; i < t.Length; i++)
{
sb.Append(t[i].ToString("x").PadLeft(2, '0'));
}
//return "rtmp://" + domain + "/agapp/" + streamName + "?auth_key=" + TimeStamp + "-0-0-" + sb.ToString();
return "rtmp://" + domain + "/live/" + streamName + "?txSecret=" + sb.ToString() + "&txTime=" + TimeStamp;// + "&txHost=" + domain
}
///
/// 获取直播地址
///
/// 您用来直播的域名
/// 您用来区别不同推流地址的唯一流名称
/// 安全密钥
/// 过期时间
///
public static string getLiveUrl(string domain, string streamName, string liveKey, DateTime time)
{
//return "http://" + domain + "/live/" + streamName + "_zm001" + ".m3u8";
StringBuilder sb = new StringBuilder(32);
string TimeStamp = GetTimeStamp16(time, false);
MD5 md5 = new MD5CryptoServiceProvider();
string strkey = liveKey + streamName + TimeStamp;
byte[] t = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(strkey));
for (int i = 0; i < t.Length; i++)
{
sb.Append(t[i].ToString("x").PadLeft(2, '0'));
}
return "http://" + domain + "/live/" + streamName + ".m3u8?txSecret=" + sb.ToString() + "&txTime=" + TimeStamp;
/*StringBuilder sb = new StringBuilder(32);
string TimeStamp = GetTimeStamp16(time, false);
MD5 md5 = new MD5CryptoServiceProvider();
string strkey = "/agapp/" + streamName + "-" + TimeStamp + "-0-0-" + liveKey;
byte[] t = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(strkey));
for (int i = 0; i < t.Length; i++)
{
sb.Append(t[i].ToString("x").PadLeft(2, '0'));
}
return "rtmp://" + domain + "/agapp/" + streamName + "?auth_key=" + TimeStamp + "-0-0-" + sb.ToString();*/
}
///
/// 取16进制时间戳,高并发情况下会有重复。想要解决这问题请使用sleep线程睡眠1毫秒。
///
/// 精确到毫秒
/// 返回一个字符串
public static string GetTimeStamp16(DateTime date, bool AccurateToMilliseconds = false)
{
if (AccurateToMilliseconds)
{
// 使用当前时间计时周期数(636662920472315179)减去1970年01月01日计时周期数(621355968000000000)除去(删掉)后面4位计数(后四位计时单位小于毫秒,快到不要不要)再取整(去小数点)。
//备注:DateTime.Now.ToUniversalTime不能缩写成DateTime.Now.Ticks,会有好几个小时的误差。
//621355968000000000计算方法 long ticks = (new DateTime(1970, 1, 1, 8, 0, 0)).ToUniversalTime().Ticks;
return Convert.ToString((date.ToUniversalTime().Ticks - 621355968000000000) / 10000, 16).ToUpper();
}
else
{
//上面是精确到毫秒,需要在最后除去(10000),这里只精确到秒,只要在10000后面加三个0即可(1秒等于1000毫米)。
return Convert.ToString((date.ToUniversalTime().Ticks - 621355968000000000) / 10000000, 16).ToUpper();
}
}
#endregion
#region 返回byte[]数据
///
/// 返回byte[]数据
///
/// 要处理的JSON数据
/// 要提交的URL
/// 返回的byte[]
public static byte[] GetResponsebyte(string JSONData, string Url)
{
byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = "text/xml";
Stream reqstream = request.GetRequestStream();
reqstream.Write(bytes, 0, bytes.Length);
//声明一个HttpWebRequest请求
request.Timeout = 90000;
//设置连接超时时间
request.Headers.Set("Pragma", "no-cache");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
byte[] img = StreamToBytes(streamReceive);
streamReceive.Dispose();
return img;
}
public static byte[] StreamToBytes(Stream stream)
{
List bytes = new List();
int temp = stream.ReadByte();
while (temp != -1)
{
bytes.Add((byte)temp);
temp = stream.ReadByte();
}
return bytes.ToArray();
}
#endregion
#region 根据经纬度返回详细地址
public static string GetAddress(string lng, string lat)
{
try
{
string url = @"http://api.map.baidu.com/reverse_geocoding/v3/?ak=dvQ2j8UtSdoSlKOStN2rGj2YwroKzKGn&callback=showLocation&location=" + lat + "," + lng + @"&output=xml&coordtype=wgs84ll";
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
XmlDocument xmlDoc = new XmlDocument();
string sendData = xmlDoc.InnerXml;
byte[] byteArray = Encoding.Default.GetBytes(sendData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream, System.Text.Encoding.GetEncoding("utf-8"));
string responseXml = reader.ReadToEnd();
//Mtxfw.Utility.Common.WriteHtml("/weixin/getindexdata.txt", responseXml);
XmlDocument xml = new XmlDocument();
xml.LoadXml(responseXml);
string status = xml.DocumentElement.SelectSingleNode("status").InnerText;
if (status == "0")
{
XmlNodeList nodes = xml.DocumentElement.GetElementsByTagName("formatted_address");
if (nodes.Count > 0)
{
return nodes[0].InnerText;
}
else
return "未获取到位置信息,错误码3";
}
else
{
return "未获取到位置信息,错误码1";
}
}
catch (System.Exception ex)
{
return "未获取到位置信息,错误码2";
}
}
#endregion
#region 计算经纬度距离
public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
{
double radLat1 = Rad(lat1);
double radLat2 = Rad(lat2);
double a = radLat1 - radLat2;
double b = Rad(lng1) - Rad(lng2);
double s = 2 * Math.Asin(Math.Sqrt(
Math.Pow(Math.Sin(a / 2), 2) +
Math.Cos(radLat1) * Math.Cos(radLat2)
* Math.Pow(Math.Sin(b / 2), 2)));
s = s * 6378137.0;
s = Math.Round(s * 10000) / 10000;
return s;
}
private static double Rad(double d)
{
return d * Math.PI / 180.0;
}
#endregion
#region 姓名隐藏
///
/// 姓名隐藏
///
public static string CName(string realname)
{
if (realname.Length > 0)
{
realname = realname.Substring(0, 1) + "*" + (realname.Length >= 3 ? realname.Substring(2, realname.Length - 2) : "");
}
return realname;
}
#endregion
#region 转换输出腾讯云文件地址
public static string cfileurl(string url)
{
if (url.IndexOf("http://1301659355.vod2.myqcloud.com") != -1)
{
string key = "fHI4e1IgVr69Gx4sf1dC";
string strp = url.Replace("http://1301659355.vod2.myqcloud.com", "");
string Dir = strp.Substring(0, strp.LastIndexOf("/")) + "/";
string t = GetTimeStamp16(DateTime.Now.AddHours(24), false).ToLower();
string exper = "0";
string rlimit = "";
string us = DateTime.Now.ToString("yyyyMMddHHmmss");
StringBuilder sb = new StringBuilder(32);
MD5 md5 = new MD5CryptoServiceProvider();
string strkey = key + Dir + t + exper + rlimit + us;
byte[] st = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(strkey));
for (int i = 0; i < st.Length; i++)
{
sb.Append(st[i].ToString("x").PadLeft(2, '0'));
}
string sign = sb.ToString();
url += "?t=" + t + "&exper=" + exper + "&rlimit=" + rlimit + "&us=" + us + "&sign=" + sign;
}
else
{
//url = cqnurl(url);
}
return url;
}
#endregion
#region 转换输出七牛云文件地址
public static string cqnurl(string url)
{
if (url.IndexOf("http://fv.fuanmei.cn") != -1)
{
string key = "619a6299ed8a71996d89d3b9ef8881ab59b81d9b";
string strp = url.Replace("http://fv.fuanmei.cn", "");
string Dir = strp.Split('?')[0];
string t = GetTimeStamp16(DateTime.Now.AddHours(24), false).ToLower();
StringBuilder sb = new StringBuilder(32);
MD5 md5 = new MD5CryptoServiceProvider();
string strkey = key + Dir + t;
byte[] st = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(strkey));
for (int i = 0; i < st.Length; i++)
{
sb.Append(st[i].ToString("x").PadLeft(2, '0'));
}
string sign = sb.ToString().ToLower();
if (url.IndexOf("?") != -1)
{
url += "&sign=" + sign + "&t=" + t + "";
}
else
{
url += "?sign=" + sign + "&t=" + t + "";
}
}
return url;
}
#endregion
#region 生成设置范围内的Double的随机数
//
/// 生成设置范围内的Double的随机数
/// eg:_random.NextDouble(1.5, 2.5)
///
/// Random
/// 生成随机数的最大值
/// 生成随机数的最小值
/// 当Random等于NULL的时候返回0;
public static Double NextDouble(Random random, Double miniDouble, Double maxiDouble)
{
if (random != null)
{
return random.NextDouble() * (maxiDouble - miniDouble) + miniDouble;
}
else
{
return 0.0d;
}
}
#endregion
#region decimal保留指定位数小数
///
/// decimal保留指定位数小数
///
/// 原始数量
/// 保留小数位数
/// 截取指定小数位数后的数量字符串
public static string DecimalToString(Decimal num, int scale)
{
string numToString = num.ToString();
int index = numToString.IndexOf(".");
int length = numToString.Length;
if (index != -1)
{
return string.Format("{0}.{1}",
numToString.Substring(0, index),
numToString.Substring(index + 1, Math.Min(length - index - 1, scale)));
}
else
{
return num.ToString();
}
}
#endregion
///
/// Image 转成 base64
///
///
public static string ImageToBase64(string fileFullName)
{
try
{
using (Image image = Image.FromFile(fileFullName))
{
using (MemoryStream mStream = new MemoryStream())
{
// 保存图片到内存流中,并用相应的图片格式
image.Save(mStream, image.RawFormat);
// 转换图片为字节数组
byte[] imageBytes = mStream.ToArray();
// 将字节数组转换为Base64字符串
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
catch
{
return "";
}
}
public static string BitmapToBase64(Bitmap bmp)
{
try
{
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Png);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
String strbaser64 = Convert.ToBase64String(arr);
return strbaser64;
}
catch (Exception ex)
{
return "";
}
}
public static string cstarlevel(string starlevel)
{
return "" + starlevel + "星";
}
public static string cminimage(string uploadimages)
{
string src = uploadimages;
if (uploadimages.IndexOf("https://vip.ksd2023.com") != -1)
{
src = "https://vip.ksd2023.com/GetFiles.ashx?image=" + uploadimages.Replace("https://vip.ksd2023.com", "").Replace("Files/Image/", "") + "&itsize=100x100&itmode=cut";
}
else if (uploadimages.IndexOf("https://www.pmhapp.cn") != -1)
{
src = "https://www.pmhapp.cn/GetFiles.ashx?image=" + uploadimages.Replace("https://www.pmhapp.cn", "").Replace("Files/Image/", "") + "&itsize=100x100&itmode=cut";
}
else if (uploadimages.IndexOf("http://fv.fuanmei.cn") != -1)
{
src = src+"?imageView2/2/w/100/h/100/q/75";
}
else
{
if (uploadimages.IndexOf("https://") == -1 && uploadimages.IndexOf("http://") == -1)
{
src = "https://vip.ksd2023.com/GetFiles.ashx?image=" + uploadimages.Replace("Files/Image/", "") + "&itsize=100x100&itmode=cut";
}
}
return src;
}
public static string cminimage0(string uploadimages)
{
string src = uploadimages;
if (uploadimages.IndexOf("https://vip.ksd2023.com") != -1)
{
src = "https://vip.ksd2023.com/GetFiles.ashx?image=" + uploadimages.Replace("https://vip.ksd2023.com", "").Replace("Files/Image/", "") + "&itsize=220x220&itmode=cut";
}
else if (uploadimages.IndexOf("https://www.pmhapp.cn") != -1)
{
src = "https://www.pmhapp.cn/GetFiles.ashx?image=" + uploadimages.Replace("https://www.pmhapp.cn", "").Replace("Files/Image/", "") + "&itsize=220x220&itmode=cut";
}
else if (uploadimages.IndexOf("http://fv.fuanmei.cn") != -1)
{
src = src+"?imageView2/2/w/220/h/220/q/75";
}
else
{
if (uploadimages.IndexOf("https://") == -1 && uploadimages.IndexOf("http://") == -1)
{
src = "https://vip.ksd2023.com/GetFiles.ashx?image=" + uploadimages.Replace("Files/Image/", "") + "&itsize=220x220&itmode=cut";
}
}
return src;
}
public static string cmaximage(string uploadimages)
{
string src = uploadimages;
if (uploadimages.IndexOf("https://vip.ksd2023.com") != -1)
{
src = "https://vip.ksd2023.com/GetFiles.ashx?image=" + uploadimages.Replace("https://vip.ksd2023.com", "").Replace("Files/Image/", "") + "&itsize=720x460&itmode=cut";
}
else if (uploadimages.IndexOf("https://www.pmhapp.cn") != -1)
{
src = "https://www.pmhapp.cn/GetFiles.ashx?image=" + uploadimages.Replace("https://www.pmhapp.cn", "").Replace("Files/Image/", "") + "&itsize=720x460&itmode=cut";
}
else if (uploadimages.IndexOf("http://fv.fuanmei.cn") != -1)
{
src = src + "?imageView2/2/w/720/h/460/q/75";
}
else
{
if (uploadimages.IndexOf("https://") == -1 && uploadimages.IndexOf("http://") == -1)
{
src = "https://vip.ksd2023.com/GetFiles.ashx?image=" + uploadimages.Replace("Files/Image/", "") + "&itsize=720x460&itmode=cut";
}
}
return src;
}
///
/// 获取星级奖励
///
public static Double GetXJJLmoney(int uLevel, Mtxfw.Utility.Config config)
{
Double bb = 0;
switch (uLevel)
{
case 0:
bb = Convert.ToDouble(config.webMoney65);
break;
case 1:
bb = Convert.ToDouble(config.webMoney71);
break;
case 2:
bb = Convert.ToDouble(config.webMoney104);
break;
case 3:
bb = Convert.ToDouble(config.webMoney57);
break;
case 4:
bb = Convert.ToDouble(config.webMoney67);
break;
case 5:
bb = Convert.ToDouble(config.webMoney68);
break;
}
return bb;
}
///
/// 获取董事奖励
///
public static Double GetDSJLmoney(int uLevel, Mtxfw.Utility.Config config)
{
Double bb = 0;
switch (uLevel)
{
case 1:
bb = Convert.ToDouble(config.webMoney156);
break;
case 2:
bb = Convert.ToDouble(config.webMoney157);
break;
case 3:
bb = Convert.ToDouble(config.webMoney158);
break;
case 4:
bb = Convert.ToDouble(config.webMoney159);
break;
case 5:
bb = Convert.ToDouble(config.webMoney160);
break;
case 6:
bb = Convert.ToDouble(config.webMoney161);
break;
case 7:
bb = Convert.ToDouble(config.webMoney162);
break;
case 8:
bb = Convert.ToDouble(config.webMoney163);
break;
}
return bb;
}
public static Double GetHSDMoney(int uLevel, Mtxfw.Utility.Config config)
{
Double bb = 0.00;
switch (uLevel)
{
case 1:
bb = Convert.ToDouble(config.webMoney40);
break;
case 2:
bb = Convert.ToDouble(config.webMoney25);
break;
case 3:
bb = Convert.ToDouble(config.webMoney26);
break;
case 4:
bb = Convert.ToDouble(config.webMoney136);
break;
case 5:
bb = Convert.ToDouble(config.webMoney137);
break;
case 6:
bb = Convert.ToDouble(config.webMoney138);
break;
case 7:
bb = Convert.ToDouble(config.webMoney139);
break;
}
return bb;
}
public static Double GetTJHSDMoney(int tjcount, Mtxfw.Utility.Config config)
{
Double bb = 0.00;
switch (tjcount)
{
case 1:
bb = Convert.ToDouble(config.webMoney127);
break;
case 2:
bb = Convert.ToDouble(config.webMoney128);
break;
case 3:
bb = Convert.ToDouble(config.webMoney129);
break;
case 4:
bb = Convert.ToDouble(config.webMoney130);
break;
case 5:
bb = Convert.ToDouble(config.webMoney131);
break;
}
if (tjcount > 5)
{
bb = Convert.ToDouble(config.webMoney131);
}
return bb;
}
public static Double GetZTMoney(int tjcount, Mtxfw.Utility.Config config)
{
Double bb = 0.00;
switch (tjcount)
{
case 0:
bb = Convert.ToDouble(config.webMoney104);
break;
case 1:
bb = Convert.ToDouble(config.webMoney105);
break;
case 2:
bb = Convert.ToDouble(config.webMoney106);
break;
case 3:
bb = Convert.ToDouble(config.webMoney107);
break;
case 4:
bb = Convert.ToDouble(config.webMoney140);
break;
case 5:
bb = Convert.ToDouble(config.webMoney141);
break;
case 6:
bb = Convert.ToDouble(config.webMoney142);
break;
case 7:
bb = Convert.ToDouble(config.webMoney143);
break;
}
return bb;
}
public static Double GetDTMoney(int uLevel5, Mtxfw.Utility.Config config)
{
Double bb = 0.00;
switch (uLevel5)
{
case 1:
bb = Convert.ToDouble(config.webMoney81);
break;
case 2:
bb = Convert.ToDouble(config.webMoney82);
break;
case 3:
bb = Convert.ToDouble(config.webMoney83);
break;
case 4:
bb = Convert.ToDouble(config.webMoney84);
break;
case 5:
bb = Convert.ToDouble(config.webMoney85);
break;
case 6:
bb = Convert.ToDouble(config.webMoney27);
break;
}
return bb;
}
public static Double GetTemJL(int uLevel, Mtxfw.Utility.Config config)
{
Double bb = 0.00;
switch (uLevel)
{
/*case 0:
bb = Convert.ToDouble(config.webMoney2);
break;*/
case 1:
bb = Convert.ToDouble(config.webMoney24);
break;
case 2:
bb = Convert.ToDouble(config.webMoney25);
break;
case 3:
bb = Convert.ToDouble(config.webMoney26);
break;
case 4:
bb = Convert.ToDouble(config.webMoney27);
break;
case 5:
bb = Convert.ToDouble(config.webMoney28);
break;
case 6:
bb = Convert.ToDouble(config.webMoney29);
break;
case 7:
bb = Convert.ToDouble(config.webMoney30);
break;
}
return bb;
}
public static Double GetQWJL(int uLevel, Mtxfw.Utility.Config config)
{
Double bb = 0.00;
switch (uLevel)
{
case 1:
bb = Convert.ToDouble(config.webMoney31);
break;
case 2:
bb = Convert.ToDouble(config.webMoney32);
break;
case 3:
bb = Convert.ToDouble(config.webMoney33);
break;
case 4:
bb = Convert.ToDouble(config.webMoney34);
break;
case 5:
bb = Convert.ToDouble(config.webMoney35);
break;
case 6:
bb = Convert.ToDouble(config.webMoney36);
break;
case 7:
bb = Convert.ToDouble(config.webMoney37);
break;
}
return bb;
}
public static Double GetSXF(int uLevel, Mtxfw.Utility.Config config)
{
Double bb = 0.00;
if (uLevel == 0)
{
bb = Convert.ToDouble(Convert.ToDouble(config.webMoney38).ToString("f2"));
}
else if (uLevel == 1)
{
bb = Convert.ToDouble(Convert.ToDouble(config.webMoney39).ToString("f2"));
}
else if (uLevel == 2)
{
bb = Convert.ToDouble(Convert.ToDouble(config.webMoney40).ToString("f2"));
}
else if (uLevel == 3)
{
bb = Convert.ToDouble(Convert.ToDouble(config.webMoney41).ToString("f2"));
}
else if (uLevel == 4)
{
bb = Convert.ToDouble(Convert.ToDouble(config.webMoney42).ToString("f2"));
}
else
{
bb = Convert.ToDouble(Convert.ToDouble(config.webMoney43).ToString("f2"));
}
return bb;
}
///
/// 获取充值方式
///
public static string GetCZPayType(int PayType)
{
string strPayType = "";
switch (PayType)
{
case 0:
strPayType = "银行汇款";
break;
case 1:
strPayType = "POS机和现金";
break;
case 2:
strPayType = "支付宝转账";
break;
case 3:
strPayType = "微信转账";
break;
case 4:
strPayType = "现金券余额";
break;
case 5:
strPayType = "在线支付";
break;
}
return strPayType;
}
///
/// 订单类型
///
public static string GetOrderType(int GType)
{
string strType = "";
switch (GType)
{
case 0:
strType = "热卖推荐商品";
break;
case 1:
strType = "兑换商城商品";
break;
case 2:
strType = "精选商品";
break;
case 3:
strType = "套餐";
break;
case 4:
strType = "服务中心订单";
break;
case 5:
strType = "广告区订单";
break;
case 6:
strType = "枣享福订单";
break;
case 7:
strType = "其它订单";
break;
case 8:
strType = "事业联盟订单";
break;
case 9:
strType = "助农专区订单";
break;
case 10:
strType = "推广员订单";
break;
case 11:
strType = "爆品专区订单";
break;
}
return strType;
}
///
/// 获取支付方式
///
///
public static string GetPayType(int t)
{
string strType = "";
switch (t)
{
case 0:
strType = "余额";
break;
case 1:
strType = "兑换券兑换";
break;
case 2:
strType = "微信支付";
break;
case 3:
strType = "支付宝";
break;
case 4:
strType = "赠送";
break;
case 5:
strType = "广告积分";
break;
case 6:
strType = "佣金";
break;
case 7:
strType = "KSD";
break;
}
return strType;
}
///
/// 获取充值方式
///
///
public static string GetChongZhiType(int t)
{
string strType = "";
switch (t)
{
case 0:
strType = "银行汇款";
break;
case 1:
strType = "POS机";
break;
case 2:
strType = "支付宝转账";
break;
case 3:
strType = "微信转账";
break;
case 4:
strType = "现金";
break;
}
return strType;
}
///
/// 获取购买图标类型
///
///
public static string GetGMTBType(int t)
{
string strType = "";
switch (t)
{
case 0:
strType = "VIP";
break;
case 1:
strType = "经验值图标";
break;
case 2:
strType = "加速图标";
break;
case 3:
strType = "金卡图标";
break;
case 4:
strType = "手续费图标";
break;
}
return strType;
}
///
/// 获取商家一级分类
///
public static Dictionary GetBusinessClass()
{
Dictionary dic = new Dictionary();
dic.Add(1, "饮食");
dic.Add(2, "服务");
dic.Add(3, "零售");
dic.Add(4, "服装");
dic.Add(5, "酒店");
dic.Add(6, "房产");
dic.Add(7, "数码");
dic.Add(8, "茶叶");
dic.Add(9, "健身");
dic.Add(10, "珠宝");
dic.Add(11, "美容");
dic.Add(12, "汽车");
dic.Add(18, "其他");
return dic;
}
///
/// 获取栏目分类
///
///
public static Dictionary GetMenuClass()
{
Dictionary dic = new Dictionary();
dic.Add(6, "关于我们");
dic.Add(4, "需要帮助");
dic.Add(2, "我的订单");
dic.Add(1, "服务说明");
dic.Add(3, "售后服务");
dic.Add(0, "生活馆");
dic.Add(7, "会员体系");
return dic;
}//dic.Add(0, "配送范围");dic.Add(5, "商家入驻");
public static String GetMenuName(int key)
{
return GetMenuClass()[key];
}
///
/// 获取团队
///
///
public static Dictionary GetTems()
{
Dictionary dic = new Dictionary();
dic.Add(8633, "A仓");
dic.Add(8634, "B仓");
dic.Add(8635, "C仓");
dic.Add(8636, "D仓");
dic.Add(8637, "E仓");
dic.Add(8638, "F仓");
dic.Add(8639, "G仓");
dic.Add(8640, "H仓");
dic.Add(8641, "I仓");
dic.Add(8642, "J仓");
dic.Add(8928, "K仓");
dic.Add(10795, "L仓");
dic.Add(10796, "M仓");
dic.Add(10797, "N仓");
dic.Add(10798, "O仓");
dic.Add(10799, "P仓");
dic.Add(10800, "Q仓");
dic.Add(10801, "R仓");
dic.Add(10802, "S仓");
dic.Add(10803, "T仓");
dic.Add(10804, "U仓");
dic.Add(10805, "V仓");
dic.Add(10806, "W仓");
dic.Add(10808, "X仓");
dic.Add(10809, "Y仓");
dic.Add(10810, "Z仓");
dic.Add(0, "");
return dic;
}
public static String GetTem(int key)
{
try
{
return GetTems()[key];
}
catch
{
return "";
}
}
///
/// 获取加盟级别
///
///
public static Dictionary GetuLevels()
{
Dictionary dic = new Dictionary();
dic.Add(0, "普通消费商");
dic.Add(1, "会员店");
dic.Add(2, "品牌店");
dic.Add(3, "旗舰店");
dic.Add(4, "");
dic.Add(5, "");
dic.Add(6, "");
return dic;
}
public static String GetuLevelname(int key)
{
return GetuLevels()[key];
}
///
/// 获取加盟级别
///
///
public static Dictionary GetuLevel4s()
{
Dictionary dic = new Dictionary();
dic.Add(0, "");
dic.Add(1, "银钻");
dic.Add(2, "金钻");
dic.Add(3, "铂钻");
return dic;
}
public static String GetuLevel4name(int key)
{
return GetuLevel4s()[key];
}
///
/// 获取加盟级别
///
///
public static Dictionary GetuLevel24s()
{
Dictionary dic = new Dictionary();
dic.Add(0, "");
dic.Add(1, "一星董事");
dic.Add(2, "二星董事");
dic.Add(3, "三星董事");
dic.Add(4, "四星董事");
dic.Add(5, "五星董事");
dic.Add(6, "六星董事");
dic.Add(7, "七星董事");
dic.Add(8, "八星董事");
return dic;
}
public static String GetuLevel24name(int key)
{
return GetuLevel24s()[key];
}
///
/// 获取加盟级别
///
///
public static Dictionary GetuLevel25s()
{
Dictionary dic = new Dictionary();
dic.Add(0, "");
dic.Add(1, "");
dic.Add(2, "乡镇服务中心");
dic.Add(3, "县服务中心");
dic.Add(4, "市服务中心");
dic.Add(5, "省服务中心");
return dic;
}
public static String GetuLevel25name(int key)
{
return GetuLevel25s()[key];
}
public static String GetuLevelStar(int key)
{
string str = "";
if (key == 0)
{
str = "";
}
if (key == 1)
{
str = "";
}
if (key == 2)
{
str = "";
}
if (key == 3)
{
str = "";
}
if (key == 4)
{
str = "";
}
if (key == 5)
{
str = "";
}
return str;
}
public static String GetuLevel4Star(int key)
{
string str = "";
if (key == 1)
{
str = "";
}
if (key == 2)
{
str = "";
}
if (key == 3)
{
str = "";
}
if (key == 4)
{
str = "";
}
if (key == 5)
{
str = "";
}
if (key == 6)
{
str = "";
}
if (key == 7)
{
str = "";
}
return str;
}
///
/// 获取金卡状态
///
///
public static string Getseef(string seef)
{
if (seef == "已审核")
{
seef = "已审核";
}
else
{
seef = "未审核";
}
return seef;
}
///
/// 获取论坛文章分类
///
///
public static string GetB_TType(string B_TType)
{
if (B_TType == "0")
{
B_TType = "普通";
}
else if (B_TType == "1")
{
B_TType = "贴图";
}
else if (B_TType == "2")
{
B_TType = "转贴";
}
else if (B_TType == "3")
{
B_TType = "原创";
}
else if (B_TType == "4")
{
B_TType = "新闻";
}
else if (B_TType == "5")
{
B_TType = "活动";
}
else if (B_TType == "6")
{
B_TType = "投票";
}
else if (B_TType == "7")
{
B_TType = "公告";
}
else if (B_TType == "8")
{
B_TType = "公告";
}
return B_TType;
}
///
/// 获取论坛文章分类
///
///
public static string Getrefundstatus(int refundstatus)
{
string str = "";
switch (refundstatus)
{
case 0:
str = "";
break;
case 1:
str = "退款成功";
break;
case 2:
str = "退款关闭";
break;
case 3:
str = "退款处理中";
break;
case 4:
str = "退款异常";
break;
}
return str;
}
///
/// 获取订单状态和操作状态
///
///
public static string[] GetOrderStatus(string utype, string O_Id, string OrderId, int ptype,int peitype, string O_SubmitDate, string O_Payed, string O_Payed_Date, string O_Shipped, string O_Shipped_Date, string O_received, string O_received_Date, string kdgs, string ydh, string Contacttel, string wlremarks,int refundstatus, string refund_channel, string user_received_account, string success_time,int O_Seef,Double Totalprice,String ReturnReason, int p)
{
string[] strStatus = new string[3];
string strO_Payed = "";
string IFGQ = "";
string addtime = O_Payed_Date;
if (wlremarks != "")
{
wlremarks = wlremarks.Replace("\r", "\\r").Replace("\n", "\\n").Replace("\t", "\\t").Replace("\"", "\\\"");
}
if (O_Payed == "0")
{
addtime = O_SubmitDate;
}
if (p == 0)
{
switch (O_Payed)
{
case "-1":
strO_Payed = "已取消";
break;
case "-2":
strO_Payed = "您已申请退款,等待商家同意退款";
break;
case "-3":
strO_Payed = "您已申请退货,等待商家同意退货";
break;
case "-4":
strO_Payed = "商家已同意退货,请您把商品退还给商家";
break;
case "-5":
strO_Payed = "退款完成,交易结束";
break;
case "-6":
strO_Payed = "退货完成,交易结束";
break;
case "0":
strO_Payed = "您未付款";
IFGQ = "付款";
IFGQ += "取消订单";
break;
case "1":
if (utype == "5" && O_Shipped == "2")
{
strO_Payed = "您已退货,退货时间:" + O_Shipped_Date;
}
else
{
strO_Payed = "您已付款,等待商家确认发货
付款时间:" + O_Payed_Date;
//IFGQ = "删除订单";
//IFGQ = "申请退款";
}
break;
case "2":
strO_Payed = "部分已发货";
break;
case "3":
strO_Payed = "已全部发货";
break;
case "4":
strO_Payed = "交易完成
完成时间:" + O_Payed_Date;
break;
case "5":
strO_Payed = "已核销";
break;
case "6":
strO_Payed = "确认中";
break;
case "7":
strO_Payed = "已退货"; //+ (utype == "2" ? Getrefundstatus(refundstatus) + " " + refund_channel + " " + user_received_account + " " + success_time : (utype == "4" ? "已退回消费积分中" : "已退回余额中"));
break;
case "8":
strO_Payed = "申请退货中";
break;
}
}
if (p == 10)
{
switch (O_Payed)
{
case "-1":
strO_Payed = "已取消";
break;
case "-2":
strO_Payed = "您已申请退款,等待商家同意退款";
break;
case "-3":
strO_Payed = "您已申请退货,等待商家同意退货";
break;
case "-4":
strO_Payed = "商家已同意退货,请您把商品退还给商家";
break;
case "-5":
strO_Payed = "退款完成,交易结束";
break;
case "-6":
strO_Payed = "退货完成,交易结束";
break;
case "0":
strO_Payed = "您未付款";
//IFGQ = "付款";
IFGQ += "取消订单";
break;
case "1":
strO_Payed = "您已付款,等待商家确认发货 付款时间:" + O_Payed_Date;
//IFGQ = "删除订单";
//IFGQ = "申请退款";
break;
case "2":
strO_Payed = "部分已发货";
break;
case "3":
strO_Payed = "已全部发货";
break;
case "4":
strO_Payed = "交易完成
完成时间:" + O_Payed_Date;
break;
case "5":
strO_Payed = "确认中";
IFGQ = "委托寄售";
IFGQ += "我要提货";
break;
case "6":
strO_Payed = "已退货";
break;
case "7":
strO_Payed = "申请退货中";
break;
}
}
else if (p == 1)
{
switch (O_Payed)
{
case "-1":
strO_Payed = "已取消";
break;
case "-2":
strO_Payed = "会员已申请退款,等待您同意退款";
IFGQ = "同意退款";
IFGQ += "不同意退款";
break;
case "-3":
strO_Payed = "会员已申请退货,等待您同意退货";
IFGQ = "同意退货";
IFGQ += "不同意退货";
break;
case "-4":
strO_Payed = "您已同意退货,等待您确认收到退货";
IFGQ = "确认收到退货";
IFGQ += "未收到退货";
break;
case "-5":
strO_Payed = "退款完成,交易结束";
break;
case "-6":
strO_Payed = "退货完成,交易结束";
break;
case "0":
strO_Payed = "未付款";
//IFGQ = "申请退款";
break;
case "1":
strO_Payed = "会员已付款,等待您确认发货
付款时间:" + O_Payed_Date;
IFGQ = "确认发货";
break;
case "2":
strO_Payed = "部分已发货";
IFGQ = "继续发货";
break;
case "3":
strO_Payed = "已全部发货";
break;
case "4":
strO_Payed = "交易完成
完成时间:" + O_Payed_Date;
break;
case "5":
strO_Payed = "确认中";
break;
case "6":
strO_Payed = "已退货,退货理由:" + ReturnReason; //+ (utype == "2" ? Getrefundstatus(refundstatus) + " " + refund_channel + " " + user_received_account + " " + success_time : (utype == "4" ? "已退回消费积分中" : "已退回余额中"));
break;
case "7":
strO_Payed = "申请退货中,退货理由:" + ReturnReason;
break;
default:
//IFGQ += "设为已付款";
break;
}
}
else if (p == 2)
{
switch (O_Payed)
{
case "-1":
strO_Payed = "已取消";
break;
case "-2":
strO_Payed = "申请退款中";
break;
case "-3":
strO_Payed = "申请退货中";
break;
case "-4":
strO_Payed = "退货中";
break;
case "-5":
strO_Payed = "退款完成,交易结束";
break;
case "-6":
strO_Payed = "退货完成,交易结束";
break;
case "1":
strO_Payed = "已付款
付款时间:" + O_Payed_Date;
break;
case "2":
strO_Payed = "已确认发货
发货时间:" + O_Payed_Date;
//strO_Payed += " " + Getkdcompay(kdgs) + "运单号:" + ydh;
break;
case "3":
strO_Payed = "交易完成
完成时间:" + O_Payed_Date;
//strO_Payed += " " + Getkdcompay(kdgs) + "运单号:" + ydh;
/*if (ptype == 1)
{
if (O_Seef == 0)
{
strO_Payed = "已确认";
}
}*/
break;
case "4":
strO_Payed = "已核销";
break;
case "5":
strO_Payed = "确认中";
break;
case "6":
strO_Payed = "已退货"; //+ (utype == "2" ? Getrefundstatus(refundstatus) + " " + refund_channel + " " + user_received_account + " " + success_time : (utype == "4" ? "已退回消费积分中" : "已退回余额中"));
break;
case "7":
strO_Payed = "申请退货中";
break;
}
}
else if (p == 3)
{
switch (O_Payed)
{
case "-1":
strO_Payed = "已取消";
break;
case "0":
strO_Payed = "未付款";
break;
case "1":
strO_Payed = "会员已付款,等待您确认发货
付款时间:" + O_Payed_Date;
IFGQ = "确认发货";
//IFGQ += "修改配送地址";
break;
case "2":
strO_Payed = "您已确认发货,等待会员确认收货
发货时间:" + O_Payed_Date;
IFGQ += "修改物流";
IFGQ += "取消发货";
//IFGQ += "修改配送地址";
break;
case "3":
strO_Payed = "交易完成
完成时间:" + O_Payed_Date;
//strO_Payed += " " + Getkdcompay(kdgs) + "运单号:" + ydh;
if (ptype == 1)
{
if (O_Seef == 0)
{
strO_Payed = "已确认";
}
}
break;
case "4":
strO_Payed = "已核销";
break;
case "5":
strO_Payed = "确认中";
break;
case "6":
strO_Payed = "已退货"; //+ (utype == "2" ? Getrefundstatus(refundstatus) + " " + refund_channel + " " + user_received_account + " " + success_time : (utype == "4" ? "已退回消费积分中" : "已退回余额中"));
break;
case "7":
strO_Payed = "申请退货中";
break;
default:
//IFGQ += "设为已付款";
break;
}
if (ptype == 1)
{
if (O_Payed == "2" || O_Payed == "3")
{
IFGQ += "查看物流信息";
}
}
}
strStatus[0] = strO_Payed;
strStatus[1] = IFGQ;
strStatus[2] = addtime;
return strStatus;
}
public static string GetProZT(int ProZT)
{
string str = "";
if (ProZT == 0)
{
str = "#000000";
}
else if (ProZT == 1)
{
str = "#0c5fb2";
}
else if (ProZT == 2)
{
str = "#979505";
}
else if (ProZT == 3)
{
str = "#0c7f12";
}
return str;
}
public static string GetProZT(int ProZT, int b2, int b3, int b7, int b8, int b14, int b16)
{
string str = "";
if (b8 == 0)
{
if (b2 == 0)
{
if (b3 == 0)
{
str = "待确认";
}
else
{
str = "已完成";
}
}
else
{
if (b7 == 1)
{
str = "已代售";
}
else if (b7 == 2)
{
str = "已提货";
}
else if (b7 == 3)
{
str = "已退货";
}
else if (b7 == 4)
{
str = "已完成";
}
else
{
str = "待确认";
}
}
}
else
{
if (ProZT == 0)
{
if (b16 == 1)
{
str = "待确认";
}
else
{
str = "待审核";
}
}
else if (ProZT == 1)
{
str = "待确认";
}
else if (ProZT == 2)
{
str = "待确认";
}
else
{
str = "已完成";
}
}
return str;
}
public static string GetProZT0(int ProZT, int b2, int b3, int b7, int b8, int b14, int b16)
{
string str = "";
if (b8 == 0)
{
if (b2 == 0)
{
if (b3 == 0)
{
str = "待确认";
}
else
{
str = "待提货";
if (b7 == 1)
{
str = "已自提";
}
else if (b7 == 2)
{
str = "已提货";
}
}
}
else
{
if (ProZT == 0)
{
if (b3 == 1)
{
str = "已代售";
}
else if (b3 == 2)
{
str = "已提货";
}
else
{
str = "待发货";
}
}
else if (ProZT == 1)
{
if (b3 == 1)
{
str = "已代售";
}
else if (b3 == 2)
{
str = "已提货";
}
}
else
{
str = "已完成";
}
}
}
else
{
if (ProZT == 0)
{
if (b16 == 1)
{
str = "待确认";
}
else
{
str = "待审核";
}
}
else if (ProZT == 1)
{
str = "待确认";
}
else if (ProZT == 2)
{
str = "待确认";
}
else
{
str = "已完成";
}
}
return str;
}
public static string[] GetProZT(int ProZT, int t, Mtxfw.Utility.Config config, DateTime addtime, DateTime seeftime)
{
string str = "", str2 = "";
TimeSpan ts1, ts2, ts;
DateTime dt1;
DateTime dt2;
string SJC = "";
if (t == 0)
{
switch (ProZT)
{
case 0:
str = "未达成";
//str2 = "确认交易";
break;
case 1:
dt1 = seeftime.AddMinutes(Convert.ToInt32(config.webMoney40));
dt2 = DateTime.Now;
if (dt1 >= dt2)
{
ts1 = new TimeSpan(seeftime.AddMinutes(Convert.ToInt32(config.webMoney40)).Ticks);
ts2 = new TimeSpan(DateTime.Now.Ticks);
ts = ts1.Subtract(ts2).Duration();
SJC = (ts.Days * 24 * 3600 + ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds).ToString();
int hours = (ts.Days * 24 + ts.Hours);
if (hours > 0)
{
str = "交流中,确认支付倒计时 " + hours + " 计时";
}
else
{
str = "交流中,确认支付倒计时 ";
}
str2 = "确认支付 举报";
}
else
{
str = "超时未确认支付";
}
break;
case 2:
dt1 = seeftime.AddMinutes(Convert.ToInt32(config.webMoney40));
dt2 = DateTime.Now;
if (dt1 >= dt2)
{
ts1 = new TimeSpan(seeftime.AddMinutes(Convert.ToInt32(config.webMoney40)).Ticks);
ts2 = new TimeSpan(DateTime.Now.Ticks);
ts = ts1.Subtract(ts2).Duration();
SJC = (ts.Days * 24 * 3600 + ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds).ToString();
int hours = (ts.Days * 24 + ts.Hours);
if (hours > 0)
{
str = "已支付,等待确认倒计时 " + hours + " 计时";
}
else
{
str = "已支付,等待确认倒计时 ";
}
str2 = "确认收到 举报";
}
else
{
str = "超时未确认收到";
}
break;
case 3:
str = "已完成";
break;
}
}
else if (t == 1)
{
switch (ProZT)
{
case 0:
str = "未达成";
//str2 = "确认交易";
break;
case 1:
dt1 = seeftime.AddMinutes(Convert.ToInt32(config.webMoney40));
dt2 = DateTime.Now;
if (dt1 >= dt2)
{
ts1 = new TimeSpan(seeftime.AddMinutes(Convert.ToInt32(config.webMoney40)).Ticks);
ts2 = new TimeSpan(DateTime.Now.Ticks);
ts = ts1.Subtract(ts2).Duration();
SJC = (ts.Days * 24 * 3600 + ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds).ToString();
int hours = (ts.Days * 24 + ts.Hours);
if (hours > 0)
{
str = "交流中,确认支付倒计时 " + hours + " 计时";
}
else
{
str = "交流中,确认支付倒计时 ";
}
str2 = "确认支付 举报";
}
else
{
str = "超时未确认支付";
}
break;
case 2:
dt1 = seeftime.AddMinutes(Convert.ToInt32(config.webMoney40));
dt2 = DateTime.Now;
if (dt1 >= dt2)
{
ts1 = new TimeSpan(seeftime.AddMinutes(Convert.ToInt32(config.webMoney40)).Ticks);
ts2 = new TimeSpan(DateTime.Now.Ticks);
ts = ts1.Subtract(ts2).Duration();
SJC = (ts.Days * 24 * 3600 + ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds).ToString();
int hours = (ts.Days * 24 + ts.Hours);
if (hours > 0)
{
str = "已支付,确认收到倒计时 " + hours + " 计时";
}
else
{
str = "已支付,确认收到倒计时 ";
}
str2 = "确认收到 举报";
}
else
{
str = "超时未确认收到";
}
break;
case 3:
str = "已完成";
break;
}
}
else if (t == 2)
{
switch (ProZT)
{
case 0:
str = "未达成";
//str2 = "确认交易";
break;
case 1:
dt1 = seeftime.AddMinutes(Convert.ToInt32(config.webMoney40));
dt2 = DateTime.Now;
if (dt1 >= dt2)
{
ts1 = new TimeSpan(seeftime.AddMinutes(Convert.ToInt32(config.webMoney40)).Ticks);
ts2 = new TimeSpan(DateTime.Now.Ticks);
ts = ts1.Subtract(ts2).Duration();
SJC = (ts.Days * 24 * 3600 + ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds).ToString();
int hours = (ts.Days * 24 + ts.Hours);
if (hours > 0)
{
str = "交流中,确认支付倒计时 " + hours + " 计时";
}
else
{
str = "交流中,确认支付倒计时 ";
}
str2 = "确认支付";
}
else
{
str = "超时未确认支付";
}
break;
case 2:
dt1 = seeftime.AddMinutes(Convert.ToInt32(config.webMoney40));
dt2 = DateTime.Now;
if (dt1 >= dt2)
{
ts1 = new TimeSpan(seeftime.AddMinutes(Convert.ToInt32(config.webMoney40)).Ticks);
ts2 = new TimeSpan(DateTime.Now.Ticks);
ts = ts1.Subtract(ts2).Duration();
SJC = (ts.Days * 24 * 3600 + ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds).ToString();
int hours = (ts.Days * 24 + ts.Hours);
if (hours > 0)
{
str = "已支付,确认收到倒计时 " + hours + " 计时";
}
else
{
str = "已支付,确认收到倒计时 ";
}
str2 = "确认收到";
}
else
{
str = "超时未确认收到";
str2 = "确认收到";
}
break;
case 3:
str = "已完成";
break;
}
}
string[] stra = new string[2];
stra[0] = str;
stra[1] = str2;
return stra;
}
///
/// 获取快递公司名称
///
///
public static string Getkdcompay(string kdcompay)
{
string str = "";
switch (kdcompay)
{
case "sf":
str = "顺丰";
break;
case "sto":
str = "申通";
break;
case "yt":
str = "圆通";
break;
case "yd":
str = "韵达";
break;
case "tt":
str = "天天";
break;
case "ems":
str = "EMS";
break;
case "zto":
str = "中通";
break;
case "ht":
str = "百世快递";
break;
case "qf":
str = "全峰";
break;
case "db":
str = "德邦";
break;
case "gt":
str = "国通";
break;
case "rfd":
str = "如风达";
break;
case "jd":
str = "京东快递";
break;
case "zjs":
str = "宅急送";
break;
case "emsg":
str = "EMS国际";
break;
case "fedex":
str = "Fedex国际";
break;
case "yzgn":
str = "邮政国内(挂号信)";
break;
case "ups":
str = "UPS国际快递";
break;
case "ztky":
str = "中铁快运";
break;
case "anwl":
str = "安能物流";
break;
case "auto":
str = "自提";
break;
}
return str;
}
///
/// 获取快递公司编号
///
///
public static string GetkdcompayPH(string kdcompay)
{
string str = "";
switch (kdcompay)
{
case "sf":
str = "SF";
break;
case "sto":
str = "STO";
break;
case "yt":
str = "YTO";
break;
case "yd":
str = "YUNDA";
break;
case "tt":
str = "HHTT";
break;
case "ems":
str = "EMS";
break;
case "zto":
str = "ZTO";
break;
case "ht":
str = "BEST";
break;
case "jtsd":
str = "JTSD";
break;
case "qf":
str = "QF";
break;
case "db":
str = "DB";
break;
case "gt":
str = "GT";
break;
case "rfd":
str = "RFD";
break;
case "jd":
str = "JDL";
break;
case "zjs":
str = "ZJS";
break;
case "emsg":
str = "emsg";
break;
case "fedex":
str = "Fedex";
break;
case "yzgn":
str = "yzgn";
break;
case "ups":
str = "UPS";
break;
case "ztky":
str = "ZTKY";
break;
case "anwl":
str = "ANWL";
break;
case "auto":
str = "自提";
break;
}
return str;
}
///
/// 按年月日生产文件夹 格式 /YYYY/MM/DD
///
public static string GetDateString()
{
StringBuilder sb = new StringBuilder();
sb.Append(DateTime.Now.Year);
sb.Append("\\");
sb.Append(DateTime.Now.Month);
sb.Append("\\");
sb.Append(DateTime.Now.Day);
sb.Append("\\");
return sb.ToString();
}
///
/// 生成GUID字符串
///
public static string GetGuidString()
{
return Guid.NewGuid().ToString("N");
}
///
/// 判断是否为允许的缩略图尺寸
///
public static bool Is_ThumbNail_AllowSizes(string request_size)
{
request_size = request_size.Trim().ToLower();
if (request_size == "") return false;
string[] sizes = ThumbNail_AllowSizes.Split('|');
foreach (string size in sizes)
{
if (request_size.Equals(size, StringComparison.OrdinalIgnoreCase)) return true;
}
return false;
}
///
/// 是否为允许上传的文件类型
///
public static bool Is_Allow_File_Types(string extname)
{
bool isBool = false;
extname = extname.Trim();
if (extname == "")
{
return isBool;
}
string[] exts = new Config("").webUpType.Split(',');
foreach (string ext in exts)
{
if (ext.Equals(extname, StringComparison.OrdinalIgnoreCase))
{
isBool = true;
break;
}
}
return isBool;
}
///
/// 缩略图大小
///
public static string ThumbNail_AllowSizes
{
get
{
return new Config("").webImgAllowSize;
}
}
///
/// 获取缩略图
///
public static string GetCoverPic(string picPath, string picSize, string itmode)
{
string rtnValue = string.Empty;
Config config = new Config("");
return "/GetFiles.ashx?image=" + System.Web.HttpUtility.UrlEncode(picPath) + "&itsize=" + picSize + "&itmode=" + itmode;
}
///
/// 删除指定文件
///
public static void DeleteFile(string path)
{
if (File.Exists(path))
{
File.Delete(path);
}
}
//发送Email
public static void SendEmail(String strEmail, String strSubject, String strBody)
{
//下面一段设置信件内容
if (strEmail.IndexOf("@") != -1)
{
MailMessage mmsg = new MailMessage();
mmsg.Subject = strSubject;
mmsg.BodyFormat = MailFormat.Html;
mmsg.Body = strBody;
mmsg.BodyEncoding = Encoding.UTF8;
//优先级
mmsg.Priority = MailPriority.High;
mmsg.From = "zdyhft@126.com";
mmsg.To = strEmail;
mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
//用户名
mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "zdyhft");
//密码
mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "KUEAHPBQOYNDLLQS");//snghymwiphorjgag
//端口
mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 465);
//使用SSL
mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
//Smtp服务器
SmtpMail.SmtpServer = "smtp.126.com";
SmtpMail.Send(mmsg);
}
}
//备份数据库
public static void BackUpData(int p, string apath)
{
string ServerName = ConfigurationManager.AppSettings["ServerName"];
string UserID = ConfigurationManager.AppSettings["UserID"];
string UserPwd = ConfigurationManager.AppSettings["UserPwd"];
string DatabaseName = ConfigurationManager.AppSettings["DatabaseName"];
string deviceName = DatabaseName + "_Data_" + DateTime.Now.ToString("yyyy_MM_dd", DateTimeFormatInfo.InvariantInfo) + ".bak";
if (p == 1)
{
deviceName = DatabaseName + "_Data_" + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss", DateTimeFormatInfo.InvariantInfo) + ".bak";
}
string selfName = ConfigurationManager.AppSettings["selfName"] + deviceName;
string remark = "数据备份";
//◆数据备份:
SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
oBackup.Action = 0;
oBackup.Initialize = true;
SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
oBackup.PercentComplete += pceh;
oSQLServer.LoginSecure = false;
oSQLServer.Connect(ServerName, UserID, UserPwd);
oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
oBackup.Database = DatabaseName;//数据库名
string path = "";
if (apath != "")
{
path = apath + selfName;
}
else
{
path = System.Web.HttpContext.Current.Request.PhysicalApplicationPath.ToString() + selfName;
}
oBackup.Files = path;//文件路径
oBackup.BackupSetName = deviceName;//备份名称
oBackup.BackupSetDescription = remark;//备份描述
oBackup.Initialize = true;
oBackup.SQLBackup(oSQLServer);
}
//还原数据库
public static void DbRestore(string FileName)
{
string ServerName = ConfigurationManager.AppSettings["ServerName"];
string UserID = ConfigurationManager.AppSettings["UserID"];
string UserPwd = ConfigurationManager.AppSettings["UserPwd"];
string DatabaseName = ConfigurationManager.AppSettings["DatabaseName"];
SQLDMO.Restore oRestore = new SQLDMO.RestoreClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
oSQLServer.LoginSecure = false;
oSQLServer.Connect(ServerName, UserID, UserPwd);
oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
oRestore.Database = DatabaseName;
oRestore.Files = System.Web.HttpContext.Current.Server.MapPath(FileName);
oRestore.FileNumber = 1;
oRestore.ReplaceDatabase = true;
oRestore.SQLRestore(oSQLServer);
}
///
/// 显示还原进度条
///
private static void Step(string message, int percent)
{
//this.pBar1.Value = percent;
}
///
///遍文件夹下的文件
///
///文件夹
private static DataTable GetFilesToDataTable(string ObjDirPath)
{
//构造DataTABLE
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("FilePath", typeof(string)));
dt.Columns.Add(new DataColumn("FileName", typeof(string)));
dt.Columns.Add(new DataColumn("FileLength", typeof(int)));
dt.Columns.Add(new DataColumn("FileLastWriteTime", typeof(string)));
DataRow dr;
DirectoryInfo SourceDir = new DirectoryInfo(ObjDirPath);
foreach (FileSystemInfo FSI in SourceDir.GetFileSystemInfos())
{
string FilePath = FSI.FullName;
if (FilePath.IndexOf("App_Data") != -1)
{
FilePath = "\\" + FilePath.Substring(FilePath.LastIndexOf("App_Data"));
}
else
{
FilePath = "\\" + FilePath.Substring(FilePath.IndexOf("dd"));
}
dr = dt.NewRow();
dr[0] = FilePath;//文件路径
dr[1] = Path.GetFileName(System.Web.HttpContext.Current.Server.MapPath("/" + FilePath));//文件名
//获取文件大小
FileInfo FI = new FileInfo(System.Web.HttpContext.Current.Server.MapPath("/" + FilePath));
dr[2] = Convert.ToInt32(FI.Length / 1000);//获取的是字节byte,还需要转换为千字节KB
string LastWriteTime = FI.LastWriteTime.ToString();
dr[3] = CDate(LastWriteTime);
dt.Rows.Add(dr);
}
return dt;
}
///文件夹
public static DataTable GetFilesDataView(int PageIndex, string ObjDirPath, out int rcount)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("FilePath", typeof(string)));
dt.Columns.Add(new DataColumn("FileName", typeof(string)));
dt.Columns.Add(new DataColumn("FileLength", typeof(int)));
dt.Columns.Add(new DataColumn("FileLastWriteTime", typeof(string)));
DataRow dr;
int j = 0;
DataView dv = GetFilesToDataTable(ObjDirPath).DefaultView;
dv.Sort = "FileLastWriteTime Desc";
if (dv.Count > 0)
{
int pagedata = 10 * (PageIndex - 1);
int pagedata2 = 10 * (PageIndex);
for (int i = dv.Count - 1; i >= 0; i--)
{
if (j >= pagedata && j < pagedata2)
{
dr = dt.NewRow();
dr[0] = dv.Table.Rows[i]["FilePath"].ToString();//文件路径
dr[1] = dv.Table.Rows[i]["FileName"].ToString();//文件名
dr[2] = dv.Table.Rows[i]["FileLength"].ToString();//获取的是字节byte,还需要转换为千字节KB
dr[3] = dv.Table.Rows[i]["FileLastWriteTime"].ToString();
dt.Rows.Add(dr);
}
j += 1;
}
}
rcount = j;
return dt;
}
public static string CDate(string Date)
{
DateTime dt = Convert.ToDateTime(Date);
string year = dt.Year.ToString();
string Month = dt.Month.ToString();
if (Month.Length == 1)
{
Month = "0" + Month;
}
string Day = dt.Day.ToString();
if (Day.Length == 1)
{
Day = "0" + Day;
}
string Hour = dt.Hour.ToString();
if (Hour.Length == 1)
{
Hour = "0" + Hour;
}
string Minute = dt.Minute.ToString();
if (Minute.Length == 1)
{
Minute = "0" + Minute;
}
string Second = dt.Second.ToString();
if (Second.Length == 1)
{
Second = "0" + Second;
}
return year + "-" + Month + "-" + Day + " " + Hour + ":" + Minute + ":" + Second;
}
///
/// 执行导出
///
/// 要导出的DataTable
/// 要导出的文件名
public static void doExport(DataTable dt, string strExcelFileName)
{
Excel.Application excel = new Excel.Application();
int rowIndex = 1;
int colIndex = 0;
excel.Application.Workbooks.Add(true);
System.Data.DataTable table = dt;
foreach (DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
}
foreach (DataRow row in table.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
}
excel.Visible = false;
//excel.Sheets[0] = "sss";
excel.ActiveWorkbook.SaveAs(strExcelFileName, Excel.XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null);
excel.Quit();
excel = null;
GC.Collect();//垃圾回收
}
public static string CIntro(string strIntro)
{
strIntro = strIntro.ToLower();
string str = "";
Regex R1 = new Regex(@"<([\S\s\n\t]*?)>");
Match M1 = R1.Match(strIntro);
while (M1.Success)
{
str = M1.Groups[1].ToString();
strIntro = strIntro.Replace("<" + str + ">", "");
M1 = M1.NextMatch();
}
strIntro = strIntro.Replace(" ", "");
strIntro = strIntro.Replace(" ", "");
strIntro = strIntro.Replace(" ", "");
strIntro = strIntro.Replace("●", "");
strIntro = strIntro.Replace("
", "");
strIntro = strIntro.Replace("\n", "");
strIntro = strIntro.Replace("\t", "");
strIntro = strIntro.Replace("\r", "");
return strIntro;
}
public static string CYIntro(string strIntro)
{
string str = "";
Regex R1 = new Regex(@"<([\S\s\n\t]*?)>");
Match M1 = R1.Match(strIntro);
while (M1.Success)
{
str = M1.Groups[1].ToString();
strIntro = strIntro.Replace("<" + str + ">", "");
M1 = M1.NextMatch();
}
strIntro = strIntro.Replace(" ", "");
strIntro = strIntro.Replace(" ", "");
strIntro = strIntro.Replace(" ", "");
strIntro = strIntro.Replace("●", "");
strIntro = strIntro.Replace("
", "");
strIntro = strIntro.Replace("\n", "");
strIntro = strIntro.Replace("\t", "");
strIntro = strIntro.Replace("\r", "");
return strIntro;
}
public static string CIntro0(string strIntro)
{
if (!String.IsNullOrEmpty(strIntro))
{
strIntro = strIntro.Replace("\n", "");
strIntro = strIntro.Replace("\t", "");
strIntro = strIntro.Replace("\r", "");
}
return strIntro;
}
///
/// 截取中英文混合字符串
///
/// 原始字符串
/// 截取长度
/// 截取串小于原始串时,尾部附加字符串
///
public static String CnCutString(String original, Int32 length, String fill)
{
Regex CnRegex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
Char[] CharArray = original.ToCharArray();
Int32 tmplength = 0;
for (Int32 i = 0; i < CharArray.Length; i++)
{
tmplength += CnRegex.IsMatch(CharArray[i].ToString()) ? 2 : 1;
if (tmplength > length) return original.Substring(0, i - fill.Length) + fill;
}
return original;
}
//
/// 截取字符串
///
/// 原始字符串
/// 截取长度
/// 截取串小于原始串时,尾部附加字符串
///
public static String CnCutString2(String original, Int32 length, String fill)
{
if (original.Length > length) original = original.Substring(0, length) + fill;
return original;
}
#region 中国短信网数据发送
/*public static string sendsms(string mobile, string strContent)
{
string postReturn = "";
try
{
//string sendurl = "http://gbk.sms.webchinese.cn/";
string sendurl = "http://api.sms.cn/sms/";
StringBuilder sbTemp = new StringBuilder();
string uid = "woerke";
string pwd = "hzabc567";
string Pass = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd + uid, "MD5"); //密码进行MD5加密
//POST 传值
//sbTemp.Append("?Uid=" + HttpUtility.UrlEncode(uid) + "&Key=" + HttpUtility.UrlEncode(Pass) + "&smsMob=" + HttpUtility.UrlEncode(mobile) + "&csmsText=" + HttpUtility.UrlEncode(strContent));
//postReturn = GetHtmlFromUrl(sendurl + sbTemp.ToString());
sbTemp.Append("ac=send&uid=" + uid + "&pwd=" + Pass + "&mobile=" + mobile + "&content=" + HttpUtility.UrlEncode(strContent));
byte[] bTemp = System.Text.Encoding.GetEncoding("GBK").GetBytes(sbTemp.ToString());
Getsms sms = (Getsms)Getsmsjson(doPostRequest(sendurl, bTemp));
postReturn = sms.stat;
Mtxfw.Utility.Common.WriteHtml("/weixin/sendsms0.txt", postReturn + "|" + sendurl + sbTemp.ToString());
}
catch (Exception err)
{
postReturn = "发生错误";
Mtxfw.Utility.Common.WriteHtml("/weixin/sendsms.txt", err.ToString());
}
return postReturn;
}*/
public static object Getsmsjson(string json)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Deserialize(json);
}
public static void sendsms(string mobile, string TemplateID, string TemplateParams, Utility.Config config)
{
try
{
// 必要步骤:
// 实例化一个认证对象,入参需要传入腾讯云账户密钥对 SecretId,SecretKey。
// 本示例采用从环境变量读取的方式,则需要在环境变量中先设置这两个值。
// 您也可以直接将密钥对写入代码中,但是注意不要复制、上传或分享代码,以免泄露密钥对危及您的财产安全。
Credential cred = new Credential
{
SecretId = "AKIDoY6RYR8cuzrWyCC6oJbfW9YkiSzIPJ0T",
SecretKey = "INErGSQAgy8GJGC1e6NTbbOzOZifQyJQ"
};
// 实例化一个 client 选项,可选的,没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
// 指定签名算法(默认为 HmacSHA256)
clientProfile.SignMethod = ClientProfile.SIGN_SHA1;
// 非必要步骤
// 实例化一个客户端配置对象,可以指定超时时间等配置
HttpProfile httpProfile = new HttpProfile();
// SDK 默认使用 POST 方法。
// 如果您一定要使用 GET 方法,可以在这里设置。GET 方法无法处理一些较大的请求。
httpProfile.ReqMethod = "POST";
// SDK 有默认的超时时间,非必要请不要进行调整。
// 如有需要请在代码中查阅以获取最新的默认值。
httpProfile.Timeout = 120; // 请求连接超时时间,单位为秒,默认值为60
// SDK 会自动指定域名。通常无需指定域名,但如果您访问的是金融区的服务,则必须手动指定域名。
// 例如云服务器的上海金融区域名:cvm.ap-shanghai-fsi.tencentcloudapi.com
// 代理服务器,当您的环境下有代理服务器时设定
httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");
clientProfile.HttpProfile = httpProfile;
// 实例化要请求产品(以 CVM 为例)的 client 对象
// 第二个参数是地域信息,可以直接填写字符串 ap-guangzhou,或者引用预设的常量,clientProfile 是可选的
SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);
SendSmsRequest req = new SendSmsRequest();
req.PhoneNumberSet = ("+86" + mobile).Split('|');
req.TemplateID = TemplateID;
if (TemplateParams != null)
{
req.TemplateParamSet = TemplateParams.Split('|');
}
req.SmsSdkAppid = "1401043931";
req.Sign = "银花优选";
SendSmsResponse res = client.SendSmsSync(req);
// 输出 JSON 格式的字符串回包
//Mtxfw.Utility.Common.WriteHtml("/weixin/sendsms.txt", AbstractModel.ToJsonString(res));
}
catch (Exception err)
{
Mtxfw.Utility.Common.WriteHtml("/weixin/sendsmserr.txt", err.ToString());
}
}
public static String sha256(String data)
{
try
{
SHA256 sha256 = SHA256Managed.Create();
byte[] resultByteArray = sha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(data));
return ByteArrayToHex(resultByteArray);
}
catch (Exception e)
{
e.ToString();
return null;
}
}
// 将二进制的数值转换为 16 进制字符串,如 "abc" => "616263"
private static string ByteArrayToHex(byte[] byteArray)
{
string returnStr = "";
if (byteArray != null)
{
for (int i = 0; i < byteArray.Length; i++)
{
returnStr += byteArray[i].ToString("x2");
}
}
return returnStr;
}
//POST方式发送得结果
private static String doPostRequest(string url, byte[] bData)
{
System.Net.HttpWebRequest hwRequest;
System.Net.HttpWebResponse hwResponse;
string strResult = string.Empty;
try
{
hwRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
hwRequest.Timeout = 5000;
hwRequest.Method = "POST";
hwRequest.ContentType = "application/x-www-form-urlencoded";
hwRequest.ContentLength = bData.Length;
System.IO.Stream smWrite = hwRequest.GetRequestStream();
smWrite.Write(bData, 0, bData.Length);
smWrite.Close();
}
catch (System.Exception err)
{
WriteErrLog(err.ToString());
return strResult;
}
//get response
try
{
hwResponse = (System.Net.HttpWebResponse)hwRequest.GetResponse();
StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.ASCII);
strResult = srReader.ReadToEnd();
srReader.Close();
hwResponse.Close();
}
catch (System.Exception err)
{
WriteErrLog(err.ToString());
}
return strResult;
}
private static void WriteErrLog(string strErr)
{
Console.WriteLine(strErr);
System.Diagnostics.Trace.WriteLine(strErr);
}
#endregion
#region 身份证实名认证
public static string SFZSMYZ(string sfz, string name)
{
String host = "http://idcard.market.alicloudapi.com";
String path = "/lianzhuo/idcard";
String method = "GET";
String appcode = "d3c296a9414647479e24ccb0575fdeef";
String querys = "cardno=" + sfz + "&name=" + name;
String bodys = "";
String url = host + path;
HttpWebRequest httpRequest = null;
HttpWebResponse httpResponse = null;
if (0 < querys.Length)
{
url = url + "?" + querys;
}
httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = method;
httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
if (0 < bodys.Length)
{
byte[] data = Encoding.UTF8.GetBytes(bodys);
using (Stream stream = httpRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
Stream st = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
string strResult = reader.ReadToEnd();
return strResult;
}
#endregion
#region 获取快递信息
public static String HMACSHA1Text(String EncryptText, String EncryptKey)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
public static string GetKDXX(string express_id, string express_name, string mobile)
{
String url = "https://service-hjszen58-1316452486.gz.apigw.tencentcs.com/release/express/query";
String method = "POST";
String querys = "";
String postData = "mobile=" + mobile + "&waybillNo=" + express_id;
//云市场分配的密钥Id
String secretId = "AKIDk2njd1xf67uv6zl1n9h0ev7xrz0g1uo2902j";
//云市场分配的密钥Key
String secretKey = "aBhZBamLCu14AdfJ9m9rB9ThylfvbwjHJc05WgDz";
String source = "market";
String dt = DateTime.UtcNow.GetDateTimeFormats('r')[0];
url = url + "?" + querys;
String signStr = "x-date: " + dt + "\n" + "x-source: " + source;
String sign = HMACSHA1Text(signStr, secretKey);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"";
auth = auth + sign + "\"";
HttpWebRequest httpRequest = null;
HttpWebResponse httpResponse = null;
if (url.Contains("https://"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
httpRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpRequest.Method = method;
httpRequest.ContentLength = postData.Length;
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.Headers.Add("Authorization", auth);
httpRequest.Headers.Add("X-Source", source);
httpRequest.Headers.Add("X-Date", dt);
httpRequest.GetRequestStream().Write(System.Text.Encoding.ASCII.GetBytes(postData), 0, postData.Length);
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
//Console.WriteLine(httpResponse.StatusCode);
//Console.WriteLine(httpResponse.Headers);
Stream st = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
string strResult = reader.ReadToEnd();
return strResult;
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
#endregion
#region 获取IP
public static string GetIP
{
get
{
string result = String.Empty;
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (result != null && result != String.Empty)
{
//可能有代理
if (result.IndexOf(".") == -1) //没有"."肯定是非IPv4格式
result = null;
else
{
if (result.IndexOf(",") != -1)
{
//有",",估计多个代理。取第一个不是内网的IP。
result = result.Replace(" ", "").Replace("\"", "");
string[] temparyip = result.Split(",;".ToCharArray());
for (int i = 0; i < temparyip.Length; i++)
{
if (IsIPAddress(temparyip[i])
&& temparyip[i].Substring(0, 3) != "10."
&& temparyip[i].Substring(0, 7) != "192.168"
&& temparyip[i].Substring(0, 7) != "172.16.")
{
return temparyip[i]; //找到不是内网的地址
}
}
}
else if (IsIPAddress(result)) //代理即是IP格式
return result;
else
result = null; //代理中的内容 非IP,取IP
}
}
//string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]!=null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] !=String.Empty)?HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]:HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (null == result || result == String.Empty)
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (result == null || result == String.Empty)
result = HttpContext.Current.Request.UserHostAddress;
return result;
}
}
/**/
///
/// 判断是否是IP地址格式 0.0.0.0
///
/// 待判断的IP地址
/// true or false
public static bool IsIPAddress(string str1)
{
if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
return regex.IsMatch(str1);
}
#endregion
#region 获取IP
///
/// get MacAddress
///
///
public static string GetMac()
{
string MacAddress = String.Empty;
try
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
MacAddress = mo["MacAddress"].ToString();
break;
}
}
moc = null;
mc = null;
// 将MAC地址用-分割
MacAddress = MacAddress.Replace(":", "-");
}
catch
{
MacAddress = "";
}
return MacAddress;
}
#endregion
#region GET数据
//GET数据
public static string getPage2(String url, string strr, string pm)
{
HttpWebResponse res = null;
string strResult = "";
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.KeepAlive = true;
req.AllowAutoRedirect = false;
req.Referer = strr;
req.Accept = "*/*";
req.Timeout = 10000;
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)";
res = (HttpWebResponse)req.GetResponse();
Stream ReceiveStream = res.GetResponseStream();
//将 byte 数组 转换为 string textBox2.Text = Encoding.Default.GetString(temp);
Encoding encode = System.Text.Encoding.GetEncoding(pm);
StreamReader sr = new StreamReader(ReceiveStream, encode);
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
string str = new string(read, 0, count);
strResult += str;
count = sr.Read(read, 0, 256);
}
req.GetResponse().Close();
}
catch (Exception e)
{
strResult = e.ToString();
}
finally
{
if (res != null)
{
res.Close();
}
}
return strResult;
}
//GET数据
public static string getPage2(String url, string strr, string pm, bool IFJSON, bool IFPOST, string paramString)
{
System.GC.Collect();
HttpWebResponse res = null;
string strResult = "";
try
{
HttpWebRequest req;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
| SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
req = (HttpWebRequest)HttpWebRequest.Create(url);
req.ProtocolVersion = HttpVersion.Version10;
}
else
{
req = (HttpWebRequest)HttpWebRequest.Create(url);
}
if (!IFPOST)
{
req.Method = "GET";
}
else
{
req.Method = "POST";
}
req.ContentType = "application/x-www-form-urlencoded";
if (IFJSON)
{
req.ContentType = "application/json";
}
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
if (IFPOST)
{
//Post 参数
if (paramString != "")
{
byte[] data = Encoding.UTF8.GetBytes(paramString);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
}
}
using (WebResponse myWebResponse = req.GetResponse())
{
StreamReader readStream = new StreamReader(myWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding(pm));
strResult = readStream.ReadToEnd();
}
}
catch (Exception e)
{
strResult = e.ToString();
}
finally
{
if (res != null)
{
res.Close();
}
}
return strResult;
}
#endregion
#region 返回JSon数据
///
/// 返回JSon数据
///
/// 要处理的JSON数据
/// 要提交的URL
/// 返回的JSON处理字符串
public static string GetResponseData(string JSONData, string Url, string contenttype)
{
byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = contenttype;// "text/xml";
Stream reqstream = request.GetRequestStream();
reqstream.Write(bytes, 0, bytes.Length);
//声明一个HttpWebRequest请求
request.Timeout = 90000;
//设置连接超时时间
request.Headers.Set("Pragma", "no-cache");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
Encoding encoding = Encoding.UTF8;
StreamReader streamReader = new StreamReader(streamReceive, encoding);
string strResult = streamReader.ReadToEnd();
streamReceive.Dispose();
streamReader.Dispose();
return strResult;
}
#endregion
#region 读取文件
public static string LoadTemplet(string what)
{
StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(what), Encoding.GetEncoding("utf-8"));
string str = reader.ReadToEnd();
reader.Close();
return str;
}
#endregion
#region 写入文件
public static void WriteHtml(string what, string MyHtml)
{
if (!Directory.Exists(HttpContext.Current.Server.MapPath(what.Substring(0, what.LastIndexOf("/")))))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(what.Substring(0, what.LastIndexOf("/"))));
}
StreamWriter writer = new StreamWriter(HttpContext.Current.Server.MapPath(what), false, Encoding.GetEncoding("utf-8"), 1);
writer.Write(MyHtml);
writer.Close();
}
#endregion
#region 真正判断文件类型的关键函数
//真正判断文件类型的关键函数
public static bool IsAllowedExtension(string FileName)
{
System.IO.FileStream fs = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
string fileclass = "";
//这里的位长要具体判断.
/*文件扩展名说明
* 255216 jpg
* 208207 doc xls ppt wps
* 8075 docx pptx xlsx zip
* 5150 txt
* 8297 rar
* 7790 exe
* 3780 pdf
*
* 4946/104116 txt
* 7173 gif
* 255216 jpg
* 13780 png
* 6677 bmp
* 239187 txt,aspx,asp,sql
* 208207 xls.doc.ppt
* 6063 xml
* 6033 htm,html
* 4742 js
* 8075 xlsx,zip,pptx,mmap,zip
* 8297 rar
* 01 accdb,mdb
* 7790 exe,dll
* 5666 psd
* 255254 rdp
* 10056 bt种子
* 64101 bat
* 4059 sgf
* 7076 flv
* 255251 mp3
* 00 mp4
*/
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch
{
}
r.Close();
fs.Close();
if (fileclass == "255216" || fileclass == "7173" || fileclass == "6677" || fileclass == "13780" || fileclass == "13780" || fileclass == "208207" || fileclass == "8075" || fileclass == "8297" || fileclass == "3780" || fileclass == "7076" || fileclass == "255251" || fileclass == "00")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
{
return true;
}
else
{
return false;
}
}
#endregion
#region 字符串转换成html
//字符串转换成html
public static string InputText(string inputString)
{
StringBuilder builder = new StringBuilder();
if ((inputString != null) && (inputString != string.Empty))
{
for (int i = 0; i < inputString.Length; i++)
{
switch (inputString[i])
{
case '<':
{
builder.Append("<");
continue;
}
case '>':
{
builder.Append(">");
continue;
}
case '"':
{
builder.Append(""");
continue;
}
}
builder.Append(inputString[i]);
}
builder.Replace("\n", "
");
builder.Replace("\040", " ");
builder.Replace("\t", " ");
builder.Replace(" ", " ");
}
return builder.ToString();
}
#endregion
#region 取得某月的某一天
///
/// 取得某月的第一天
///
/// 要取得月份第一天的时间
///
public static DateTime FirstDayOfMonth(DateTime datetime)
{
return datetime.AddDays(1 - datetime.Day);
}
/**/
///
/// 取得某月的最后一天
///
/// 要取得月份最后一天的时间
///
public static DateTime LastDayOfMonth(DateTime datetime)
{
return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
}
/**/
///
/// 取得上个月第一天
///
/// 要取得上个月第一天的当前时间
///
public static DateTime FirstDayOfPreviousMonth(DateTime datetime)
{
return datetime.AddDays(1 - datetime.Day).AddMonths(-1);
}
/**/
///
/// 取得上个月的最后一天
///
/// 要取得上个月最后一天的当前时间
///
public static DateTime LastDayOfPrdviousMonth(DateTime datetime)
{
return datetime.AddDays(1 - datetime.Day).AddDays(-1);
}
#endregion
public static object Fromreturn_upload_shipping_info(string json)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Deserialize(json);
}
}
public class WXaccess_token
{
public String access_token { get; set; }
}
public class return_upload_shipping_info
{
public int errcode { get; set; }
public String errmsg { get; set; }
}
public class hjpay_returns0
{
public String statusCode { get; set; }
public String message { get; set; }
public hjpay_returns0_data data { get; set; }
}
public class hjpay_returns0_data
{
public String errorCode { get; set; }
public String errorDesc { get; set; }
public String userNo { get; set; }
public String merchantOrderNo { get; set; }
}
public class Code39
{
private Hashtable m_Code39 = new Hashtable();
private byte m_Magnify = 0;
///
/// 放大倍数
///
public byte Magnify { get { return m_Magnify; } set { m_Magnify = value; } }
private int m_Height = 40;
///
/// 图形高
///
public int Height { get { return m_Height; } set { m_Height = value; } }
private Font m_ViewFont = null;
///
/// 字体大小
///
public Font ViewFont { get { return m_ViewFont; } set { m_ViewFont = value; } }
public Code39()
{
m_Code39.Add("A", "1101010010110");
m_Code39.Add("B", "1011010010110");
m_Code39.Add("C", "1101101001010");
m_Code39.Add("D", "1010110010110");
m_Code39.Add("E", "1101011001010");
m_Code39.Add("F", "1011011001010");
m_Code39.Add("G", "1010100110110");
m_Code39.Add("H", "1101010011010");
m_Code39.Add("I", "1011010011010");
m_Code39.Add("J", "1010110011010");
m_Code39.Add("K", "1101010100110");
m_Code39.Add("L", "1011010100110");
m_Code39.Add("M", "1101101010010");
m_Code39.Add("N", "1010110100110");
m_Code39.Add("O", "1101011010010");
m_Code39.Add("P", "1011011010010");
m_Code39.Add("Q", "1010101100110");
m_Code39.Add("R", "1101010110010");
m_Code39.Add("S", "1011010110010");
m_Code39.Add("T", "1010110110010");
m_Code39.Add("U", "1100101010110");
m_Code39.Add("V", "1001101010110");
m_Code39.Add("W", "1100110101010");
m_Code39.Add("X", "1001011010110");
m_Code39.Add("Y", "1100101101010");
m_Code39.Add("Z", "1001101101010");
m_Code39.Add("0", "1010011011010");
m_Code39.Add("1", "1101001010110");
m_Code39.Add("2", "1011001010110");
m_Code39.Add("3", "1101100101010");
m_Code39.Add("4", "1010011010110");
m_Code39.Add("5", "1101001101010");
m_Code39.Add("6", "1011001101010");
m_Code39.Add("7", "1010010110110");
m_Code39.Add("8", "1101001011010");
m_Code39.Add("9", "1011001011010");
m_Code39.Add("+", "1001010010010");
m_Code39.Add("-", "1001010110110");
m_Code39.Add("*", "1001011011010");
m_Code39.Add("/", "1001001010010");
m_Code39.Add("%", "1010010010010");
m_Code39.Add("$", "1001001001010");
m_Code39.Add(".", "1100101011010");
m_Code39.Add(" ", "1001101011010");
}
public enum Code39Model
{
///
/// 基本类别 1234567890ABC
///
Code39Normal,
///
/// 全ASCII方式 +A+B 来表示小写
///
Code39FullAscII
}
///
/// 获得条码图形
///
/// 文字信息
/// 类别
/// 是否增加前后*号
/// 是否显示数字
/// 图形
public Bitmap GetCodeImage(string p_Text, Code39Model p_Model, bool p_StarChar, bool IFShowNum)
{
string _ValueText = "";
string _CodeText = "";
char[] _ValueChar = null;
switch (p_Model)
{
case Code39Model.Code39Normal:
_ValueText = p_Text.ToUpper();
break;
default:
_ValueChar = p_Text.ToCharArray();
for (int i = 0; i != _ValueChar.Length; i++)
{
if ((int)_ValueChar[i] >= 97 && (int)_ValueChar[i] <= 122)
{
_ValueText += "+" + _ValueChar[i].ToString().ToUpper();
}
else
{
_ValueText += _ValueChar[i].ToString();
}
}
break;
}
_ValueChar = _ValueText.ToCharArray();
if (p_StarChar == true) _CodeText += m_Code39["*"];
for (int i = 0; i != _ValueChar.Length; i++)
{
if (p_StarChar == true && _ValueChar[i] == '*') throw new Exception("带有起始符号不能出现*");
object _CharCode = m_Code39[_ValueChar[i].ToString()];
if (_CharCode == null) throw new Exception("不可用的字符" + _ValueChar[i].ToString());
_CodeText += _CharCode.ToString();
}
if (p_StarChar == true) _CodeText += m_Code39["*"];
Bitmap _CodeBmp = GetImage(_CodeText);
if (IFShowNum)
{
GetViewImage(_CodeBmp, p_Text);
}
return _CodeBmp;
}
///
/// 绘制编码图形
///
/// 编码
/// 图形
private Bitmap GetImage(string p_Text)
{
char[] _Value = p_Text.ToCharArray();
//宽 == 需要绘制的数量*放大倍数 + 两个字的宽
Bitmap _CodeImage = new Bitmap(_Value.Length * ((int)m_Magnify + 1), (int)m_Height);
Graphics _Garphics = Graphics.FromImage(_CodeImage);
_Garphics.FillRectangle(Brushes.White, new Rectangle(0, 0, _CodeImage.Width, _CodeImage.Height));
int _LenEx = 0;
for (int i = 0; i != _Value.Length; i++)
{
int _DrawWidth = m_Magnify + 1;
if (_Value[i] == '1')
{
_Garphics.FillRectangle(Brushes.Black, new Rectangle(_LenEx, 0, _DrawWidth, m_Height));
}
else
{
_Garphics.FillRectangle(Brushes.White, new Rectangle(_LenEx, 0, _DrawWidth, m_Height));
}
_LenEx += _DrawWidth;
}
_Garphics.Dispose();
return _CodeImage;
}
///
/// 绘制文字
///
/// 图形
/// 文字
private void GetViewImage(Bitmap p_CodeImage, string p_Text)
{
if (m_ViewFont == null) return;
Graphics _Graphics = Graphics.FromImage(p_CodeImage);
SizeF _FontSize = _Graphics.MeasureString(p_Text, m_ViewFont);
if (_FontSize.Width > p_CodeImage.Width || _FontSize.Height > p_CodeImage.Height - 20)
{
_Graphics.Dispose();
return;
}
int _StarHeight = p_CodeImage.Height - (int)_FontSize.Height;
_Graphics.FillRectangle(Brushes.White, new Rectangle(0, _StarHeight, p_CodeImage.Width, (int)_FontSize.Height));
int _StarWidth = (p_CodeImage.Width - (int)_FontSize.Width) / 2;
_Graphics.DrawString(p_Text, m_ViewFont, Brushes.Black, _StarWidth, _StarHeight);
_Graphics.Dispose();
}
}
public class Getsms
{
public String stat { get; set; }
public String message { get; set; }
}
public struct Block
{
///
/// 区块位置
///
public int Index { get; set; }
///
/// 区块生成时间戳
///
public string TimeStamp { get; set; }
///
/// 心率数值
///
public int BPM { get; set; }
///
/// 区块 SHA-256 散列值
///
public string Hash { get; set; }
///
/// 前一个区块 SHA-256 散列值
///
public string PrevHash { get; set; }
///
/// 下一个区块生成难度
///
public int Difficulty { get; set; }
///
/// 随机值
///
public string Nonce { get; set; }
}
}