Commits

ManicBlowfish committed 7496ce2

Initial commit.

  • Participants

Comments (0)

Files changed (37)

+/backup/*.suo
+/backup/bin
+/backup/obj

File backup/App.config

+<?xml version="1.0" encoding="utf-8"?>
+<configuration>
+  <appSettings>
+    <add key="ToEmail" value="EDIT_ME" />
+    <add key="ConnectionString" value="EDIT_ME" />
+    <add key="DbName" value="EDIT_ME"/>
+    <add key="AWSAccessKey" value="EDIT_ME" />
+    <add key="AWSSecretKey" value="EDIT_ME" />
+    <add key="BackupBucket" value="EDIT_ME" />
+  </appSettings>
+  <system.net>
+    <mailSettings>
+      <smtp deliveryMethod="Network" from="EDIT_ME">
+        <network host="EDIT_ME" userName="EDIT_ME" password="EDIT_ME" port="EDIT_ME" />
+      </smtp>
+    </mailSettings>
+  </system.net>
+</configuration>

File backup/BlobStorage.cs

+using System.Configuration;
+using System.IO;
+using Amazon;
+using Amazon.S3;
+using Amazon.S3.Model;
+
+namespace backup
+{
+    public static class BlobStorage
+    {
+        private static string BACKUP_BUCKET = ConfigurationManager.AppSettings["BackupBucket"];
+
+        private static AmazonS3 GetClient()
+        {
+            return AWSClientFactory.CreateAmazonS3Client();
+        }
+
+        public static void UploadFile(string filepath)
+        {
+            var client = GetClient();
+
+            using (FileStream fs = new FileStream(filepath, FileMode.Open))
+            {
+                string filename = Path.GetFileName(filepath);
+
+                client.PutObject(new PutObjectRequest
+                {
+                    BucketName = BACKUP_BUCKET,
+                    Key = filename,
+                    InputStream = fs
+                });
+            }
+        }
+    }
+}

File backup/DbScripter.cs

+using System;
+using System.Configuration;
+using System.IO;
+using Ionic.Zip;
+using Microsoft.SqlServer.Management.Common;
+using Microsoft.SqlServer.Management.Smo;
+
+namespace backup
+{
+    public class DbScripter
+    {
+        public void ScriptDb()
+        {
+            string tempfile = Path.GetTempPath() + "backup.sql";
+
+            Server server = new Server(new ServerConnection
+            {
+                ConnectionString = ConfigurationManager.AppSettings["ConnectionString"]
+            });
+            Database db = server.Databases[ConfigurationManager.AppSettings["DbName"]];
+
+            var tables = new Table[db.Tables.Count];
+            db.Tables.CopyTo(tables, 0);
+
+            var scripter = new Scripter(server);
+            scripter.Options = new ScriptingOptions
+            {
+                ScriptDrops = true,
+                WithDependencies = true,
+                EnforceScriptingOptions = true,
+                FileName = tempfile,
+                ToFileOnly = true,
+                DriAllConstraints = true
+            };
+            scripter.Script(tables);
+
+            scripter.Options = new ScriptingOptions
+            {
+                ScriptDrops = false,
+                ScriptSchema = true,
+                ScriptData = true,
+                DriAllConstraints = true,
+                Indexes = true,
+                WithDependencies = true,
+                EnforceScriptingOptions = true,
+                FileName = tempfile,
+                ToFileOnly = true,
+                AppendToFile = true
+            };
+            scripter.EnumScript(tables);
+
+
+
+            using (var zip = new ZipFile())
+            {
+                zip.Name = string.Format(Path.GetTempPath() + "dbbackup-{0}.zip", DateTime.Now.ToString("yyyyMMddTHHmmss"));
+                zip.AddFile(tempfile, "");
+                zip.Save();
+
+                BlobStorage.UploadFile(zip.Name);
+            }
+
+        }
+    }
+}

File backup/Program.cs

+
+using System;
+using System.Configuration;
+using System.Net.Mail;
+using Quartz;
+using Quartz.Impl;
+namespace backup
+{
+    class Program
+    {
+        static void Main(string[] args)
+        {
+            // construct a scheduler
+            var schedulerFactory = new StdSchedulerFactory();
+            var scheduler = schedulerFactory.GetScheduler();
+            scheduler.Start();
+
+            var job = JobBuilder.Create<BackupJob>().Build();
+
+            var trigger = TriggerBuilder.Create()
+                            .WithSimpleSchedule(x => x.WithIntervalInHours(24).RepeatForever())
+                            .StartAt(DateTime.Now.Date.AddHours(6))  // 6am UTC, early morning EST
+                            .Build();
+
+            scheduler.ScheduleJob(job, trigger);
+        }
+    }
+
+    class BackupJob : IJob
+    {
+        public void Execute(IJobExecutionContext context)
+        {
+            try
+            {
+                new DbScripter().ScriptDb();
+                SendMail("Backup Succeeded", "done!");
+            }
+            catch (Exception ex)
+            {
+                SendMail("Backup Failed", ex.ToString());
+            }
+        }
+
+        private void SendMail(string status, string detail)
+        {
+            SmtpClient smtp = new SmtpClient();
+            MailMessage msg = new MailMessage();
+            msg.To.Add(ConfigurationManager.AppSettings["ToEmail"]);
+            msg.Subject = status;
+            msg.Body = detail;
+            smtp.Send(msg);
+        }
+    }
+}

File backup/Properties/AssemblyInfo.cs

+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("backup")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("backup")]
+[assembly: AssemblyCopyright("Copyright ©  2012")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("c9821080-835c-4792-bbb1-b877e379f10c")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]

File backup/backup.csproj

+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
+    <ProductVersion>8.0.30703</ProductVersion>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>{9F81DDED-4D4E-4EC5-B02D-C2BF41B595C4}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>backup</RootNamespace>
+    <AssemblyName>backup</AssemblyName>
+    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+    <TargetFrameworkProfile>Client</TargetFrameworkProfile>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <PlatformTarget>x86</PlatformTarget>
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <PlatformTarget>x86</PlatformTarget>
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="AWSSDK">
+      <HintPath>packages\AWSSDK.1.5.5.1\lib\AWSSDK.dll</HintPath>
+    </Reference>
+    <Reference Include="C5">
+      <HintPath>packages\Quartz.2.0.1\lib\net40-client\C5.dll</HintPath>
+    </Reference>
+    <Reference Include="Common.Logging">
+      <HintPath>packages\Common.Logging.2.0.0\lib\2.0\Common.Logging.dll</HintPath>
+    </Reference>
+    <Reference Include="Ionic.Zip">
+      <HintPath>packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>lib\Microsoft.SqlServer.ConnectionInfo.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>lib\Microsoft.SqlServer.Management.Sdk.Sfc.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>lib\Microsoft.SqlServer.Smo.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.SqlServer.SqlClrProvider, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>lib\Microsoft.SqlServer.SqlClrProvider.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>lib\Microsoft.SqlServer.SqlEnum.dll</HintPath>
+    </Reference>
+    <Reference Include="Quartz">
+      <HintPath>packages\Quartz.2.0.1\lib\net40-client\Quartz.dll</HintPath>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.ComponentModel.DataAnnotations" />
+    <Reference Include="System.configuration" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Data.Entity" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="BlobStorage.cs" />
+    <Compile Include="DbScripter.cs" />
+    <Compile Include="Program.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="App.config" />
+    <None Include="packages.config" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>

File backup/backup.sln

+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "backup", "backup.csproj", "{9F81DDED-4D4E-4EC5-B02D-C2BF41B595C4}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|x86 = Debug|x86
+		Release|x86 = Release|x86
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{9F81DDED-4D4E-4EC5-B02D-C2BF41B595C4}.Debug|x86.ActiveCfg = Debug|x86
+		{9F81DDED-4D4E-4EC5-B02D-C2BF41B595C4}.Debug|x86.Build.0 = Debug|x86
+		{9F81DDED-4D4E-4EC5-B02D-C2BF41B595C4}.Release|x86.ActiveCfg = Release|x86
+		{9F81DDED-4D4E-4EC5-B02D-C2BF41B595C4}.Release|x86.Build.0 = Release|x86
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal

File backup/lib/readme.txt

+The following dll's are required here.  Due to MSFT licensing issues they can't be
+included in the repository.
+
+Microsoft.SqlServer.ConnectionInfo.dll
+Microsoft.SqlServer.Management.Sdk.Sfc.dll
+Microsoft.SqlServer.Smo.dll
+Microsoft.SqlServer.SqlClrProvider.dll
+Microsoft.SqlServer.SqlEnum.dll
+
+Note that if you have SQL Server installed on your build machine, VS will be smart 
+enough to locate the assemblies, and the project will build.  However, they do need 
+to be included in the project in order to be uploaded to the AppHarbor worker machine.

File backup/packages.config

+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+  <package id="AWSSDK" version="1.5.5.1" />
+  <package id="Common.Logging" version="2.0.0" />
+  <package id="DotNetZip" version="1.9.1.8" />
+  <package id="Quartz" version="2.0.1" />
+</packages>