public LocationCreatedReceiver(IConfiguration configuration, ILogger <ServiceBusReceiver> logger,
                                UserLocationsService userLocationsService, AzureBlobService azureBlobService) : base(configuration, logger)
 {
     this.logger = logger;
     this.userLocationsService = userLocationsService;
     this.azureBlobService     = azureBlobService;
 }
예제 #2
0
        public string modify([FromBody] DocumentHeader documentHeader)
        {
            IBlobService blobService  = new AzureBlobService();
            var          blobContents = blobService.getBlobContents(blobContainerConnString, blobContainerName, documentHeader.BlobItemName);
            var          tempGUID     = Guid.NewGuid().ToString();
            var          tempDocPath  = $"./local/{tempGUID}";

            System.IO.Directory.CreateDirectory(tempDocPath);
            System.IO.File.WriteAllBytes($"{tempDocPath}.docx", blobContents);

            var bookmarkReplacements = new Dictionary <string, string>();

            bookmarkReplacements.Add("Commentor_adresse", "Andevej 14");
            bookmarkReplacements.Add("Commentor_navn_header", "Anders And");
            bookmarkReplacements.Add("Commentor_navn_body", "Anders And");
            bookmarkReplacements.Add("Commentor_registreringsnummer", "1234 1234512345");
            bookmarkReplacements.Add("Commentor_dato", DateTime.Now.ToString("dd.MM.yyyy"));
            bookmarkReplacements.Add("Commentor_bodytext", documentHeader.BodyText);
            openDocument.ReplaceBookmarks($"{tempDocPath}.docx", $"{tempDocPath} - REPLACED.docx", bookmarkReplacements);

            var htmlSimpleInputBytes = System.IO.File.ReadAllBytes($"{tempDocPath} - REPLACED.docx");
            var serviceUser          = docProvider.GetUser("*****@*****.**");

            byte[] pdfHTMLSimpleDocBytes = docProvider.ConvertDocumentToPDF(htmlSimpleInputBytes, $"Temp/{Guid.NewGuid()}.docx", serviceUser.Id);
            System.IO.File.WriteAllBytes($"{tempDocPath} - REPLACED.pdf", pdfHTMLSimpleDocBytes);

            return(tempGUID);
        }
예제 #3
0
        public static BlobServiceProvider GetBlobServiceProviders(string serviceProvider)
        {
            BlobServiceProvider serviceprovider = null;

            /*BlobStorage serviceProvider = _context.BlobStorages.Where(blob =>
             *                                     blob.BlobStorageTypeId == (_context.Companies.Where(comp => comp.id == companyId))
             *                                     .FirstOrDefault().BlobStorageTypeId)
             *                                     .FirstOrDefault<BlobStorage>();
             */
            if (!string.IsNullOrEmpty(serviceProvider))
            {
                switch (serviceProvider.ToUpper())
                {
                case "AZURE":
                    serviceprovider = new AzureBlobService();
                    break;

                case "AMAZONS3":
                    serviceprovider = new AmazonS3BlobService();
                    break;

                default: throw new Exception("No BLOB storage provider found for this company.");
                }
            }

            return(serviceprovider);
        }
예제 #4
0
        }//end CaptureToFile

        /// <summary>
        /// Upload the Picture to Blob
        /// </summary>
        private async void UploadToBlob() //TODO: AndDeleteFile
        {
            //Upload to Azure Blob

            // User cancelled
            if (file == null)
            {
                return;
            }

            // Prepare the photo
            IRandomAccessStream irandom = await file.OpenAsync(FileAccessMode.Read);

            BitmapImage bitmapImage = new BitmapImage();
            await bitmapImage.SetSourceAsync(irandom);

            string faToken = null;

            faToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);

            // Set the Token and Add it to the list
            await AzureBlobService.UploadImageFromImageToken(faToken, fileNameWithType);


            //Delete the file
            //file.DeleteAsync();
            await CleanupCameraAsync();
        }
예제 #5
0
        public async Task <string> UploadPhotoAsync(Photo photo)
        {
            var blobService = new AzureBlobService();

            return(await blobService.UploadFileAsync(photo.FileName,
                                                     photo.BinaryContent, photo.ContainerName,
                                                     photo.ContentType));
        }
예제 #6
0
 public HomeController(IWebHostEnvironment hostEnvironment,
                       ILogger <HomeController> logger,
                       IIguanaTrackerService iguanaTrackerService,
                       BlobServiceClient blobServiceClient)
 {
     _hostEnvironment      = hostEnvironment;
     _logger               = logger;
     _iguanaTrackerService = iguanaTrackerService;
     _azureBlobService     = new AzureBlobService(blobServiceClient, "iguana-image-container");
 }
 public UsersController(UserLocationsService locationService,
                        ILogger <UsersController> logger,
                        IConfiguration config,
                        AzureBlobService azureBlobService,
                        LocationCreatedSender locationCreatedSender
                        )
 {
     this.locationService       = locationService;
     this.logger                = logger;
     this.config                = config;
     this.azureBlobService      = azureBlobService;
     this.locationCreatedSender = locationCreatedSender;
 }
예제 #8
0
        public List <String> getTemplates()
        {
            IBlobService blobService = new AzureBlobService();
            var          blobItems   = blobService.getBlobItems(blobContainerConnString, blobContainerName, 10);
            var          blobNames   = new List <String>();

            foreach (var blobItem in blobItems)
            {
                blobNames.Add(((CloudBlockBlob)blobItem).Name);
            }

            return(blobNames);
        }
예제 #9
0
        public static IServiceCollection AddBlobServiceClient(this IServiceCollection services, BlobServiceOptions options)
        {
            services.AddSingleton <IStorage>(provider =>
            {
                var blobContainerClient = new BlobContainerClient(options.ConnectionString, options.Container);
                var fileSystem          = provider.GetService <IFileSystem>();
                var logger    = provider.GetService <ILogger <StorageLoggerDecorator> >();
                var decorated = new AzureBlobService(blobContainerClient, fileSystem);

                return(new StorageLoggerDecorator(logger, decorated));
            });

            return(services);
        }
예제 #10
0
        public static void BreakContainerLeaseImmediately(
            SqlString accountName, SqlString sharedKey, SqlBoolean useHTTPS,
            SqlString containerName,
            SqlInt32 timeoutSeconds,
            SqlGuid xmsclientrequestId)
        {
            AzureBlobService abs  = new AzureBlobService(accountName.Value, sharedKey.Value, useHTTPS.Value);
            Container        cont = abs.GetContainer(containerName.Value);

            Responses.LeaseBlobResponse lbr = cont.BreakLeaseImmediately(
                timeoutSeconds.IsNull ? 0 : timeoutSeconds.Value,
                xmsclientrequestId.IsNull ? (Guid?)null : xmsclientrequestId.Value);

            PushLeaseBlobResponse(lbr);
        }
예제 #11
0
        private async void createWarningInfo(Person person)
        {
            WarningImage.Visibility = Visibility.Visible;

            //Dialog Appearance
            RiskGrid.Visibility               = Visibility.Visible;
            VideoStackPanel.Visibility        = Visibility.Visible;
            PersonDialog.Title                = "Stranger Warning Enquiry";
            PersonDialogPanel.BorderThickness = new Thickness(3, 3, 3, 3);

            //Show the Person's Data
            defaultImage.Source = await AzureBlobService.DisplayImageFile(person.DefaultImageAddress);

            //TODO: find a list of face images...
        }
예제 #12
0
        public async Task <IActionResult> GetAll()
        {
            int currentUserId = User.Claims.GetUserId();

            AzureBlobService blobService = new AzureBlobService();
            await blobService.InitializeBlob();

            var quizzes = quizRepository.GetQuizByUserId(currentUserId);

            foreach (var quiz in quizzes)
            {
                quiz.PictureUrl = blobService.urlPath.AbsoluteUri.ToString() + "users/" + quiz.PictureUrl;
            }

            return(Ok(quizzes.Select(quiz => this.entityToVmMapper.Map(quiz))));
        }
예제 #13
0
        public static void AcquireContainerInfiniteLease(
            SqlString accountName, SqlString sharedKey, SqlBoolean useHTTPS,
            SqlString containerName,
            SqlGuid proposedLeaseId,
            SqlInt32 timeoutSeconds,
            SqlGuid xmsclientrequestId)
        {
            AzureBlobService abs  = new AzureBlobService(accountName.Value, sharedKey.Value, useHTTPS.Value);
            Container        cont = abs.GetContainer(containerName.Value);

            Responses.LeaseBlobResponse lbr = cont.AcquireInfiniteLease(
                proposedLeaseId.IsNull ? (Guid?)null : proposedLeaseId.Value,
                timeoutSeconds.IsNull ? 0 : timeoutSeconds.Value,
                xmsclientrequestId.IsNull ? (Guid?)null : xmsclientrequestId.Value);

            PushLeaseBlobResponse(lbr);
        }
예제 #14
0
        public async Task <IActionResult> Delete(int id)
        {
            int currentUserId = User.Claims.GetUserId();
            var deletedQuiz   = quizRepository.DeleteQuiz(id, currentUserId);

            if (deletedQuiz != null)
            {
                AzureBlobService blobService = new AzureBlobService();
                await blobService.InitializeBlob();

                blobService.DeletePhoto(deletedQuiz.PictureUrl);
                return(Ok());
            }
            else
            {
                return(BadRequest("Deletion Impossible. Quiz does not exist."));
            }
        }
예제 #15
0
        public async Task <IActionResult> Put(NewQuizViewModel quizBodyData, int id)
        {
            int           currentUserId     = User.Claims.GetUserId();
            IActionResult imageHttpResponse = FileValidityChecker(quizBodyData);

            if (IActionResult.Equals(imageHttpResponse, Ok()))
            {
                return(imageHttpResponse);
            }

            string           fileUrl;
            AzureBlobService blobService;

            try {
                blobService = new AzureBlobService();
                await blobService.InitializeBlob();

                var previousQuizState = quizRepository.GetQuizById(id);

                blobService.DeletePhoto(previousQuizState.PictureUrl);
                fileUrl = await blobService.UploadPhoto(quizBodyData.Files[0]);
            }
            catch (Exception) {
                return(BadRequest("Image could not be uploaded."));
            }

            Quiz updatedQuiz = quizRepository.UpdateQuiz(new Quiz {
                Title      = quizBodyData.Title,
                PictureUrl = fileUrl,
                UserId     = currentUserId,
                Id         = id
            });

            if (updatedQuiz == null)
            {
                return(BadRequest("Quiz does not exist."));
            }

            QuizViewModel quizVm = entityToVmMapper.Map(updatedQuiz);

            quizVm.PictureUrl = blobService.urlPath.AbsoluteUri.ToString() + "users/" + fileUrl;

            return(Ok(new { quizVm.Id, quizVm.Title, quizVm.PictureUrl }));
        }
예제 #16
0
        public static void RenewBlobLease(
            SqlString accountName, SqlString sharedKey, SqlBoolean useHTTPS,
            SqlString containerName,
            SqlString blobName,
            SqlGuid leaseId,
            SqlInt32 timeoutSeconds,
            SqlGuid xmsclientrequestId)
        {
            AzureBlobService abs  = new AzureBlobService(accountName.Value, sharedKey.Value, useHTTPS.Value);
            Container        cont = abs.GetContainer(containerName.Value);
            Blob             blob = cont.GetBlob(blobName.Value);

            Responses.LeaseBlobResponse lbr = blob.RenewLease(
                leaseId.IsNull ? Guid.Empty : leaseId.Value,
                timeoutSeconds.IsNull ? 0 : timeoutSeconds.Value,
                xmsclientrequestId.IsNull ? (Guid?)null : xmsclientrequestId.Value);

            PushLeaseBlobResponse(lbr);
        }
예제 #17
0
        public async Task <IActionResult> GetQuiz(int id)
        {
            int currentUserId = User.Claims.GetUserId();

            AzureBlobService blobService = new AzureBlobService();
            await blobService.InitializeBlob();

            Quiz quiz = quizRepository.GetQuizById(id);

            if (quiz == null || quiz.UserId != currentUserId)
            {
                return(NotFound("Quiz doesn't exist"));
            }

            quiz.PictureUrl = blobService.urlPath.AbsoluteUri.ToString() + "users/" + quiz.PictureUrl;
            QuizViewModel quizVm = this.entityToVmMapper.Map(quiz);

            return(Ok(quizVm));
        }
예제 #18
0
        public async Task<IActionResult> Create([Bind("Name,Birthday,Phone,PhotoUrl,Email,Id")] Client client)
        {
            if (ModelState.IsValid)
            {
                client.Id = Guid.NewGuid();
                _context.Add(client);

                //==== Upload da foto do Cliente ====
                for (int i=0; i<Request.Form.Files.Count; i++)
                {
                    var file = Request.Form.Files[i];
                    var blobService = new AzureBlobService();
                    client.PhotoUrl = blobService.UploadFileAsync(file.FileName, file.OpenReadStream(), "clients", file.ContentType).Result;
                }
                //===================================

                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(client);
        }
        public ActionResult Import(UserImportViewModel model)
        {
            IStorageServiceProvider storageService = null;

            if (model.StorageProvider == "azure")
            {
                storageService = new AzureBlobService();
            }
            if (model.StorageProvider == "aws")
            {
                storageService = new AWSBlobService();
            }
            if (storageService != null)
            {
                string myBucketName = System.Configuration.ConfigurationManager.AppSettings["ContainerBucketName"];
                Tuple <string, string> resultUpload = storageService.UploadPublicFile(model.ImportedFile.InputStream, model.ImportedFile.FileName, myBucketName);
                model.FinalUrl = resultUpload.Item1;
            }

            return(View("Index", model));
        }
예제 #20
0
        public async Task <IActionResult> Create([Bind("NomeProduto,Preco,FotoProdutoURL,Id")] Produto produto)
        {
            if (ModelState.IsValid)
            {
                //produto.Id = Guid.NewGuid();
                _context.Add(produto);

                //==== Upload da foto do Cliente ====
                for (int i = 0; i < Request.Form.Files.Count; i++)
                {
                    var file        = Request.Form.Files[i];
                    var blobService = new AzureBlobService();
                    produto.FotoProdutoURL = blobService.UploadFile(file.FileName, file.OpenReadStream(), "jennyfer", file.ContentType);
                }
                //===================================

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(produto));
        }
        public ActionResult Import(MonitorViewModel model)
        {
            IStorageServiceProvider storageService = null;

            if (model.StorageProvider == "azure")
            {
                storageService = new AzureBlobService();
            }
            if (model.StorageProvider == "aws")
            {
                storageService = new AWSBlobService();
            }
            if (storageService != null)
            {
                string myBucketName = System.Configuration.ConfigurationManager.AppSettings["ContainerBucketName"];
                Tuple <string, string> resultUpload = storageService.UploadPublicFile(model.ImportedFile.InputStream, model.ImportedFile.FileName, myBucketName);
                model.FinalUrl = resultUpload.Item1;
            }

            HttpResponseMessage  response = ProcessImageUrl(model.FinalUrl);
            IEnumerable <string> values;

            if (response.Headers.TryGetValues("Operation-Location", out values))
            {
                model.FinalUrl = values.First();
            }

            Thread.Sleep(3000);

            model.Content = ProcessResultUrl(model.FinalUrl);

            ResultMonitor result = JsonUtil.ConvertToObject <ResultMonitor>(model.Content);

            model.ResultMonitor = result;

            return(View("Index", model));
        }
 public OnRouteToDeliveryController()
 {
     _azureBlobService = new AzureBlobService();
 }
예제 #23
0
        public IActionResult GetUrlOfContainer(string containerName)
        {
            string containerUrl = new AzureBlobService(containerName).GetFullUrlOfContainer();

            return(Ok(containerUrl));
        }
예제 #24
0
 public SendController()
 {
     _blobService = new AzureBlobService();
 }
예제 #25
0
        private async void AddNewPersonFromDB(Person person, ObservableCollection <Face> faces)
        {
            //var dialog = new AddPersonContentDialog();

            //dialog.ProvideExistingPerson(currentPerson);
            //await dialog.ShowAsync();

            //dialog.AddedPerson = person;
            //Person newPerson = dialog.AddedPerson;
            Person newPerson = person;


            // If there is a valid person to add, add them
            if (newPerson != null)
            {
                try
                {
                    // Get or create a directory for the user (we do this regardless of whether or not there is a profile picture)
                    StorageFolder userFolder;
                    if (person.FriendlyName != null && person.FriendlyName != "" && person.FriendlyName.Contains("stranger"))
                    {
                        userFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(("Users\\" + newPerson.FriendlyName), CreationCollisionOption.FailIfExists);
                    }
                    else
                    {
                        userFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(("Users\\" + newPerson.Name), CreationCollisionOption.FailIfExists);
                    }

                    StorageFile userFile = await userFolder.CreateFileAsync("ProfilePhoto.jpg", CreationCollisionOption.OpenIfExists);

                    foreach (Face face in faces)
                    {
                        await AzureBlobService.DownloadFaceImageAsFile(face, userFile);
                    }

                    newPerson.IsProfileImage = true;
                    newPerson.ImageFileName  = userFolder.Path + "\\ProfilePhoto.jpg";
                }
                catch
                {
                }

                // See if we have a profile photo
                //if (dialog.TemporaryFile != null)
                //{
                // Save off the profile photo and delete the temporary file
                //await dialog.TemporaryFile.CopyAsync(userFolder, "ProfilePhoto.jpg", NameCollisionOption.GenerateUniqueName);
                //await dialog.TemporaryFile.DeleteAsync();

                // Update the profile picture for the person
                await FacialSimilarity.AddTrainingImageAsync(newPerson.FriendlyName, new Uri($"ms-appdata:///local/Users/{newPerson.FriendlyName}/ProfilePhoto.jpg"));

                person = newPerson;

                //}
                // Add the user if it is new now that changes have been made
                //if (currentPerson == null)
                //{
                //    await FamilyModel.AddPersonAsync(newPerson);
                //}
                // Otherwise we had a user, so update the current one
                //else
                //{
                //    //await FamilyModel.UpdatePersonImageAsync(newPerson);
                //    Person personToUpdate = FamilyModel.PersonFromName(currentPerson.FriendlyName);
                //    if (personToUpdate != null)
                //    {
                //        personToUpdate.IsProfileImage = true;
                //        personToUpdate.ImageFileName = userFolder.Path + "\\ProfilePhoto.jpg";
                //    }
                //}
            }
        }
 public ArrivedAtNationalSortingHubController()
 {
     _azureBlobService = new AzureBlobService();
 }
예제 #27
0
        public static void Do()
        {
            string accountName = "enosg";
            string sharedKey   = "oooo+ps!";
            bool   useHTTPS    = true;

            string contName = "testsas";

            SharedAccessSignatureACL queueACL = new SharedAccessSignatureACL();

            queueACL.SignedIdentifier = new List <SignedIdentifier>();

            queueACL.SignedIdentifier.Add(new SignedIdentifier()
            {
                Id           = "sisisisisisisvvv",
                AccessPolicy = new AccessPolicy()
                {
                    Start      = DateTime.Now.AddYears(-1),
                    Expiry     = DateTime.Now.AddYears(1),
                    Permission = "rwd"
                }
            });

            queueACL.SignedIdentifier.Add(new SignedIdentifier()
            {
                Id           = "secondsigid",
                AccessPolicy = new AccessPolicy()
                {
                    Start      = DateTime.Now.AddYears(-10),
                    Expiry     = DateTime.Now.AddYears(10),
                    Permission = "rwdl"
                }
            });

            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(queueACL.GetType());

            // use this two lines to get rid of those useless namespaces :).
            System.Xml.Serialization.XmlSerializerNamespaces namespaces = new System.Xml.Serialization.XmlSerializerNamespaces();
            namespaces.Add(string.Empty, string.Empty);

            using (System.IO.FileStream fs = new System.IO.FileStream("C:\\temp\\QueueACL.xml", System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read))
            {
                ser.Serialize(fs, queueACL, namespaces);
            }

            using (System.IO.FileStream fs = new System.IO.FileStream("C:\\temp\\QueueACL.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
            {
                queueACL = (SharedAccessSignatureACL)ser.Deserialize(fs);
            }

            var result = InternalMethods.SetContainerACL(accountName, sharedKey, useHTTPS, contName, null, queueACL, ITPCfSQL.Azure.Enumerations.ContainerPublicReadAccess.Blob);

            //return;

            AzureBlobService abs = new AzureBlobService(accountName, sharedKey, useHTTPS);

            List <Container> lConts = abs.ListContainers();

            if (lConts.FirstOrDefault(item => item.Name == contName) == null)
            {
                abs.CreateContainer("testsas", ITPCfSQL.Azure.Enumerations.ContainerPublicReadAccess.Blob);
                lConts = abs.ListContainers();
            }

            Container cTest = lConts.First(item => item.Name == contName);

            ContainerPublicReadAccess containerPublicAccess;
            var output = InternalMethods.GetContainerACL(accountName, sharedKey, useHTTPS, contName, out containerPublicAccess);
        }
예제 #28
0
 public ScansController()
 {
     _dbContext   = new ApplicationDbContext();
     _blobService = new AzureBlobService();
 }
예제 #29
0
 public ArrivedAtDestinationSortingDepotController()
 {
     _azureBlobService = new AzureBlobService();
 }
예제 #30
0
 public PostsController(AzureBlobService azureBlobService, PostAdapter postAdapter, IdentityHelper identityHelper)
 {
     _azureBlobService = azureBlobService;
     _postAdapter      = postAdapter;
     _identityHelper   = identityHelper;
 }