Skip to content

Instantly share code, notes, and snippets.

@jaysonrowe
Created September 20, 2012 02:01
Show Gist options
  • Save jaysonrowe/3753546 to your computer and use it in GitHub Desktop.
Save jaysonrowe/3753546 to your computer and use it in GitHub Desktop.
TopShelf Program.cs
using System;
using System.Configuration;
using System.IO;
using System.Security.Permissions;
using System.Collections.Generic;
using System.Data;
using System.Text;
using Topshelf;
using Microsoft.SqlServer.Management.Smo;
namespace ASR
{
public class AutoSQLRestore
{
static string watcherpath = System.Configuration.ConfigurationManager.AppSettings["watcherpath"];
static string dbpath = System.Configuration.ConfigurationManager.AppSettings["dbpath"];
static string sqlserver = System.Configuration.ConfigurationManager.AppSettings["sqlserver"];
static FileSystemWatcher watcher = new FileSystemWatcher();
public AutoSQLRestore()
{
}
private static void restoredb(object source, RenamedEventArgs e)
{
Server svr = new Server(sqlserver);
Restore res = new Restore();
string[] fulldbname = e.Name.ToString().Split(new char[] { '.' });
string dbname = fulldbname[0];
res.Database = dbname;
res.Action = RestoreActionType.Database;
res.Devices.AddDevice(watcherpath + e.Name, DeviceType.File);
res.ReplaceDatabase = true;
DataTable dt;
DataRow[] foundrows;
dt = res.ReadFileList(svr);
foundrows = dt.Select();
string mdfname = foundrows[0]["LogicalName"].ToString();
string ldfname = foundrows[1]["LogicalName"].ToString();
res.RelocateFiles.Add(new RelocateFile(mdfname, dbpath + dbname + ".mdf"));
res.RelocateFiles.Add(new RelocateFile(ldfname, dbpath + dbname + "_log" + ".ldf"));
try
{
res.SqlRestore(svr);
}
catch (FailedOperationException fox)
{
Console.WriteLine("{0} Exception caught.", fox.Message);
}
catch (Exception x)
{
Console.WriteLine("{0} Exception caught.", x);
}
}
public void Start()
{
try
{
watcher.Path = watcherpath;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.bak";
watcher.Filter = "*.tmp";
watcher.Renamed += new RenamedEventHandler(restoredb);
watcher.EnableRaisingEvents = true;
}
catch (FailedOperationException)
{
Console.WriteLine("INFO: Aborted");
}
}
public void Stop()
{
watcher.Dispose();
}
}
class Program
{
public static void Main()
{
HostFactory.Run(x =>
{
x.Service<AutoSQLRestore>(s =>
{
s.ConstructUsing(name => new AutoSQLRestore());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("Automatic SQL Restore");
x.SetDisplayName("ASR");
x.SetServiceName("ASR");
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment