using System; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text; using System.Web; namespace PDF_Alchemy { class Download { const string accessKeyId = "xxxxxxxxxxxxxxxxxxxx"; const string secretAccessKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Downloads the next document from PDF Alchemy. // Returns the documentId on success, or null on failure. static private string DownloadNext() { // Generate the HMAC-SHA1 signature. string date = DateTime.UtcNow.ToString("r"); string request = '/' + accessKeyId + "/outqueue/next"; string clearText = "GET\n" + accessKeyId + '\n' + date + '\n' + request; HMACSHA1 hmac = new HMACSHA1(ASCIIEncoding.UTF8.GetBytes(secretAccessKey)); string signature = Convert.ToBase64String(hmac.ComputeHash(ASCIIEncoding.UTF8.GetBytes(clearText))); // Request the next document from PDF Alchemy. HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.pdfalchemy.com" + request); req.Headers.Add("X-PDF-Alchemy-Date", date); req.Headers.Add("X-PDF-Alchemy-Signature", signature); try { HttpWebResponse response = (HttpWebResponse)req.GetResponse(); Stream responseStream = response.GetResponseStream(); string filename = response.Headers.Get("Content-Disposition").Split(new char[] { '"' })[1]; FileStream file = File.OpenWrite(filename); byte[] buffer = new Byte[4096]; int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) file.Write(buffer, 0, bytesRead); responseStream.Close(); response.Close(); file.Close(); Console.WriteLine("Downloaded '{0}'.", filename); return response.Headers.Get("X-PDF-Alchemy-ID"); } catch (System.Net.WebException e) { Console.Write(e.Message); } return null; } // Removes documentId from the PDF Alchemy outqueue. static private void DeleteDocument(string documentId) { // Generate the HMAC-SHA1 signature. string date = DateTime.UtcNow.ToString("r"); string request = '/' + accessKeyId + "/outqueue/" + HttpUtility.UrlEncode(documentId); string clearText = "DELETE\n" + accessKeyId + '\n' + date + '\n' + request; HMACSHA1 hmac = new HMACSHA1(ASCIIEncoding.UTF8.GetBytes(secretAccessKey)); string signature = Convert.ToBase64String(hmac.ComputeHash(ASCIIEncoding.UTF8.GetBytes(clearText))); // Remove the document from PDF Alchemy. HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.pdfalchemy.com" + request); req.Method = "DELETE"; req.Headers.Add("X-PDF-Alchemy-Date", date); req.Headers.Add("X-PDF-Alchemy-Signature", signature); try { ((HttpWebResponse)req.GetResponse()).Close(); Console.WriteLine("Removed '{0}' from PDF Alchemy.", documentId); } catch (System.Net.WebException e) { Console.Write(e.Message); } } static void Main(string[] args) { string documentId; while ((documentId = DownloadNext()) != null) DeleteDocument(documentId); } } }