stock代码备份
写了一天,累死了,备份一下~
Code
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Threading;
using System.Management;
using System.Net;
using System.ServiceProcess;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using RealTimePriceFetchService.BLL;
using RealTimePriceFetchService.Model;
using LanceZhang.StockLib;
namespace LanceZhang.RealTimePriceFetchService
{
public class Program : ServiceBase
{
private static int WorkThreads = Convert.ToInt32(ConfigurationManager.AppSettings["WorkThreads"]);
private static int SleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["SleepTime"]);
private static bool LogToFile = ConfigurationManager.AppSettings["LogToFile"] == "1" ? true : false;
private static bool EnableZip = ConfigurationManager.AppSettings["EnableZip"] == "1" ? true : false;
private static string ServiceRealName = ConfigurationManager.AppSettings["ServiceName"];
private static string ServiceDisPlayName = ConfigurationManager.AppSettings["ServiceDisPlayName"];
private static string ServiceDescription = ConfigurationManager.AppSettings["ServiceDescription"];
private static object lockobj = new object();
private static string IP = GetIPAddress();
private static string MAC = GetMacAddress();
private static string prefix = "sh";
private static string endfix = ",";
//服务所在路径
private static string ServicePath = Application.ExecutablePath;
private static string ServiceDirectory = Path.GetDirectoryName(ServicePath);
//单线程
private static Thread t;
//多线程
private static Thread[] threads;
//公共StringBuilder
private static StringBuilder sb = new StringBuilder();
//股票查询字符串列表
private static List<string> querylist=new List<string>();
//调试模式开关
private static int Debug = 0;
//服务是否停止开关
private static bool Stopped = false;
private static bool CanStopped = false;
//线程状态字典
private static Dictionary<string, bool> DicStatus = new Dictionary<string, bool>();
//业务逻辑对象
private static SHAStockCodeBLL bllcode=new SHAStockCodeBLL();
private static StockTransferQueueBLL bllqueue = new StockTransferQueueBLL();
#region 应用程序初始化
private static void InitilizeCompoment()
{
Output("开始初始化1", true);
if (Debug == 1)
{
Console.Title = ServiceDisPlayName;
}
if (WorkThreads > 1)
{
WorkThreads = 9;
}
if (WorkThreads < 1)
{
WorkThreads = 1;
}
Output("IP:" + IP,true);
Output("MAC:" + MAC,true);
Output("开始获取数据",true);
//构造查询字符串
BuildQueryList();
//初始化定时器
//InitilizeTimer();
//开始启动线程
if (WorkThreads == 1)
{
t = new Thread(GetPrice);
t.IsBackground = false;
t.Start();
}
else
{
threads = new Thread[WorkThreads];
DicStatus.Clear();
for (int i = 0; i < WorkThreads; i++)
{
DicStatus.Add("Threads" + (i + 1).ToString(), false);
threads[i] = new Thread(new ParameterizedThreadStart(GetPriceMulti));
threads[i].IsBackground = false;
threads[i].Name = "Threads" + (i + 1).ToString();
threads[i].Start(i);
Output("线程启动:"+i.ToString(), true);
}
}
if (Debug == 1)
{
Console.ReadLine();
Output("启动完成", true);
}
}
//构造查询字符串
private static void BuildQueryList()
{
Output("正在构造查询字符串", true);
List<SHAStockCodeModel> all = (bllcode.GetModelList(""));
Output("数据已读取条数:" + all.Count.ToString(), true);
for (int i = 0; i < 9; i++)
{
for (int j = 1; j < 99; j++)
{
int index = i * 100 + j;
if (index > all.Count - 1)
{
break;
}
//Output("此时index:" + index.ToString() +"----"+ all[index].StockCode.ToString(), true);
sb.Append(prefix);
sb.Append(all[index].StockCode.ToString());
sb.Append(endfix);
}
querylist.Add(sb.ToString());
//debug success
//Output(querylist[i], true);
sb.Remove(0, sb.Length);
}
Output("查询字符串构造完成", true);
}
#endregion
#region 数据获取逻辑
private static void GetPrice()
{
//SmsSendList send = new SmsSendList();
//SmsReturn ret = new SmsReturn();
//SmsSendLog log = new SmsSendLog();
////返回信息
//TSMSReturnHundSunInfo retinfo = new TSMSReturnHundSunInfo();
////日志信息
//TSMSSendLogInfo loginfo = new TSMSSendLogInfo();
//IList<TSMSSendHundSunInfo> sendlist;
//Dictionary<string, TSMSSendHundSunInfo> senddic = null;
//string result = string.Empty;
//string zipresult = string.Empty;
//while (true)
//{
// if (Stopped)
// {
// CanStopped = true;
// break;
// }
// if (!Valid)
// {
// Output("身份验证失败", ConsoleColor.Red);
// Thread.Sleep(ValidateTime);
// continue;
// }
// try
// {
// sendlist = send.GetSendList(SendCountPerTime);
// }
// catch (Exception e)
// {
// Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
// Thread.Sleep(SleepTime);
// continue;
// }
// if (sendlist.Count == 0)
// {
// //Output("没有待发数据", ConsoleColor.Blue);
// Thread.Sleep(SleepTime);
// continue;
// }
// else
// {
// senddic = new Dictionary<string, TSMSSendHundSunInfo>();
// StringBuilder sb = new StringBuilder();
// foreach (TSMSSendHundSunInfo sms in sendlist)
// {
// //判断是否是合法短信
// if (ValidSms(sms))
// {
// sb.Append(sms.ToString() + "\n");
// senddic.Add(sms.LSerialno.ToString(), sms);
// }
// }
// result = sb.ToString();
// if (result != string.Empty)
// {
// result = result.Substring(0, result.Length - 2);
// zipresult = Compress.ZipString(result);
// sendlist.Clear();
// sendlist = null;
// }
// else
// {
// Thread.Sleep(SleepTime);
// continue;
// }
// }
// string sendresult = string.Empty;
// try
// {
// sendresult = obj.Send(EnterpriseCode, EnterpriseAccount, zipresult);
// Output("发送 " + senddic.Count.ToString() + " 数据");
// }
// catch (Exception e)
// {
// Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red);
// }
// if (sendresult != string.Empty)
// {
// sendresult = Compress.UnzipString(sendresult);
// string[] arr = sendresult.Split(',');
// for (int i = 0; i < arr.Length; i++)
// {
// if (senddic.ContainsKey(arr[i]))
// {
// TSMSSendHundSunInfo sms = senddic[arr[i]];
// //从待发表里删除
// try
// {
// send.DeleteSms(sms.LSerialno);
// }
// catch (Exception e)
// {
// Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
// continue;
// }
// //插入状态表
// retinfo.CContent = sms.CContent;
// retinfo.CDate = sms.CDate.ToString("yyyy-MM-dd HH:mm:ss");
// retinfo.CFrom = sms.CFrom;
// retinfo.CHandle = "0";
// retinfo.CMobile = sms.CMobileno;
// retinfo.CProperty = sms.CProperty;
// retinfo.CR1 = sms.CR1;
// retinfo.CR2 = sms.CR2;
// retinfo.CR3 = sms.CR3;
// retinfo.CR4 = sms.CR4;
// retinfo.CR5 = sms.CR5;
// retinfo.CReturn = string.Empty;
// retinfo.CReturnTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
// retinfo.CSmsID = sms.CSmsID;
// retinfo.CSmsName = sms.CSmsname;
// try
// {
// ret.Insert(retinfo);
// }
// catch (Exception e)
// {
// Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
// }
// if (EnableLogTable == 1)
// {
// //插入日志表
// loginfo.CContent = sms.CContent;
// loginfo.CDate = sms.CDate.ToString("yyyy-MM-dd HH:mm:ss");
// loginfo.CFrom = sms.CFrom;
// loginfo.CHanlde = "0";
// loginfo.CLogTime = DateTime.Now;
// loginfo.CMobileno = sms.CMobileno;
// loginfo.CProperty = sms.CProperty;
// loginfo.CR1 = sms.CR1;
// loginfo.CR2 = sms.CR2;
// loginfo.CR3 = sms.CR3;
// loginfo.CR4 = sms.CR4;
// loginfo.CR5 = sms.CR5;
// loginfo.CSmsID = sms.CSmsID;
// loginfo.CSmsname = sms.CSmsname;
// try
// {
// log.Insert(loginfo);
// }
// catch (Exception e)
// {
// Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
// }
// }
// }
// }
// }
// Thread.Sleep(SleepTime);
//}
}
private static void GetPriceMulti(object o)
{
int mod = (int)o;
string threadname = "Threads" + (mod + 1).ToString();
string result = string.Empty;
string zipresult = string.Empty;
StockTransferQueueModel model = new StockTransferQueueModel();
while (true)
{
if (Stopped)
{
lock (lockobj)
{
DicStatus[threadname] = true;
}
break;
}
result = GetJSbyWC(querylist[mod]);
if (EnableZip)
{
zipresult = Compress.ZipString(result);
model.RealTimePrice = zipresult;
}
else
{
model.RealTimePrice = result;
}
try
{
bllqueue.Add(model);
Output("线程 " + mod.ToString() + " 添加记录成功", ConsoleColor.Blue, true);
}
catch (Exception e)
{
Output("存储记录时产生错误: " + e.Message, ConsoleColor.Red, true);
}
Thread.Sleep(SleepTime);
continue;
}
}
#region 获取新浪清单,每秒4.5个,二方法耗时基本相等
private static string GetJSbyWC(string code)
{
using (WebClient wc = new WebClient())
{
Stream resStream = wc.OpenRead("http://hq.sinajs.cn/list=" + code);
StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
string result = sr.ReadToEnd();
resStream.Close();
return result;
}
}
private static string GetJSbyHTTP(string code)
{
WebRequest request = WebRequest.Create("http://hq.sinajs.cn/list=" + code);
WebResponse response = request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
string result = sr.ReadToEnd();
resStream.Close();
sr.Close();
return result;
}
#endregion
#endregion
#region 应用程序入口 OK
static void Main(string[] args)
{
Thread.GetDomain().UnhandledException += new UnhandledExceptionEventHandler(Program_UnhandledException);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
bool exists = ServiceControl.CheckService(ServiceRealName);
if (args.Length == 0)
{
ServiceBase.Run(new ServiceBase[] { new Program() });
}
else
{
string parm = args[0].ToLower();
switch (parm)
{
case "-debug":
case "/debug":
Debug = 1;
if (exists)
{
ServiceControllerStatus status = ServiceControl.GetServiceStatus(ServiceRealName);
if (status != ServiceControllerStatus.Stopped)
{
Console.WriteLine(GetDateTime() + ServiceRealName + " 服务正在运行,无法进入调试状态。请先停止该服务");
Console.WriteLine(GetDateTime() + "请关闭本窗体");
Console.ReadLine();
}
else
{
InitilizeCompoment();
}
}
else
{
InitilizeCompoment();
}
break;
case "-install":
case "-setup":
case "/install":
case "/setup":
if (exists)
{
Console.WriteLine(GetDateTime() + ServiceRealName + " 服务已经存在,如果您想升级服务,请先卸载该服务");
Console.WriteLine(GetDateTime() + "请关闭本窗体");
Console.ReadLine();
}
else
{
Console.WriteLine(GetDateTime() + ServicePath);
bool result = ServiceControl.InstallService(ServicePath, ServiceRealName, ServiceDisPlayName, ServiceDescription);
if (result)
{
Console.WriteLine(GetDateTime() + "服务安装成功");
Console.WriteLine(GetDateTime() + "正在启动服务");
ServiceControl.StartService(ServiceRealName);
while (!(ServiceControl.GetServiceStatus(ServiceRealName) == ServiceControllerStatus.Running))
{
Thread.Sleep(SleepTime);
}
Console.WriteLine(GetDateTime() + "服务已经启动");
}
else
{
Console.WriteLine(GetDateTime() + "服务安装失败");
}
Console.WriteLine(GetDateTime() + "请关闭本窗体");
Console.ReadLine();
}
break;
case "-uninstall":
case "-remove":
case "/uninstall":
case "/remove":
if (!exists)
{
Console.WriteLine(GetDateTime() + ServiceRealName + " 服务尚未安装");
}
else
{
bool result = ServiceControl.UnInstallService(ServiceRealName);
if (!result)
{
Console.WriteLine(GetDateTime() + "服务卸载失败");
}
else
{
Console.WriteLine(GetDateTime() + "服务卸载成功");
}
}
Console.WriteLine(GetDateTime() + "请关闭本窗体");
Console.ReadLine();
break;
}
}
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
Output("未处理A:" + e.Exception.Message, ConsoleColor.Red, true);
}
static void Program_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is System.Exception)
{
Output("未处理P:" + ((System.Exception)e.ExceptionObject).Message, ConsoleColor.Red, true);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
}
base.Dispose(disposing);
}
public Program()
{
base.ServiceName = ServiceRealName;
base.AutoLog = true;
}
#endregion
#region 初始化服务设置 OK
protected override void OnStart(string[] args)
{
InitilizeCompoment();
}
protected override void OnStop()
{
Stopped = true;
try
{
if (WorkThreads == 1)
{
while (!CanStopped)
{
Thread.Sleep(SleepTime);
}
}
else
{
while (!AllStop())
{
Thread.Sleep(SleepTime);
}
}
}
catch
{
}
}
/// <summary>
/// 判断工作线程是否已经都停止了
/// </summary>
/// <returns></returns>
private static bool AllStop()
{
try
{
lock (lockobj)
{
foreach (bool value in DicStatus.Values)
{
if (!value)
{
return false;
}
}
}
return true;
}
catch
{
return false;
}
}
#endregion
#region 调试辅助逻辑 OK
private static string GetDateTime()
{
return "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
}
private static void Output(string msg)
{
lock (lockobj)
{
if (Debug == 1)
{
Console.WriteLine(GetDateTime() + msg);
}
}
}
private static void Output(string msg, bool log)
{
lock (lockobj)
{
if (Debug == 1)
{
Console.WriteLine(GetDateTime() + msg);
}
if (log)
{
if (LogToFile)
{
Log.WriteToFile(ServiceDirectory + @"\log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
}
}
}
}
private static void Output(string msg, ConsoleColor color)
{
lock (lockobj)
{
if (Debug == 1)
{
Console.ForegroundColor = color;
Console.WriteLine(GetDateTime() + msg);
Console.ResetColor();
}
}
}
private static void Output(string msg, ConsoleColor color, bool log)
{
lock (lockobj)
{
if (Debug == 1)
{
Console.ForegroundColor = color;
Console.WriteLine(GetDateTime() + msg);
Console.ResetColor();
}
if (log)
{
if (LogToFile)
{
Log.WriteToFile(ServiceDirectory + @"\log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
}
}
}
}
#endregion
#region 获得IP地址 OK
private static string GetIPAddress()
{
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
string ip = string.Empty;
for (int i = 0; i < ips.Length; i++)
{
ip += ips[i].ToString() + ",";
}
if (ip != string.Empty)
{
ip = ip.Substring(0, ip.Length - 1);
}
return ip;
/*
string ip = string.Empty;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
string[] ipaddresses = (string[])mo["IPAddress"];
for (int i = 0; i < ipaddresses.Length; i++)
{
ip += ipaddresses[i].ToString() + ",";
}
}
}
if (ip != string.Empty)
{
ip = ip.Substring(0, ip.Length - 1);
}
return ip;
*/
}
#endregion
#region 获得MAC OK
private static string GetMacAddress()
{
ManagementClass adapters = new ManagementClass("Win32_NetworkAdapterConfiguration");
string MACAddress = string.Empty;
foreach (ManagementObject adapter in adapters.GetInstances())
{
if ((bool)adapter["IPEnabled"] == true)
{
MACAddress = adapter.Properties["MACAddress"].Value.ToString();
MACAddress += ",";
}
}
//去除最后一个,号
if (MACAddress != string.Empty)
{
MACAddress = MACAddress.Substring(0, MACAddress.Length - 1);
}
return MACAddress;
}
#endregion
}
}
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Threading;
using System.Management;
using System.Net;
using System.ServiceProcess;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using RealTimePriceFetchService.BLL;
using RealTimePriceFetchService.Model;
using LanceZhang.StockLib;
namespace LanceZhang.RealTimePriceFetchService
{
public class Program : ServiceBase
{
private static int WorkThreads = Convert.ToInt32(ConfigurationManager.AppSettings["WorkThreads"]);
private static int SleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["SleepTime"]);
private static bool LogToFile = ConfigurationManager.AppSettings["LogToFile"] == "1" ? true : false;
private static bool EnableZip = ConfigurationManager.AppSettings["EnableZip"] == "1" ? true : false;
private static string ServiceRealName = ConfigurationManager.AppSettings["ServiceName"];
private static string ServiceDisPlayName = ConfigurationManager.AppSettings["ServiceDisPlayName"];
private static string ServiceDescription = ConfigurationManager.AppSettings["ServiceDescription"];
private static object lockobj = new object();
private static string IP = GetIPAddress();
private static string MAC = GetMacAddress();
private static string prefix = "sh";
private static string endfix = ",";
//服务所在路径
private static string ServicePath = Application.ExecutablePath;
private static string ServiceDirectory = Path.GetDirectoryName(ServicePath);
//单线程
private static Thread t;
//多线程
private static Thread[] threads;
//公共StringBuilder
private static StringBuilder sb = new StringBuilder();
//股票查询字符串列表
private static List<string> querylist=new List<string>();
//调试模式开关
private static int Debug = 0;
//服务是否停止开关
private static bool Stopped = false;
private static bool CanStopped = false;
//线程状态字典
private static Dictionary<string, bool> DicStatus = new Dictionary<string, bool>();
//业务逻辑对象
private static SHAStockCodeBLL bllcode=new SHAStockCodeBLL();
private static StockTransferQueueBLL bllqueue = new StockTransferQueueBLL();
#region 应用程序初始化
private static void InitilizeCompoment()
{
Output("开始初始化1", true);
if (Debug == 1)
{
Console.Title = ServiceDisPlayName;
}
if (WorkThreads > 1)
{
WorkThreads = 9;
}
if (WorkThreads < 1)
{
WorkThreads = 1;
}
Output("IP:" + IP,true);
Output("MAC:" + MAC,true);
Output("开始获取数据",true);
//构造查询字符串
BuildQueryList();
//初始化定时器
//InitilizeTimer();
//开始启动线程
if (WorkThreads == 1)
{
t = new Thread(GetPrice);
t.IsBackground = false;
t.Start();
}
else
{
threads = new Thread[WorkThreads];
DicStatus.Clear();
for (int i = 0; i < WorkThreads; i++)
{
DicStatus.Add("Threads" + (i + 1).ToString(), false);
threads[i] = new Thread(new ParameterizedThreadStart(GetPriceMulti));
threads[i].IsBackground = false;
threads[i].Name = "Threads" + (i + 1).ToString();
threads[i].Start(i);
Output("线程启动:"+i.ToString(), true);
}
}
if (Debug == 1)
{
Console.ReadLine();
Output("启动完成", true);
}
}
//构造查询字符串
private static void BuildQueryList()
{
Output("正在构造查询字符串", true);
List<SHAStockCodeModel> all = (bllcode.GetModelList(""));
Output("数据已读取条数:" + all.Count.ToString(), true);
for (int i = 0; i < 9; i++)
{
for (int j = 1; j < 99; j++)
{
int index = i * 100 + j;
if (index > all.Count - 1)
{
break;
}
//Output("此时index:" + index.ToString() +"----"+ all[index].StockCode.ToString(), true);
sb.Append(prefix);
sb.Append(all[index].StockCode.ToString());
sb.Append(endfix);
}
querylist.Add(sb.ToString());
//debug success
//Output(querylist[i], true);
sb.Remove(0, sb.Length);
}
Output("查询字符串构造完成", true);
}
#endregion
#region 数据获取逻辑
private static void GetPrice()
{
//SmsSendList send = new SmsSendList();
//SmsReturn ret = new SmsReturn();
//SmsSendLog log = new SmsSendLog();
////返回信息
//TSMSReturnHundSunInfo retinfo = new TSMSReturnHundSunInfo();
////日志信息
//TSMSSendLogInfo loginfo = new TSMSSendLogInfo();
//IList<TSMSSendHundSunInfo> sendlist;
//Dictionary<string, TSMSSendHundSunInfo> senddic = null;
//string result = string.Empty;
//string zipresult = string.Empty;
//while (true)
//{
// if (Stopped)
// {
// CanStopped = true;
// break;
// }
// if (!Valid)
// {
// Output("身份验证失败", ConsoleColor.Red);
// Thread.Sleep(ValidateTime);
// continue;
// }
// try
// {
// sendlist = send.GetSendList(SendCountPerTime);
// }
// catch (Exception e)
// {
// Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
// Thread.Sleep(SleepTime);
// continue;
// }
// if (sendlist.Count == 0)
// {
// //Output("没有待发数据", ConsoleColor.Blue);
// Thread.Sleep(SleepTime);
// continue;
// }
// else
// {
// senddic = new Dictionary<string, TSMSSendHundSunInfo>();
// StringBuilder sb = new StringBuilder();
// foreach (TSMSSendHundSunInfo sms in sendlist)
// {
// //判断是否是合法短信
// if (ValidSms(sms))
// {
// sb.Append(sms.ToString() + "\n");
// senddic.Add(sms.LSerialno.ToString(), sms);
// }
// }
// result = sb.ToString();
// if (result != string.Empty)
// {
// result = result.Substring(0, result.Length - 2);
// zipresult = Compress.ZipString(result);
// sendlist.Clear();
// sendlist = null;
// }
// else
// {
// Thread.Sleep(SleepTime);
// continue;
// }
// }
// string sendresult = string.Empty;
// try
// {
// sendresult = obj.Send(EnterpriseCode, EnterpriseAccount, zipresult);
// Output("发送 " + senddic.Count.ToString() + " 数据");
// }
// catch (Exception e)
// {
// Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red);
// }
// if (sendresult != string.Empty)
// {
// sendresult = Compress.UnzipString(sendresult);
// string[] arr = sendresult.Split(',');
// for (int i = 0; i < arr.Length; i++)
// {
// if (senddic.ContainsKey(arr[i]))
// {
// TSMSSendHundSunInfo sms = senddic[arr[i]];
// //从待发表里删除
// try
// {
// send.DeleteSms(sms.LSerialno);
// }
// catch (Exception e)
// {
// Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
// continue;
// }
// //插入状态表
// retinfo.CContent = sms.CContent;
// retinfo.CDate = sms.CDate.ToString("yyyy-MM-dd HH:mm:ss");
// retinfo.CFrom = sms.CFrom;
// retinfo.CHandle = "0";
// retinfo.CMobile = sms.CMobileno;
// retinfo.CProperty = sms.CProperty;
// retinfo.CR1 = sms.CR1;
// retinfo.CR2 = sms.CR2;
// retinfo.CR3 = sms.CR3;
// retinfo.CR4 = sms.CR4;
// retinfo.CR5 = sms.CR5;
// retinfo.CReturn = string.Empty;
// retinfo.CReturnTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
// retinfo.CSmsID = sms.CSmsID;
// retinfo.CSmsName = sms.CSmsname;
// try
// {
// ret.Insert(retinfo);
// }
// catch (Exception e)
// {
// Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
// }
// if (EnableLogTable == 1)
// {
// //插入日志表
// loginfo.CContent = sms.CContent;
// loginfo.CDate = sms.CDate.ToString("yyyy-MM-dd HH:mm:ss");
// loginfo.CFrom = sms.CFrom;
// loginfo.CHanlde = "0";
// loginfo.CLogTime = DateTime.Now;
// loginfo.CMobileno = sms.CMobileno;
// loginfo.CProperty = sms.CProperty;
// loginfo.CR1 = sms.CR1;
// loginfo.CR2 = sms.CR2;
// loginfo.CR3 = sms.CR3;
// loginfo.CR4 = sms.CR4;
// loginfo.CR5 = sms.CR5;
// loginfo.CSmsID = sms.CSmsID;
// loginfo.CSmsname = sms.CSmsname;
// try
// {
// log.Insert(loginfo);
// }
// catch (Exception e)
// {
// Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
// }
// }
// }
// }
// }
// Thread.Sleep(SleepTime);
//}
}
private static void GetPriceMulti(object o)
{
int mod = (int)o;
string threadname = "Threads" + (mod + 1).ToString();
string result = string.Empty;
string zipresult = string.Empty;
StockTransferQueueModel model = new StockTransferQueueModel();
while (true)
{
if (Stopped)
{
lock (lockobj)
{
DicStatus[threadname] = true;
}
break;
}
result = GetJSbyWC(querylist[mod]);
if (EnableZip)
{
zipresult = Compress.ZipString(result);
model.RealTimePrice = zipresult;
}
else
{
model.RealTimePrice = result;
}
try
{
bllqueue.Add(model);
Output("线程 " + mod.ToString() + " 添加记录成功", ConsoleColor.Blue, true);
}
catch (Exception e)
{
Output("存储记录时产生错误: " + e.Message, ConsoleColor.Red, true);
}
Thread.Sleep(SleepTime);
continue;
}
}
#region 获取新浪清单,每秒4.5个,二方法耗时基本相等
private static string GetJSbyWC(string code)
{
using (WebClient wc = new WebClient())
{
Stream resStream = wc.OpenRead("http://hq.sinajs.cn/list=" + code);
StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
string result = sr.ReadToEnd();
resStream.Close();
return result;
}
}
private static string GetJSbyHTTP(string code)
{
WebRequest request = WebRequest.Create("http://hq.sinajs.cn/list=" + code);
WebResponse response = request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
string result = sr.ReadToEnd();
resStream.Close();
sr.Close();
return result;
}
#endregion
#endregion
#region 应用程序入口 OK
static void Main(string[] args)
{
Thread.GetDomain().UnhandledException += new UnhandledExceptionEventHandler(Program_UnhandledException);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
bool exists = ServiceControl.CheckService(ServiceRealName);
if (args.Length == 0)
{
ServiceBase.Run(new ServiceBase[] { new Program() });
}
else
{
string parm = args[0].ToLower();
switch (parm)
{
case "-debug":
case "/debug":
Debug = 1;
if (exists)
{
ServiceControllerStatus status = ServiceControl.GetServiceStatus(ServiceRealName);
if (status != ServiceControllerStatus.Stopped)
{
Console.WriteLine(GetDateTime() + ServiceRealName + " 服务正在运行,无法进入调试状态。请先停止该服务");
Console.WriteLine(GetDateTime() + "请关闭本窗体");
Console.ReadLine();
}
else
{
InitilizeCompoment();
}
}
else
{
InitilizeCompoment();
}
break;
case "-install":
case "-setup":
case "/install":
case "/setup":
if (exists)
{
Console.WriteLine(GetDateTime() + ServiceRealName + " 服务已经存在,如果您想升级服务,请先卸载该服务");
Console.WriteLine(GetDateTime() + "请关闭本窗体");
Console.ReadLine();
}
else
{
Console.WriteLine(GetDateTime() + ServicePath);
bool result = ServiceControl.InstallService(ServicePath, ServiceRealName, ServiceDisPlayName, ServiceDescription);
if (result)
{
Console.WriteLine(GetDateTime() + "服务安装成功");
Console.WriteLine(GetDateTime() + "正在启动服务");
ServiceControl.StartService(ServiceRealName);
while (!(ServiceControl.GetServiceStatus(ServiceRealName) == ServiceControllerStatus.Running))
{
Thread.Sleep(SleepTime);
}
Console.WriteLine(GetDateTime() + "服务已经启动");
}
else
{
Console.WriteLine(GetDateTime() + "服务安装失败");
}
Console.WriteLine(GetDateTime() + "请关闭本窗体");
Console.ReadLine();
}
break;
case "-uninstall":
case "-remove":
case "/uninstall":
case "/remove":
if (!exists)
{
Console.WriteLine(GetDateTime() + ServiceRealName + " 服务尚未安装");
}
else
{
bool result = ServiceControl.UnInstallService(ServiceRealName);
if (!result)
{
Console.WriteLine(GetDateTime() + "服务卸载失败");
}
else
{
Console.WriteLine(GetDateTime() + "服务卸载成功");
}
}
Console.WriteLine(GetDateTime() + "请关闭本窗体");
Console.ReadLine();
break;
}
}
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
Output("未处理A:" + e.Exception.Message, ConsoleColor.Red, true);
}
static void Program_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is System.Exception)
{
Output("未处理P:" + ((System.Exception)e.ExceptionObject).Message, ConsoleColor.Red, true);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
}
base.Dispose(disposing);
}
public Program()
{
base.ServiceName = ServiceRealName;
base.AutoLog = true;
}
#endregion
#region 初始化服务设置 OK
protected override void OnStart(string[] args)
{
InitilizeCompoment();
}
protected override void OnStop()
{
Stopped = true;
try
{
if (WorkThreads == 1)
{
while (!CanStopped)
{
Thread.Sleep(SleepTime);
}
}
else
{
while (!AllStop())
{
Thread.Sleep(SleepTime);
}
}
}
catch
{
}
}
/// <summary>
/// 判断工作线程是否已经都停止了
/// </summary>
/// <returns></returns>
private static bool AllStop()
{
try
{
lock (lockobj)
{
foreach (bool value in DicStatus.Values)
{
if (!value)
{
return false;
}
}
}
return true;
}
catch
{
return false;
}
}
#endregion
#region 调试辅助逻辑 OK
private static string GetDateTime()
{
return "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
}
private static void Output(string msg)
{
lock (lockobj)
{
if (Debug == 1)
{
Console.WriteLine(GetDateTime() + msg);
}
}
}
private static void Output(string msg, bool log)
{
lock (lockobj)
{
if (Debug == 1)
{
Console.WriteLine(GetDateTime() + msg);
}
if (log)
{
if (LogToFile)
{
Log.WriteToFile(ServiceDirectory + @"\log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
}
}
}
}
private static void Output(string msg, ConsoleColor color)
{
lock (lockobj)
{
if (Debug == 1)
{
Console.ForegroundColor = color;
Console.WriteLine(GetDateTime() + msg);
Console.ResetColor();
}
}
}
private static void Output(string msg, ConsoleColor color, bool log)
{
lock (lockobj)
{
if (Debug == 1)
{
Console.ForegroundColor = color;
Console.WriteLine(GetDateTime() + msg);
Console.ResetColor();
}
if (log)
{
if (LogToFile)
{
Log.WriteToFile(ServiceDirectory + @"\log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
}
}
}
}
#endregion
#region 获得IP地址 OK
private static string GetIPAddress()
{
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
string ip = string.Empty;
for (int i = 0; i < ips.Length; i++)
{
ip += ips[i].ToString() + ",";
}
if (ip != string.Empty)
{
ip = ip.Substring(0, ip.Length - 1);
}
return ip;
/*
string ip = string.Empty;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
string[] ipaddresses = (string[])mo["IPAddress"];
for (int i = 0; i < ipaddresses.Length; i++)
{
ip += ipaddresses[i].ToString() + ",";
}
}
}
if (ip != string.Empty)
{
ip = ip.Substring(0, ip.Length - 1);
}
return ip;
*/
}
#endregion
#region 获得MAC OK
private static string GetMacAddress()
{
ManagementClass adapters = new ManagementClass("Win32_NetworkAdapterConfiguration");
string MACAddress = string.Empty;
foreach (ManagementObject adapter in adapters.GetInstances())
{
if ((bool)adapter["IPEnabled"] == true)
{
MACAddress = adapter.Properties["MACAddress"].Value.ToString();
MACAddress += ",";
}
}
//去除最后一个,号
if (MACAddress != string.Empty)
{
MACAddress = MACAddress.Substring(0, MACAddress.Length - 1);
}
return MACAddress;
}
#endregion
}
}