2013-06-10 2 views
-1

Я работаю над этим кодом C#, который основан на Windows, теперь требуется преобразовать эту функциональность в службу Windows. Я последовал следующую ссылку из MSDN для моего преобразования подхода:Windows Service C# Issue

http://msdn.microsoft.com/en-us/library/ms733069.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

Избавления от всех функций формы, я сохранил свою логику неповрежденной, который передает файл доступ и анализирует его в текстовый формат, хотя услуга, кажется, работает но он не работает так же, как win app.

Вот код окна обслуживания:

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); 
     } 
    } 
} 

================================== =====================================

Вот код окна приложения:

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(); 
     } 
    } 
} 

Также были бы полезны любые идеи о том, как регистрировать каждое событие обслуживания.

+0

Для ведения журнала вы можете использовать log4net. http://www.codeproject.com/Articles/14819/How-to-use-log4net –

+0

И каков ваш вопрос? –

+0

Хорошо, так что это не работает. Можете ли вы предоставить более подробную информацию? Что он делает, чего раньше не делал, или не делал этого? – psubsee2003

ответ

0

Вам не нужен веб-сервис для размещения. Все, что вам нужно, это таймер в службе Windows и выполнение вашей задачи каждый раз, когда истекло время. Код службы Windows выглядит следующим образом:

private System.Timers.Timer serviceTimer = new System.Timers.Timer(); 

protected override void OnStart(string[] args) 
{ 
    InitTimer(); 
} 

protected override void OnStop() 
{ 
    serviceTimer.Stop(); 
} 

private void InitTimer() 
{ 
    serviceTimer.Start(); 
    serviceTimer.Enabled = true; 
    serviceTimer.Interval = 5000; 
    serviceTimer.Elapsed += new ElapsedEventHandler(OnServiceTimerElapsed); 
} 

public void OnServiceTimerElapsed(object sender, ElapsedEventArgs args) 
{ 
    serviceTimer.Enabled = false; 
    try 
    { 
     copyej(); 
    } 
    catch(Exception ex) 
    { 
       //Handle exception 
    } 
    finally 
    { 
     serviceTimer.Enabled = true; 
    } 
} 
+0

hi venu .. Я получаю ошибку «Имя copyej() не существует в текущем контексте» .. это потому, что функция определена в отдельном классе? – user2385057

+0

yes..you просто скопируйте функцию copyej() в том же классе обслуживания. Он должен работать нормально. –