-
Notifications
You must be signed in to change notification settings - Fork 5
/
Handler.cs
97 lines (85 loc) · 3.08 KB
/
Handler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using Microsoft.SqlServer.Management.Smo;
namespace DatabaseMinder
{
public static class Handler
{
private static Server _server;
private static CommandArgs _command;
public static void HandleCommand(CommandArgs command)
{
_command = command;
ShowHelp(command);
SetupServer(command);
EnsureDirectoriesExist(command.Folder);
DoBackup();
DoRestore();
}
private static void SetupServer(CommandArgs command)
{
var serverName = ".";
if (!string.IsNullOrEmpty(command.ServerName))
{
serverName = command.ServerName;
}
_server = new Server(serverName);
_server.ConnectionContext.StatementTimeout = 0;
}
public static void ShowHelp(CommandArgs command)
{
if (!command.Help) return;
Message.ShowHelpAndExit(command.PromptsEnabled);
}
private static void DoBackup()
{
if (!_command.Backup)
{
return;
}
Consoler.Write("Backup requested...");
BackupDatabase.Execute(_server, _command.DatabaseName, _command.NameOfCredentials, _command.BackFullPath, _command.CompressionEnabled);
if (_command.ZipBackup)
{
var dir = $"{Path.GetDirectoryName(_command.BackFullPath)}\\backup_{_command.DatabaseName}_{DateTime.Now.ToString("yyyyMMdd")}";
Directory.CreateDirectory(dir);
File.Move(_command.BackFullPath,Path.Combine(dir, Path.GetFileName(_command.BackFullPath))); // add extract folder name in for zipping, move file into it then zip it
ZipFile.CreateFromDirectory(dir,_command.BackFullPath.Replace(".bak", ".zip"),CompressionLevel.Optimal,false);
Directory.Delete(dir,true);
}
}
private static void DoRestore()
{
if (!_command.Restore)
{
return;
}
Consoler.Write("Restore requested...");
RestoreDatabase.Execute(_server,_command.DatabaseName, _command.BackFullPath, _command.Folder);
}
private static void EnsureDirectoriesExist(params string[] paths)
{
string lastPath = null;
try
{
foreach (var path in paths.Where(x=>!string.IsNullOrEmpty(x)))
{
lastPath = path;
if (!Directory.Exists(path))
{
Consoler.Information("creating directory " + path);
Directory.CreateDirectory(path);
}
}
}
catch (Exception ex)
{
Consoler.Error($"Cannot create directories {lastPath} ");
Consoler.Warn(ex.Message);
Consoler.Pause(true);
}
}
}
}