C # Write a multi-line database operation for Windows Services

Source: Internet
Author: User

I wrote a Windows service installed on the local machine so that the Service could quietly modify the database where I could not see it.

You can search for how to create and install a Windows Service on the Internet, and find a lot of things that are helpful to you. Let me simply put it.

My computer win7 flagship edition, vs2010 (after the process described in the previous blog post, I really cannot get the Unit's computer) and SQL Server 2008

Creating windows is nothing more than finding windows☞Windows Services☞Name and save path

I knocked on a timer in the background. You can also

During installation, you only need to right-click the design page☞Add and installProgram, Will appear automatically

Modify the automatic attribute of serviceinstaller1 to automatic, and the servicename attribute to customize a name;

Modify the LocalSystem attribute of serviceprocessinsertaller1 to LocalSystem;

Right-click your service to generate it, and find the storage location of your service on your computer.☞Service name folder☞Bin☞Debug☞Add two TXT files named "Install service" and "uninstall service" respectively.

C: \ windows \ Microsoft. NET \ framework \ v4.0.30319 \ installutil.exe name .exe
Pause and

C: \ windows \ Microsoft. NET \ framework \ v4.0.30319 \ installutil.exe/u name .exe
Pause

After that, change the suffix names of the two. txt files to. bat. During installation, double-click the Installation File (this is what the lazy guys do) and uninstall the files.

My service name is service1 (I know I am very lazy ~~ You have defined a time control in service1.designer. CS.

Private system. Timers. Timer timer1;

         Private   Void  Initializecomponent (){  This . Timer1 = New  System. Timers. Timer (); components = New  System. componentmodel. Container ();  This . Servicename = " Service1  "  ; (System. componentmodel. isupportinitialize )(  This  . Timer1). begininit ();  //               //  Timer1 (MS)  //  300000 five minutes  //  3600000 hour  //  86400000 days              This . Timer1.interval = 300000  ;  This . Timer1.elapsed + = New System. Timers. elapsedeventhandler ( This  . Timer1_elapsed); (system. componentmodel. isupportinitialize )(  This  . Timer1). endinit ();  //  If this sentence is missing, the service cannot be started. It seems that an error is reported indicating that the service is missing dependencies. }

And the initializecomponent () method is improved.
The following are basic operations of the service1 service:Code

Datatable =New  Datatable ();  Private Object rlock = New Object (); //  Lock          Int Ncurrowindex = 0 ; //  Global Variables          Int Times = 0 ; //  Number of Database Operations          Public Service1 () {initializecomponent (); initservice ();}  ///   <Summary>          ///  Initialize service parameters  ///   </Summary>          Private   Void  Initservice (){  Base . Autolog = False  ;  Base . Canshutdown =True  ;  Base . Canstop = True  ;  Base . Canpauseandcontinue = True  ;  Base . Servicename = "  Service1  " ; //  This name is very important. A 1083 error will occur if the settings are inconsistent!  } ///   <Summary>          ///  Start Service  ///   </Summary>          ///   <Param name = "ARGs"> </param>          Protected   Override   Void Onstart ( String  [] ARGs ){  Using (System. Io. streamwriter Sw = New System. Io. streamwriter ( "  D: \ log.txt  " , True  ) {Sw. writeline (datetime. Now. tostring (  "  Yyyy-mm-dd hh: mm: SS  " ) + "  Start.  "  );}  This . Timer1.enabled = True ;}  ///   <Summary>          ///  End of service  ///   </Summary>          Protected   Override   Void  Onstop (){  Using (System. Io. streamwriter Sw = New System. Io. streamwriter ( "  D: \ log.txt " , True  ) {Sw. writeline (datetime. Now. tostring (  "  Yyyy-mm-dd hh: mm: SS  " ) + "  Stop.  "  );}  This . Timer1.enabled = False  ;}  ///  <Summary>          ///  Service suspension  ///   </Summary>          Protected   Override   Void  Onpause (){  //  Service suspension code              Base  . Onpause ();}  Protected   Override   Void Oncontinue (){  //  Service Recovery Execution Code              Base  . Oncontinue ();}  Protected   Override   Void  Onshutdown (){  //  The system is about to close the Execution Code              Base  . Onshutdown ();}  Private   Void Elapsed () {getallwikipedia ();}  Private   Void Timersponelapsed ( Object  Sender, system. Timers. elapsedeventargs e ){  //  Execute SQL statements or other operations Getallwikipedia (); //  Take the time }

Data Query is very simple, just like a common. Net program that operates a database.

         ///   <Summary>          /// Query a table  ///   </Summary>          ///   <Returns> </returns>          Public  Datatable chaxun () {sqlconnection con = New Sqlconnection ( "  Data Source =.; initial catalog = hdqyms; persist Security info = true; user id = sa; Password = Sasa  "  );  String SQL ="  Select * from Wikipedia  "  ;  Using (Sqlcommand cmd = New  Sqlcommand (SQL, con) {dataset DS = New  Dataset (); sqldataadapter da = New  Sqldataadapter (CMD); da. Fill (DS); con. Close (); datatable dt = Ds. Tables [ 0 ]; Times ++ ;  Using (System. Io. streamwriter Sw = New System. Io. streamwriter ( "  D: \ log.txt  " , True  ) {Sw. writeline (datetime. Now. tostring (  "  Yyyy-mm-dd hh: mm: SS  " ) + " The  " + Times + "Times  Obtain the Wikipedia table in the database  "  );}  Return  DT ;}} 

Two threads are enabled to work.

  //  This is a thread function.          Private   Void  Doprocess (){  Bool Flag = True ;  While  (FLAG) {thread nonparameterthreada = New Thread ( New Threadstart (nonparameterrun )); //  Create thread Nonparameterthreada. Name = "  Threada  "  ; Nonparameterthreada. Start (); thread nonparameterthreadb = New Thread (New  Threadstart (nonparameterrun); nonparameterthreadb. Name = "  Threadb  "  ; Nonparameterthreadb. Start (); flag = False  ;}}  ///   <Summary>           ///  Start method without Parameters  ///   </Summary>          Public   Void  Nonparameterrun (){  While ( True  ){  Lock (Rlock) //  Lock  {Datarow rrow = Getrowtoprocess (); //  Get row                      If (Rrow = Null ) {Thread. Sleep (  300000  ); Ncurrowindex = 0  ;  Break  ;}  //  Processing rrow here,                      Else  {  Try  {Update (rrow ); //  What you really want to do Thread. Sleep ( 10  );}  Catch  (Exception ex ){  Using (System. Io. streamwriter Sw = New System. Io. streamwriter ( "  D: \ log.txt  " , True ) {Sw. writeline (datetime. Now. tostring (  "  Yyyy-mm-dd hh: mm: SS  " ) + "  Exception  " + Ex) ;}onstop ();}}}}} 

This is the table that I want to operate on the database. The purpose of my service is to query the table content in the database after it is enabled. The linkaddress is the website address, and I want to query the source code of the webpage online based on the website, then, let's see if the three external links qutsideaddress1, 2, and 3 are still valid. When they are valid, they are marked √. Invalid identifier ×.

But I have to say that I encountered a few problems when I did it again.

① No thread is provided. sleep (300000); when two threads are enabled, they will execute all the operations I need twice. If three threads are enabled, then execute all three times ~□ ̄ |

The solution is to sleep the thread and wait for a while. (If anyone has a good idea, or knows where I am wrong, please tell me ~ Grateful ....)

② Because there are still data modification operations after the judgment of the external chain, I wanted to use a transaction or other tasks to make them complete together. However, after multithreading, this would not seem to be easy to implement, or I have not found a method, and no specific operation code is provided here. I am still using a very stupid way to modify it.

③ I feel that the working time after the thread is put does not seem to have greatly improved. It seems that it still depends on the network speed ~ I don't know if I didn't define the priority of the two threads. Thread B is more likely to execute than thread a. There will be a shadow of thread a after four or five B threads are executed ~

④ Debugging is still a headache for me because of the first Windows service. Baidu said that debugging is found in the program after startup.☞Attach to process☞√ Display processes of all users☞Refresh☞Find your service☞The append operation can be used for debugging. However, the services I have found are gray and there is no way to append processes. So I still adopt the most stupid method, that is, writing work logs, where can I find the error? (Mom no longer has to worry about learning ~□ ̄ |)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.