コード例 #1
0
        public async Task <bool> AddNewFileAsync(AvContent avContent, StorageToken storageToken)
        {
            try
            {
                Log.Debug(storageToken?.ToString());

                var sasUri = new Uri(storageToken.SasUri);

                var blockBlob = new CloudBlockBlob(sasUri);

                blockBlob.Metadata [DocumentUpdatedMessage.DocumentIdKey] = avContent.Id;

                blockBlob.Metadata [DocumentUpdatedMessage.CollectionIdKey] = typeof(AvContent).Name;

                NetworkIndicator.ToggleVisibility(true);

                await blockBlob.UploadFromFileAsync(avContent.LocalInboxPath);

                Log.Debug($"Finished uploading new file.");

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(false);
            }
            finally
            {
                NetworkIndicator.ToggleVisibility(false);
            }
        }
コード例 #2
0
        public async Task <bool> AddNewFileAsync(AvContent avContent, StorageToken storageToken)
        {
            try
            {
                var sasUri = new Uri(storageToken.SasUri);

                var blockBlob = new CloudBlockBlob(sasUri);

                blockBlob.Metadata [StorageToken.ContentIdParam] = avContent.Id;

                blockBlob.Metadata ["displayName"] = avContent.Name.SplitOnLast('.').FirstOrDefault() ?? avContent.Name;

                await blockBlob.UploadFromFileAsync(avContent.LocalInboxPath);

                Log.Debug($"Finished uploading new file.");

                return(true);
            }
            catch (Exception ex)
            {
                Log.Debug($"{ex.Message}");

                return(false);
            }
        }
コード例 #3
0
        /// <summary>
        /// Gets a storage token for the given entity ID and <see cref="StorageTokenRequest"/>, using the provided <see cref="IContainerNameResolver"/>.
        /// </summary>
        /// <param name="id">The entity id.</param>
        /// <param name="value">The request provided by the client.</param>
        /// <param name="containerNameResolver">The instance of an <see cref="IContainerNameResolver"/> used to resolve the storage container name.</param>
        /// <returns></returns>
        public virtual async Task <StorageToken> GetStorageTokenAsync(string id, StorageTokenRequest value, IContainerNameResolver containerNameResolver)
        {
            StorageTokenScope scope = GetStorageScopeForRequest(id, value);

            StorageToken token = await this.storageProvider.GetAccessTokenAsync(value, scope, containerNameResolver);

            return(token);
        }
コード例 #4
0
        // return a storage token that can be used for blob upload or download
        public async Task <HttpResponseMessage> PostStorageTokenRequest(string id, StorageTokenRequest request)
        {
            // The file size is encoded in the start of the filename, lg, md, etc.
            // If it doesn't match the pattern then the default size of lg is used
            var requestedSize = request.TargetFile.Name.Substring(0, 2);

            StorageToken token = await GetStorageTokenAsync(id, request, new ImageNameResolver(requestedSize));

            return(Request.CreateResponse(token));
        }
コード例 #5
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = nameof(GetStorageToken))]
                                                           HttpRequestMessage req, TraceWriter log)
        {
            using (var analytic = new AnalyticService(new RequestTelemetry
            {
                Name = nameof(GetStorageToken)
            }))
            {
                try
                {
                    var kvps     = req.GetQueryNameValuePairs();
                    var blobName = kvps.FirstOrDefault(kvp => kvp.Key == "blobName").Value;

                    if (string.IsNullOrWhiteSpace(blobName))
                    {
                        var e = new ArgumentNullException(nameof(blobName));

                        // track exceptions that occur
                        analytic.TrackException(e);

                        throw e;
                    }

                    if (_storageAccount == null)
                    {
                        _storageAccount = CloudStorageAccount.Parse(ConfigManager.Instance.BlobSharedStorageKey);
                    }

                    if (_blobClient == null)
                    {
                        _blobClient = _storageAccount.CreateCloudBlobClient();
                    }

                    _container = _blobClient.GetContainerReference(ConfigManager.BlobImageContainer);
                    await _container.CreateIfNotExistsAsync();

                    var sasUri = await GetSASToken(blobName);

                    var token = new StorageToken(blobName, sasUri);

                    return(req.CreateResponse(HttpStatusCode.OK, token));
                }
                catch (Exception e)
                {
                    // track exceptions that occur
                    analytic.TrackException(e);

                    return(req.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message, e));
                }
            }
        }
コード例 #6
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, Routes.Get, Route = Routes.GenerateStorageToken)] HttpRequestMessage req,
            [DocumentDB(nameof(Content), "{collectionId}", Id = "{documentId}")] Content content, string collectionId, string documentId, TraceWriter log)
        {
            UserStore userStore = null;

            var userId = Thread.CurrentPrincipal.GetClaimsIdentity()?.UniqueIdentifier();

            if (!string.IsNullOrEmpty(userId))
            {
                log.Info($"User is authenticated and has userId: {userId}");

                userStore = await DocumentClient.GetUserStore(userId, log);
            }


            if (!userStore?.UserRole.CanWrite() ?? false)
            {
                log.Info("Not authenticated");

                return(req.CreateResponse(HttpStatusCode.Unauthorized));
            }


            if (content == null)
            {
                log.Info($"No item in database matching the documentId paramater {documentId}");

                return(req.CreateErrorResponse(HttpStatusCode.NotFound, $"No item in database matching the documentId paramater {documentId}"));
            }

            log.Info($"Successfully found document in database matching the documentId paramater {documentId}");


            // Errors creating the storage container result in a 500 Internal Server Error
            var container = BlobClient.GetContainerReference(GetUploadContainerName(collectionId));

            await container.CreateIfNotExistsAsync();


            // TODO: Check if there's already a blob with a name matching the Id


            var sasUri = GetBlobSasUri(container, content.Name);

            var token = new StorageToken(content.Name, sasUri);

            return(req.CreateResponse(HttpStatusCode.OK, token));
        }
        public async Task UploadFileAsync(MobileServiceFileMetadata metadata, IMobileServiceFileDataSource dataSource)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }

            if (dataSource == null)
            {
                throw new ArgumentNullException("dataSource");
            }

            StorageToken token = await GetStorageToken(this.client, MobileServiceFile.FromMetadata(metadata), StoragePermissions.Write);

            await this.storageProvider.UploadFileAsync(metadata, dataSource, token);
        }
コード例 #8
0
        private CloudBlockBlob GetBlobReference(StorageToken token, string fileName)
        {
            CloudBlockBlob blob = null;

            if (token.Scope == StorageTokenScope.File)
            {
                blob = new CloudBlockBlob(new Uri(token.ResourceUri, token.RawToken));
            }
            else if (token.Scope == StorageTokenScope.Record)
            {
                var container = new CloudBlobContainer(new Uri(token.ResourceUri, token.RawToken));

                blob = container.GetBlockBlobReference(fileName);
            }

            return(blob);
        }
コード例 #9
0
        public async Task <HttpResponseMessage> PostStorageTokenRequest(string id, StorageTokenRequest value)
        {
            StorageToken token = await GetStorageTokenAsync(id, value);

            return(Request.CreateResponse(token));
        }
コード例 #10
0
        // return a storage token that can be used for blob upload or download
        public async Task <HttpResponseMessage> PostStorageTokenRequest(string id, StorageTokenRequest request)
        {
            StorageToken token = await GetStorageTokenAsync(id, request, new ImageNameResolver(request.TargetFile.StoreUri));

            return(Request.CreateResponse(token));
        }
コード例 #11
0
        public Task <Uri> GetFileUriAsync(StorageToken storageToken, string fileName)
        {
            CloudBlockBlob blob = GetBlobReference(storageToken, fileName);

            return(Task.FromResult(new Uri(blob.Uri, storageToken.RawToken)));
        }
コード例 #12
0
        public async Task DownloadFileToStreamAsync(MobileServiceFile file, Stream stream, StorageToken storageToken)
        {
            CloudBlockBlob blob = GetBlobReference(storageToken, file.Name);

            await blob.DownloadToStreamAsync(stream);
        }
コード例 #13
0
        public async Task UploadFileAsync(MobileServiceFileMetadata metadata, IMobileServiceFileDataSource dataSource, StorageToken storageToken)
        {
            CloudBlockBlob blob = GetBlobReference(storageToken, metadata.FileName);

            using (var stream = await dataSource.GetStream())
            {
                await blob.UploadFromStreamAsync(stream);

                metadata.LastModified = blob.Properties.LastModified;
                metadata.FileStoreUri = blob.Uri.LocalPath;

                stream.Position     = 0;
                metadata.ContentMD5 = GetMD5Hash(stream);
            }
        }
        public async Task <Uri> GetFileUriAsync(MobileServiceFile file, StoragePermissions permissions)
        {
            StorageToken token = await GetStorageToken(this.client, file, permissions);

            return(await this.storageProvider.GetFileUriAsync(token, file.Name));
        }
        public async Task DownloadToStreamAsync(MobileServiceFile file, Stream stream)
        {
            StorageToken token = await GetStorageToken(this.client, file, StoragePermissions.Read);

            await this.storageProvider.DownloadFileToStreamAsync(file, stream, token);
        }
コード例 #16
0
        public async Task <IHttpActionResult> PostStorageTokenRequest(string id, StorageTokenRequest value)
        {
            StorageToken token = await GetStorageTokenAsync(id, value);

            return(Ok(token));
        }