我正在研究这个基于 Windows 的 c# 代码,现在的要求是将此功能转换为 Windows 服务。我按照以下链接从 msdn 获取我的转换方法:
http://msdn.microsoft.com/en-us/library/ms733069.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
摆脱所有表单功能,我保持我的逻辑完好无损,它传输访问文件并将其解析为文本格式,尽管该服务似乎正在运行,但它的工作方式与 win 应用程序不同。
这是Windows服务代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
/** Using Config File for Directories **/
using System.Configuration;
//====Read From Access namespace===============
using System.Data.Common;
using System.Data.OleDb;
//using System.IO;
//=============================================
using System.ServiceModel;
using System.ServiceProcess;
using System.Configuration.Install;
namespace Microsoft.ServiceModel.Samples
{
// Define a service contract.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface Copytask
{
[OperationContract]
void copyej();
}
public class CopyejService : Copytask
{
// Implement the Copy EJ methods.
public void copyej()
{
// Functionality Derivation
string target_dir_file = System.Configuration.ConfigurationSettings.AppSettings["TargetDir_File"];
string target_dir = System.Configuration.ConfigurationSettings.AppSettings["TargetDir"];
string text_dir = System.Configuration.ConfigurationSettings.AppSettings["TextDir"];
string file_name = System.Configuration.ConfigurationSettings.AppSettings["FileName"];
string source_dir_file = System.Configuration.ConfigurationSettings.AppSettings["SourceDir_File"];
// Check if Target Directory Exists
DirectoryInfo theFolder = new DirectoryInfo(target_dir);
if (!theFolder.Exists)
{
theFolder.Create();
}
/*
if (!File.Exists(target_dir_file))
{
// MessageBox.Show("Function Exited");
return;
}*/
// Delet if EJ file exists
if (File.Exists(target_dir_file))
{
File.Delete(target_dir_file);
}
// Copy the EJ file in Target Directory
File.Copy(source_dir_file, target_dir_file);
//=============Extract contents in Access and save it as Text File Format==========================================
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test\TestEJFolder\BWC_Ejournal.mdb";
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbConnection conn1 = new OleDbConnection(connectionString);
OleDbConnection conn2 = new OleDbConnection(connectionString);
string sql = "SELECT * FROM Events";
string dt = "SELECT TOP 1 [Date] FROM Events";
string count = "SELECT COUNT(ID) FROM Events";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
OleDbDataReader reader;
reader = cmd.ExecuteReader();
OleDbCommand cmd1 = new OleDbCommand(dt, conn1);
conn1.Open();
OleDbCommand cmd2 = new OleDbCommand(count, conn2);
conn2.Open();
string time_stmp = Convert.ToDateTime(cmd1.ExecuteScalar()).ToString("yyyyMMddhhmmss");
string s_path = text_dir + "\\" + time_stmp + "_" + "Session"+ "_" + file_name;
FileInfo oFileInfo = new FileInfo(source_dir_file);
string fname = "File Name: \"" + oFileInfo.Name + "|" + " ";
string fsize = "File total Size: " + oFileInfo.Length.ToString() + "|" + " ";
string fdts = "Date and Time File Created: " + oFileInfo.CreationTime.ToString() + "|" + " ";
Int32 r_count = (Int32)cmd2.ExecuteScalar();
StreamWriter sp = File.CreateText(s_path);
sp.WriteLine(fname + fsize + fdts + "Record Count " + r_count);
sp.Close();
conn1.Close();
conn2.Close();
string path = text_dir + "\\" + time_stmp + "_" + file_name;
StreamWriter sw = File.CreateText(path);
const string format = "{0,-22} {1,-4} {2,-4} {3,-4} {4,-20} {5,-22}";
string line;
while (reader.Read())
{
line = string.Format(format, reader.GetDateTime(5).ToString(@"dd-MM-yyyy HH:mm:ss").Trim(),
reader.GetInt32(0).ToString().Trim(),
reader.GetInt32(1).ToString().Trim(),
reader.GetInt32(2).ToString().Trim(),
reader.GetString(3).ToString().Trim(),
reader.GetString(4).ToString().Trim());
sw.WriteLine(line);
}
reader.Close();
conn.Close();
sw.Close();
sw.Dispose();
//====End Of Extract Access contents and save it as Text Format=========================================================
}
}
public class CopyEJWindowsService : ServiceBase
{
public ServiceHost serviceHost = null;
public CopyEJWindowsService()
{
// Name the Windows Service
ServiceName = "CopyEJWindowsService";
}
public static void Main()
{
ServiceBase.Run(new CopyEJWindowsService());
}
// Start the Windows service.
protected override void OnStart(string[] args)
{
if (serviceHost != null)
{
serviceHost.Close();
}
// Create a ServiceHost for the CopyEJService type and
// provide the base address.
serviceHost = new ServiceHost(typeof(CopyejService));
// Open the ServiceHostBase to create listeners and start
// listening for messages.
serviceHost.Open();
}
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
}
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller process;
private ServiceInstaller service;
public ProjectInstaller()
{
process = new ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
service = new ServiceInstaller();
service.ServiceName = "CopyEJWindowsService";
Installers.Add(process);
Installers.Add(service);
}
}
}
==================================================== ======================
这是Windows应用程序代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
/** Using Config File for Directories **/
using System.Configuration;
//====Read From Access namespace===============
using System.Data.Common;
using System.Data.OleDb;
//using System.IO;
//=============================================
namespace CopyEJTask
{
public partial class Form1 : Form
{
string log;
int ctr;
public Form1()
{
InitializeComponent();
//timer1.Interval = Int32.Parse(txtTimer.Text);
this.Opacity = 0;
this.WindowState = FormWindowState.Minimized;
}
private void Form1_Load(object sender, EventArgs e)
{
ctr = 0;
string target_dir = System.Configuration.ConfigurationSettings.AppSettings["TargetDir"];
textBox3.Text = ctr.ToString();
DirectoryInfo theFolder = new DirectoryInfo(target_dir);
if (!theFolder.Exists)
{
theFolder.Create();
}
//textBox1.Text = @"C:\Test\TestEJFolder";
textBox1.Text = target_dir;
}
private void timer1_Tick(object sender, EventArgs e)
{
success();
}
private void success()
{
//if (!theFolder.Exists)
//{
// theFolder.Create();
// }
timer1.Stop();
timerFileExist.Start();
timerCopyEJ.Start();
//System.Threading.Thread.Sleep(20000);
// timer1.Start();
//MessageBox.Show("File Copied");
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
timer1.Start();
}
private void button2_Click(object sender, EventArgs e)
{
button1.Enabled = true;
timer1.Stop();
}
private void manageToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Opacity=100;
this.WindowState=FormWindowState.Normal;
}
private void hideToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void menuItem1_Click(object sender, EventArgs e)
{
this.Opacity = 100;
this.WindowState = FormWindowState.Normal;
}
private void menuItem2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button3_Click(object sender, EventArgs e)
{
this.Opacity = 0;
this.WindowState = FormWindowState.Minimized;
}
private void manageToolStripMenuItem_Click_1(object sender, EventArgs e)
{
this.Opacity = 100;
this.WindowState = FormWindowState.Normal;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button4_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void timerFileExist_Tick(object sender, EventArgs e)
{
string target_dir_file = System.Configuration.ConfigurationSettings.AppSettings["TargetDir_File"];
if (File.Exists(target_dir_file))
{
File.Delete(target_dir_file);
}
timerFileExist.Stop();
}
private void timerCopyEJ_Tick(object sender, EventArgs e)
{
string source_dir_file = System.Configuration.ConfigurationSettings.AppSettings["SourceDir_File"];
string target_dir_file = System.Configuration.ConfigurationSettings.AppSettings["TargetDir_File"];
File.Copy(source_dir_file, target_dir_file); // Update For Pavneet
ctr = ctr + 1;
textBox3.Text = ctr.ToString();
log = DateTime.Now.ToString();
textBox2.Text = log;
timer1.Start();
timerCopyEJ.Stop();
timerExtractMDB.Start();
}
private void timerExtractMDB_Tick(object sender, EventArgs e)
{
string target_dir_file = System.Configuration.ConfigurationSettings.AppSettings["TargetDir_File"];
if (!File.Exists(target_dir_file))
{
MessageBox.Show("Function Exited");
return;
}
//=============Extract contents in Access and save it as Text File Format==========================================
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test\TestEJFolder\BWC_Ejournal.mdb";
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbConnection conn1 = new OleDbConnection(connectionString);
OleDbConnection conn2 = new OleDbConnection(connectionString);
string sql = "SELECT * FROM Events";
string dt = "SELECT TOP 1 [Date] FROM Events";
string count = "SELECT COUNT(ID) FROM Events";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
OleDbDataReader reader;
reader = cmd.ExecuteReader();
OleDbCommand cmd1 = new OleDbCommand(dt, conn1);
conn1.Open();
OleDbCommand cmd2 = new OleDbCommand(count, conn2);
conn2.Open();
string text_dir = System.Configuration.ConfigurationSettings.AppSettings["TextDir"];
string file_name = System.Configuration.ConfigurationSettings.AppSettings["FileName"];
string source_dir_file = System.Configuration.ConfigurationSettings.AppSettings["SourceDir_File"];
string time_stmp = Convert.ToDateTime(cmd1.ExecuteScalar()).ToString("yyyyMMddhhmmss");
string s_path = text_dir + "\\" + time_stmp + "_" + "Session"+ "_" + file_name;
FileInfo oFileInfo = new FileInfo(source_dir_file);
string fname = "File Name: \"" + oFileInfo.Name + "|" + " ";
string fsize = "File total Size: " + oFileInfo.Length.ToString() + "|" + " ";
string fdts = "Date and Time File Created: " + oFileInfo.CreationTime.ToString() + "|" + " ";
Int32 r_count = (Int32)cmd2.ExecuteScalar();
StreamWriter sp = File.CreateText(s_path);
sp.WriteLine(fname + fsize + fdts + "Record Count " + r_count);
sp.Close();
conn1.Close();
conn2.Close();
string path = text_dir + "\\" + time_stmp + "_" + file_name;
StreamWriter sw = File.CreateText(path);
const string format = "{0,-22} {1,-4} {2,-4} {3,-4} {4,-20} {5,-22}";
string line;
while (reader.Read())
{
line = string.Format(format, reader.GetDateTime(5).ToString(@"dd-MM-yyyy HH:mm:ss").Trim(),
reader.GetInt32(0).ToString().Trim(),
reader.GetInt32(1).ToString().Trim(),
reader.GetInt32(2).ToString().Trim(),
reader.GetString(3).ToString().Trim(),
reader.GetString(4).ToString().Trim());
sw.WriteLine(line);
}
reader.Close();
conn.Close();
sw.Close();
sw.Dispose();
//====End Of Extract Access contents and save it as Text Format=========================================================
timerExtractMDB.Stop();
}
}
}
此外,有关如何记录每个服务事件的任何想法都会有所帮助。