예제 #1
0
        // GET: api/Data/5
        public HttpResponseMessage Get(int id)
        {
            HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.OK);

            //Check that there is a record with the supplied ID.
            if (db.Samples.Any(o => o.SampleID == id))
            {
                var sample = db.Samples.Find(id);

                if (sample.SampleMP3Blob == null || sample.SampleMP3Blob == "")
                {
                    res.StatusCode = HttpStatusCode.NotFound;
                    res.Content    = new StringContent("No content found for that sample");

                    return(res);
                }

                //Get blob from the container via its SampleMP3Blob attribute.
                CloudBlockBlob blob = GetSoundsContainer().GetBlockBlobReference(sample.SampleMP3Blob);

                Stream blobStream = blob.OpenRead();

                //Set the content to the blob's stream.
                res.Content = new StreamContent(blobStream);

                //Set HTTP headers.
                res.Content.Headers.ContentLength = blob.Properties.Length;
                res.Content.Headers.ContentType   = new
                                                    System.Net.Http.Headers.MediaTypeHeaderValue("audio/mpeg3");
                res.Content.Headers.ContentDisposition = new
                                                         System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = blob.Name,
                    Size     = blob.Properties.Length
                };

                return(res);
            }
            else
            {
                //Sample not found
                res.Content    = new StringContent("Sample with id " + id + " doesn't exist, so you can't download it");
                res.StatusCode = HttpStatusCode.NotFound;
            }


            //1. Connect to DB, check if sample with that ID exists, if not return 404.
            //2. Set response headers, etc.
            //3. Connect to Azure, get reference to the blob.
            //4. Set message's content.
            //5. return the message.

            db.SaveChanges();
            return(res);
        }
예제 #2
0
        public IHttpActionResult PutSample(int id, Sample sample)
        {
            //Check if supplied model is valid.
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != sample.SampleID)
            {
                return(BadRequest());
            }

            //Check if there was a previous
            var oldSample = db.Samples.Find(id);

            if (oldSample.SampleMP3Blob != null)
            {
                if (GetSoundsContainer().GetBlockBlobReference(oldSample.SampleMP3Blob).Exists())
                {
                    //Delete the old blob
                    CloudBlockBlob blob = GetSoundsContainer().GetBlockBlobReference(oldSample.SampleMP3Blob);
                    blob.Delete();
                }
            }


            db.Entry(oldSample).State = EntityState.Detached;
            //Update the record.
            db.Entry(sample).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SampleExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #3
0
파일: Program.cs 프로젝트: abaula/MixedCode
 private static void InsertSampleValues()
 {
     using (var ctx = new SamplesContext(GetOptions()))
     {
         ctx.SampleEntries.Add(new SampleEntry {
             Value = $"Value at {DateTime.Now}"
         });
         ctx.SaveChanges();
     }
 }
예제 #4
0
        private void ProcessQueueMessageFromApi(CloudQueueMessage msg, int id)
        {
            //Get connection to the DB via the Samples Context.
            var            dbConnString = CloudConfigurationManager.GetSetting("ShortenerDbConnectionString");
            SamplesContext db           = new SamplesContext(dbConnString);

            //Find the record with the ID that was taken from the Message.
            var sample = db.Samples.Find(id);

            Log("ID from queue is " + id);
            Log("CloudQueueMessage is " + msg.AsString);

            Log("File name from DB for ID " + id + " is: " + sample.Title);

            //Store the Blob path as a local variable
            string path = sample.MP3Blob;

            //get input blob
            CloudBlockBlob inputBlob = soundBlobContainer.GetBlockBlobReference(path);

            //make folder for blob to be downloaded into
            string folder = path.Split('\\')[0];

            System.IO.Directory.CreateDirectory(GetLocalStoragePath() + @"\" + folder);

            //download file to local storage
            Log("Downloading blob to local storage...");
            soundBlobContainer.GetBlockBlobReference(path).DownloadToFile(GetLocalStoragePath() + path, FileMode.Create);
            Log("Done downloading");

            //get file's current location
            fullInPath = GetLocalStoragePath() + path;

            //new file name
            string soundName = Path.GetFileNameWithoutExtension(inputBlob.Name) + "cropped.mp3";

            Log("New file name: " + soundName);

            //get and make directory for file output
            fullOutPath = GetLocalStoragePath() + @"out\" + soundName;
            CloudBlockBlob outputBlob = this.soundBlobContainer.GetBlockBlobReference(@"out\" + soundName);

            System.IO.Directory.CreateDirectory(GetLocalStoragePath() + @"out\");

            //shorten the sound to 10s
            Log("Shortening MP3 to 10s.");
            stopWatch.Start();

            CropSound(10);

            stopWatch.Stop();
            Log("Took " + stopWatch.ElapsedMilliseconds + " ms to shorten mp3.");
            stopWatch.Reset();

            //set content type to mp3
            outputBlob.Properties.ContentType = "audio/mpeg3";

            //set id3 tags
            Log("Setting ID3 tags.");
            TagLib.File tagFile = TagLib.File.Create(fullOutPath);


            tagFile.Tag.Comment   = "Shortened on WorkerRole Instance " + GetInstanceIndex();
            tagFile.Tag.Conductor = "Craig";
            //Check that title tag isn't null
            fileTitle = tagFile.Tag.Title ?? "File has no original Title Tag";
            tagFile.Save();

            LogMP3Metadata(tagFile);


            //upload blob  from local storage to container
            Log("Returning mp3 to the blob container.");
            using (var fileStream = File.OpenRead(fullOutPath))
            {
                outputBlob.UploadFromStream(fileStream);
            }

            //Add metadata to blob
            Log("Adding metadata to the blob.");
            outputBlob.FetchAttributes();
            outputBlob.Metadata["Title"]      = fileTitle;
            outputBlob.Metadata["InstanceNo"] = GetInstanceIndex();
            outputBlob.SetMetadata();

            //Add the SampleMP3Date to the DB record.
            sample.SampleMP3Blob        = @"out\" + soundName;
            sample.DateOfSampleCreation = DateTime.Now;

            //Save changes made to the record.
            db.SaveChanges();

            //Print blob metadata to console
            Log("Blob's metadata: ");
            foreach (var item in outputBlob.Metadata)
            {
                Log("   " + item.Key + ": " + item.Value);
            }

            //remove message from queue
            Log("Removing message from the queue.");
            soundQueue.DeleteMessage(msg);

            //remove initial blob
            Log("Deleting the input blob.");
            inputBlob.Delete();

            //remove files from local storage
            Log("Deleting files from local storage.");
            File.Delete(fullInPath);
            File.Delete(fullOutPath);
        }