예제 #1
0
        public async Task Upload([ActivityTrigger] BlobModel input, Binder binder)
        {
            // Use a binder to dynamically set the binding output path
            using Stream fileOutputStream = await binder.BindAsync <Stream>(FunctionUtils.GetBindingAttributes(input.Analysis.Category, input.Name));

            await fileOutputStream.WriteAsync(input.Blob, 0, input.Blob.Length);
        }
예제 #2
0
        public async Task <Result <BlobModel> > Get(string id)
        {
            bool      ok      = false;
            string    message = "";
            BlobModel model   = null;

            try
            {
                var key = new PartitionKey(_partitionId + "_" + _userInfo.UserId);
                model = await RepositoryContainer.ReadItemAsync <BlobModel>(id, key);

                ok = true;
            }
            catch (CosmosException e)
            {
                if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    message = Enum.GetName(typeof(System.Net.HttpStatusCode), System.Net.HttpStatusCode.NotFound);
                }
                else
                {
                    message = e.Message;
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return(_result.Create(ok, message, model));
        }
예제 #3
0
        public async Task <IActionResult> CreateBlob(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "Blobs/Create")] HttpRequestMessage req,
            HttpRequest request, ILogger log)
        {
            var resultAuth = validAuthorized(req, request);

            if (!resultAuth.Success)
            {
                if (resultAuth.Message == _errors.NotAuthorized)
                {
                    return(new UnauthorizedResult());
                }
                else
                {
                    var objectResult = new ObjectResult(resultAuth.Message)
                    {
                        StatusCode = StatusCodes.Status401Unauthorized
                    };

                    return(objectResult);
                }
            }

            BlobModel data = await req.Content.ReadAsAsync <BlobModel>();

            var dataResult = await _controller.Create(data);

            if (!dataResult.Success)
            {
                return(new BadRequestObjectResult(dataResult.Message));
            }

            return(new OkObjectResult(dataResult.Value));
        }
        public async Task ZipIt([ActivityTrigger] BlobModel input, Binder binder)
        {
            SemaphoreSlim semaphore = GetSemaphoreForContainer(input.Analysis.Category);
            await semaphore.WaitAsync();

            try
            {
                string name = $"{input.Analysis.Category}.zip";
                using Stream zipStream = await binder.BindAsync <Stream>(FunctionUtils.GetBindingAttributes("zip-collection", name));

                using var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true);
                BlobContainerClient containerClient = GetCloudBlobContainer(input.Analysis.Category);
                containerClient.DeleteBlobIfExists(name);

                Pageable <BlobItem> blobs = containerClient.GetBlobs();

                foreach (BlobItem blob in blobs)
                {
                    BlobClient client = containerClient.GetBlobClient(blob.Name);
                    using var blobStream = new MemoryStream();
                    client.DownloadTo(blobStream);
                    using Stream entryStream = archive.CreateEntry(blob.Name).Open();
                    blobStream.Seek(0, SeekOrigin.Begin);
                    blobStream.CopyTo(entryStream);
                }
            }
            finally
            {
                semaphore.Release();
            }
        }
예제 #5
0
        public async Task <Result <string> > Update(BlobModel item)
        {
            bool   ok      = false;
            string message = "";

            try
            {
                UpdateMetadata(item, false);
                var tenatId = new PartitionKey(_partitionId + "_" + _userInfo.UserId);
                await RepositoryContainer.ReplaceItemAsync <dynamic>(item, item.id, tenatId,
                                                                     new ItemRequestOptions { });

                ok = true;
            }
            catch (CosmosException ex)
            {
                message = ex.Message;
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return(_result.Create <string>(ok, message, ""));
        }
예제 #6
0
        public async Task <Result <string> > Create(BlobModel item)
        {
            bool   ok      = false;
            string message = "";

            try
            {
                item.id = Guid.NewGuid().ToString();
                UpdateMetadata(item, true);
                var tenatId = new PartitionKey(_partitionId + "_" + _userInfo.UserId);
                await RepositoryContainer.CreateItemAsync <BlobModel>(item, tenatId);

                message = item.id;

                ok = true;
            }
            catch (CosmosException ex)
            {
                message = ex.Message;
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return(_result.Create <string>(ok, message, message));
        }
예제 #7
0
        // POST api/file
        public async Task <IEnumerable <InputImageDTO> > Post()
        {
            var tempPath = Path.GetTempPath();
            var provider = new MultipartFormDataStreamProvider(tempPath);

            await this.Request.Content.ReadAsMultipartAsync(provider);

            var list = new List <InputImageDTO>();

            foreach (var file in provider.FileData)
            {
                // アップロードファイル名の取得
                // var fileName = file.Headers.ContentDisposition.FileName;
                // fileName = fileName.StartsWith("\"") || fileName.StartsWith("'") ? fileName.Substring(1, fileName.Length - 1) : fileName;
                // fileName = fileName.EndsWith("\"") || fileName.EndsWith("'") ? fileName.Substring(0, fileName.Length - 1) : fileName;
                // fileName = Path.GetFileName(fileName);

                // ファイル名は乱数を入れておく
                Guid   g       = System.Guid.NewGuid();
                string imageId = g.ToString("N").Substring(0, 15);

                // ファイルの移動
                // File.Move(file.LocalFileName, Path.Combine("C:\\temp\\", fileName));
                BlobModel.Upload(imageId, file.LocalFileName);

                InputImageModel.Create(imageId);

                list.Add(new InputImageDTO()
                {
                    ImageId = imageId
                });
            }

            return(list);
        }
예제 #8
0
        public async Task <BlobUploadModel> Upload(Guid userId, string fileName, Stream fileStream, string contentType = "application/jpeg")
        {
            ExceptionHelper.ThrowArgumentNullIfEmpty(userId, nameof(userId));
            ExceptionHelper.ThrowParameterNullIfEmpty(fileName, nameof(fileName));

            var blobName   = GetFullBlobName(userId);
            var blobClient = GetBlobClient(userId, blobName);

            var response = await blobClient.UploadAsync(fileStream,
                                                        new BlobHttpHeaders
            {
                ContentType = contentType
            });

            ExceptionHelper.ThrowNotFoundIfEmpty(response, "Blob");

            var createModel = new BlobModel
            {
                ImageName = fileName,
                UserId    = userId
            };

            var createdBlob = await _blobDataService.Create(createModel, blobName);

            var result = new BlobUploadModel
            {
                Blob            = createdBlob,
                BlobContentInfo = response.Value
            };

            return(result);
        }
        public ActionResult EditForm(Form formModel, HttpPostedFileBase formFile)
        {
            formModel.DateAdded = DateTime.Now;
            if (ModelState.IsValid)
            {
                if (FileVerification.IsFileAPDF(formFile) == "not")
                {
                    ViewBag.errorMessage = "Please upload pdf file only.";
                    return(View(formModel));
                }
                else
                {
                    websiteActions.UpdateForm(formModel);

                    if (formFile != null)
                    {
                        string fileName = websiteActions.UploadFormBlobFile(formFile);

                        string urlFileName = System.Web.HttpUtility.UrlPathEncode(fileName);

                        BlobModel blobModel = websiteActions.getAzureFormsObject().GetBlobs().Where(blob => blob.FileName == urlFileName).FirstOrDefault();
                        blobModel.FileName = HttpUtility.UrlDecode(blobModel.FileName);
                        websiteActions.InsertFormToFormResource(formModel, blobModel);
                    }

                    return(RedirectToAction("Forms", "Admin"));
                }
            }
            else
            {
                return(View(formModel));
            }
        }
예제 #10
0
        public static async Task DeleteBlob(
            ApplicationDbContext context, int id)
        {
            var blob = new BlobModel {
                ID = id
            };

            context.Entry(blob).State = EntityState.Deleted;
            await context.SaveChangesAsync();
        }
        public async Task <AnalysisResult> Analyze([ActivityTrigger] BlobModel input)
        {
            using var image = new MemoryStream(input.Blob);
            ImageAnalysis analysis = await VisionClient.AnalyzeImageInStreamAsync(image, Features);

            return(new AnalysisResult
            {
                Category = AnalyseCategory(analysis),
                Brand = AnalyseBrand(analysis),
                IsRejectedContent = IsRejectedContent(analysis)
            });
        }
예제 #12
0
        public Task <BlobModel> OpenReadBlobAsync(string blobContainer, string blobName)
        {
            var blockBlob = _redis.Get <byte[]>(blobName);

            var readModel = new BlobModel
            {
                BlobName        = blobName,
                Stream          = new MemoryStream(blockBlob),
                CurrentPosition = 0
            };

            return(Task.FromResult(readModel));
        }
 public async Task StartOrchestratorBlobTrigger(
     [BlobTrigger("uploads/{name}", Connection = "BlobStorageConnection")] Stream blob,
     string name,
     [DurableClient] IDurableOrchestrationClient starter)
 {
     BinaryReader binaryReader = new BinaryReader(blob);
     var          input        = new BlobModel
     {
         Blob = binaryReader.ReadBytes((int)blob.Length),
         Name = name
     };
     await starter.StartNewAsync("UploadOrchestratorFunction", input);
 }
        public void InsertFormToFormResource(Form formModel, BlobModel blobModel)
        {
            int newFileID = InsertBlobToFileLocationStorage(blobModel, "Form");

            FormsResource formResource = new FormsResource()
            {
                FileID = newFileID,
                FormID = formModel.FormID
            };

            dbObject.FormsResources.Add(formResource);
            dbObject.SaveChanges();
        }
예제 #15
0
        public static async Task Main(string[] args)
        {
            var environment = Environment.GetEnvironmentVariable("ENVIRONMENT") ?? "DEV";

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
                                .AddEnvironmentVariables()
                                .Build();

            var services = new ServiceCollection();

            services.Configure <Settings>(configuration.GetSection(nameof(Settings)));
            services.AddSingleton <ISettings>(provider =>
            {
                var options = provider.GetService <IOptions <Settings> >();
                return(options.Value);
            });
            services.AddSingleton <IBlobClient, BlobClient>();

            var serviceProvider = services.BuildServiceProvider();
            var blobClient      = serviceProvider.GetService <IBlobClient>();

            var name      = $"{Guid.NewGuid()}.txt";
            var blobModel = new BlobModel <TvShow>
            {
                Name    = name,
                Content = new TvShow
                {
                    Id           = "#1",
                    Name         = "OnePunchMan",
                    CreationDate = DateTime.UtcNow
                },
                Metadata = new Dictionary <string, string>
                {
                    ["Author"] = "One"
                }
            };

            await blobClient.SaveBlobAsync <BlobModel <TvShow>, TvShow>(blobModel);

            Console.WriteLine($"Blob '{blobModel.Name}' is uploaded");

            var blobFound = await blobClient.GetBlobAsync <BlobModel <TvShow>, TvShow>(name);

            Console.WriteLine($"Blob content '{blobFound.Content}' is found");

            Console.WriteLine("Press any key to exit !");
            Console.ReadKey();
        }
예제 #16
0
        public async Task <BlobModel> Update(Guid id, BlobModel model)
        {
            var entity = await _repository.GetById(id);

            ExceptionHelper.ThrowNotFoundIfEmpty(entity, nameof(Blob));

            entity.CategoryId = model.CategoryId;

            var updatedEntity = _repository.Update(entity);

            await _repository.Save();

            return(_mapper.Map <BlobModel>(updatedEntity));
        }
예제 #17
0
        // GET api/result/{id}
        public HttpResponseMessage Get(string id)
        {
            HttpResponseMessage response = Request.CreateResponse();

            MemoryStream ms = new MemoryStream();

            BlobModel.DownloadResult(id, ms);

            response.Content = new ByteArrayContent(ms.ToArray());
            // only jpeg
            response.Content.Headers.TryAddWithoutValidation("Content-Type", "image/png");

            return(response);
        }
예제 #18
0
        public Task <BlobModel> OpenWriteBlobAsync(string blobContainer, string blobName)
        {
            var stream = new MemoryStream();

            _redis.Set <byte[]>(blobName, null);

            var blobWriteModel = new BlobModel
            {
                BlobName = blobName,
                Stream   = stream
            };

            return(Task.FromResult(blobWriteModel));
        }
        public async Task CreateThumbnail([ActivityTrigger] BlobModel input, Binder binder)
        {
            using Stream thumbnail = await binder.BindAsync <Stream>(FunctionUtils.GetBindingAttributes($"{input.Analysis.Category}-thumbs", input.Name));

            using Image <Rgba32> image = Image.Load(input.Blob);
            image.Mutate(i =>
            {
                i.Resize(340, 0);
                int height = i.GetCurrentSize().Height;
                i.Crop(new Rectangle(0, 0, 340, height < 226 ? height : 226));
            });

            image.SaveAsJpeg(thumbnail);
        }
예제 #20
0
        public async Task <BlobModel> Create(BlobModel model, string blobName)
        {
            ExceptionHelper.ThrowParameterNullIfEmpty(model, "Blob model");
            ExceptionHelper.ThrowParameterNullIfEmpty(blobName, nameof(blobName));

            var mappedEntity = _mapper.Map <Blob>(model);

            mappedEntity.Name = blobName;

            var blob = await _repository.Create(mappedEntity);

            await _repository.Save();

            return(_mapper.Map <BlobModel>(blob));
        }
        private int InsertBlobToFileLocationStorage(BlobModel blobModel, string type)
        {
            FileLocationStorage locStorage = new FileLocationStorage()
            {
                DateAdded    = DateTime.Now,
                FileLocation = blobModel.FileURI,
                FileName     = blobModel.FileName,
                Type         = type.ToUpper()
            };

            dbObject.FileLocationStorages.Add(locStorage);
            dbObject.SaveChanges();

            return(locStorage.FileID);
        }
예제 #22
0
        public static async Task <int> SaveBlob(
            ApplicationDbContext context, IFormFile file)
        {
            var blob = new BlobModel
            {
                FileName = file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1),
                Content  = new byte[file.Length]
            };

            file.OpenReadStream().Read(blob.Content, 0, (int)file.Length);

            context.Add(blob);
            await context.SaveChangesAsync();

            return(blob.ID);
        }
        public void UploadRequestToResource(ValidationRequest requestModel, BlobModel blobModel)
        {
            //insert to file location storage
            //get id of the file location storage
            int fileID = InsertBlobToFileLocationStorage(blobModel, "Requirements");

            //upload resource
            RequestResource resource = new RequestResource()
            {
                RequestID = requestModel.RequestID,
                FileID    = fileID
            };

            dbObject.RequestResources.Add(resource);
            dbObject.SaveChanges();
        }
예제 #24
0
        public async Task <BlobModel> OpenReadBlobAsync(string blobContainer, string blobName)
        {
            var container = _storageAccount
                            .CreateCloudBlobClient()
                            .GetContainerReference(blobContainer);

            var blockBlob = container.GetBlockBlobReference(blobName: blobName);

            var blobReadModel = new BlobModel
            {
                BlobName        = blobName,
                Stream          = await blockBlob.OpenReadAsync(),
                CurrentPosition = 0
            };

            return(blobReadModel);
        }
 /*
  * Handles the uploading of photos to azure blob storage and announcement resource.
  * */
 private void UploadAnnouncementToDatabase(Announcement announcementModel, HttpPostedFileBase[] photos)
 {
     if (photos.Length >= 1)
     {
         foreach (var photo in photos)
         {
             if (photo != null)
             {
                 string    fileName    = websiteActions.UploadAnnouncementBlobFile(photo);
                 string    urlFileName = System.Web.HttpUtility.UrlPathEncode(fileName);
                 BlobModel blobModel   = websiteActions.getAzureAnnouncementsObject().GetBlobs().Where(blob => blob.FileName == urlFileName).FirstOrDefault();
                 blobModel.FileName = HttpUtility.UrlDecode(blobModel.FileName);
                 websiteActions.InsertPhotoToAnnouncementResources(announcementModel, blobModel);
             }
         }
     }
 }
예제 #26
0
        public static async Task RunOrchestrator(
            [OrchestrationTrigger] IDurableOrchestrationContext context)
        {
            BlobModel blob = context.GetInput <BlobModel>();

            blob.ApplyAnalysis(await context.CallActivityAsync <AnalysisResult>("ImageAnalyzationFunction", blob));

            var tasks = new List <Task>();

            // Using a FanOut/FanIn strategy to process all activities in parrallel
            AddThumbnailTask(tasks, context, blob);
            AddUploadTask(tasks, context, blob);
            AddZipTask(tasks, context, blob);

            await Task.WhenAll(tasks);

            await context.CallActivityAsync("CleanupFunction", blob);
        }
예제 #27
0
        public async Task <BlobModel> OpenWriteBlobAsync(string blobContainer, string blobName)
        {
            var container = _storageAccount
                            .CreateCloudBlobClient()
                            .GetContainerReference(blobContainer);

            await container.CreateIfNotExistsAsync();

            var blockBlob = container.GetBlockBlobReference(blobName: blobName);

            var blobWriteModel = new BlobModel
            {
                BlobName = blobName,
                Stream   = await blockBlob.OpenWriteAsync()
            };

            return(blobWriteModel);
        }
예제 #28
0
        public async Task <IActionResult> ViewDoctor()
        {
            var userid   = _userManager.GetUserId(User);
            var clinicid = (from a in _context.Clinic
                            where a.UserID.Equals(userid)
                            select a.Id).Single();
            var clinicname = (from a in _context.Clinic
                              where a.Id.Equals(clinicid)
                              select a.ClinicName).Single();

            var model  = new BlobModel();
            var result = (from a in _context.Doctor
                          where a.Clinic_Id.Equals(clinicid)
                          select new BlobModel()
            {
                id = a.id,
                DoctorName = a.DoctorName,
                DoctorContactNumber = a.DoctorContactNumber,
                imgurl = a.profileImage,
                clinic_name = clinicname,
                clinic_id = clinicid
            }).ToList();

            model.doctor = result;
            if (result.Count() != 0)
            {
                model.profileImage = await _azureBlobService.ListAsync("view", model);
            }

            else
            {
                AzureBlobService.blob_files = null; return(View(model));
            }

            if (model.profileImage.Count().Equals(0))
            {
                AzureBlobService.blob_files = null;
            }
            //dynamic mymodel = new ExpandoObject();

            return(View(model));
        }
 public IActionResult OnGetDownloadBlob(string containerName, string blobName)
 {
     try
     {
         BlobModel blob = _blobStorageService.GetBlobContents(containerName, blobName);
         return(new FileStreamResult(blob.Content, blob.ContentType)
         {
             FileDownloadName = blob.Name
         });
     }
     catch (ApplicationException ex)
     {
         MessageModel message = new MessageModel()
         {
             Level = MessageLevel.Warning, Message = ex.Message
         };
         TempData.Put <MessageModel>("Message", message);
     }
     return(RedirectToPage("index", "Get", new { container = SelectedContainer }));
 }
예제 #30
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Model init
            CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            BlobModel.Init(storageAccount);
            QueueModel.Init(storageAccount);
            ImageProcessJobModel.Init(storageAccount);
            InputImageModel.Init(storageAccount);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
예제 #31
0
        public async Task<object> QueryUserID(Game game, string token, HttpRequest request)
        {
            string oauthIDList = request.Params["onlyIDlist"];
            string tokenRawString = game.id.ToString() + request.Params["action"] + oauthIDList + game.guid + request.Params["tstamp"];
            string generatedToken = Helper.CalculateMD5Hash(tokenRawString);
            if (string.Compare(token, generatedToken, true) != 0)
                return FailResult(ErrorCodes.INVALID_TOKEN.ToErrorMessage());

            var param = new Dictionary<string, string>()
            {
                {ConstantValues.S_GAME_ID, game.guid},
                {ConstantValues.S_IP_ADDRESS, request.UserHostAddress},
                {ConstantValues.S_OAUTH_ID, string.Empty},
            };
            List<BlobModel> responseBlob = new List<BlobModel>();
            var api = GoplayService.Instance;
            foreach (var oauthID in oauthIDList.Split(','))
            {
                param[ConstantValues.S_OAUTH_ID] = oauthID;
                var result = await api.SendAPIRequest<ResultResponse>(param, EGoPlayAction.QueryUserId, true);
                if (result != null && result.success)
                {
                    BlobModel blob = new BlobModel()
                    {
                        uid = result.user_id,
                        otherID = oauthID
                    };
                    responseBlob.Add(blob);
                }
            }
            return new
            {
                success = true,
                list = responseBlob
            };
        }