Skip to content

Instantly share code, notes, and snippets.

@anlai
Created November 29, 2012 21:44
Show Gist options
  • Save anlai/4172128 to your computer and use it in GitHub Desktop.
Save anlai/4172128 to your computer and use it in GitHub Desktop.
private readonly string _storageUrl;
private readonly string _serverName;
private readonly string _sqlUsername;
private readonly string _sqlPassword;
private readonly string _storageAccountName;
private readonly string _storageKey;
private readonly string _storageContainer;
public string Backup(string database, string[] selectedTables, out string filename)
{
var time = DateTime.Now;
filename = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.bacpac", database, time.Year, time.Month, time.Day, time.Hour, time.Minute);
var credentials = new BlobStorageAccessKeyCredentials() { StorageAccessKey = _storageKey, Uri = StorageUrl + filename};
var connectionInfo = new ConnectionInfo();
connectionInfo.ServerName = _serverName;
connectionInfo.DatabaseName = database;
connectionInfo.UserName = _sqlUsername;
connectionInfo.Password = _sqlPassword;
var se = selectedTables != null && selectedTables.Any();
// create the request
var request = WebRequest.Create(string.Format(ServiceUrl, "SelectiveExport"));
request.Method = "POST";
request.ContentType = "application/xml";
// tables specified, do selective export
if (se)
{
// select to export the names listed
var tables = selectedTables.Select(a => new TableName() {Name = a});
// this can be done for just the schema as well
//var tables = new List<TableName>() {new TableName() {SchemaName = "dbo"}};
var selectiveExport = new SelectiveExportInput() { ConnectionInfo = connectionInfo, BlobCredentials = credentials, Tables = tables.ToArray() };
using(var stream = request.GetRequestStream())
{
var dcs = new DataContractSerializer(typeof(SelectiveExportInput));
dcs.WriteObject(stream, selectiveExport);
}
}
// full export of database
else
{
var exportInput = new ExportInput() { ConnectionInfo = connectionInfo, BlobCredentials = credentials };
using (var stream = request.GetRequestStream())
{
var dcs = new DataContractSerializer(typeof(ExportInput));
dcs.WriteObject(stream, exportInput);
}
}
// make the post
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new HttpException((int)response.StatusCode, response.StatusDescription);
}
var sr = new System.IO.StreamReader(response.GetResponseStream());
var result = sr.ReadToEnd().Trim();
// read out the tracking code, so you can lookup status
var xml = XDocument.Parse(result);
var node = xml.Descendants().First();
return node.Value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment