• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# OperationContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中OperationContext的典型用法代码示例。如果您正苦于以下问题:C# OperationContext类的具体用法?C# OperationContext怎么用?C# OperationContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



OperationContext类属于命名空间,在下文中一共展示了OperationContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: SignRequest

        /// <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));
            }
        }
开发者ID:jianghaolu,项目名称:azure-storage-net,代码行数:33,代码来源:SharedKeyAuthenticationHandler.cs


示例2: BeginOpenRead

        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;
        }
开发者ID:huoxudong125,项目名称:azure-sdk-for-net,代码行数:29,代码来源:CloudBlockBlob.cs


示例3: SendNotification

 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);
 }
开发者ID:yuanfei05,项目名称:vita,代码行数:7,代码来源:LoginModule_Notifications.cs


示例4: RetryDelayShouldBeCancellableAsync

        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);
        }
开发者ID:huoxudong125,项目名称:azure-sdk-for-net,代码行数:33,代码来源:RetryPoliciesTests.cs


示例5: ShouldRetry

        /// <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;
        }
开发者ID:Juliako,项目名称:azure-sdk-for-net,代码行数:41,代码来源:ExponentialRetry.cs


示例6: CreateWebRequest

        /// <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;
        }
开发者ID:nberardi,项目名称:azure-sdk-for-net,代码行数:36,代码来源:HttpWebRequestFactory.cs


示例7: ListQueues

        /// <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);
        }
开发者ID:Juliako,项目名称:azure-sdk-for-net,代码行数:15,代码来源:CloudQueueClient.cs


示例8: IncomingWebRequestContext

		internal IncomingWebRequestContext (OperationContext context)
		{
			if (context.IncomingMessageProperties != null)
				hp = (HttpRequestMessageProperty) context.IncomingMessageProperties [HttpRequestMessageProperty.Name];
			else
				hp = new HttpRequestMessageProperty ();
		}
开发者ID:nickchal,项目名称:pash,代码行数:7,代码来源:IncomingWebRequestContext.cs


示例9: FileWriteStreamOpenAndCloseAsync

        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();
            }
        }
开发者ID:Gajendra-Bahakar,项目名称:azure-storage-net,代码行数:30,代码来源:FileWriteStreamTest.cs


示例10: IndexAddTask

 public IndexAddTask(QueryIndexManager indexManager, object key, CacheEntry value, OperationContext operationContext)
 {
     _key = key;
     _entry = value;
     _indexManager = indexManager;
     _operationContext = operationContext;
 }
开发者ID:javithalion,项目名称:NCache,代码行数:7,代码来源:QueryIndexManager.cs


示例11: Put

        /// <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;
        }
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:72,代码来源:BlobHttpRequestMessageFactory.cs


示例12: SearchLogins

        //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;
        }
开发者ID:yuanfei05,项目名称:vita,代码行数:26,代码来源:LoginModule_Administration.cs


示例13: RegisterForReplay

 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;
 }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:7,代码来源:BufferedReceiveMessageProperty.cs


示例14: BindParameter

        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;
        }
开发者ID:neuecc,项目名称:PhotonWire,代码行数:60,代码来源:ParameterBinder.cs


示例15: OpenWrite

        /// <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);
        }
开发者ID:jdkillian,项目名称:azure-sdk-for-net,代码行数:36,代码来源:CloudBlockBlob.cs


示例16: ShouldRetry

        /// <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;
        }
开发者ID:BurtHarris,项目名称:azure-storage-net,代码行数:38,代码来源:ExponentialRetry.cs


示例17: CloudBlockBlobCopyTestAsync

        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();
            }
        }
开发者ID:Juliako,项目名称:azure-sdk-for-net,代码行数:60,代码来源:CopyBlobTest.cs


示例18: InitController

 public override void InitController(OperationContext context)
 {
     base.InitController(context);
       _processService = context.App.GetService<ILoginProcessService>();
       _incidentLog = Context.App.GetService<IIncidentLogService>();
       _loginSettings = Context.App.GetConfig<LoginModuleSettings>();
 }
开发者ID:yuanfei05,项目名称:vita,代码行数:7,代码来源:PasswordResetController.cs


示例19: OpenWriteAsync

        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);
        }
开发者ID:mirobers,项目名称:azure-storage-net,代码行数:31,代码来源:CloudAppendBlob.cs


示例20: LogIncident

 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;
 }
开发者ID:yuanfei05,项目名称:vita,代码行数:30,代码来源:IncidentLogModule.cs



注:本文中的OperationContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# OperationMode类代码示例发布时间:2022-05-24
下一篇:
C# OperationCode类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap