public ICancellableAsyncResult BeginOpenRead(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state) { StorageAsyncResult<Stream> storageAsyncResult = new StorageAsyncResult<Stream>(callback, state); ICancellableAsyncResult result = this.BeginFetchAttributes( accessCondition, options, operationContext, ar => { try { this.EndFetchAttributes(ar); storageAsyncResult.UpdateCompletedSynchronously(ar.CompletedSynchronously); AccessCondition streamAccessCondition = AccessCondition.CloneConditionWithETag(accessCondition, this.Properties.ETag); BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, this.BlobType, this.ServiceClient, false); storageAsyncResult.Result = new BlobReadStream(this, streamAccessCondition, modifiedOptions, operationContext); storageAsyncResult.OnComplete(); } catch (Exception e) { storageAsyncResult.OnComplete(e); } }, null /* state */); storageAsyncResult.CancelDelegate = result.Cancel; return storageAsyncResult; }
/// <summary> /// Signs the specified HTTP request with a shared key. /// </summary> /// <param name="request">The HTTP request to sign.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> public void SignRequest(HttpWebRequest request, OperationContext operationContext) { CommonUtility.AssertNotNull("request", request); if (!request.Headers.AllKeys.Contains(Constants.HeaderConstants.Date, StringComparer.Ordinal)) { string dateString = HttpWebUtility.ConvertDateTimeToHttpString(DateTime.UtcNow); request.Headers.Add(Constants.HeaderConstants.Date, dateString); } if (this.credentials.IsSharedKey) { string message = this.canonicalizer.CanonicalizeHttpRequest(request, this.accountName); Logger.LogVerbose(operationContext, SR.TraceStringToSign, message); StorageAccountKey accountKey = this.credentials.Key; string signature = CryptoUtility.ComputeHmac256(accountKey.KeyValue, message); if (!string.IsNullOrEmpty(accountKey.KeyName)) { request.Headers.Add(Constants.HeaderConstants.KeyNameHeader, accountKey.KeyName); } request.Headers.Add( "Authorization", string.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}", this.canonicalizer.AuthorizationScheme, this.credentials.AccountName, signature)); } }
public Stream OpenWrite(long? size, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { this.attributes.AssertNoSnapshot(); BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.PageBlob, this.ServiceClient); bool createNew = size.HasValue; if (createNew) { this.Create(size.Value, accessCondition, modifiedOptions, operationContext); } else { if (modifiedOptions.StoreBlobContentMD5.Value) { throw new ArgumentException(SR.MD5NotPossible); } this.FetchAttributes(accessCondition, modifiedOptions, operationContext); size = this.Properties.Length; } if (accessCondition != null) { accessCondition = AccessCondition.GenerateLeaseCondition(accessCondition.LeaseId); } return new BlobWriteStream(this, size.Value, createNew, accessCondition, modifiedOptions, operationContext); }
public void RetryPolicyEnsure304IsNotRetried() { CloudBlobContainer container = BlobTestBase.GetRandomContainerReference(); container.Create(); try { CloudBlockBlob blob = container.GetBlockBlobReference("blob"); blob.UploadFromStream(new MemoryStream(new byte[50])); AccessCondition accessCondition = AccessCondition.GenerateIfModifiedSinceCondition(blob.Properties.LastModified.Value.AddMinutes(10)); OperationContext context = new OperationContext(); TestHelper.ExpectedException( () => blob.FetchAttributes(accessCondition, new BlobRequestOptions() { RetryPolicy = new ExponentialRetry() }, context), "FetchAttributes with invalid modified condition should return NotModified", HttpStatusCode.NotModified); TestHelper.AssertNAttempts(context, 1); context = new OperationContext(); TestHelper.ExpectedException( () => blob.FetchAttributes(accessCondition, new BlobRequestOptions() { RetryPolicy = new LinearRetry() }, context), "FetchAttributes with invalid modified condition should return NotModified", HttpStatusCode.NotModified); TestHelper.AssertNAttempts(context, 1); } finally { container.Delete(); } }
protected virtual void SendNotification(OperationContext context, string notificationType, string mediaType, string recipient, Guid? userId, IDictionary<string, object> parameters) { var msg = new NotificationMessage() { Type = notificationType, MediaType = mediaType, Recipients = recipient, MainRecipientUserId = userId, Culture = context.UserCulture, Parameters = parameters }; msg.From = _settings.DefaultEmailFrom; msg.Parameters[LoginNotificationKeys.BackHitUrlBase] = _settings.BackHitUrlBase; _notificationService.Send(context, msg); }
internal static object[] BindParameter(IPhotonSerializer serializer, OperationContext context) { var arguments = context.Method.Arguments; var methodParameters = new object[arguments.Length]; for (int i = 0; i < arguments.Length; i++) { var item = arguments[i]; object rawValue; context.OperationRequest.Parameters.TryGetValue((byte)i, out rawValue); if (rawValue == null) { if (item.IsOptional) { methodParameters[i] = item.DefaultValue; } else if (item.ParameterTypeIsClass || item.ParameterTypeIsNullable) { methodParameters[i] = null; } else if (item.ParameterTypeIsArray) { methodParameters[i] = Array.CreateInstance(item.ParameterType.GetElementType(), 0); } else { throw new InvalidOperationException($"Parameter Missing, {context.Hub.HubName}/{context.Method.MethodName}({item.Name})"); } } else { if (rawValue.GetType() != typeof(byte[])) { if (item.ParameterType != rawValue.GetType()) { if (item.ParameterTypeIsNullable) { methodParameters[i] = rawValue; // if nullable, use rawValue. continue; } var parameters = string.Join(", ", arguments.Select(x => { return (x == item) ? "[" + x.ParameterType.Name + " " + x.Name + "]" : x.ParameterType.Name + " " + x.Name; })); throw new InvalidOperationException($"Parameter Type Unmatch, {context.Hub.HubName}/{context.Method.MethodName}({parameters}) ReceivedType:{rawValue.GetType().Name} Value:{rawValue}"); } } methodParameters[i] = serializer.Deserialize(item.ParameterType, rawValue); } } return methodParameters; }
public override void InitController(OperationContext context) { base.InitController(context); _processService = context.App.GetService<ILoginProcessService>(); _incidentLog = Context.App.GetService<IIncidentLogService>(); _loginSettings = Context.App.GetConfig<LoginModuleSettings>(); }
/// <summary> /// Determines whether the operation should be retried and the interval until the next retry. /// </summary> /// <param name="currentRetryCount">An integer specifying the number of retries for the given operation. A value of zero signifies this is the first error encountered.</param> /// <param name="statusCode">An integer containing the status code for the last operation.</param> /// <param name="lastException">An <see cref="Exception"/> object that represents the last exception encountered.</param> /// <param name="retryInterval">A <see cref="TimeSpan"/> indicating the interval to wait until the next retry.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns><c>true</c> if the operation should be retried; otherwise, <c>false</c>.</returns> public bool ShouldRetry(int currentRetryCount, int statusCode, Exception lastException, out TimeSpan retryInterval, OperationContext operationContext) { CommonUtility.AssertNotNull("lastException", lastException); retryInterval = TimeSpan.Zero; // If this method is called after a successful response, it means // we failed during the response body download. So, we should not // check for success codes here. if ((statusCode >= 300 && statusCode < 500 && statusCode != 408) || statusCode == 501 // Not Implemented || statusCode == 505 // Version Not Supported || lastException.Message == SR.BlobTypeMismatch) { return false; } if (currentRetryCount < this.maximumAttempts) { Random r = new Random(); double increment = (Math.Pow(2, currentRetryCount) - 1) * r.Next((int)(this.deltaBackoff.TotalMilliseconds * 0.8), (int)(this.deltaBackoff.TotalMilliseconds * 1.2)); retryInterval = (increment < 0) ? ExponentialRetry.MaxBackoff : TimeSpan.FromMilliseconds(Math.Min(ExponentialRetry.MaxBackoff.TotalMilliseconds, ExponentialRetry.MinBackoff.TotalMilliseconds + increment)); return true; } return false; }
/// <summary> /// Creates the web request. /// </summary> /// <param name="method">The HTTP method.</param> /// <param name="uri">The request URI.</param> /// <param name="timeout">The timeout.</param> /// <param name="builder">An object of type <see cref="UriQueryBuilder"/>, containing additional parameters to add to the URI query string.</param> /// <param name="operationContext">An <see cref="OperationContext" /> object for tracking the current operation.</param> /// <returns> /// A web request for performing the operation. /// </returns> internal static HttpWebRequest CreateWebRequest(string method, Uri uri, int? timeout, UriQueryBuilder builder, OperationContext operationContext) { if (builder == null) { builder = new UriQueryBuilder(); } if (timeout != 0) { builder.Add("timeout", timeout.ToString()); } Uri uriRequest = builder.AddToUri(uri); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriRequest); request.Method = method; request.Headers.Add(Constants.HeaderConstants.StorageVersionHeader, Constants.HeaderConstants.TargetStorageVersion); request.UserAgent = Constants.HeaderConstants.UserAgent; request.KeepAlive = true; // Disable the Expect 100-Continue request.ServicePoint.Expect100Continue = false; return request; }
/// <summary> /// Returns an enumerable collection of the queues in the storage account whose names begin with the specified prefix and that are retrieved lazily. /// </summary> /// <param name="prefix">The queue name prefix.</param> /// <param name="queueListingDetails">An enumeration value that indicates which details to include in the listing.</param> /// <param name="options">An object that specifies any additional options for the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation. This object is used to track requests, and to provide additional runtime information about the operation.</param> /// <returns>An enumerable collection of objects that implement <see cref="CloudQueue"/> and are retrieved lazily.</returns> public IEnumerable<CloudQueue> ListQueues(string prefix, QueueListingDetails queueListingDetails = QueueListingDetails.None, QueueRequestOptions options = null, OperationContext operationContext = null) { QueueRequestOptions modifiedOptions = QueueRequestOptions.ApplyDefaults(options, this); operationContext = operationContext ?? new OperationContext(); return General.LazyEnumerable((token) => this.ListQueuesSegmentedCore(prefix, queueListingDetails, 0, token as QueueContinuationToken, modifiedOptions, operationContext), long.MaxValue, operationContext); }
//Login admin - add interface for admins public SearchResults<ILogin> SearchLogins(OperationContext context, LoginSearch search) { var utcNow = context.App.TimeService.UtcNow; var session = context.OpenSession(); search = search.DefaultIfNull(take: 20, defaultOrderBy: "UserName"); var where = session.NewPredicate<ILogin>() .AndIfNotEmpty(search.TenantId, lg => lg.TenantId == search.TenantId.Value) .AndIfNotEmpty(search.UserName, lg => lg.UserName.StartsWith(search.UserName)) .AndIfNotEmpty(search.UserId, lg => lg.UserId == search.UserId) .AndIfNotEmpty(search.ExpiringBefore, lg => lg.Expires != null && lg.Expires < search.ExpiringBefore.Value) .AndIfNotEmpty(search.CreatedAfter, lg => lg.CreatedOn >= search.CreatedAfter.Value) .AndIfNotEmpty(search.CreatedBefore, lg => lg.CreatedOn <= search.CreatedBefore.Value) .AndIf(search.EnabledOnly, lg => (lg.Flags & LoginFlags.Disabled) == 0) .AndIf(search.SuspendedOnly, lg => (lg.Flags & LoginFlags.Suspended) == 0 && lg.SuspendedUntil > utcNow); if (!string.IsNullOrWhiteSpace(search.Email)) { var factorHash = Util.StableHash(search.Email.Trim().ToLowerInvariant()); var subQuery = session.EntitySet<ILoginExtraFactor>().Where(f => f.InfoHash == factorHash).Select(f => f.Login.Id); where = where.And(lg => subQuery.Contains(lg.Id)); }; var result = session.ExecuteSearch(where, search); if(LoginExtensions.CheckSuspensionEnded(result.Results, utcNow)) { } return result; }
public Stream OpenRead(AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { this.FetchAttributes(accessCondition, options, operationContext); AccessCondition streamAccessCondition = AccessCondition.CloneConditionWithETag(accessCondition, this.Properties.ETag); BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, this.BlobType, this.ServiceClient, false); return new BlobReadStream(this, streamAccessCondition, modifiedOptions, operationContext); }
/// <summary> /// Opens a stream for writing to the blob. /// </summary> /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the access conditions for the blob. If <c>null</c>, no condition is used.</param> /// <param name="options">A <see cref="BlobRequestOptions"/> object that specifies any additional options for the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A stream to be used for writing to the blob.</returns> public Stream OpenWrite(AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { this.attributes.AssertNoSnapshot(); BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.BlockBlob, this.ServiceClient); if ((accessCondition != null) && accessCondition.IsConditional) { try { this.FetchAttributes(accessCondition, modifiedOptions, operationContext); } catch (StorageException e) { if ((e.RequestInformation != null) && (e.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound) && string.IsNullOrEmpty(accessCondition.IfMatchETag)) { // If we got a 404 and the condition was not an If-Match, // we should continue with the operation. } else { throw; } } } return new BlobWriteStream(this, accessCondition, modifiedOptions, operationContext); }
/// <summary> /// Constructs a web request to create a new block blob or page blob, or to update the content /// of an existing block blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="properties">The properties to set for the blob.</param> /// <param name="blobType">The type of the blob.</param> /// <param name="pageBlobSize">For a page blob, the size of the blob. This parameter is ignored /// for block blobs.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static HttpRequestMessage Put(Uri uri, int? timeout, BlobProperties properties, BlobType blobType, long pageBlobSize, AccessCondition accessCondition, HttpContent content, OperationContext operationContext) { if (blobType == BlobType.Unspecified) { throw new InvalidOperationException(SR.UndefinedBlobType); } HttpRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, null /* builder */, content, operationContext); if (properties.CacheControl != null) { request.Headers.CacheControl = CacheControlHeaderValue.Parse(properties.CacheControl); } if (content != null) { if (properties.ContentType != null) { content.Headers.ContentType = MediaTypeHeaderValue.Parse(properties.ContentType); } if (properties.ContentMD5 != null) { content.Headers.ContentMD5 = Convert.FromBase64String(properties.ContentMD5); } if (properties.ContentLanguage != null) { content.Headers.ContentLanguage.Add(properties.ContentLanguage); } if (properties.ContentEncoding != null) { content.Headers.ContentEncoding.Add(properties.ContentEncoding); } if (properties.ContentDisposition != null) { content.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse(properties.ContentDisposition); } } if (blobType == BlobType.PageBlob) { request.Headers.Add(Constants.HeaderConstants.BlobType, Constants.HeaderConstants.PageBlob); request.Headers.Add(Constants.HeaderConstants.BlobContentLengthHeader, pageBlobSize.ToString(NumberFormatInfo.InvariantInfo)); properties.Length = pageBlobSize; } else if (blobType == BlobType.BlockBlob) { request.Headers.Add(Constants.HeaderConstants.BlobType, Constants.HeaderConstants.BlockBlob); } else { request.Headers.Add(Constants.HeaderConstants.BlobType, Constants.HeaderConstants.AppendBlob); } request.ApplyAccessCondition(accessCondition); return request; }
public virtual Task<CloudBlobStream> OpenWriteAsync(bool createNew, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { this.attributes.AssertNoSnapshot(); BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.AppendBlob, this.ServiceClient, false); if (!createNew && modifiedOptions.StoreBlobContentMD5.Value) { throw new ArgumentException(SR.MD5NotPossible); } return Task.Run(async () => { if (createNew) { await this.CreateOrReplaceAsync(accessCondition, options, operationContext, cancellationToken); } else { // Although we don't need any properties from the service, we should make this call in order to honor the user specified conditional headers // while opening an existing stream and to get the append position for an existing blob if user didn't specify one. await this.FetchAttributesAsync(accessCondition, options, operationContext, cancellationToken); } if (accessCondition != null) { accessCondition = new AccessCondition() { LeaseId = accessCondition.LeaseId, IfAppendPositionEqual = accessCondition.IfAppendPositionEqual, IfMaxSizeLessThanOrEqual = accessCondition.IfMaxSizeLessThanOrEqual }; } CloudBlobStream stream = new BlobWriteStream(this, accessCondition, modifiedOptions, operationContext); return stream; }, cancellationToken); }
public async Task CloudBlockBlobCopyTestAsync() { CloudBlobContainer container = GetRandomContainerReference(); try { await container.CreateAsync(); CloudBlockBlob source = container.GetBlockBlobReference("source"); string data = "String data"; await UploadTextAsync(source, data, Encoding.UTF8); source.Metadata["Test"] = "value"; await source.SetMetadataAsync(); CloudBlockBlob copy = container.GetBlockBlobReference("copy"); string copyId = await copy.StartCopyFromBlobAsync(TestHelper.Defiddler(source)); await WaitForCopyAsync(copy); Assert.AreEqual(CopyStatus.Success, copy.CopyState.Status); Assert.AreEqual(source.Uri.AbsolutePath, copy.CopyState.Source.AbsolutePath); Assert.AreEqual(data.Length, copy.CopyState.TotalBytes); Assert.AreEqual(data.Length, copy.CopyState.BytesCopied); Assert.AreEqual(copyId, copy.CopyState.CopyId); Assert.IsTrue(copy.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1))); OperationContext opContext = new OperationContext(); await TestHelper.ExpectedExceptionAsync( async () => await copy.AbortCopyAsync(copyId, null, null, opContext), opContext, "Aborting a copy operation after completion should fail", HttpStatusCode.Conflict, "NoPendingCopyOperation"); await source.FetchAttributesAsync(); Assert.IsNotNull(copy.Properties.ETag); Assert.AreNotEqual(source.Properties.ETag, copy.Properties.ETag); Assert.IsTrue(copy.Properties.LastModified > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1))); string copyData = await DownloadTextAsync(copy, Encoding.UTF8); Assert.AreEqual(data, copyData, "Data inside copy of blob not similar"); await copy.FetchAttributesAsync(); BlobProperties prop1 = copy.Properties; BlobProperties prop2 = source.Properties; Assert.AreEqual(prop1.CacheControl, prop2.CacheControl); Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding); Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage); Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5); Assert.AreEqual(prop1.ContentType, prop2.ContentType); Assert.AreEqual("value", copy.Metadata["Test"], false, "Copied metadata not same"); await copy.DeleteAsync(); } finally { container.DeleteIfExistsAsync().AsTask().Wait(); } }
/// <summary> /// Creates the web request. /// </summary> /// <param name="uri">The request Uri.</param> /// <param name="timeout">The timeout.</param> /// <param name="builder">The builder.</param> /// <returns>A web request for performing the operation.</returns> internal static StorageRequestMessage CreateRequestMessage(HttpMethod method, Uri uri, int? timeout, UriQueryBuilder builder, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { if (builder == null) { builder = new UriQueryBuilder(); } if (timeout.HasValue && timeout.Value > 0) { builder.Add("timeout", timeout.ToString()); } #if WINDOWS_RT && !NETCORE // Windows Phone does not allow the caller to disable caching, so a random GUID // is added to every URI to make it look like a different request. builder.Add("randomguid", Guid.NewGuid().ToString("N")); #endif Uri uriRequest = builder.AddToUri(uri); StorageRequestMessage msg = new StorageRequestMessage(method, uriRequest, canonicalizer, credentials, credentials.AccountName); msg.Content = content; return msg; }
public async Task StreamWriteAsyncTest() { byte[] buffer = GetRandomBuffer(1 * 1024 * 1024); MemoryStream stream1 = new MemoryStream(buffer); MemoryStream stream2 = new MemoryStream(); OperationContext tempOperationContext = new OperationContext(); RESTCommand<NullType> cmd = new RESTCommand<NullType>(TestBase.StorageCredentials, null); ExecutionState<NullType> tempExecutionState = new ExecutionState<NullType>(cmd, null, tempOperationContext); // Test basic write await stream1.WriteToAsync(stream2, null, null, false, tempExecutionState, null, CancellationToken.None); stream1.Position = 0; TestHelper.AssertStreamsAreEqual(stream1, stream2); stream2.Dispose(); stream2 = new MemoryStream(); await TestHelper.ExpectedExceptionAsync<ArgumentException>( async () => await stream1.WriteToAsync(stream2, 1024, 1024, false, tempExecutionState, null, CancellationToken.None), "Parameters copyLength and maxLength cannot be passed simultaneously."); stream1.Dispose(); stream2.Dispose(); }
/// <summary> /// Opens a stream for writing to the blob. /// </summary> /// <param name="size">The size of the write operation, in bytes. The size must be a multiple of 512.</param> /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the access conditions for the blob. If <c>null</c>, no condition is used.</param> /// <param name="options">A <see cref="BlobRequestOptions"/> object that specifies any additional options for the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A stream to be used for writing to the blob.</returns> public IAsyncOperation<IOutputStream> OpenWriteAsync(long? size, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { this.attributes.AssertNoSnapshot(); BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.PageBlob, this.ServiceClient); bool createNew = size.HasValue; if (!createNew && modifiedOptions.StoreBlobContentMD5.Value) { throw new ArgumentException(SR.MD5NotPossible); } return AsyncInfo.Run(async (token) => { if (createNew) { await this.CreateAsync(size.Value, accessCondition, modifiedOptions, operationContext); } else { await this.FetchAttributesAsync(accessCondition, modifiedOptions, operationContext); size = this.Properties.Length; } if (accessCondition != null) { accessCondition = AccessCondition.GenerateLeaseCondition(accessCondition.LeaseId); } return new BlobWriteStream(this, size.Value, createNew, accessCondition, modifiedOptions, operationContext).AsOutputStream(); }); }
public async Task FileWriteStreamOpenAndCloseAsync() { CloudFileShare share = GetRandomShareReference(); try { await share.CreateAsync(); CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1"); OperationContext opContext = new OperationContext(); await TestHelper.ExpectedExceptionAsync( async () => await file.OpenWriteAsync(null, null, null, opContext), opContext, "Opening a file stream with no size should fail on a file that does not exist", HttpStatusCode.NotFound); using (Stream writeStream = await file.OpenWriteAsync(1024)) { } using (Stream writeStream = await file.OpenWriteAsync(null)) { } CloudFile file2 = share.GetRootDirectoryReference().GetFileReference("file1"); await file2.FetchAttributesAsync(); Assert.AreEqual(1024, file2.Properties.Length); } finally { share.DeleteAsync().Wait(); } }
public IIncidentLog LogIncident(string incidentType, string message, string incidentSubType = null, Guid? keyId1 = null, Guid? keyId2 = null, string key1 = null, string key2 = null, string key3 = null, string key4 = null, string notes = null, OperationContext context = null) { var session = App.OpenSystemSession(); var log = session.NewEntity<IIncidentLog>(); log.CreatedOn = App.TimeService.UtcNow; log.Type = incidentType; log.SubType = incidentSubType; log.Message = message; log.KeyId1 = keyId1; log.KeyId2 = keyId2; log.Key1 = key1; log.Key2 = key2; log.LongKey3 = key3; log.LongKey4 = key4; log.Notes = notes; //Get web call id if available if(context != null) { log.UserName = context.User.UserName; if (context.UserSession != null) log.UserSessionId = context.UserSession.SessionId; if (context.WebContext != null) log.WebCallId = context.WebContext.Id; } session.SaveChanges(); OnNewIncident(log); return log; }
internal IncomingWebRequestContext (OperationContext context) { if (context.IncomingMessageProperties != null) hp = (HttpRequestMessageProperty) context.IncomingMessageProperties [HttpRequestMessageProperty.Name]; else hp = new HttpRequestMessageProperty (); }
public async Task RetryDelayShouldBeCancellableAsync() { TaskCompletionSource<bool> responseTask = new TaskCompletionSource<bool>(); BlobRequestOptions options = new BlobRequestOptions(); options.RetryPolicy = new AlwaysRetry(TimeSpan.FromMinutes(1), 1); OperationContext context = new OperationContext(); context.ResponseReceived += (sender, e) => responseTask.SetResult(true); CloudBlobClient blobClient = GenerateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("test" + DateTime.UtcNow.Ticks.ToString()); CancellationTokenSource token = new CancellationTokenSource(); Task task = container.FetchAttributesAsync(null, options, context).AsTask(token.Token); await responseTask.Task; await Task.Delay(10 * 1000); Stopwatch stopwatch = Stopwatch.StartNew(); try { token.Cancel(); await task; } catch (Exception) { // This is expected, because we went for an invalid domain name. } stopwatch.Stop(); Assert.IsTrue(stopwatch.Elapsed < TimeSpan.FromSeconds(10), stopwatch.Elapsed.ToString()); Assert.AreEqual(1, context.RequestResults.Count); }
public IndexAddTask(QueryIndexManager indexManager, object key, CacheEntry value, OperationContext operationContext) { _key = key; _entry = value; _indexManager = indexManager; _operationContext = operationContext; }
/// <summary> /// Determines if the operation should be retried and how long to wait until the next retry. /// </summary> /// <param name="currentRetryCount">The number of retries for the given operation. A value of zero signifies this is the first error encountered.</param> /// <param name="statusCode">The status code for the last operation.</param> /// <param name="lastException">An <see cref="Exception"/> object that represents the last exception encountered.</param> /// <param name="retryInterval">The interval to wait until the next retry.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object for tracking the current operation.</param> /// <returns><c>true</c> if the operation should be retried; otherwise, <c>false</c>.</returns> public bool ShouldRetry(int currentRetryCount, int statusCode, Exception lastException, out TimeSpan retryInterval, OperationContext operationContext) { retryInterval = TimeSpan.Zero; if ((statusCode >= 400 && statusCode < 500) || statusCode == 306 // Internal error / Cancellation || statusCode == 501 // Not Implemented || statusCode == 505 // Version Not Supported || lastException.Message == SR.BlobTypeMismatch) { return false; } if (currentRetryCount < this.maximumAttempts) { Random r = new Random(); int increment = (int)((Math.Pow(2, currentRetryCount) - 1) * r.Next((int)(this.deltaBackoff.TotalMilliseconds * 0.8), (int)(this.deltaBackoff.TotalMilliseconds * 1.2))); if (increment < 0 || increment > this.maxBackoff.TotalMilliseconds) { retryInterval = this.maxBackoff; } else { retryInterval = TimeSpan.FromMilliseconds(this.minBackoff.TotalMilliseconds + increment); } return true; } return false; }
public void RegisterForReplay(OperationContext operationContext) { this.messageBuffer = (MessageBuffer)operationContext.IncomingMessageProperties[ChannelHandler.MessageBufferPropertyName]; // cannot remove the MessageBufferProperty from messageProperties because it causes the message buffer associated with the property // to be disposed of. Assigning null to the property has the same effect, so we assign dummyMessageBuffer to the property. operationContext.IncomingMessageProperties[ChannelHandler.MessageBufferPropertyName] = dummyMessageBuffer; }
internal static HttpWebRequest BuildRequestForTableQuery(Uri uri, UriQueryBuilder builder, int? timeout, bool useVersionHeader, OperationContext ctx, TablePayloadFormat payloadFormat) { HttpWebRequest msg = BuildRequestCore(uri, builder, "GET", timeout, useVersionHeader, ctx); SetAcceptHeaderForHttpWebRequest(msg, payloadFormat); Logger.LogInformational(ctx, SR.PayloadFormat, payloadFormat); return msg; }
public static void SuppressContextOnReply(OperationContext operationContext) { if (operationContext == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operationContext"); } operationContext.OutgoingMessageProperties[suppressContextOnReply] = true; }
public void Create(BlobContainerPublicAccessType accessType, BlobRequestOptions requestOptions = null, OperationContext operationContext = null) { BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(requestOptions, BlobType.Unspecified, this.ServiceClient); Executor.ExecuteSync( this.CreateContainerImpl(modifiedOptions, accessType), modifiedOptions.RetryPolicy, operationContext); }
internal TableResult Execute(CloudTableClient client, CloudTable table, TableRequestOptions requestOptions, OperationContext operationContext) { TableRequestOptions modifiedOptions = TableRequestOptions.ApplyDefaults(requestOptions, client); operationContext = operationContext ?? new OperationContext(); CommonUtility.AssertNotNullOrEmpty("tableName", table.Name); return Executor.ExecuteSync(this.GenerateCMDForOperation(client, table, modifiedOptions), modifiedOptions.RetryPolicy, operationContext); }
public bool ShouldRetry(int currentRetryCount, int statusCode, Exception lastException, out TimeSpan retryInterval, OperationContext operationContext) { retryInterval = this.deltaBackoff; return(currentRetryCount < this.maximumAttempts); }
/// <summary> /// Returns a result segment containing a collection of queues. /// </summary> /// <param name="prefix">A string containing the queue name prefix.</param> /// <param name="queueListingDetails">A <see cref="QueueListingDetails"/> enumeration describing which items to include in the listing.</param> /// <param name="maxResults">A non-negative integer value that indicates the maximum number of results to be returned at a time, up to the /// per-operation limit of 5000. If this value is <c>null</c>, the maximum possible number of results will be returned, up to 5000.</param> /// <param name="currentToken">A <see cref="QueueContinuationToken"/> returned by a previous listing operation.</param> /// <param name="options">A <see cref="QueueRequestOptions"/> object that specifies additional options for the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A <see cref="ResultSegment{T}"/> of type <see cref="CloudQueue"/>.</returns> private ResultSegment <CloudQueue> ListQueuesSegmentedCore(string prefix, QueueListingDetails queueListingDetails, int?maxResults, QueueContinuationToken currentToken, QueueRequestOptions options, OperationContext operationContext) { return(Executor.ExecuteSync( this.ListQueuesImpl(prefix, maxResults, queueListingDetails, options, currentToken), options.RetryPolicy, operationContext)); }
/// <summary> /// Return a task that asynchronously delete the specified blob /// </summary> /// <param name="blob">ICloudBlob object</param> /// <param name="deleteSnapshotsOption">Snapshot delete option</param> /// <param name="accessCondition">Access condition</param> /// <param name="requestOptions">Blob request option</param> /// <param name="operationContext">Operation context</param> /// <param name="cmdletCancellationToken">Cancellation token</param> /// <returns>Return a task that asynchronously delete the specified blob</returns> public Task DeleteICloudBlobAsync(ICloudBlob blob, DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { return(blob.DeleteAsync(deleteSnapshotsOption, accessCondition, requestOptions, operationContext, cancellationToken)); }
/// <summary> /// Return a task that asynchronously set blob meta data /// </summary> /// <param name="blob">ICloud blob object</param> /// <param name="accessCondition">Access condition</param> /// <param name="options">Blob request options</param> /// <param name="operationContext">An object that represents the context for the current operation.</param> public Task SetBlobMetadataAsync(ICloudBlob blob, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cmdletCancellationToken) { return(blob.SetMetadataAsync(accessCondition, options, operationContext, cmdletCancellationToken)); }
/// <summary> /// Return a task that asynchronously fetch blob attributes /// </summary> /// <param name="blob">ICloud blob object</param> /// <param name="accessCondition">Access condition</param> /// <param name="options">Blob request options</param> /// <param name="operationContext">Operation context</param> /// <param name="cmdletCancellationToken">Cancellation token</param> /// <returns>Return a task that asynchronously fetch blob attributes</returns> public Task FetchBlobAttributesAsync(ICloudBlob blob, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { return(blob.FetchAttributesAsync(accessCondition, options, operationContext, cancellationToken)); }
/// <summary> /// Get a list of cloudblobcontainer in azure /// </summary> /// <param name="prefix">Container prefix</param> /// <param name="detailsIncluded">Container listing details</param> /// <param name="options">Blob request option</param> /// <param name="operationContext">Operation context</param> /// <returns>An enumerable collection of cloudblobcontainer</returns> public IEnumerable <CloudBlobContainer> ListContainers(string prefix, ContainerListingDetails detailsIncluded, BlobRequestOptions options, OperationContext operationContext) { return(blobClient.ListContainers(prefix, detailsIncluded, options, operationContext)); }
/// <summary> /// Generates a web request to return the user-defined metadata for this container. /// </summary> /// <param name="uri">A <see cref="System.Uri"/> specifying the absolute URI to the container.</param> /// <param name="timeout">An integer specifying the server timeout interval.</param> /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the condition that must be met in order for the request to proceed.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns> public static HttpWebRequest GetMetadata(Uri uri, int?timeout, AccessCondition accessCondition, OperationContext operationContext) { UriQueryBuilder containerBuilder = GetContainerUriQueryBuilder(); HttpWebRequest request = HttpWebRequestFactory.GetMetadata(uri, timeout, containerBuilder, operationContext); request.ApplyAccessCondition(accessCondition); return(request); }
public MemoryLog(OperationContext context, int maxEntries = 200) { _context = context; MaxEntries = maxEntries; }
public string Foo(OperationContext context, string p1) { Util.Check(context != null, "Operation context not provided"); return("Foo:" + p1); }
protected override WorkflowCreationContext OnGetCreationContext(object[] inputs, OperationContext operationContext, Guid instanceId, WorkflowHostingResponseContext responseContext) { WorkflowCreationContext creationContext = new WorkflowCreationContext(); if (operationContext.IncomingMessageHeaders.Action.EndsWith("Create")) { Dictionary <string, object> arguments = (Dictionary <string, object>)inputs[0]; if (arguments != null && arguments.Count > 0) { foreach (KeyValuePair <string, object> pair in arguments) { //arguments to pass to the workflow creationContext.WorkflowArguments.Add(pair.Key, pair.Value); } } //reply to client with instanceId responseContext.SendResponse(instanceId, null); } else if (operationContext.IncomingMessageHeaders.Action.EndsWith("CreateWithInstanceId")) { Dictionary <string, object> arguments = (Dictionary <string, object>)inputs[0]; if (arguments != null && arguments.Count > 0) { foreach (KeyValuePair <string, object> pair in arguments) { //arguments to pass to workflow creationContext.WorkflowArguments.Add(pair.Key, pair.Value); } } } else { throw new InvalidOperationException("Invalid Action: " + operationContext.IncomingMessageHeaders.Action); } return(creationContext); }
/// <summary> /// Return a task that asynchronously delete the specified container. /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="accessCondition">Access condition</param> /// <param name="requestOptions">Blob request option</param> /// <param name="operationContext">Operation context</param> /// <param name="cmdletCancellationToken">Cancellation token</param> /// <returns>Return a task that asynchronously delete the specified container.</returns> public Task DeleteContainerAsync(CloudBlobContainer container, AccessCondition accessCondition, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { return(container.DeleteAsync(accessCondition, requestOptions, operationContext, cancellationToken)); }
/// <summary> /// Return a task that asynchronously set the container permission /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="permissions">Container permission</param> /// <param name="accessCondition">Access condition</param> /// <param name="requestOptions">Blob request option</param> /// <param name="operationContext">Operation context</param> /// <param name="cmdletCancellationToken">cancellation token</param> /// <returns>Return a task that asynchronously set the container permission</returns> public Task SetContainerPermissionsAsync(CloudBlobContainer container, BlobContainerPermissions permissions, AccessCondition accessCondition, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { return(container.SetPermissionsAsync(permissions, accessCondition, requestOptions, operationContext, cancellationToken)); }
public override void ReadEntity(IDictionary <string, EntityProperty> properties, OperationContext operationContext) { base.ReadEntity(properties, operationContext); Attachments = JsonConvert.DeserializeObject <List <TestRunAttachmentLink> >(properties["attachments"].StringValue); }
/// <summary> /// Constructor /// </summary> /// <param name="cache"></param> /// <param name="key"></param> public AsyncRemove(Cache cache, object key, OperationContext operationContext) { _cache = cache; _key = key; _operationContext = operationContext; }
/// <summary> /// Get container presssions /// </summary> /// <param name="container">A cloudblobcontainer object</param> /// <param name="accessCondition">Access condition</param> /// <param name="options">Blob request option</param> /// <param name="operationContext">Operation context</param> /// <returns>The container's permission</returns> public BlobContainerPermissions GetContainerPermissions(CloudBlobContainer container, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { return(container.GetPermissions(accessCondition, options, operationContext)); }
/// <summary> /// Constructs a web request to create a new container. /// </summary> /// <param name="uri">A <see cref="System.Uri"/> specifying the absolute URI to the container.</param> /// <param name="timeout">An integer specifying the server timeout interval.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns> public static HttpWebRequest Create(Uri uri, int?timeout, OperationContext operationContext) { return(ContainerHttpWebRequestFactory.Create(uri, timeout, operationContext, BlobContainerPublicAccessType.Off)); }
/// <summary> /// Get a list of cloudblobcontainer in azure /// </summary> /// <param name="prefix">Container prefix</param> /// <param name="detailsIncluded">Container listing details</param> /// <param name="options">Blob request option</param> /// <param name="operationContext">Operation context</param> /// <returns>An enumerable collection of cloudblobcontainer</returns> public ContainerResultSegment ListContainersSegmented(string prefix, ContainerListingDetails detailsIncluded, int?maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext) { return(blobClient.ListContainersSegmented(prefix, detailsIncluded, maxResults, currentToken, options, operationContext)); }
/// <summary> /// Generates a web request to return a listing of all blobs in the container. /// </summary> /// <param name="uri">A <see cref="System.Uri"/> specifying the absolute URI to the container.</param> /// <param name="timeout">An integer specifying the server timeout interval.</param> /// <param name="listingContext">A <see cref="ListingContext"/> object.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns> public static HttpWebRequest ListBlobs(Uri uri, int?timeout, BlobListingContext listingContext, OperationContext operationContext) { UriQueryBuilder builder = ContainerHttpWebRequestFactory.GetContainerUriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "list"); if (listingContext != null) { if (listingContext.Prefix != null) { builder.Add("prefix", listingContext.Prefix); } if (listingContext.Delimiter != null) { builder.Add("delimiter", listingContext.Delimiter); } if (listingContext.Marker != null) { builder.Add("marker", listingContext.Marker); } if (listingContext.MaxResults != null) { builder.Add("maxresults", listingContext.MaxResults.ToString()); } if (listingContext.Details != BlobListingDetails.None) { StringBuilder sb = new StringBuilder(); bool started = false; if ((listingContext.Details & BlobListingDetails.Snapshots) == BlobListingDetails.Snapshots) { if (!started) { started = true; } else { sb.Append(","); } sb.Append("snapshots"); } if ((listingContext.Details & BlobListingDetails.UncommittedBlobs) == BlobListingDetails.UncommittedBlobs) { if (!started) { started = true; } else { sb.Append(","); } sb.Append("uncommittedblobs"); } if ((listingContext.Details & BlobListingDetails.Metadata) == BlobListingDetails.Metadata) { if (!started) { started = true; } else { sb.Append(","); } sb.Append("metadata"); } if ((listingContext.Details & BlobListingDetails.Copy) == BlobListingDetails.Copy) { if (!started) { started = true; } else { sb.Append(","); } sb.Append("copy"); } builder.Add("include", sb.ToString()); } } HttpWebRequest request = HttpWebRequestFactory.CreateWebRequest(WebRequestMethods.Http.Get, uri, timeout, builder, operationContext); return(request); }
/// List part of blobs. /// </summary> /// <param name="prefix">Blob prefix</param> /// <param name="useFlatBlobListing">Use flat blob listing</param> /// <param name="blobListingDetails">Blob listing details.</param> /// <param name="maxResults">Max results.</param> /// <param name="currentToken">Current token.</param> /// <param name="options">Request options</param> /// <param name="operationContext">Operation Context.</param> /// <returns>BlobResultSegment object</returns> public BlobResultSegment ListBlobsSegmented(CloudBlobContainer container, string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int?maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext) { return(container.ListBlobsSegmented(prefix, useFlatBlobListing, blobListingDetails, maxResults, currentToken, options, operationContext)); }
public static HttpWebRequest SetAcl(Uri uri, int?timeout, BlobContainerPublicAccessType publicAccess, AccessCondition accessCondition, OperationContext operationContext) { HttpWebRequest request = HttpWebRequestFactory.SetAcl(uri, GetContainerUriQueryBuilder(), timeout, operationContext); if (publicAccess != BlobContainerPublicAccessType.Off) { request.Headers.Add(Constants.HeaderConstants.ContainerPublicAccessType, publicAccess.ToString().ToLower()); } request.ApplyAccessCondition(accessCondition); return(request); }
/// <summary> /// Constructs a web request to return the ACL for a container. /// </summary> /// <param name="uri">A <see cref="System.Uri"/> specifying the absolute URI to the container.</param> /// <param name="timeout">An integer specifying the server timeout interval.</param> /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the condition that must be met in order for the request to proceed.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns> public static HttpWebRequest GetAcl(Uri uri, int?timeout, AccessCondition accessCondition, OperationContext operationContext) { HttpWebRequest request = HttpWebRequestFactory.GetAcl(uri, GetContainerUriQueryBuilder(), timeout, operationContext); request.ApplyAccessCondition(accessCondition); return(request); }
/// <summary> /// Constructs a web request to return a listing of all containers in this storage account. /// </summary> /// <param name="uri">A <see cref="System.Uri"/> specifying the Blob service endpoint.</param> /// <param name="timeout">An integer specifying the server timeout interval.</param> /// <param name="listingContext">A <see cref="ListingContext"/> object.</param> /// <param name="detailsIncluded">A <see cref="ContainerListingDetails"/> enumeration value that indicates whether to return container metadata with the listing.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A web request for the specified operation.</returns> public static HttpWebRequest List(Uri uri, int?timeout, ListingContext listingContext, ContainerListingDetails detailsIncluded, OperationContext operationContext) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "list"); if (listingContext != null) { if (listingContext.Prefix != null) { builder.Add("prefix", listingContext.Prefix); } if (listingContext.Marker != null) { builder.Add("marker", listingContext.Marker); } if (listingContext.MaxResults != null) { builder.Add("maxresults", listingContext.MaxResults.ToString()); } } if ((detailsIncluded & ContainerListingDetails.Metadata) != 0) { builder.Add("include", "metadata"); } HttpWebRequest request = HttpWebRequestFactory.CreateWebRequest(WebRequestMethods.Http.Get, uri, timeout, builder, operationContext); return(request); }
/// <summary> /// Return a task that asynchronously check whether the specified blob exists. /// </summary> /// <param name="blob">ICloudBlob object</param> /// <param name="options">Blob request options</param> /// <param name="operationContext">Operation context</param> /// <param name="cmdletCancellationToken">Cancellation token</param> /// <returns>A task object that asynchronously check whether the specified blob exists.</returns> public Task <bool> DoesBlobExistAsync(ICloudBlob blob, BlobRequestOptions options, OperationContext operationContext, CancellationToken cmdletCancellationToken) { return(blob.ExistsAsync(options, operationContext, cmdletCancellationToken)); }
/// <summary> /// Generates a web request to use to acquire, renew, change, release or break the lease for the container. /// </summary> /// <param name="uri">A <see cref="System.Uri"/> specifying the absolute URI to the container.</param> /// <param name="timeout">An integer specifying the server timeout interval.</param> /// <param name="action">A <see cref="LeaseAction"/> enumeration value indicating the lease action to perform.</param> /// <param name="proposedLeaseId">A string specifying the lease ID to propose for the result of an acquire or change operation, /// or <c>null</c> if no ID is proposed for an acquire operation. This parameter should be <c>null</c> for renew, release, and break operations.</param> /// <param name="leaseDuration">The lease duration, in seconds, for acquire operations. /// If this is -1 then an infinite duration is specified. This should be <c>null</c> for renew, change, release, and break operations.</param> /// <param name="leaseBreakPeriod">The amount of time to wait, in seconds, after a break operation before the lease is broken. /// If this is <c>null</c> then the default time is used. This should be <c>null</c> for acquire, renew, change, and release operations.</param> /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the condition that must be met in order for the request to proceed.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns> public static HttpWebRequest Lease(Uri uri, int?timeout, LeaseAction action, string proposedLeaseId, int?leaseDuration, int?leaseBreakPeriod, AccessCondition accessCondition, OperationContext operationContext) { UriQueryBuilder builder = GetContainerUriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "lease"); HttpWebRequest request = HttpWebRequestFactory.CreateWebRequest(WebRequestMethods.Http.Put, uri, timeout, builder, operationContext); // Add Headers BlobHttpWebRequestFactory.AddLeaseAction(request, action); BlobHttpWebRequestFactory.AddLeaseDuration(request, leaseDuration); BlobHttpWebRequestFactory.AddProposedLeaseId(request, proposedLeaseId); BlobHttpWebRequestFactory.AddLeaseBreakPeriod(request, leaseBreakPeriod); request.ApplyAccessCondition(accessCondition); return(request); }
/// <summary> /// Return a task that asynchronously abort the blob copy operation /// </summary> /// <param name="blob">ICloudBlob object</param> /// <param name="abortCopyId">Copy id</param> /// <param name="accessCondition">Access condition</param> /// <param name="abortRequestOption">Blob request options</param> /// <param name="operationContext">Operation context</param> /// <param name="cmdletCancellationToken">Cancellation token</param> /// <returns>Return a task that asynchronously abort the blob copy operation</returns> public Task AbortCopyAsync(ICloudBlob blob, string copyId, AccessCondition accessCondition, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { return(blob.AbortCopyAsync(copyId, accessCondition, requestOptions, operationContext, cancellationToken)); }
/// <summary> /// Returns a result segment containing a collection of queues. /// </summary> /// <param name="prefix">A string containing the queue name prefix.</param> /// <param name="queueListingDetails">A <see cref="QueueListingDetails"/> enumeration describing which items to include in the listing.</param> /// <param name="maxResults">A non-negative integer value that indicates the maximum number of results to be returned at a time, up to the /// per-operation limit of 5000. If this value is <c>null</c>, the maximum possible number of results will be returned, up to 5000.</param> /// <param name="currentToken">A <see cref="QueueContinuationToken"/> returned by a previous listing operation.</param> /// <param name="options">A <see cref="QueueRequestOptions"/> object that specifies additional options for the request. If <c>null</c>, default options are applied to the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A <see cref="QueueResultSegment"/> object.</returns> public virtual QueueResultSegment ListQueuesSegmented(string prefix, QueueListingDetails queueListingDetails, int?maxResults, QueueContinuationToken currentToken, QueueRequestOptions options = null, OperationContext operationContext = null) { QueueRequestOptions modifiedOptions = QueueRequestOptions.ApplyDefaults(options, this); operationContext = operationContext ?? new OperationContext(); ResultSegment <CloudQueue> resultSegment = this.ListQueuesSegmentedCore(prefix, queueListingDetails, maxResults, currentToken, modifiedOptions, operationContext); return(new QueueResultSegment(resultSegment.Results, (QueueContinuationToken)resultSegment.ContinuationToken)); }
/// <summary> /// Return a task that asynchronously get the blob reference from server /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">Blob name</param> /// <param name="accessCondition">Access condition</param> /// <param name="options">Blob request options</param> /// <param name="operationContext">Operation context</param> /// <param name="cmdletCancellationToken">Cancellation token</param> /// <returns>A task object that asynchronously get the blob reference from server</returns> public async Task <ICloudBlob> GetBlobReferenceFromServerAsync(CloudBlobContainer container, string blobName, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { try { ICloudBlob blob = await container.GetBlobReferenceFromServerAsync(blobName, accessCondition, options, operationContext, cancellationToken); return(blob); } catch (StorageException e) { if (e.IsNotFoundException()) { return(null); } else { throw; } } }
public virtual Task <QueueResultSegment> ListQueuesSegmentedAsync(string prefix, QueueListingDetails queueListingDetails, int?maxResults, QueueContinuationToken currentToken, QueueRequestOptions options, OperationContext operationContext) { return(this.ListQueuesSegmentedAsync(prefix, queueListingDetails, maxResults, currentToken, options, operationContext, CancellationToken.None)); }
/// <summary> /// Begins an asynchronous operation to return a result segment containing a collection of queues. /// </summary> /// <param name="prefix">A string containing the queue name prefix.</param> /// <param name="queueListingDetails">A <see cref="QueueListingDetails"/> enumeration describing which items to include in the listing.</param> /// <param name="maxResults">A non-negative integer value that indicates the maximum number of results to be returned at a time, up to the /// per-operation limit of 5000. If this value is <c>null</c>, the maximum possible number of results will be returned, up to 5000.</param> /// <param name="currentToken">A <see cref="QueueContinuationToken"/> returned by a previous listing operation.</param> /// <param name="options">A <see cref="QueueRequestOptions"/> object that specifies additional options for the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <param name="callback">An <see cref="AsyncCallback"/> delegate that will receive notification when the asynchronous operation completes.</param> /// <param name="state">A user-defined object that will be passed to the callback delegate.</param> /// <returns>An <see cref="ICancellableAsyncResult"/> that references the asynchronous operation.</returns> public virtual ICancellableAsyncResult BeginListQueuesSegmented(string prefix, QueueListingDetails queueListingDetails, int?maxResults, QueueContinuationToken currentToken, QueueRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state) { return(CancellableAsyncResultTaskWrapper.Create(token => this.ListQueuesSegmentedAsync(prefix, queueListingDetails, maxResults, currentToken, options, operationContext, token), callback, state)); }
/// <summary> /// Return a task that asynchronously create a container if it doesn't exist. /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="accessType">Blob container public access type</param> /// <param name="requestOptions">Blob request options</param> /// <param name="operationContext">Operation context</param> /// <param name="cmdletCancellationToken">Cancellation token</param> /// <returns>Return a task that asynchronously create a container if it doesn't exist.</returns> public Task <bool> CreateContainerIfNotExistsAsync(CloudBlobContainer container, BlobContainerPublicAccessType accessType, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { return(container.CreateIfNotExistsAsync(accessType, requestOptions, operationContext, cancellationToken)); }