Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Windows服务C#问题_C#_.net_Winforms_Windows Services - Fatal编程技术网

Windows服务C#问题

Windows服务C#问题,c#,.net,winforms,windows-services,C#,.net,Winforms,Windows Services,我正在编写基于windows的c#代码,现在的要求是将此功能转换为windows服务。对于我的转换方法,我遵循了msdn中的以下链接: 为了摆脱所有的表单函数,我保持了我的逻辑完整,将access文件传输并解析为文本格式,尽管该服务似乎正在运行,但它的工作方式与win app不同 以下是windows服务代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Da

我正在编写基于windows的c#代码,现在的要求是将此功能转换为windows服务。对于我的转换方法,我遵循了msdn中的以下链接:

为了摆脱所有的表单函数,我保持了我的逻辑完整,将access文件传输并解析为文本格式,尽管该服务似乎正在运行,但它的工作方式与win app不同

以下是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应用程序代码:
关于如何记录每个服务事件的任何想法都会很有帮助。

您不需要托管web服务。您只需要在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;
    }
}

对于日志记录,可以使用log4net。你的问题到底是什么?好吧,那么它的作用就不一样了。你能提供更多的细节吗?它做了什么以前没有做过的,还是没有做它做过的?核心功能不起作用,似乎主功能copyej()没有启动,理想情况下,它应该移动访问文件,然后将数据转换为文本文件,并根据提到的代码执行其他一些操作。因此,根据函数copyej()中编码的逻辑:它应该从提到的位置移动.mdb文件,然后我根据mdb文件中的信息创建中间会话文件,然后最终以文本格式读取数据并创建文本文件。所有这些在winform代码中都能正常工作,服务不起作用。没有任何东西在调用
copyej()
,所以它当然不会被“踢开”。嗨,venu。。我收到错误“当前上下文中不存在copyej()名称”。。这是因为函数是在单独的类中定义的吗?是的。您只需在同一服务类中复制copyej()函数。它应该很好用。
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;
    }
}