Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace XMLMatrixConvert
{
static class Program
{
static void Main()
{
if (Debugger.IsAttached)
{
Service1 ser1 = new Service1();
Console.ReadLine();
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}
}
关键字:Dbugger.IsAttached
此处的作用的,调试状态下,作为调整。
Services1
using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Timers;
namespace TestNamespace
{
public partial class Service1 : ServiceBase
{
#region Variables
private string _SourceSQLConnORC = string.Empty;
private string _SourceSQLConnVRS = string.Empty;
private Timer _Timer = new Timer();
private int _TimerInterval = 0;
private string _MappingFolderPath = string.Empty;
#endregion
public Service1()
{
ServiceInitial();
InitializeComponent();
}
public void ServiceInitial()
{
GetConfig();
GeneralFunctions.WriteLog.WriteLogFun("ServiceInitial: Get config end");
_Timer.Interval = _TimerInterval * 1000 * 60; //30s
if (Debugger.IsAttached)
{
_Timer.Interval = 5000;
}
_Timer.Elapsed += new ElapsedEventHandler(TimedEvent); //此处委托给TimeEvent
_Timer.Enabled = true;
_Timer.AutoReset = false;
_Timer.Start();
GeneralFunctions.WriteLog.WriteLogFun("ServiceInitial: Get config and Timer Started.");
}
private void GetConfig()
{
_SourceSQLConnORC = GeneralFunctions.ReadAndSetConfigFile.GetAppConfig("SourceSQLConnORC");
_SourceSQLConnVRS = GeneralFunctions.ReadAndSetConfigFile.GetAppConfig("SourceSQLConnVRS");
_MappingFolderPath = GeneralFunctions.ReadAndSetConfigFile.GetAppConfig("MappingFolderPath");
if (Debugger.IsAttached || string.IsNullOrWhiteSpace(_MappingFolderPath))
{
_MappingFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "eTest");
DirectoryInfo dinfo = new DirectoryInfo(_MappingFolderPath);
dinfo.Create();
GeneralFunctions.WriteLog.WriteLogFun("Create eTest folder.");
}
try
{
_TimerInterval = int.Parse(GeneralFunctions.ReadAndSetConfigFile.GetAppConfig("TimerInterval"));
}
catch
{
_TimerInterval = 30;
}
}
public void TimedEvent(object source, ElapsedEventArgs e)
{
_Timer.Enabled = false;
try
{
//get orc data
DataTable dt_orc = DataBaseFunctions.GetORCData.GetORCDataFunc(_SourceSQLConnORC);
//get Json data
//DataView dataView = dt_orc.DefaultView;DataTable dataTableDistinct = dataView.ToTable(true, "PanelId");
eMapFunctions.loadlAndUpdateXml.CreateAndUpdateXml(dt_orc, _MappingFolderPath, _SourceSQLConnVRS);
}
catch (Exception ex)
{
GeneralFunctions.WriteLog.WriteLogFun("Error:" + ex.Message);
GeneralFunctions.WriteLog.WriteLogFun("StackTrace:" + ex.StackTrace);
}
finally
{
GeneralFunctions.WriteLog.WriteLogFun("Process End.");
//next timer
//_Timer.Enabled = true;
_Timer.Enabled = false;
}
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
}
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SourceSQLConnORC" value="############"/>
<add key="SourceSQLConnVRS" value="############"/>
<!-- TimerInterval unit is min -->
<add key="TimerInterval" value="30"/>
<add key="SourceDataPath" value="D:\ATS\Application\C#\ETest\XMLMatrixConvert\XMLMatrixConvert\bin\Debug\SourceDataPath"/>
<add key="MappingFolderPath" value="D:\ATS\Application\C#\ETest\XMLMatrixConvert\XMLMatrixConvert\bin\Debug\TargetDataPath\eTest"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
LogInfo
using System;
using System.IO;
namespace XMLMatrixConvert.GeneralFunctions
{
class WriteLog
{
//Record log
public static void WriteLogFun(String msg)
{
string logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
string tempfileFolder = Path.Combine(logPath, "Log");
if (!Directory.Exists(tempfileFolder))
{
Directory.CreateDirectory(tempfileFolder);
}
string tempfile = Path.Combine(tempfileFolder, string.Format("Log_{0}.log", DateTime.Now.ToString("yyyyMMdd")));
if (!File.Exists(tempfile))
{
File.Create(tempfile).Close();
}
StreamWriter writer = null;
try
{
writer = File.AppendText(tempfile);
writer.WriteLine("{0}: {1}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), msg);
writer.Flush();
}
catch
{
}
finally
{
if (writer != null)
{
writer.Close();
}
}
}
}
}
ReadAndSetConfigFile
using System;
using System.Collections.Generic;
using System.Configuration;
namespace XMLMatrixConvert.GeneralFunctions
{
class ReadAndSetConfigFile
{
//Error Code
const string Error_ConfigLoadFail = "Load Config file is Fail.";
const string Error_ConfigSetFail = "Set Config file is Fail";
const string Error_SQL_Fail = "Query SQL DB fail.";
/// <summary>
/// 查询AppConfig中Key = Key1的value
/// </summary>
/// <param name="Key1">Key ID</param>
/// <returns></returns>
public static string GetAppConfig(string Key1)
{
string str = string.Empty;
try
{
ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == Key1)
{
str = ConfigurationManager.AppSettings[Key1];
}
}
return str;
}
catch
{
return str;
}
}
/// <summary>
/// 查询AppConfig, contain Key1的Key, 并添加value到List , 返回List<string>
/// </summary>
/// <param name="Key1">Key ID</param>
/// <returns></returns>
public static List<string> GetAppConfig_Contain(string Key1)
{
List<string> TempList = new List<string>();
try
{
ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
foreach (string key in ConfigurationManager.AppSettings)
{
if (key.ToUpper().Contains(Key1.ToUpper()))
{
if (ConfigurationManager.AppSettings[key] != string.Empty)
{
TempList.Add(ConfigurationManager.AppSettings[key]);
}
}
}
return TempList;
}
catch
{
TempList = new List<string>();
TempList.Add(Error_ConfigLoadFail);
return TempList;
}
finally
{
}
}
/// <summary>
/// Search config items which name contain key1 and key2
/// </summary>
/// <param name="Key1"></param>
/// <param name="Key2"></param>
/// <returns></returns>
public static List<string> GetAppConfig_Contain(string Key1, string Key2)
{
List<string> TempList = new List<string>();
try
{
ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
foreach (string key in ConfigurationManager.AppSettings)
{
if (key.ToUpper().Contains(Key1.ToUpper()) && key.ToUpper().Contains(Key2.ToUpper()))
{
if (ConfigurationManager.AppSettings[key] != string.Empty)
{
TempList.Add(ConfigurationManager.AppSettings[key]);
}
}
}
return TempList;
}
catch
{
TempList = new List<string>();
TempList.Add(Error_ConfigLoadFail);
return TempList;
}
finally
{
}
}
/// <summary>
/// 修改AppConfig中Key1的value
/// </summary>
/// <param name="Key1">Key ID</param>
/// <param name="value1">Key Value</param>
public static void SetAppConfig(string Key1, string value1)
{
Configuration AppConfig = null;
try
{
AppConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = AppConfig.AppSettings;
if (app.Settings[Key1] == null)
{
app.Settings.Add(Key1, value1);
}
else
{
app.Settings[Key1].Value = value1;
}
AppConfig.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
}
catch (Exception Ex)
{
throw new Exception(Error_ConfigSetFail + Ex.Message);
}
finally
{
AppConfig = null;
}
}
}
}
PaserParameter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XMLMatrixConvert.GeneralFunctions
{
class PaserParameter
{
public static string PaserString(string msg, string key, string spliter)
{
string result = string.Empty;
if (!msg.Contains(key))
{
return result;
}
int indexKey = msg.IndexOf(key, 0);
int indexSpliter = msg.IndexOf(spliter, indexKey);
if (indexSpliter == -1)
{
result = msg.Substring(indexKey).Replace(key, "");
}
else
{
result = msg.Substring(indexKey, indexSpliter - indexKey).Replace(key, "");
}
return result;
}
public static string GetParentFolderFullPath(string filePath)
{
string folderPath = string.Empty;
int lastChar = filePath.LastIndexOf(@"\");
folderPath = filePath.Substring(0, lastChar);
return folderPath;
}
}
}