/// <summary> /// Generates a task sequence for getting the properties of the queue service. /// </summary> /// <param name="setResult">A delegate to receive the service properties.</param> /// <returns>A task sequence that gets the properties of the queue service.</returns> private TaskSequence GetServicePropertiesImpl(Action <ServiceProperties> setResult) { HttpWebRequest request = QueueRequest.GetServiceProperties(this.BaseUri, this.Timeout.RoundUpToSeconds()); CommonUtils.ApplyRequestOptimizations(request, -1); this.Credentials.SignRequest(request); // Get the web response. StorageTask <WebResponse> responseTask = request.GetResponseAsyncWithTimeout(this, this.Timeout); yield return(responseTask); using (HttpWebResponse response = responseTask.Result as HttpWebResponse) using (Stream responseStream = response.GetResponseStream()) using (MemoryStream memoryStream = new MemoryStream()) { // Download the service properties. StorageTask <NullTaskReturn> downloadTask = new InvokeTaskSequenceTask(() => { return(responseStream.WriteTo(memoryStream)); }); yield return(downloadTask); // Materialize any exceptions. NullTaskReturn scratch = downloadTask.Result; Console.WriteLine(scratch); // Get the result from the memory stream. memoryStream.Seek(0, SeekOrigin.Begin); setResult(QueueResponse.ReadServiceProperties(memoryStream)); } }
public async Task NextDesktopBackground(string path) { var activeDesktopTheme = GetActiveDesktopTheme(); if (activeDesktopTheme == null) { return; } // Get the Storage File StorageTask storageTask = new StorageTask(); var file = await storageTask.GetFileFromPath(new Uri(path)); Debug.WriteLine($"{nameof(ActiveThemeService)}.{nameof(NextDesktopBackground)} - Converted Path to File: {file.Name}"); // Set the Wallpaper if (await m_wallpaperManager.SetImage(file)) { // Add it to the history if successful m_activeDesktopThemeHistorySetting.Add(path); m_activeDesktopThemeCurrentWallpaperSetting.Value = path; m_activeDesktopThemeNextRunSetting.Value = DateTime.UtcNow.Add(activeDesktopTheme.WallpaperChangeFrequency); Debug.WriteLine($"{nameof(ActiveThemeService)}.{nameof(NextDesktopBackground)} - Successfully Changed Image"); } else { Debug.WriteLine($"{nameof(ActiveThemeService)}.{nameof(NextDesktopBackground)} - Failed"); if (DebugTools.DebugMode) { m_activeDesktopThemeHistorySetting.Add(path); // REMOVEME: DEBUGGING PURPOSES } } }
private async Task CreateTasksAsync(BatchClient batchClient, string jobId, StorageTask task) { TaskContainerSettings cmdContainerSettings = new TaskContainerSettings( imageName: "ImageName", containerRunOptions: "" ); // create a simple task. Each task within a job must have a unique ID for (var i = 0; i < task.Services.Count; i++) { var commandLine = $"cmd /c c:\\TestAppService.exe {task.Id} 1"; CloudTask cloudTask = new CloudTask( $"{task.Services[i]}{i}", commandLine); cloudTask.ContainerSettings = cmdContainerSettings; //La tâche doit être éxécutée en administrateur cloudTask.UserIdentity = new UserIdentity(new AutoUserSpecification(elevationLevel: ElevationLevel.Admin, scope: AutoUserScope.Task)); cloudTask.Constraints = new TaskConstraints { MaxTaskRetryCount = 3 }; await batchClient.JobOperations.AddTaskAsync(jobId, cloudTask); } }
/// <summary> /// Copies the file to the Application Storage and Sets the Image /// </summary> /// <param name="path">The Full Path to an Image File within the Computers File System</param> /// <returns>If the Image was successfully Set</returns> public virtual async Task <bool> SetImageFromFileSystem(string path) { if (!IsSetupComplete) { return(false); } if (ClearImagesFolderEveryXImages != 0) { int fileCount = await StorageTask.Instance.FileCount(ImagesFolder); if (fileCount > ClearImagesFolderEveryXImages) { await DeleteFilesInFoldersAsync(); } } var tmpFile = await StorageFile.GetFileFromPathAsync(path); if (tmpFile == null) { return(false); } var copiedFile = await tmpFile.CopyAsync(ImagesFolder, tmpFile.Name, NameCollisionOption.ReplaceExisting); var localStorageUri = StorageTask.CreateUri(StorageLocationPrefix.LocalFolder, $"{ImagesFolderName}/{copiedFile.Name}"); var localStorageFile = await StorageFile.GetFileFromApplicationUriAsync(localStorageUri); return(await SetImage(localStorageFile)); }
private void RunStorageThread() { while (true) { bool sleep = false; //bug prevents the processTask(task) line below from compiling because it thinks task is aunassigned if we leave the RHS of the assignment off. StorageTask task = null; lock (_lock) { if (stop) { return; } if (storageTasks.Count() > 0) { sleep = false; working = true; task = storageTasks.Dequeue(); } else { working = false; sleep = true; } } if (sleep) { Thread.Sleep(100); continue; } processTask(task); } }
/// <summary> /// Adds a BackupTask to the end of the task queue. Blocks if the queue is locked by another thread. /// </summary> /// <param name="task">The BackupTask that should be processed</param> public void EnqueueStorageTask(StorageTask task) { lock (_lock) { storageTasks.Enqueue(task); working = true; } }
private async void OpenFileButton(object sender, RoutedEventArgs e) { Button btn = (Button)sender; FileDiscoveryCache cache = btn.DataContext as FileDiscoveryCache; StorageFile file = await StorageFile.GetFileFromPathAsync(cache.FilePath); StorageTask.OpenFile(file); }
/// <summary> /// Adds a BackupTask to the end of the task queue. Blocks if the queue is locked by another thread. /// </summary> /// <param name="task">The BackupTask that should be processed</param> public void EnqueueStorageTask(StorageTask task) { lock (_lock) { storageTasks.Enqueue(task); working = true; } }
public void IsFalsy_WhenTitleTaskIsNull() { //Arrange var storageTask = new StorageTask(); //Act var isValid = _addTaskValidator.Validate(storageTask); //Assert Assert.False(isValid); }
public async Task AssertExpectedExceptionAsync <T, U>(StorageTask <U> task, T expectedException, Action <T, T> assertion) where T : Exception { Assert.IsNotNull(assertion); try { await task; Assert.Fail("Expected exception not found"); } catch (T actualException) { assertion(expectedException, actualException); } }
private async void OpenDirectoryButton(object sender, RoutedEventArgs e) { Button btn = (Button)sender; FileDiscoveryCache cache = btn.DataContext as FileDiscoveryCache; StorageFile file = await StorageFile.GetFileFromPathAsync(cache.FilePath); StorageFolder folder = await file.GetParentAsync(); if (folder != null) { FolderLauncherOptions launchOptions = new FolderLauncherOptions(); launchOptions.ItemsToSelect.Add(file); StorageTask.OpenFolderInExplorer(folder, launchOptions); } }
private void processTask(StorageTask task) { if (task is BackupTask) { processTask((BackupTask)task); } else if (task is RestoreTask) { processTask((RestoreTask)task); } else { Logger.Error("StorageThread:processTask:StorageTask What kind of StorageTask is this?"); } }
public void IsFalsy_WhenServicesAreNotFilled() { //Arrange var storageTask = new StorageTask { Title = "Mon titre", Services = new List <Service>() }; //Act var isValid = _addTaskValidator.Validate(storageTask); //Assert Assert.False(isValid); }
public bool Validate(StorageTask storageTask) { if (string.IsNullOrEmpty(storageTask.Title)) { return(false); } if (storageTask.Services == null || !storageTask.Services.Any()) { return(false); } return(storageTask.Services.All(s => s == Service.Dematerialization || s == Service.Adr || s == Service.Signing)); }
/// <summary> /// Generates a task sequence for setting the properties of the queue service. /// </summary> /// <param name="properties">The queue service properties to set.</param> /// <returns>A task sequence that sets the properties of the queue service.</returns> private TaskSequence SetServicePropertiesImpl(ServiceProperties properties) { CommonUtils.AssertNotNull("properties", properties); HttpWebRequest request = QueueRequest.SetServiceProperties(this.BaseUri, this.Timeout.RoundUpToSeconds()); using (MemoryStream memoryStream = new MemoryStream()) { try { QueueRequest.WriteServiceProperties(properties, memoryStream); } catch (InvalidOperationException invalidOpException) { throw new ArgumentException(invalidOpException.Message, "properties"); } memoryStream.Seek(0, SeekOrigin.Begin); CommonUtils.ApplyRequestOptimizations(request, memoryStream.Length); this.Credentials.SignRequest(request); // Get the request stream StorageTask <Stream> getStreamTask = request.GetRequestStreamAsyncEx(); yield return(getStreamTask); using (Stream requestStream = getStreamTask.Result) { // Upload the service properties. StorageTask <NullTaskReturn> uploadTask = new InvokeTaskSequenceTask(() => { return((memoryStream as Stream).WriteTo(requestStream)); }); yield return(uploadTask); // Materialize any exceptions. NullTaskReturn scratch = uploadTask.Result; Console.WriteLine(scratch); } } // Get the web response. StorageTask <WebResponse> responseTask = request.GetResponseAsyncWithTimeout(this, this.Timeout); yield return(responseTask); // Materialize any exceptions. using (HttpWebResponse response = responseTask.Result as HttpWebResponse) { } }
public async Task ReturnFail_WhenAddTaskIsNotOk() { //Arrange var storageTask = new StorageTask { Title = "Mon titre" }; _storageQueueService.Setup(sto => sto.AddMessageAsync(storageTask)).ThrowsAsync(new ArgumentException()); //Act var result = await _addTask.ExecuteAsync(storageTask); //Assert _storageQueueService.Verify(sto => sto.AddMessageAsync(storageTask), Times.Once); Assert.Equal(Status.Fail, result.Status); }
public void IsTruthy_WhenServiceIsSigning() { //Arrange var storageTask = new StorageTask { Title = "Mon titre", Services = new List <Service> { Service.Signing } }; //Act var isValid = _addTaskValidator.Validate(storageTask); //Assert Assert.True(isValid); }
public async Task AddMessageAsync(StorageTask storageTask) { CloudStorageAccount storageAccount = new CloudStorageAccount( new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials( _appSettings.AccountName, _appSettings.AccountKey), true); // Create the CloudQueueClient object for the storage account. CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); // Get a reference to the CloudQueue named "messagequeue" CloudQueue messageQueue = queueClient.GetQueueReference(_appSettings.StorageQueueName); // Create a message and add it to the queue. CloudQueueMessage message = new CloudQueueMessage(JsonConvert.SerializeObject(storageTask, Formatting.Indented)); await messageQueue.AddMessageAsync(message); }
public async Task CreateJobAsync(StorageTask task) { var credentials = new BatchSharedKeyCredentials(BatchUrl, AccountName, AccountKey); using (BatchClient batchClient = await BatchClient.OpenAsync(credentials)) { // a job is uniquely identified by its ID so your account name along with a timestamp is added as suffix var jobId = $"{task.Id}"; var poolService = new PoolService(); var existingPoolJob = await poolService.CreatePoolIfNotExistAsync(batchClient, "pool-job"); await SubmitJobAsync(batchClient, jobId, existingPoolJob.Id); await CreateTasksAsync(batchClient, jobId, task); } }
public async Task ReturnSuccess_WhenHandleAzureBatchIsOk() { //Arrange var storageTask = new StorageTask { Title = "Mon titre" }; _azureBatchService.Setup(sto => sto.CreateJobAsync(It.IsAny <StorageTask>())).Returns(Task.CompletedTask); //Act var result = await _handleAzureBatch.ExecuteAsync(storageTask); //Assert _azureBatchService.Verify(sto => sto.CreateJobAsync(It.IsAny <StorageTask>()), Times.Once); Assert.Equal(Status.Success, result.Status); }
public async Task ReturnFail_WhenHandleAzureBatchIsNotOk() { //Arrange var storageTask = new StorageTask { Title = "Mon titre" }; _azureBatchService.Setup(sto => sto.CreateJobAsync(It.IsAny <StorageTask>())).ThrowsAsync(new ArgumentException()); //Act var result = await _handleAzureBatch.ExecuteAsync(storageTask); //Assert _azureBatchService.Verify(sto => sto.CreateJobAsync(It.IsAny <StorageTask>()), Times.Once); Assert.Equal(Status.Fail, result.Status); }
public async Task ReturnSuccess_WhenAddTaskIsOk() { //Arrange var storageTask = new StorageTask { Title = "Mon titre" }; _storageQueueService.Setup(sto => sto.AddMessageAsync(storageTask)).Returns(Task.CompletedTask); //Act var result = await _addTask.ExecuteAsync(storageTask); //Assert _storageQueueService.Verify(sto => sto.AddMessageAsync(storageTask), Times.Once); Assert.Equal(Status.Success, result.Status); }
public async Task <SecondaryTile> CreateTile(string tileID, string displayName, string activationArguments, TileImages tileImages, bool roamingEnabled = false) { Uri tileImage = null; if (tileImages.Square310x310.OriginalString.Contains("http://") || tileImages.Square310x310.OriginalString.Contains("https://")) { StorageFolder folder = await StorageTask.Instance.CreateFolder(RootFolder, TileManager.TileImagesFolderName, CreationCollisionOption.OpenIfExists); if (folder != null) { string fileName = tileID + ".jpg"; if (await StorageTask.Instance.SaveFileFromServer(folder, fileName, tileImages.Square310x310)) { tileImage = StorageTask.CreateUri(StorageLocationPrefix.LocalFolder, TileImagesFolderName + "/" + fileName); } } } if (tileImage == null) { tileImage = tileImages.Square310x310; } SecondaryTile secondaryTile = new SecondaryTile(tileID, displayName, activationArguments, tileImage, TileSize.Square150x150); secondaryTile.VisualElements.ForegroundText = ForegroundText.Dark; // Images //secondaryTile.VisualElements.Square30x30Logo = tileImage; // Deprecated in Windows 10 //secondaryTile.VisualElements.Square70x70Logo = tileImage; // Deprecated in Windows 10 secondaryTile.VisualElements.Square44x44Logo = tileImage; secondaryTile.VisualElements.Square71x71Logo = tileImage; secondaryTile.VisualElements.Square310x310Logo = tileImage; secondaryTile.VisualElements.Wide310x150Logo = tileImage; // Names secondaryTile.VisualElements.ShowNameOnSquare150x150Logo = true; secondaryTile.VisualElements.ShowNameOnWide310x150Logo = true; secondaryTile.VisualElements.ShowNameOnSquare310x310Logo = true; // Roaming secondaryTile.RoamingEnabled = roamingEnabled; return(secondaryTile); }
private async void Button_Tapped(object sender, TappedRoutedEventArgs e) { if (string.IsNullOrWhiteSpace(TestInput.Text)) { var folder = await StorageTask.Instance.GetFolder(StorageTask.LocalFolder, LockscreenManager.LockscreenImagesFolderName); var items = await StorageTask.Instance.GetAllFilesInFolder(folder); CurrentLockscreenImage.Source = new BitmapImage(new Uri(items[0].Path)); } else { var file = await StorageTask.Instance.GetFileFromPath(new Uri(TestInput.Text)); var bitmapImage = await StorageTask.StorageFileToBitmapImage(file); CurrentLockscreenImage.Source = bitmapImage; } }
public async Task <bool> UnPin(SecondaryTile tile, Rect elementRect) { bool result = await tile.RequestDeleteForSelectionAsync(elementRect, Windows.UI.Popups.Placement.Below); if (result) { try { StorageFolder tileFolder = await StorageTask.Instance.GetFolder(RootFolder, TileManager.TileImagesFolderName); StorageFile imageFile = await StorageTask.Instance.GetFile(tileFolder, tile.TileId + ".jpg"); await StorageTask.Instance.DeleteItem(StorageTask.StorageFileToIStorageItem(imageFile), StorageDeleteOption.PermanentDelete); } catch (Exception) { } } return(result); }
/// <summary> /// Begins an asynchronous write operation. /// </summary> /// <param name="buffer">The buffer to write data from.</param> /// <param name="offset">The byte offset in buffer from which to begin writing.</param> /// <param name="count">The number of bytes to write.</param> /// <param name="callback">An optional asynchronous callback, to be called when the write is complete.</param> /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param> /// <returns>An IAsyncResult that represents the asynchronous write, which could still be pending.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="buffer"/> is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">offset or count is negative.</exception> /// <exception cref="System.ObjectDisposedException">Thrown if blob is already committed/closed</exception> /// <remarks>The operation will be completed synchronously if the buffer is not filled</remarks> public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { this.CheckWriteState(); StreamUtilities.CheckBufferArguments(buffer, offset, count); StorageTask <NullTaskReturn> task = null; if (this.UseBlocks) { task = new InvokeTaskSequenceTask(() => { return(this.WriteBlockBlobImpl(buffer, offset, count)); }); } else { task = this.WriteNonBlockedBlobImpl(buffer, offset, count); } return(task.ToAsyncResult(callback, state)); }
public async Task <IActionResult> Post([FromBody] AddTaskInput addTaskInput) { var task = new StorageTask { Id = Guid.NewGuid(), Title = addTaskInput.Title, IsSuccess = addTaskInput.IsSuccess, Services = addTaskInput.Services }; //var resultHandle = await _handleAzureBatch.ExecuteAsync(task); var result = await _addTask.ExecuteAsync(task); var resultCreateInstance = _createContainerInstance.Execute(task); if (result.Status == Status.Success && resultCreateInstance.Status == Status.Success) { return(Ok("Task has been successfully added")); } return(BadRequest("Task cannot be added")); }
public async Task <IStorageResponse[]> GetDataAsync(params IStorageRequest[] requests) { var fixedrequests = new IStorageRequest[requests.Length]; for (int i = 0; i < requests.Length; ++i) { if (requests[i].Shape != null) { for (int j = 0; j < requests[i].Shape.Length; ++j) { int top = (requests[i].Origin == null ? 0 : requests[i].Origin[j]) + (requests[i].Stride == null ? 1 : requests[i].Stride[j]) * requests[i].Shape[j]; if (top > definition.DimensionsLengths[definition.VariablesDimensions[requests[i].VariableName][j]]) { throw new IndexOutOfRangeException("Requested area is out of bounds."); } } fixedrequests[i] = requests[i]; } else { int[] shp = new int[definition.VariablesDimensions[requests[i].VariableName].Length]; for (int j = 0; j < shp.Length; ++j) { shp[j] = (definition.DimensionsLengths[definition.VariablesDimensions[requests[i].VariableName][j]] - (requests[i].Origin == null ? 0 : requests[i].Origin[j])) / (requests[i].Stride == null ? 1 : requests[i].Stride[j]); } fixedrequests[i] = new StorageRequest(requests[i].VariableName, requests[i].Origin, requests[i].Stride, shp); } } var st = new StorageTask { Completion = new TaskCompletionSource <IStorageResponse[]>(), Request = fixedrequests }; requestHandler.OnNext(st); return(await st.Completion.Task); }
private void Perform(StorageTask task) { try { task.Completion.SetResult( task.Request.Select(r => { int[] shape = r.Shape == null ? dataSet.Variables[r.VariableName].GetShape() : r.Shape; //lock ("bytesCounter") //{ // bytesRead += // System.Runtime.InteropServices.Marshal.SizeOf(dataSet.Variables[r.VariableName].TypeOfData) // * shape.Aggregate(1L, (accShape, dimLen) => accShape * dimLen); //multipling dims length inside each request //} return(dataSet.PerformRequest(r)); }).ToArray()); } catch (Exception exc) { task.Completion.SetException(exc); } }
public void timePointStateBaseTest() { byte[] data = new byte[100]; string filename = "timePointStateBaseTest.data"; StorageReference storageReference = mAGCStorageManagement.getStorageReference(filename); UploadTask task = storageReference.putBytes(data, new FileMetadata()); StorageTask.ErrorResult err = task.getTimePointState(); StorageTask.TimePointStateBase timePoint = HmsUtil.GetHmsBase <StorageTask.TimePointStateBase>(err.obj); Exception e = timePoint.getError(); if (e == null) { Debug.Log("timePointStateBaseTest fail, error result is null"); return; } StorageReference timeRef = timePoint.getStorage(); if (timeRef == null) { Debug.Log("timePointStateBaseTest fail, timeRef is null"); return; } StorageTask storageTask = timePoint.getTask(); if (storageTask == null) { Debug.Log("timePointStateBaseTest fail, storageTask is null"); return; } Debug.Log("timePointStateBaseTest success"); }
public StorageTransferTaskWrapper(StorageTask transferTask) { _transferTask = transferTask; _observerDict = new Dictionary <Action <IStorageTaskSnapshot>, Object>(); }
private void processTask(StorageTask task) { if (task is BackupTask) { processTask((BackupTask)task); } else if (task is RestoreTask) { processTask((RestoreTask)task); } else { Logger.Error("StorageThread:processTask:StorageTask What kind of StorageTask is this?"); } }