using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.IO;
using Ionic.Zip;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
namespace WorkerRole1
{
public class WorkerRole : RoleEntryPoint
{
const string Perlfolder = @"strawberry";
const string PerlDownloadAddresses = @"http://strawberryperl.com/download/5.12.2.0/strawberry-perl-5.12.2.0-portable.zip";
public override void Run()
{
while (true)
{
Thread.Sleep(10000);
Trace.WriteLine("Working", "Information");
}
}
public override bool OnStart()
{
ServicePointManager.DefaultConnectionLimit = 12;
DownloadPortablePerl();
return base.OnStart();
}
private void DownloadPortablePerl()
{
var perlDownloadAddress = PerlDownloadAddresses;
var locations = perlDownloadAddress.Split(' ').Select(a => a.Trim()).Where(l => l.Trim().Length > 0);
if (locations.Count() == 0)
throw new Exception("No download locations for Perl configured (setting 'PerlDownloadAddresses').");
locations.ToList().ForEach(a => Trace.TraceInformation("Download location " + a));
var perlarchive = locations.First();
perlarchive = perlarchive.Substring(perlarchive.LastIndexOf('/') + 1);
Trace.TraceInformation("File is " + perlarchive);
if (File.Exists(perlarchive))
Trace.TraceInformation(string.Format("Found local perl archive copy at {0}", (new FileInfo(perlarchive)).FullName));
else
{
Trace.TraceInformation("Downloading...");
var client = new WebClient();
bool success = false;
foreach (var loc in locations)
{
try
{
Trace.TraceInformation(string.Format("Trying location {0}", loc));
client.DownloadFile(loc, perlarchive);
Trace.TraceInformation(string.Format("Successfully downloaded from {0}", loc));
success = true;
break;
}
catch (Exception ex)
{
Trace.TraceError(string.Format("Failure downloading from {0}", loc));
Trace.TraceError(ex.Message);
}
}
if (!success)
throw new Exception("Could not download Perl distibution");
}
if (!Directory.Exists(Perlfolder))
Trace.TraceInformation("Perl distribution needs to be unpacked. Starting...");
using (var zip = new ZipFile(perlarchive))
{
zip.ExtractAll(Perlfolder,
ExtractExistingFileAction.DoNotOverwrite);
Trace.TraceInformation("Perl distribution is unpacked. Done...");
}
}
}
}