0

I want to do backup of my database on regular basis using windows services.But i am not able to run this service . Below is my code.i was able to successfully installed this service to my local system But when i tried to start it giving me error "The Service xyz.exe started and then stopped.Some Services stopped automatically if they used by other services." when i manually start service from services.msc .I am helpless please if anyone can help me.Below is my code

public static void BackupDatabase(string backUpFile)
{

    ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;
    string MyConnectionString = connections["MDASconfig"].ConnectionString;

    ServerConnection con = new ServerConnection(MyConnectionString);
    Server server = new Server(con);
    Backup source = new Backup();
    source.Action = BackupActionType.Database;
    source.Database = "MDAS";
    BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
    source.Devices.Add(destination);
    source.SqlBackup(server);
    con.Disconnect();
}

i have already applied some solutions like increase size through Event viewer and started service using same logon account by logon properties of this service.Service is listing in Services.msc but not starting due to above error.

Yuval Itzchakov
  • 136,303
  • 28
  • 230
  • 296
techV
  • 897
  • 2
  • 16
  • 37
  • Add a try catch block around your code and write the errors go a file. It seems to me that your service is not starting due to code errors. – user3514987 Sep 28 '14 at 09:56
  • 1
    @vivek, I have a question please: why using Windows Services and not Task Scheduler? – user3165438 Sep 28 '14 at 10:07
  • Check this question http://stackoverflow.com/questions/125964/easier-way-to-start-debugging-a-windows-service-in-c-sharp. You should debug your service form Visual Studio to see what is going on. – Vojtěch Dohnal Sep 28 '14 at 11:25
  • Also, check the event viewer logs on the machine. Anything that you aren't catching will end up in there. – Keith Payne Sep 28 '14 at 13:38
  • @user3165438 once that service startd then definately i'll schedule it through task schedular . – techV Sep 28 '14 at 16:44
  • @vivek, What do you mean? You create a program and when it works you schedule it, or I misunderstood something? – user3165438 Sep 29 '14 at 09:29

1 Answers1

0

You need to keep running thread in the memory, use the following code:

Dim delPeriodicalCheck As New TimerCallback(AddressOf BackupDatabase)
Dim objTimer As System.Threading.Timer
Dim dueTime = 1000 '1 Sec, delay start
Dim period = 60000 '1 Min, you may change this value

Protected Overrides Sub OnStart(ByVal args() As String)
objTimer = New System.Threading.Timer(delPeriodicalCheck, Nothing, dueTime,period)
Catch ex As Exception
EventLog1.WriteEntry(ex.Message)
End Try


Private Sub BackupDatabase(ByVal stateInfo As Object)
'Your code
End Sub
Sameh
  • 764
  • 1
  • 13
  • 36