Exemplo n.º 1
0
        public async static Task DeleteImagesAsync([QueueTrigger("deleterequest")] BlobInformation blobInfo,
                                                   [Blob("{BlobName}/{BlobNameLG}")] CloudBlockBlob blobLarge,
                                                   [Blob("{BlobName}/{BlobNameXS}")] CloudBlockBlob blobExtraSmall,
                                                   [Blob("{BlobName}/{BlobNameSM}")] CloudBlockBlob blobSmall,
                                                   [Blob("{BlobName}/{BlobNameMD}")] CloudBlockBlob blobMedium)
        {
            try
            {
                Trace.TraceInformation("Deleting LARGE image with ImageID = " + blobInfo.ImageId);
                await blobLarge.DeleteAsync();

                Trace.TraceInformation("Deleting EXTRA SMALL image with ImageID = " + blobInfo.ImageId);
                await blobExtraSmall.DeleteAsync();

                Trace.TraceInformation("Deleting SMALL image with ImageID = " + blobInfo.ImageId);
                await blobSmall.DeleteAsync();

                Trace.TraceInformation("Deleting MEDIUM image with ImageID = " + blobInfo.ImageId);
                await blobMedium.DeleteAsync();

                Trace.TraceInformation("Done processing 'deleterequest' message");
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error while deleting images: " + ex.Message);
            }
        }
Exemplo n.º 2
0
        public async Task <CommitBlobResponse> Post([FromBody] CommitBlobRequest commitBlobRequest)
        {
            var    res     = new CommitBlobResponse();
            var    cs      = new ContosoStorage();
            string fileExt = BlobInformation.DEFAULT_FILE_EXT;

            fileExt = cs.CommitUpload(commitBlobRequest);

            var    url           = commitBlobRequest.SasUrl.Replace(AppSettings.StorageWebUri, "");
            var    urldata       = url.Split('?');
            var    index         = urldata[0].IndexOf('/');
            var    content       = urldata[0].Split('/');
            var    containerName = urldata[0].Substring(0, index);
            string fileGuidName  = urldata[0].Replace(containerName + "/lg/", "").Replace(".temp", "");

            var ibl   = new ImageBusinessLogic();
            var image = ibl.AddImageToDB(commitBlobRequest.AlbumId, commitBlobRequest.UserId, containerName, fileGuidName + "." + fileExt, commitBlobRequest.IsMobile);

            if (image != null)
            {
                res.Success = true;
                res.ImageId = image.Id;
            }

            var qm       = new QueueManager();
            var blobInfo = new BlobInformation(fileExt);

            blobInfo.BlobUri = cs.GetBlobUri(containerName, urldata[0].Replace(containerName, ""));
            blobInfo.ImageId = fileGuidName;
            await qm.PushToResizeQueue(blobInfo);

            return(res);
        }
Exemplo n.º 3
0
        public static void GenerateThumbnail(
            [QueueTrigger("thumbnailrequest")] BlobInformation blobInfo,
            [Blob("images/{BlobName}", FileAccess.Read)] Stream input,
            [Blob("images/{BlobNameWithoutExtension}_thumbnail.jpg")] CloudBlockBlob outputBlob)
        {
            using (Stream output = outputBlob.OpenWrite())
            {
                ConvertImageToThumbnailJPG(input, output);
                outputBlob.Properties.ContentType = "image/jpeg";
            }

            // Entity Framework context class is not thread-safe, so it must
            // be instantiated and disposed within the function.
            using (ContosoAdsContext db = new ContosoAdsContext())
            {
                var id = blobInfo.AdId;
                Ad  ad = db.Ads.Find(id);
                if (ad == null)
                {
                    throw new Exception(String.Format("AdId {0} not found, can't create thumbnail", id.ToString()));
                }
                ad.ThumbnailURL = outputBlob.Uri.ToString();
                db.SaveChanges();
            }
        }
 public void SetBlobInformation(BlobInformation blobinformation)
 {
     Logger.Log("azureBlobUrl= " + blobinformation.azureBlobUrl);
     Logger.Log("Before SetBlobInformation: " + _blobInformation.azureBlobUrl);
     _blobInformation = blobinformation;
     Logger.Log("After SetBlobInformation: " + _blobInformation.azureBlobUrl);
 }
Exemplo n.º 5
0
        public async Task PushToResizeQueue(BlobInformation blobInformation)
        {
            //var namespaceManager = NamespaceManager.CreateFromConnectionString(AppSettings.ServiceBusConnectionString);

            //if (!namespaceManager.QueueExists(AppSettings.ResizeQueueName))
            //{
            //    namespaceManager.CreateQueue(AppSettings.ResizeQueueName);
            //}
            //QueueClient Client = QueueClient.CreateFromConnectionString(AppSettings.ServiceBusConnectionString, AppSettings.ResizeQueueName);
            //Client.Send(new BrokeredMessage(blobInformation));

            try
            {
                CloudStorageAccount account;
                string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AppSettings.StorageAccountName, AppSettings.StorageAccountKey);

                if (CloudStorageAccount.TryParse(storageConnectionString, out account))
                {
                    CloudQueueClient queueClient = account.CreateCloudQueueClient();
                    CloudQueue resizeRequestQueue = queueClient.GetQueueReference(AppSettings.ResizeQueueName);
                    resizeRequestQueue.CreateIfNotExists(); 

                    var queueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(blobInformation));
                    await resizeRequestQueue.AddMessageAsync(queueMessage);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Exception in QueueManager.PushToQueue => " + ex.Message);
            }

        }
Exemplo n.º 6
0
        //   private const string resizeQueue = AppSettings.ResizeQueueName;
        #region Queue handlers
        public async static Task StartImageScalingAsync([QueueTrigger("resizerequest")] BlobInformation blobInfo,
                                                        [Blob("{BlobName}/{BlobNameLG}")] CloudBlockBlob blobInput,
                                                        [Blob("{BlobName}/{BlobNameXS}")] CloudBlockBlob blobOutputExtraSmall,
                                                        [Blob("{BlobName}/{BlobNameSM}")] CloudBlockBlob blobOutputSmall,
                                                        [Blob("{BlobName}/{BlobNameMD}")] CloudBlockBlob blobOutputMedium)
        {
            Stream input = await blobInput.OpenReadAsync();

            Trace.TraceInformation("Scaling " + blobInfo.ImageId + " to MEDIUM size");
            bool res = await scaleImage(input, blobOutputMedium, Medium, blobInput.Properties.ContentType);

            TraceInfo(blobInfo.ImageId, "MEDIUM", res);

            input.Position = 0;
            Trace.TraceInformation("Scaling " + blobInfo.ImageId + " to SMALL size");
            res = await scaleImage(input, blobOutputSmall, Small, blobInput.Properties.ContentType);

            TraceInfo(blobInfo.ImageId, "SMALL", res);

            input.Position = 0;
            Trace.TraceInformation("Scaling " + blobInfo.ImageId + " to EXTRA SMALL size");
            res = await scaleImage(input, blobOutputExtraSmall, ExtraSmall, blobInput.Properties.ContentType);

            TraceInfo(blobInfo.ImageId, "EXTRA SMALL", res);


            input.Dispose();
            Trace.TraceInformation("Done processing 'resizerequest' message");
        }
Exemplo n.º 7
0
        public static void GenerateThumbnail(
            [QueueTrigger(AzureConfig.ThumbnailQueueName)] BlobInformation blobInfo,
            [Blob("images/{BlobName}", FileAccess.Read)] Stream input,
            [Blob("images/{BlobNameWithoutExtension}_thumbnail.jpg")] CloudBlockBlob outputBlob)
        {
            using (Stream output = outputBlob.OpenWrite())
            {
                ConvertImageToThumbnailJpeg(input, output);
                outputBlob.Properties.ContentType = "image/jpeg";
            }

            // Entity Framework context class is not thread-safe, so it must
            // be instantiated and disposed within the function.
            using (var db = new GoodEntities())
            {
                var id = blobInfo.AdId;
                var ad = db.Ads.Find(id);
                if (ad == null)
                {
                    throw new ArgumentException($"Ad (Id={id}) not found, can't create thumbnail");
                }
                ad.Thumbnail_Url = outputBlob.Uri.ToString();
                db.SaveChanges();
            }
        }
Exemplo n.º 8
0
        public async Task Post(JObject body)
        {
            string imageId   = body["imageId"].ToString();
            string extension = body["extension"].ToString();
            var    qm        = new QueueManager();
            var    blobInfo  = new BlobInformation(extension);

            blobInfo.BlobUri = new Uri(string.Format("https://{0}.blob.core.windows.net", AppSettings.StorageAccountName));
            blobInfo.ImageId = imageId;

            await qm.PushToResizeQueue(blobInfo);

            Trace.WriteLine("Sent resize request for blob: " + imageId);
        }
Exemplo n.º 9
0
        //creating a queue called "thumbnailrequest" and pushing imageUrl from blob and employee id.
        private void PostMessageToQueue(int empId, string imageUrl)
        {
            var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"].ToString());
            //To create the Queue with BlobInformation
            CloudQueueClient queueClient           = storageAccount.CreateCloudQueueClient();
            CloudQueue       thumbnailRequestQueue = queueClient.GetQueueReference("thumbnailrequest");

            thumbnailRequestQueue.CreateIfNotExists();
            BlobInformation blobInfo = new BlobInformation()
            {
                EmpId = empId, BlobUri = new Uri(imageUrl)
            };
            var queueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(blobInfo));

            thumbnailRequestQueue.AddMessage(queueMessage);
        }
        private async Task PostToQueue(string blobName)
        {
            var    fileNameParts = blobName.Split('.');
            string imageId       = fileNameParts[0];
            string extension     = fileNameParts.Length > 1 ? fileNameParts[1] : "";

            var qm       = new QueueManager();
            var blobInfo = new BlobInformation(extension);

            blobInfo.BlobUri = new Uri(string.Format("https://{0}.blob.core.windows.net", AppSettings.StorageAccountName));
            blobInfo.ImageId = imageId;

            await qm.PushToResizeQueue(blobInfo);

            Trace.WriteLine("Sent resize request for blob: " + imageId);
        }
Exemplo n.º 11
0
        // DELETE tables/Images/48D68C86-6EA6-4C25-AA33-223FC9A27959
        public async Task DeleteImage(string id)
        {
            var image         = Lookup(id).Queryable.First();
            var filenameParts = image.FileName.Split('.');
            var filename      = filenameParts[0];
            var fileExt       = filenameParts[1];
            var containerName = image.ContainerName;

            var qm       = new QueueManager();
            var blobInfo = new BlobInformation(fileExt);

            blobInfo.BlobUri = new Uri(containerName);
            blobInfo.ImageId = filename;
            await qm.PushToDeleteQueue(blobInfo);

            await DeleteAsync(id);

            return;
        }
Exemplo n.º 12
0
        public async Task <ActionResult> Create(
            [Bind(Include = "Title,Price,Description,Category,Phone")] Ad ad,
            HttpPostedFileBase imageFile)
        {
            CloudBlockBlob imageBlob = null;

            if (ModelState.IsValid)
            {
                if (imageFile != null && imageFile.ContentLength != 0)
                {
                    imageBlob = await UploadBlobAsync(imageFile);

                    ad.ImageUrl = imageBlob.Uri.ToString();
                }

                ad.PostedDate = DateTime.Now;

                _adContext.Ads.Add(ad);
                await _adContext.SaveChangesAsync();

                Trace.TraceInformation("Created AdId {0} in database", ad.AdId);

                if (imageBlob != null)
                {
                    var blobInfo = new BlobInformation()
                    {
                        AdId    = ad.AdId,
                        BlobUri = new Uri(ad.ImageUrl)
                    };

                    var queueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(blobInfo));
                    await _requestQueue.AddMessageAsync(queueMessage);

                    Trace.TraceInformation("Created queue message for AdId {0}", ad.AdId);
                }
                return(RedirectToAction("Index"));
            }
            return(View(ad));
        }
Exemplo n.º 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="DocObj">При записи в БД нового обьекта, DocObj это новый обьект созданный предварительным вызовом CreateDoc(); при добавлении файла к существующей сборке, DocObj - обьект сборки"</param>
        /// <param name="filePath"></param>
        private void Blob(ref IDBObject DocObj, MyStruct _object)
        {
            if (_object.Flag == 5)// пишем Blob не в новый документ, а в сборку
            {
                DocObj = createdDocs.Where(x => x.Key.Equals(_object.RefAsmName)).Select(y => y.Value).First();
            }

            int          attrFile = MetaDataHelper.GetAttributeTypeID(new Guid(SystemGUIDs.attributeFile));// атрибут "Файл"
            IDBAttribute fileAtr  = DocObj.GetAttributeByID(attrFile);

            if (fileAtr.Values.Count() >= 1)
            {
                fileAtr.AddValue(_object.Path);
            }
            using (var ms = new MemoryStream(File.ReadAllBytes(_object.Path)))
            {
                BlobInformation blInfo = new BlobInformation(0, 0, DateTime.Now, _object.Path, ArcMethods.NotPacked, null);
                BlobProcWriter  writer = new BlobProcWriter(fileAtr, (int)AttributableElements.Object, blInfo, ms, null, null);

                writer.WriteData();
            }
        }
Exemplo n.º 14
0
        public async Task PushToDeleteQueue(BlobInformation blobInformation)
        {
            try
            {
                CloudStorageAccount account;
                string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AppSettings.StorageAccountName, AppSettings.StorageAccountKey);

                if (CloudStorageAccount.TryParse(storageConnectionString, out account))
                {
                    CloudQueueClient queueClient        = account.CreateCloudQueueClient();
                    CloudQueue       deleteRequestQueue = queueClient.GetQueueReference(AppSettings.DeleteQueueName);
                    deleteRequestQueue.CreateIfNotExists();

                    var queueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(blobInformation));
                    await deleteRequestQueue.AddMessageAsync(queueMessage);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Exception in QueueManager.PushToQueue => " + ex.Message);
            }
        }
        public async Task <ActionResult> Edit(
            [Bind(Include = "AdId,Title,Price,Description,ImageURL,ThumbnailURL,PostedDate,Category,Phone")] Ad ad,
            HttpPostedFileBase imageFile)
        {
            CloudBlockBlob imageBlob = null;

            if (ModelState.IsValid)
            {
                if (imageFile != null && imageFile.ContentLength != 0)
                {
                    // User is changing the image -- delete the existing
                    // image blobs and then upload and save a new one.
                    await DeleteAdBlobsAsync(ad);

                    imageBlob = await UploadAndSaveBlobAsync(imageFile);

                    ad.ImageURL = imageBlob.Uri.ToString();
                }
                db.Entry(ad).State = EntityState.Modified;
                await db.SaveChangesAsync();

                Trace.TraceInformation("Updated AdId {0} in database", ad.AdId);

                if (imageBlob != null)
                {
                    BlobInformation blobInfo = new BlobInformation()
                    {
                        AdId = ad.AdId, BlobUri = new Uri(ad.ImageURL)
                    };
                    var queueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(blobInfo));
                    await thumbnailRequestQueue.AddMessageAsync(queueMessage);

                    Trace.TraceInformation("Created queue message for AdId {0}", ad.AdId);
                }
                return(RedirectToAction("Index"));
            }
            return(View(ad));
        }
Exemplo n.º 16
0
        public async Task <ActionResult> Create(
            [Bind(Include = "Title,Price,Description,Category,Phone")] Ad ad,
            HttpPostedFileBase imageFile)
        {
            CloudBlockBlob imageBlob = null;

            // A production app would implement more robust input validation.
            // For example, validate that the image file size is not too large.
            if (ModelState.IsValid)
            {
                if (imageFile != null && imageFile.ContentLength != 0)
                {
                    imageBlob = await UploadAndSaveBlobAsync(imageFile);

                    ad.ImageURL = imageBlob.Uri.ToString();
                }
                ad.PostedDate = DateTime.Now;
                db.Ads.Add(ad);
                await db.SaveChangesAsync();

                Trace.TraceInformation("Created AdId {0} in database", ad.AdId);

                if (imageBlob != null)
                {
                    BlobInformation blobInfo = new BlobInformation()
                    {
                        AdId = ad.AdId, BlobUri = new Uri(ad.ImageURL)
                    };
                    var queueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(blobInfo));
                    await thumbnailRequestQueue.AddMessageAsync(queueMessage);

                    Trace.TraceInformation("Created queue message for AdId {0}", ad.AdId);
                }
                return(RedirectToAction("Index"));
            }

            return(View(ad));
        }
Exemplo n.º 17
0
        public async Task PushToDeleteQueue(BlobInformation blobInformation)
        {
            try
            {
                CloudStorageAccount account;
                string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AppSettings.StorageAccountName, AppSettings.StorageAccountKey);

                if (CloudStorageAccount.TryParse(storageConnectionString, out account))
                {
                    CloudQueueClient queueClient = account.CreateCloudQueueClient();
                    CloudQueue deleteRequestQueue = queueClient.GetQueueReference(AppSettings.DeleteQueueName);
                    deleteRequestQueue.CreateIfNotExists();

                    var queueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(blobInformation));
                    await deleteRequestQueue.AddMessageAsync(queueMessage);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Exception in QueueManager.PushToQueue => " + ex.Message);
            }

        }
Exemplo n.º 18
0
        public static void GenerateThumbnail(
            [QueueTrigger("thumbnailrequest-poison")] BlobInformation blobInfo,
            [Blob("images/{BlobName}", FileAccess.Read)] Stream input,
            [Blob("images/{BlobNameWithoutExtension}_thumbnail.jpg")] CloudBlockBlob outputBlob, ILogger log)
        {
            using (Stream output = outputBlob.OpenWrite())
            {
                ConvertImageToThumbnailJPG(input, output);
                outputBlob.Properties.ContentType = "image/jpeg";
            }

            using (MyDemoContext db = new MyDemoContext())
            {
                var      id  = blobInfo.EmpId;
                Employee emp = db.Employees.Find(id);
                if (emp == null)
                {
                    throw new Exception(String.Format("EmpId: {0} not found, can't create thumbnail", id.ToString()));
                }
                emp.ThumbnailURL = outputBlob.Uri.ToString();
                db.SaveChanges();
            }
        }
Exemplo n.º 19
0
        //POST: Ad/Create
        public async Task <ActionResult> Create(
            [Bind(Include = "Title,Proce,Description,Category,Phone")] Ad ad,
            HttpPostedFileBase imageFile)
        {
            if (ModelState.IsValid)
            {
                CloudBlockBlob imageBlob = null;

                if (imageFile != null && imageFile.ContentLength != 0)
                {
                    Trace.TraceInformation("Uploading imagefile {0}", imageFile.FileName);
                    imageBlob = await UploadAndSaveBlobAsync(imageFile);

                    ad.ImageURL = imageBlob.Uri.ToString();
                }
                ad.PostedDate = DateTime.Now;
                db.Ads.Add(ad);
                await db.SaveChangesAsync();

                Trace.TraceInformation("Created AdId {0} in database", ad.AdId);

                if (imageBlob != null)
                {
                    Trace.TraceInformation("Creating queue message for AdId {0}", ad.AdId);
                    BlobInformation blobInfo = new BlobInformation {
                        AdId = ad.AdId, BlobUri = imageBlob.Uri
                    };
                    await thumbmailRequestQueue.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(blobInfo)));

                    Trace.TraceInformation("Created queue message for AdId {0}", ad.AdId);
                }

                return(RedirectToAction("Index"));
            }

            return(View(ad));
        }
Exemplo n.º 20
0
        public static void GenerateThumbnail(
            [QueueTrigger("thumbnailrequest")] BlobInformation blobInfo,
            [Blob("images/{BlobName}", FileAccess.Read)] Stream input,
            [Blob("images/{BlobNameWithoutExtension}_thumbnail.jpg")] CloudBlockBlob outputBlob)
        {
            using (Stream output = outputBlob.OpenWrite())
            {
                ConvertImageToThumbnailJpg(input, output);
                outputBlob.Properties.ContentType = "image/jpeg";
            }

            using (AdContext adContext = new AdContext())
            {
                var ad = adContext.Ads.Find(blobInfo.AdId);

                if (ad == null)
                {
                    throw new Exception(String.Format("Cannot create thumbnail for AdId {0}", blobInfo.AdId));
                }

                ad.ThumbnailUrl = outputBlob.Uri.ToString();
                adContext.SaveChanges();
            }
        }