Windows Service 小程序

主要功能:定时启动,调用

webservice,将返回的xmlstring上传给服务器。

 

定时启动使用的是timer组件,工具箱里面的timer控件没有Elapsed事件,所以要在程序里面写private System.Timers.Timer timer1;程序主要的功能都是在private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)函数中完成的;调用webservice是直接添加的web References在本地生成代理类,就可以直接调用了;上传xmlstring是利用HttpWebRequest 和HttpWebResponse这两个类。

 


程序有两个入口参数:定时启动的时间和上传
xmlstring所在服务器的IP,这个是用c++写的控制面板程序,服务启动的时候会到注册表中读取这两个值。。

 

注意:服务的Account是设为user(我设的是隶属于Administrator的帐户),其他三种类型的帐号都不适用。

下面是程序的代码:

  1 using System;
  2  using System.Collections.Generic;
  3  using System.ComponentModel;
  4  using System.Data;
  5  using System.Diagnostics;
  6  using System.ServiceProcess;
  7  using System.Text;
  8  using System.IO;
  9 using System.Timers;
 10 using System.Xml;
 11 using System.Web;
 12 using Microsoft.Win32;
 13 using System.Net;
 14 
 15 namespace ServiceText
 16 {
 17     public partial class Service1 : ServiceBase
 18     {
 19         private System.Timers.Timer timer1;
 20 
 21         static string strTime = "";
 22 
 23         static string strIp = "";
 24 
 25         public CookieContainer cookie = new CookieContainer();
 26 
 27         public Service1()
 28         {
 29 
 30             InitializeComponent();
 31 
 32         }
 33 
 34         protected override void OnStart(string[] args)
 35         {
 36             // TODO: Add code here to perform any tear-down necessary to start your service.
 37 
 38             this.timer1.Enabled = true;
 39 
 40             WriteLog("服务开始启动。。");
 41 
 42             readKey();
 43 
 44           
 45         }
 46 
 47         protected override void OnStop()
 48         {
 49             // TODO: Add code here to perform any tear-down necessary to stop your service.
 50             this.timer1.Enabled = false;
 51 
 52             WriteLog("服务已经停止。。");
 53         }
 54 
 55         private void readKey()//读注册表
 56         {
 57 
 58             RegistryKey serviceKey = Registry.LocalMachine.OpenSubKey("System");
 59 
 60             RegistryKey myserviceKey = serviceKey.OpenSubKey("CurrentControlSet");
 61 
 62             RegistryKey ohmyserviceKey = myserviceKey.OpenSubKey("Services");
 63 
 64             RegistryKey ohmygodserviceKey = ohmyserviceKey.OpenSubKey("ServiceText");
 65  
 66             strTime = (string)ohmygodserviceKey.GetValue("time");
 67 
 68             strIp = (string)ohmygodserviceKey.GetValue("ip");
 69              
 70         
 71  
 72         }
 73 
 74 
 75         private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
 76         {
 77 
 78             if (DateTime.Now.ToString("HH:mm") == strTime)// the time
 79             {
 80                 WriteLog("定时程序开始运行。。");
 81 
 82                 GetandPutXml();
 83              
 84              
 85             }
 86            
 87         }
 88 
 89         public static void WriteLog(string strLog)
 90         {
 91 
 92             string strPath;
 93 
 94       //    strPath = System.Environment.SystemDirectory;
 95 
 96             strPath = @"c:\log.txt";
 97 
 98             FileStream fs = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write);
 99 
100             StreamWriter m_streamWriter = new StreamWriter(fs);
101 
102             m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
103 
104             m_streamWriter.WriteLine(strLog);
105 
106             m_streamWriter.Flush();
107 
108             m_streamWriter.Close();
109 
110             fs.Close();
111 
112         }
113 
114 
115 
116         public void GetandPutXml()
117         {
118             RichMall.RichMall ws = new ServiceText.RichMall.RichMall();
119 
120             string xmlstring1 = ws.GetData();
121 
122             string page = login();
123 
124             if (page.IndexOf("<Value>1</Value>") > 0)//服务器返回的xml
125             {
126                 LoadupFile(xmlstring1);
127             }
128             logout();
129         }
130 
131         public string login()
132         {
133             string url = "http://" + strIp + "/xia/server/xia.php?COMMAND=Login&Account=puretime&Password=54321";//呵呵,这IP无效
134 
135             HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
136 
137             myRequest.AllowAutoRedirect = true;
138 
139             myRequest.CookieContainer = cookie;
140 
141             HttpWebResponse myresponse = (HttpWebResponse)myRequest.GetResponse();
142 
143             myresponse.Cookies = cookie.GetCookies(myRequest.RequestUri);
144 
145             Stream mystream = null;
146 
147             mystream = myresponse.GetResponseStream();
148 
149             StreamReader myreader = new StreamReader(mystream, System.Text.Encoding.Default, true);
150 
151             string pagefile = myreader.ReadToEnd();
152 
153             WriteLog(pagefile);
154 
155             return pagefile;
156 
157         }
158 
159 
160         public void LoadupFile(string xmlstring)
161         {
162 
163                 string postUrl = "http://" + strIp + "/xia/Server/xia.php?CMD=Add";  //上传xml
164 
165                 HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(postUrl);
166 
167                 Request.CookieContainer = cookie;
168 
169                 Request.Method = "POST";
170 
171                 Request.ContentType = "application/x-www-form-urlencoded";
172 
173                 Request.AllowAutoRedirect = true;
174 
175                 //    string strXML = "XMLDATA=<book><author>Irina</author><title>Piano Fort A</title><price>4.95</price></book>";
176 
177                 string strXML = "XMLDATA=" + xmlstring;
178 
179                 byte[] data = Encoding.UTF8.GetBytes(strXML);
180 
181                 Stream newStream = Request.GetRequestStream();
182 
183                 newStream.Write(data, 0, data.Length);
184 
185                 newStream.Close();
186 
187                 HttpWebResponse response = (HttpWebResponse)Request.GetResponse();
188 
189                 Stream stream = null;
190 
191                 stream = response.GetResponseStream();
192 
193                 StreamReader reader = new StreamReader(stream, System.Text.Encoding.Default, true);
194 
195                 string file = reader.ReadToEnd();
196 
197                 WriteLog(file);
198 
199         }
200 
201         public void logout()
202         {
203             string outUrl = "http://" + strIp + "/xia/Server/xia.php?CMD=Logout "; //登出
204 
205             HttpWebRequest outRequest = (HttpWebRequest)WebRequest.Create(outUrl);
206 
207             outRequest.AllowAutoRedirect = true;
208 
209             outRequest.CookieContainer = cookie;
210 
211             HttpWebResponse outresponse = (HttpWebResponse)outRequest.GetResponse();
212 
213             Stream outstream = null;
214 
215             outstream = outresponse.GetResponseStream();
216 
217             StreamReader outreader = new StreamReader(outstream, System.Text.Encoding.Default, true);
218 
219             string outfile = outreader.ReadToEnd();
220 
221             WriteLog(outfile);
222         }
223 
224          
225 
226 
227     }
228 }
229 

 

 

namespace ServiceText
{
    partial 
class ProjectInstaller
    {
        
/**//// <summary>
        
/// Required designer variable.
        
/// </summary>
        private System.ComponentModel.IContainer components = null;

        
/**//// <summary> 
        
/// Clean up any resources being used.
        
/// </summary>
        
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            
if (disposing && (components != null))
            {
                components.Dispose();
            }
            
base.Dispose(disposing);
        }

    
//    #region Component Designer generated code

        
/**//// <summary>
        
/// Required method for Designer support - do not modify
        
/// the contents of this method with the code editor.
        
/// </summary>
        private void InitializeComponent()
        {
            
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
            
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();

            
            
// 
            
// serviceProcessInstaller1
            
// 
            this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.User;

            
this.serviceProcessInstaller1.Username = null;

            
this.serviceProcessInstaller1.Password = null;
           
            
// 
            
// serviceInstaller1
            
// 
            this.serviceInstaller1.Description = "tigger the program of webservice on time,then get xml string,and send them to another service.";
         
            
this.serviceInstaller1.ServiceName = "ServerText";

            
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;

//         初始化注册表里的值
            Microsoft.Win32.RegistryKey serviceKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System", true);

            Microsoft.Win32.RegistryKey myserviceKey 
= serviceKey.CreateSubKey("CurrentControlSet");

            Microsoft.Win32.RegistryKey ohmyserviceKey 
= myserviceKey.CreateSubKey("Services");

            Microsoft.Win32.RegistryKey ohmygodserviceKey 
= ohmyserviceKey.CreateSubKey("ServerText ");

            ohmygodserviceKey.SetValue(
"time", "20:00");

            ohmygodserviceKey.SetValue(
"ip", "192.168.1.1");  
            
// 
            
// ProjectInstaller 
            
// 
            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
            
this.serviceProcessInstaller1,
            
this.serviceInstaller1});

        }

      
//  #endregion

        
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
        
public System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
    }
}

 

namespace ServiceText
{
    partial 
class Service1
    {
        
/**//// <summary> 
        
/// Required designer variable.
        
/// </summary>
        private System.ComponentModel.IContainer components = null;

        
/**//// <summary>
        
/// Clean up any resources being used.
        
/// </summary>
        
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            
if (disposing && (components != null))
            {
                components.Dispose();
            }
            
base.Dispose(disposing);
        }

        Component Designer generated code
#region Component Designer generated code

        
/**//// <summary> 
        
/// Required method for Designer support - do not modify 
        
/// the contents of this method with the code editor.
        
/// </summary>
        private void InitializeComponent()
        {
            
this.timer1 = new System.Timers.Timer();
            ((System.ComponentModel.ISupportInitialize)
      (
this.timer1)).BeginInit();
            
//     
            
//   timer1     
            
//     
            this.timer1.Interval = 60000; //一分钟
            this.timer1.Elapsed +=
          
new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
            
//     
            
//   MyService     
            
//     

            ((System.ComponentModel.ISupportInitialize)
      (
this.timer1)).EndInit();

        }

        
#endregion

    }
}

posted @ 2007-08-08 10:10  宿远  阅读(512)  评论(0)    收藏  举报