示例#1
0
        /// <inheritdoc/>
        public async Task <bool> ContainerCreateAsync(string storageAccountName, string containerName, StorageClientProviderContext context)
        {
            _ = StringHelpers.NullIfNullOrEmpty(storageAccountName) ?? throw new ArgumentNullException(nameof(storageAccountName));
            _ = StringHelpers.NullIfNullOrEmpty(containerName) ?? throw new ArgumentNullException(nameof(containerName));
            _ = context ?? throw new ArgumentNullException(nameof(context));

            BlobContainerInfo blobContainerInfo;
            var containerUri = StorageHelpers.BuildBlobStorageUri(storageAccountName, containerName);

            try
            {
                var containerSleeve = _blobContainerClientProvider.GetBlobContainerSleeveForUri(containerUri, context);
                blobContainerInfo = await containerSleeve.Client.CreateAsync().ConfigureAwait(false);
            }
            catch (Exception e)
            {
                throw new GridwichStorageServiceException(containerUri, "Failed to create the container.",
                                                          LogEventIds.FailedToCreateContainer, context.ClientRequestIdAsJObject, e);
            }

            if (blobContainerInfo != null)
            {
                _log.LogEventObject(LogEventIds.ContainerCreateProgress, blobContainerInfo);
                return(true);
            }

            throw new GridwichStorageServiceException(containerUri, "Failed to create the container.",
                                                      LogEventIds.FailedToCreateContainer, context.ClientRequestIdAsJObject);
        }
示例#2
0
        public PackageHandler GetFile(string id, string version)
        {
            var sourceBlob = SourceContainer.GetBlockBlobReference(
                StorageHelpers.GetPackageBlobName(id, version));

            return(new AzurePackageHandler(sourceBlob));
        }
        public void SaveStateReward(
            string previousAgentState,
            string currentAgentState,
            double reward,
            TransportType previousAction,
            TransportType[] availableTransportTypes)
        {
            if (!statesToQFuncInfos.ContainsKey(previousAgentState))
            {
                statesToQFuncInfos.Add(previousAgentState, StorageHelpers.CreateRandomQFuncInfo(previousAgentState, availableTransportTypes));
            }
            else
            {
                var previousQFunc = statesToQFuncInfos[previousAgentState];
                if (!statesToQFuncInfos.ContainsKey(currentAgentState))
                {
                    var qFuncInfo = StorageHelpers.CreateRandomQFuncInfo(currentAgentState, availableTransportTypes);
                    statesToQFuncInfos.Add(currentAgentState, qFuncInfo);
                }

                var currentQFunc = statesToQFuncInfos[currentAgentState];

                var maxNextReward = currentQFunc.GetBestReward();

                var previousReward = previousQFunc.GetReward(previousAction);
                var newReward      = QLearningAlgorithm.GetUpdateReward(previousReward, maxNextReward, reward);
                previousQFunc.SetReward(previousAction, newReward);
            }
        }
示例#4
0
        /// <summary>
        /// Loads all saved data
        /// </summary>
        public static void LoadData()
        {
            try
            {
                var storeNames = StorageHelpers.LoadAndDeserialize <List <string> >(Constants.ParamStoresNames);
                _results = StorageHelpers.LoadAndDeserialize <List <Result> >(Constants.ParamResults)?.ToDictionary(r => new Tuple <int, bool>(r.LearnerId, r.WithBody), r => r)
                           ?? new Dictionary <Tuple <int, bool>, Result>();

                if (storeNames != null && storeNames.Count > 0)
                {
                    var userStores = OutlookHelpers.GetDictionaryStores();
                    _analyzedStoresIds = userStores.Where(d => storeNames.Contains(d.Value.DisplayName)).Select(s => s.Value.StoreID).ToList();
                    foreach (var userStore in userStores)
                    {
                        if (_analyzedStoresIds.Contains(userStore.Value.StoreID))
                        {
                            var storeModel = new StoreModel(userStore.Value);
                            storeModel.LoadStoreModel();
                            _storeModels.Add(storeModel.StoreId, storeModel);
                        }
                    }
                    _finishedLoading = true;
                    Globals.Ribbons.MainRibbon.labelInfo.Label = " ";
                }
                else
                {
                    Globals.Ribbons.MainRibbon.labelInfo.Label = "Not analyzed";
                }
            }
            catch (System.Exception ex)
            {
                MyMessageBox.Show("Error when loading data. Error: " + ex);
            }
        }
示例#5
0
 public virtual async void DeleteItem(RoutedEventArgs e)
 {
     var items = SlimContentPage.SelectedItems.ToList().Select((item) => StorageHelpers.FromPathAndType(
                                                                   item.ItemPath,
                                                                   item.PrimaryItemAttribute == StorageItemTypes.File ? FilesystemItemType.File : FilesystemItemType.Directory));
     await FilesystemHelpers.DeleteItemsAsync(items, true, false, true);
 }
示例#6
0
        /// <inheritdoc/>
        public async Task <bool> ContainerDeleteAsync(string storageAccountName, string containerName, StorageClientProviderContext context)
        {
            _ = StringHelpers.NullIfNullOrWhiteSpace(storageAccountName) ?? throw new ArgumentNullException(nameof(storageAccountName));
            _ = StringHelpers.NullIfNullOrWhiteSpace(containerName) ?? throw new ArgumentNullException(nameof(containerName));
            _ = context ?? throw new ArgumentNullException(nameof(context));

            Response response;
            var      containerUri = StorageHelpers.BuildBlobStorageUri(storageAccountName, containerName);

            try
            {
                var containerSleeve = _blobContainerClientProvider.GetBlobContainerSleeveForUri(containerUri, context);
                response = await containerSleeve.Client.DeleteAsync().ConfigureAwait(false);
            }
            catch (Exception e)
            {
                _log.LogExceptionObject(LogEventIds.FailedToDeleteContainer, e, containerUri);
                throw new GridwichStorageServiceException(containerUri, "Could not delete blob container.",
                                                          LogEventIds.FailedToDeleteContainer, context.ClientRequestIdAsJObject, e);
            }

            if (response.Status == 200)
            {
                return(true);
            }

            _log.LogEventObject(LogEventIds.DeleteContainerUnexpectedResponse, new { containerUri, response });
            throw new GridwichStorageServiceException(containerUri, $"Unexpected response while deleting blob container: {response.Status} {response.ReasonPhrase}",
                                                      LogEventIds.DeleteContainerUnexpectedResponse, context.ClientRequestIdAsJObject);
        }
示例#7
0
        public async Task <ActionResult <HomeLoanClass> > GetTodoItem(string appid, string email)
        {
            // string storageConnectionString = AppSettings.LoadAppSettings().StorageConnectionString;
            string storageConnectionString = _envvars.STORAGE_ENDPOINT;
            string homeloantablenameString = _envvars.STORAGE_TABLE_NAME;

            // string homeloantablenameString = AppSettings.LoadAppSettings().HomeLoanTableName;
            StorageHelpers.HomeLoanApplicationTableEntity loanapplication = new StorageHelpers.HomeLoanApplicationTableEntity();
            // Retrieve storage account information from connection string.
            CloudStorageAccount storageAccount = StorageHelpers.CreateStorageAccountFromConnectionString(storageConnectionString);

            // Create a table client for interacting with the table service
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());

            // Console.WriteLine("Create a Table for the demo");

            // Create a table client for interacting with the table service
            CloudTable table = tableClient.GetTableReference(homeloantablenameString);

            loanapplication = await StorageHelpers.RetrieveEntityUsingPointQueryAsync(table, email, appid);

            HomeLoanClass applicationdetails = new HomeLoanClass();

            if (loanapplication != null)
            {
                applicationdetails = JsonConvert.DeserializeObject <HomeLoanClass>(loanapplication.JsonBody);
                return(Ok(applicationdetails));
            }
            else
            {
                return(Ok());
            }
        }
示例#8
0
        public static async Task <ReferenceFile> GetFile(StorageFile referenceFile, ReferenceFileData referenceFileData)
        {
            if (referenceFileData == null || string.IsNullOrEmpty(referenceFileData.path))
            {
                return(new ReferenceFile(referenceFile, null)
                {
                    LastError = new SafeWrapperResult(OperationErrorCode.InvalidArgument, new ArgumentNullException(), "The Reference File data is corrupt.")
                });
            }

            SafeWrapper <StorageFile> file = await StorageHelpers.ToStorageItemWithError <StorageFile>(referenceFileData.path);

            if (!file)
            {
                if (file == OperationErrorCode.NotFound)
                {
                    // If NotFound, use custom exception for LoadCanvasFromCollection()
                    return(new ReferenceFile(referenceFile, null)
                    {
                        LastError = new SafeWrapperResult(OperationErrorCode.NotFound, new ReferencedFileNotFoundException(), "The file referenced could not be found.")
                    });
                }
                else
                {
                    return(new ReferenceFile(referenceFile, null)
                    {
                        LastError = (SafeWrapperResult)file
                    });
                }
            }

            return(new ReferenceFile(referenceFile, file));
        }
示例#9
0
        public void SaveStateReward(
            string previousAgentState,
            string currentAgentState,
            double reward,
            TransportType previousAction)
        {
            var previousQFunc = db.QFuncInfos.FirstOrDefault(x => x.State == previousAgentState);

            if (previousQFunc == null)
            {
                db.Add(StorageHelpers.CreateRandomQFuncInfo(previousAgentState));
            }
            else
            {
                var currenQFunc = db.QFuncInfos.FirstOrDefault(x => x.State == currentAgentState);
                if (currenQFunc == null)
                {
                    currenQFunc = StorageHelpers.CreateRandomQFuncInfo(currentAgentState);
                    db.Add(currenQFunc);
                }

                var maxNextReward = currenQFunc.GetBestReward();

                if (previousAction == TransportType.Bus)
                {
                    previousQFunc.BusReward = QLearningAlgoritm.GetUpdateReward(previousQFunc.BusReward, maxNextReward, reward);
                }
                else
                {
                    previousQFunc.CarReward = QLearningAlgoritm.GetUpdateReward(previousQFunc.CarReward, maxNextReward, reward);
                }
            }

            db.SaveChanges();
        }
示例#10
0
        private IList <PackageRef> PackagesToCopyOrOverwrite(IList <PackageRef> packagesInDB, Dictionary <string, DateTimeOffset> packages)
        {
            var packagesToCopy = packagesInDB.Where(pkgRef =>
            {
                var blobName = StorageHelpers.GetPackageBlobName(pkgRef);
                DateTimeOffset lastModified;
                if (packages.TryGetValue(blobName, out lastModified))
                {
                    if (pkgRef.LastEdited == null)
                    {
                        // Package Exists and Don't overwrite
                        // LastEdited is null meaning packages was not edited after getting published
                        return(false);
                    }
                    else
                    {
                        // Overwrite if LastEdited of the package is greater than the last modified of the package blob
                        return(lastModified < pkgRef.LastEdited.Value.ToUniversalTime());
                    }
                }
                else
                {
                    // Package does not exist at all
                    // Copy the package
                    return(true);
                }
            });

            return(packagesToCopy.ToList());
        }
        public static async Task HandleFileSystemPermissionDialog(IWindowTitleBarControlModel windowTitleBar)
        {
            string testForFolderOnFS = Path.GetFullPath(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
            SafeWrapper <StorageFolder> testFolderResult = await StorageHelpers.ToStorageItemWithError <StorageFolder>(testForFolderOnFS);

            if (!testFolderResult)
            {
                App.IsInRestrictedAccessMode = true;

                DialogResult dialogResult = await App.DialogService.ShowDialog(new FileSystemAccessDialogViewModel());

                if (dialogResult == DialogResult.Primary)
                {
                    // Restart the app
                    await CoreApplication.RequestRestartAsync(string.Empty);
                }
                else
                {
                    // Continue in Restricted Access
                    windowTitleBar.IsInRestrictedAccess = true;
                }
            }
            else
            {
                return;
            }
        }
示例#12
0
        public HttpResponseMessage GetAllImages()
        {
            CloudStorageAccount storageAccount = StorageHelpers.StorageAccount();

            //Create the blob client object.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            //Get a reference to a container to use for the sample code, and create it if it does not exist.
            CloudBlobContainer container = blobClient.GetContainerReference(Constant.IMAGE_STORAGE_CONTAINER_NAME);

            //Create a list to store blob URIs returned by a listing operation on the container.
            List <ICloudBlob> blobList = new List <ICloudBlob>();

            foreach (ICloudBlob blob in container.ListBlobs())
            {
                blobList.Add(blob);
            }

            var blobListAsJson = JsonConvert.SerializeObject(blobList);

            //IEnumerable<PictureInfo> picsInfo = this.picturesInfo.All().ToList<PictureInfo>();

            //var picsInfoAsJson = JsonConvert.SerializeObject(picsInfo);

            return(Request.CreateResponse(HttpStatusCode.OK, blobListAsJson));
        }
 private IList <Tuple <string, string> > CalculateBackupSet(IList <PackageRef> packages, ISet <string> backups)
 {
     return(packages
            .AsParallel()
            .Select(r => Tuple.Create(StorageHelpers.GetPackageBlobName(r), StorageHelpers.GetPackageBackupBlobName(r)))
            .Where(t => !backups.Contains(t.Item2))
            .ToList());
 }
示例#14
0
 public void Save(string storeName)
 {
     StorageHelpers.SaveItem(_bayesLearning.Model, Constants.ParamModel, storeName);
     StorageHelpers.SaveItem(_inputBagOfWords, Constants.ParamInputBoW, storeName);
     StorageHelpers.SaveItem(_subjectBagOfWords, Constants.ParamSubjectBoW, storeName);
     StorageHelpers.SaveItem(_textBagOfWords, Constants.ParamTextBoW, storeName);
     StorageHelpers.SaveItem(_outputCodeBook, Constants.ParamCodeBook, storeName);
 }
示例#15
0
        private IList <string> PackagesToDelete(IList <PackageRef> packagesInDB, Dictionary <string, DateTimeOffset> packages)
        {
            var packagesInDBAsFilenames = new HashSet <string>(from pkgRef in packagesInDB
                                                               select StorageHelpers.GetPackageBlobName(pkgRef));

            return((from pkg in packages.Where(p => !packagesInDBAsFilenames.Contains(p.Key))
                    select pkg.Key).ToList());
        }
示例#16
0
 public void Load(string storeName)
 {
     CreateBayesLearner();
     _bayesLearning.Model = StorageHelpers.LoadItem <NaiveBayes>(Constants.ParamModel, storeName);
     _outputCodeBook      = StorageHelpers.LoadItem <Codification>(Constants.ParamCodeBook, storeName);
     _inputBagOfWords     = StorageHelpers.LoadItem <BagOfWords>(Constants.ParamInputBoW, storeName);
     _subjectBagOfWords   = StorageHelpers.LoadItem <BagOfWords>(Constants.ParamSubjectBoW, storeName);
     _textBagOfWords      = StorageHelpers.LoadItem <BagOfWords>(Constants.ParamTextBoW, storeName);
 }
示例#17
0
        public async Task SetUp()
        {
            this.testQueueName = StorageHelpers.GetRandomQueueName(TestPrefix);

            var queueReference = StorageHelpers.GetQueueReference(this.testQueueName);
            await queueReference.DeleteIfExistsAsync().ConfigureAwait(false);

            await queueReference.CreateIfNotExistsAsync().ConfigureAwait(false);
        }
示例#18
0
        /// <summary>
        /// Returns the relative file paths to all files in a given folder
        /// </summary>
        /// <param name="folderPath">Folder path</param>
        /// <param name="includeSubfolders">Should subfolder files be included?</param>
        /// <returns>List of full file paths</returns>
        public async Task <IEnumerable <string> > GetFilePathsAsync(string folderPath, bool includeSubfolders)
        {
            var absoluteFolderPath = Path.Combine(Package.Current.InstalledLocation.Path, folderPath);
            var targetFolder       = await StorageFolder.GetFolderFromPathAsync(absoluteFolderPath);

            var files = await StorageHelpers.GetFilesInFolder(targetFolder, includeSubfolders);

            return(files.Select(f => f.Path));
        }
示例#19
0
        public async Task InitializeAsync()
        {
            await DatabaseHelpers.ResetDatabase();

            await EmailHelpers.ResetEmail();

            await StorageHelpers.ResetStorage();

            await SetupConfiguration();
        }
        public TransportType GetBestNextTransport(string currentAgentState, TransportType[] availableTransportTypes)
        {
            if (!statesToQFuncInfos.ContainsKey(currentAgentState))
            {
                var qFuncInfo = StorageHelpers.CreateRandomQFuncInfo(currentAgentState, availableTransportTypes);
                statesToQFuncInfos.Add(currentAgentState, qFuncInfo);
            }

            return(QLearningAlgorithm.GetBestNextTransportWithEpsilonMush(statesToQFuncInfos[currentAgentState], availableTransportTypes));
        }
示例#21
0
        public async Task BackupAsync(string path, string id, string version, string hash)
        {
            var backupBlob = BackupsContainer.GetBlockBlobReference(
                StorageHelpers.GetPackageBackupBlobName(id, version, hash));

            if (!await backupBlob.ExistsAsync())
            {
                await backupBlob.UploadFromFileAsync(path);
            }
        }
        private async Task Archive(CloudBlobContainer destinationContainer)
        {
            var cursorJObject = await GetJObject(destinationContainer, CursorBlob);

            var cursorDateTime = cursorJObject[CursorDateTimeKey].Value <DateTime>();

            Log.CursorData(cursorDateTime.ToString(DateTimeFormatSpecifier));

            Log.GatheringPackagesToArchiveFromDB(PackageDatabase.DataSource, PackageDatabase.InitialCatalog);
            List <PackageRef> packages;

            using (var connection = await PackageDatabase.ConnectTo())
            {
                packages = (await connection.QueryAsync <PackageRef>(@"
			    SELECT pr.Id, p.NormalizedVersion AS Version, p.Hash, p.LastEdited, p.Published
			    FROM Packages p
			    INNER JOIN PackageRegistrations pr ON p.PackageRegistrationKey = pr.[Key]
			    WHERE Published > @cursorDateTime OR LastEdited > @cursorDateTime"            , new { cursorDateTime = cursorDateTime }))
                           .ToList();
            }
            Log.GatheredPackagesToArchiveFromDB(packages.Count, PackageDatabase.DataSource, PackageDatabase.InitialCatalog);

            var archiveSet = packages
                             .AsParallel()
                             .Select(r => Tuple.Create(StorageHelpers.GetPackageBlobName(r), StorageHelpers.GetPackageBackupBlobName(r)))
                             .ToList();

            if (!WhatIf)
            {
                await destinationContainer.CreateIfNotExistsAsync();
            }

            if (archiveSet.Count > 0)
            {
                Log.StartingArchive(archiveSet.Count);
                await Extend(TimeSpan.FromMinutes(archiveSet.Count * 10));

                foreach (var archiveItem in archiveSet)
                {
                    await ArchivePackage(archiveItem.Item1, archiveItem.Item2, SourceContainer, destinationContainer);
                }

                var maxLastEdited = packages.Max(p => p.LastEdited);
                var maxPublished  = packages.Max(p => p.Published);

                // Time is ever increasing after all, simply store the max of published and lastEdited as cursorDateTime
                var newCursorDateTime       = maxLastEdited > maxPublished ? new DateTime(maxLastEdited.Value.Ticks, DateTimeKind.Utc) : new DateTime(maxPublished.Value.Ticks, DateTimeKind.Utc);
                var newCursorDateTimeString = newCursorDateTime.ToString(DateTimeFormatSpecifier);

                Log.NewCursorData(newCursorDateTimeString);
                cursorJObject[CursorDateTimeKey] = newCursorDateTimeString;
                await SetJObject(destinationContainer, CursorBlob, cursorJObject);
            }
        }
示例#23
0
 public virtual async void RestoreItem(RoutedEventArgs e)
 {
     var items = SlimContentPage.SelectedItems.ToList().Where(x => x is RecycleBinItem).Select((item) => new
     {
         Source = StorageHelpers.FromPathAndType(
             item.ItemPath,
             item.PrimaryItemAttribute == StorageItemTypes.File ? FilesystemItemType.File : FilesystemItemType.Directory),
         Dest = (item as RecycleBinItem).ItemOriginalPath
     });
     await FilesystemHelpers.RestoreItemsFromTrashAsync(items.Select(x => x.Source), items.Select(x => x.Dest), true);
 }
示例#24
0
 /// <summary>
 /// Removes all addin saved data.
 /// </summary>
 public static void RemoveSavedData()
 {
     StorageHelpers.RemoveStores();
     foreach (var store in OutlookHelpers.GetDictionaryStores())
     {
         StorageHelpers.RemoveStorage(store.Value.DisplayName);
     }
     SelectedMailScores = new Dictionary <string, double>();
     _analyzedStoresIds = new List <string>();
     _storeModels       = new Dictionary <string, StoreModel>();
     SelectionChanged(SelectedItem);
 }
示例#25
0
        public TransportType GetBestNextTransport(string currentAgentState)
        {
            var qFuncInfo = qFuncInfos.FirstOrDefault(x => x.State == currentAgentState);

            if (qFuncInfo == null)
            {
                qFuncInfo = StorageHelpers.CreateRandomQFuncInfo(currentAgentState);
                qFuncInfos.Add(qFuncInfo);
            }

            return(QLearningAlgoritm.GetBestNextTransportWithEpsilonMush(qFuncInfo));
        }
        public async Task <IActionResult> Upload(ICollection <IFormFile> files)
        {
            bool isUploaded = false;

            try
            {
                if (files.Count == 0)
                {
                    return(BadRequest("No files received from the upload"));
                }
                if (storageConfig.ImageContainer == string.Empty)
                {
                    return(BadRequest("Please provide a name for your image container in the azure blob storage "));
                }
                foreach (var formfile in files)
                {
                    if (StorageHelpers.IsImage(formfile))
                    {
                        if (formfile.Length > 0)
                        {
                            using (Stream stream = formfile.OpenReadStream())
                            {
                                isUploaded = await StorageHelpers.UploadFileTorStorage(stream, formfile.FileName, storageConfig);
                            }
                        }
                    }
                    else
                    {
                        return(new UnsupportedMediaTypeResult());
                    }
                }
                if (isUploaded)
                {
                    if (storageConfig.ThumbnailContainer != string.Empty)
                    {
                        return(new AcceptedAtActionResult("GetThumbNails", "Images", null, null));
                    }
                    else
                    {
                        return(new AcceptedResult());
                    }
                }
                else
                {
                    return(BadRequest("Look like the image couldn't upload to the storage"));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
示例#27
0
        public TransportType GetBestNextTransport(string currentAgentState, TransportType[] availableTransportTypes)
        {
            var qFuncInfo = db.QFuncInfos.FirstOrDefault(x => x.State == currentAgentState);

            if (qFuncInfo == null)
            {
                qFuncInfo = StorageHelpers.CreateRandomQFuncInfo(currentAgentState, availableTransportTypes);
                db.QFuncInfos.Add(qFuncInfo);
                db.SaveChanges();
            }

            return(QLearningAlgorithm.GetBestNextTransportWithEpsilonMush(qFuncInfo, availableTransportTypes));
        }
示例#28
0
        /// <inheritdoc/>
        public string GetSasUrlForBlob(Uri blobUri, TimeSpan ttl, StorageClientProviderContext context)
        {
            _ = blobUri ?? throw new ArgumentNullException(nameof(blobUri));
            _ = context ?? throw new ArgumentNullException(nameof(context));

            try
            {
                var blobUriBuilder = new BlobUriBuilder(blobUri);

                // Create a SAS token that's valid for the TimeSpan, plus a back-off start for clock skew.
                var            timeRange  = StorageHelpers.CreateTimeRangeForUrl(ttl);
                BlobSasBuilder sasBuilder = new BlobSasBuilder
                {
                    BlobContainerName = blobUriBuilder.BlobContainerName,
                    BlobName          = blobUriBuilder.BlobName,
                    Resource          = "b", // "b" is for blob
                    StartsOn          = timeRange.StartTime,
                    ExpiresOn         = timeRange.EndTime,
                }.UnescapeTargetPath();                             // Important adjustment(s) for SAS computation

                sasBuilder.SetPermissions(BlobSasPermissions.Read); // read permissions only for the SAS.

                var sleeve         = _blobBaseClientProvider.GetBlobClientSleeveForUri(blobUri, context);
                var userDelegation = sleeve.Service.GetUserDelegationKey(sasBuilder.StartsOn, sasBuilder.ExpiresOn)?.Value;

                if (userDelegation == null)
                {
                    var msg = $@"Unable to get a user delegation key from the Storage service for blob {blobUri}";
                    _log.LogEvent(LogEventIds.StorageServiceMissingConnectionString, msg);
                    throw new GridwichStorageServiceException(blobUri, msg, LogEventIds.StorageServiceMissingConnectionString, context.ClientRequestIdAsJObject);
                }

                var sasToken = sasBuilder.ToSasQueryParameters(userDelegation, blobUriBuilder.AccountName);
                blobUriBuilder.Sas = sasToken;

                // Construct the full URI, including the SAS token. AbsoluteUri (vs. ToString) is to ensure the %HH escaping is used.
                return(blobUriBuilder.ToUri().AbsoluteUri);
            }
            catch (RequestFailedException e)
            {
                var msg = $@"Unable to get a user delegation key from the Storage service for blob {blobUri}";
                _log.LogEvent(LogEventIds.StorageServiceMissingConnectionString, msg);
                throw new GridwichStorageServiceException(blobUri, msg, LogEventIds.StorageServiceMissingConnectionString, context.ClientRequestIdAsJObject, e);
            }
            catch (Exception e)
            {
                _log.LogExceptionObject(LogEventIds.FailedToCreateBlobSasUriInStorageService, e, blobUri);
                throw new GridwichStorageServiceException(blobUri, "Failed to generate the SAS url.",
                                                          LogEventIds.FailedToCreateBlobSasUriInStorageService, context.ClientRequestIdAsJObject, e);
            }
        }
示例#29
0
        public void WriteReadTest(ulong value, int length)
        {
            using (var stream = new MemoryStream())
            {
                var writer = new BinaryWriter(stream, Encoding.UTF8, false);

                StorageHelpers.Write7BitEncodedInt(writer, value);

                stream.Position = 0;
                var reader = new BinaryReader(stream, Encoding.UTF8, false);

                StorageHelpers.Read7BitEncodedInt(reader).Should().Be(value);
            }
        }
        public async void DecompressArchiveToChildFolder()
        {
            var selectedItem = associatedInstance?.SlimContentPage?.SelectedItem;

            if (selectedItem == null)
            {
                return;
            }

            BaseStorageFile archive = await StorageHelpers.ToStorageItem <BaseStorageFile>(selectedItem.ItemPath);

            BaseStorageFolder currentFolder = await StorageHelpers.ToStorageItem <BaseStorageFolder>(associatedInstance.FilesystemViewModel.CurrentFolder.ItemPath);

            BaseStorageFolder destinationFolder = null;

            if (currentFolder != null)
            {
                destinationFolder = await FilesystemTasks.Wrap(() => currentFolder.CreateFolderAsync(Path.GetFileNameWithoutExtension(archive.Path), CreationCollisionOption.OpenIfExists).AsTask());
            }

            if (archive != null && destinationFolder != null)
            {
                CancellationTokenSource extractCancellation = new CancellationTokenSource();
                PostedStatusBanner      banner = App.OngoingTasksViewModel.PostOperationBanner(
                    string.Empty,
                    "ExtractingArchiveText".GetLocalized(),
                    0,
                    ReturnResult.InProgress,
                    FileOperationType.Extract,
                    extractCancellation);

                Stopwatch sw = new Stopwatch();
                sw.Start();

                await ZipHelpers.ExtractArchive(archive, destinationFolder, banner.Progress, extractCancellation.Token);

                sw.Stop();
                banner.Remove();

                if (sw.Elapsed.TotalSeconds >= 6)
                {
                    App.OngoingTasksViewModel.PostBanner(
                        "ExtractingCompleteText".GetLocalized(),
                        "ArchiveExtractionCompletedSuccessfullyText".GetLocalized(),
                        0,
                        ReturnResult.Success,
                        FileOperationType.Extract);
                }
            }
        }