private void ValidateCosistencyLevel(DocumentClient client) { DocumentCollection collection = TestCommon.CreateOrGetDocumentCollection(client); // Value not supported INameValueCollection headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.ConsistencyLevel, "Not a valid value"); try { ReadDocumentFeedRequest(client, collection.ResourceId, headers); Assert.Fail("Should throw an exception"); } catch (Exception ex) { var innerException = ex.InnerException as DocumentClientException; Assert.IsTrue(innerException.StatusCode == HttpStatusCode.BadRequest, "invalid status code"); } // Supported value headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.ConsistencyLevel, ConsistencyLevel.Eventual.ToString()); var response = ReadDocumentFeedRequest(client, collection.ResourceId, headers); Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, "Invalid status code"); }
/// <summary> /// Gets the response headers for the context. /// </summary> /// <returns>The response headers for the context.</returns> public INameValueCollection GetResponseHeaders() { StringKeyValueCollection responseHeaders = new StringKeyValueCollection(); responseHeaders[HttpConstants.HttpHeaders.Continuation] = this.ContinuationToken; if (this.ContinuationToken == "[]") { throw new InvalidOperationException("Somehow a document query execution context returned an empty array of continuations."); } this.SetQueryMetrics(); IReadOnlyDictionary <string, QueryMetrics> groupedQueryMetrics = this.GetQueryMetrics(); if (groupedQueryMetrics != null && groupedQueryMetrics.Count != 0) { responseHeaders[HttpConstants.HttpHeaders.QueryMetrics] = QueryMetrics .CreateFromIEnumerable(groupedQueryMetrics.Values) .ToDelimitedString(); } responseHeaders[HttpConstants.HttpHeaders.RequestCharge] = this.requestChargeTracker .GetAndResetCharge() .ToString(CultureInfo.InvariantCulture); return(responseHeaders); }
public async Task AddPartitionKeyRangeToContinuationTokenOnNotNullBackendContinuation() { ResolvedRangeInfo currentPartitionKeyRange = new ResolvedRangeInfo(new PartitionKeyRange { Id = "1", MinInclusive = "B", MaxExclusive = "C" }, null); Mock <IRoutingMapProvider> routingMapProvider = new Mock <IRoutingMapProvider>(); routingMapProvider.Setup(m => m.TryGetOverlappingRangesAsync( It.IsAny <string>(), It.IsAny <Range <string> >(), It.IsAny <bool>() )).Returns(Task.FromResult <IReadOnlyList <PartitionKeyRange> >(null)).Verifiable(); PartitionRoutingHelper partitionRoutingHelper = new PartitionRoutingHelper(); StringKeyValueCollection headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.Continuation, "something"); bool result = await partitionRoutingHelper.TryAddPartitionKeyRangeToContinuationTokenAsync( headers, null, routingMapProvider.Object, CollectionId, currentPartitionKeyRange, RntdbEnumerationDirection.Reverse ); Assert.IsTrue(true); routingMapProvider.Verify(m => m.TryGetOverlappingRangesAsync( It.IsAny <string>(), It.IsAny <Range <string> >(), It.IsAny <bool>() ), Times.Never); }
private void ValidateEmitVerboseTracesInQuery(DocumentClient client, bool isHttps = false) { // Value not boolean INameValueCollection headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.EmitVerboseTracesInQuery, "Not a boolean"); try { var response = ReadDatabaseFeedRequest(client, headers); if (isHttps) { Assert.Fail("Should throw an exception"); } else { // Invalid boolean is treated as false by TCP Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, "Invalid status code"); } } catch (Exception ex) { var innerException = ex.InnerException as DocumentClientException; Assert.IsTrue(innerException.StatusCode == HttpStatusCode.BadRequest, "Invalid status code"); } // Valid boolean headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.EmitVerboseTracesInQuery, "true"); var response2 = ReadDatabaseFeedRequest(client, headers); Assert.IsTrue(response2.StatusCode == HttpStatusCode.OK, "Invalid status code"); }
private void ValidateIfNonMatch(DocumentClient client) { // Valid if-match var document = CreateDocumentRequest(client, new StringKeyValueCollection()).GetResource <Document>(); var headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.IfNoneMatch, document.ETag); var response = ReadDocumentRequest(client, document, headers); Assert.IsTrue(response.StatusCode == HttpStatusCode.NotModified, "Invalid status code"); // validateInvalidIfMatch AccessCondition condition = new AccessCondition() { Type = AccessConditionType.IfMatch, Condition = "invalid etag" }; try { var replacedDoc = client.ReplaceDocumentAsync(document.SelfLink, document, new RequestOptions() { AccessCondition = condition }).Result.Resource; Assert.Fail("should not reach here"); } catch (Exception ex) { var innerException = ex.InnerException as DocumentClientException; Assert.IsTrue(innerException.StatusCode == HttpStatusCode.PreconditionFailed, "Invalid status code"); } }
protected override void WriteHotfixTriggerContent() { var properties = new StringKeyValueCollection(); properties.Add(new StringKeyValue(Build.AntPropertyNames.InstallerVersion, this.Version.ToString())); properties.Add(new StringKeyValue(Build.AntPropertyNames.TriggerDate, DateTime.Now.ToString())); this.Location.Parent.Parent.HotfixTrigger.TriggerIni.SetTextContent(properties.ToString()); }
private void Run(StringKeyValueCollection commandLineArgs) { if (commandLineArgs.Contains(CLIArgs.identity)) { ManualClickOnceInit(commandLineArgs[CLIArgs.identity].Value); } _appBootstrapper.Start(); }
private async Task <DocumentServiceResponse> GetFeedResponseAsync(string resourceLink, ResourceType resourceType, IDocumentClientRetryPolicy retryPolicyInstance, CancellationToken cancellationToken) { INameValueCollection headers = new StringKeyValueCollection(); if (this.feedOptions.MaxItemCount.HasValue) { headers.Set(HttpConstants.HttpHeaders.PageSize, this.feedOptions.MaxItemCount.ToString()); } if (this.feedOptions.SessionToken != null) { headers.Set(HttpConstants.HttpHeaders.SessionToken, this.feedOptions.SessionToken); } if (resourceType.IsPartitioned() && this.feedOptions.PartitionKeyRangeId == null && this.feedOptions.PartitionKey == null) { throw new ForbiddenException(RMResources.PartitionKeyRangeIdOrPartitionKeyMustBeSpecified); } // On REST level, change feed is using IfNoneMatch/ETag instead of continuation. if (this.nextIfNoneMatch != null) { headers.Set(HttpConstants.HttpHeaders.IfNoneMatch, this.nextIfNoneMatch); } if (this.ifModifiedSince != null) { headers.Set(HttpConstants.HttpHeaders.IfModifiedSince, this.ifModifiedSince); } headers.Set(HttpConstants.HttpHeaders.A_IM, HttpConstants.A_IMHeaderValues.IncrementalFeed); if (this.feedOptions.PartitionKey != null) { PartitionKeyInternal partitionKey = feedOptions.PartitionKey.InternalKey; headers.Set(HttpConstants.HttpHeaders.PartitionKey, partitionKey.ToJsonString()); } using (DocumentServiceRequest request = this.client.CreateDocumentServiceRequest( OperationType.ReadFeed, resourceLink, resourceType, headers)) { if (retryPolicyInstance != null) { retryPolicyInstance.OnBeforeSendRequest(request); } if (resourceType.IsPartitioned() && this.feedOptions.PartitionKeyRangeId != null) { request.RouteTo(new PartitionKeyRangeIdentity(this.feedOptions.PartitionKeyRangeId)); } return(await this.client.ReadFeedAsync(request, cancellationToken)); } }
private async Task <FeedResource <Address> > GetMasterAddressesViaGatewayAsync( DocumentServiceRequest request, ResourceType resourceType, string resourceAddress, string entryUrl, bool forceRefresh, bool useMasterCollectionResolver) { INameValueCollection addressQuery = new StringKeyValueCollection(StringComparer.Ordinal); addressQuery.Add(HttpConstants.QueryStrings.Url, HttpUtility.UrlEncode(entryUrl)); INameValueCollection headers = new StringKeyValueCollection(StringComparer.Ordinal); if (forceRefresh) { headers.Set(HttpConstants.HttpHeaders.ForceRefresh, bool.TrueString); } if (useMasterCollectionResolver) { headers.Set(HttpConstants.HttpHeaders.UseMasterCollectionResolver, bool.TrueString); } if (request.ForceCollectionRoutingMapRefresh) { headers.Set(HttpConstants.HttpHeaders.ForceCollectionRoutingMapRefresh, bool.TrueString); } addressQuery.Add(HttpConstants.QueryStrings.Filter, this.protocolFilter); string resourceTypeToSign = PathsHelper.GetResourcePath(resourceType); headers.Set(HttpConstants.HttpHeaders.XDate, DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture)); string token = this.tokenProvider.GetUserAuthorizationToken( resourceAddress, resourceTypeToSign, HttpConstants.HttpMethods.Get, headers, AuthorizationTokenType.PrimaryMasterKey); headers.Set(HttpConstants.HttpHeaders.Authorization, token); Uri targetEndpoint = UrlUtility.SetQuery(this.addressEndpoint, UrlUtility.CreateQuery(addressQuery)); string identifier = GatewayAddressCache.LogAddressResolutionStart(request, targetEndpoint); using (HttpResponseMessage httpResponseMessage = await this.httpClient.GetAsync(targetEndpoint, headers)) { using (DocumentServiceResponse documentServiceResponse = await ClientExtensions.ParseResponseAsync(httpResponseMessage)) { GatewayAddressCache.LogAddressResolutionEnd(request, identifier); return(documentServiceResponse.GetResource <FeedResource <Address> >()); } } }
private static StringKeyValueCollection ParseCommandLineArgs(string[] args) { if (args == null || args.Length == 0) { return(new StringKeyValueCollection()); } return(StringKeyValueCollection.Parse(string.Join(Environment.NewLine, args))); }
public async Task ValidateRetryOnWriteForbiddenExceptionAsync() { this.Initialize( useMultipleWriteLocations: false, enableEndpointDiscovery: true, isPreferredLocationsListEmpty: false); await this.endpointManager.RefreshLocationAsync(this.databaseAccount); ClientRetryPolicy retryPolicy = new ClientRetryPolicy(this.endpointManager, true, new RetryOptions()); using (DocumentServiceRequest request = this.CreateRequest(isReadRequest: false, isMasterResourceType: false)) { int retryCount = 0; await BackoffRetryUtility <bool> .ExecuteAsync( () => { retryCount++; retryPolicy.OnBeforeSendRequest(request); if (retryCount == 1) { this.mockedClient.ResetCalls(); Uri expectedEndpoint = LocationCacheTests.EndpointByLocation[this.preferredLocations[0]]; Assert.AreEqual(expectedEndpoint, request.RequestContext.LocationEndpointToRoute); StringKeyValueCollection headers = new StringKeyValueCollection(); headers[WFConstants.BackendHeaders.SubStatus] = ((int)SubStatusCodes.WriteForbidden).ToString(); DocumentClientException forbiddenException = new ForbiddenException(RMResources.Forbidden, headers); throw forbiddenException; } else if (retryCount == 2) { this.mockedClient.Verify(client => client.GetDatabaseAccountInternalAsync(It.IsAny <Uri>(), It.IsAny <CancellationToken>()), Times.Once); // Next request must go to next preferred endpoint Uri expectedEndpoint = LocationCacheTests.EndpointByLocation[this.preferredLocations[1]]; Assert.AreEqual(expectedEndpoint, request.RequestContext.LocationEndpointToRoute); return(Task.FromResult(true)); } else { Assert.Fail(); } return(Task.FromResult(true)); }, retryPolicy); } }
public static StringKeyValueCollection BuildGameDescriptionProperties(IComponentUniqueId componentUniqueId, string gameName, VersionNumber version, IComponentUniqueId engineUniqueId, string gamePart, IServerPath projectPath) { var properties = new StringKeyValueCollection(); properties.Add(new StringKeyValue(AntPropertyNames.GamePartUniqueID, componentUniqueId.Value)); properties.Add(new StringKeyValue(AntPropertyNames.GameUniqueName, gameName)); properties.Add(new StringKeyValue(AntPropertyNames.GameVersion, version.ToString())); properties.Add(new StringKeyValue(AntPropertyNames.ParentGameEngineUniqueID, engineUniqueId.Value)); properties.Add(new StringKeyValue(AntPropertyNames.GamePart, gamePart)); properties.Add(new StringKeyValue(AntPropertyNames.ProjDir, projectPath.AsString())); properties.Add(new StringKeyValue(AntPropertyNames.PublishDate, DateTime.Now.ToString())); return(properties); }
private async Task ValidateRetryOnSessionNotAvailabeWithEndpointDiscoveryDisabled(bool isPreferredLocationsListEmpty, bool useMultipleWriteLocations, bool isReadRequest) { const bool enableEndpointDiscovery = false; this.Initialize( useMultipleWriteLocations: useMultipleWriteLocations, enableEndpointDiscovery: enableEndpointDiscovery, isPreferredLocationsListEmpty: isPreferredLocationsListEmpty); ClientRetryPolicy retryPolicy = new ClientRetryPolicy(this.endpointManager, enableEndpointDiscovery, new RetryOptions()); using (DocumentServiceRequest request = this.CreateRequest(isReadRequest: isReadRequest, isMasterResourceType: false)) { int retryCount = 0; try { await BackoffRetryUtility <bool> .ExecuteAsync( () => { retryPolicy.OnBeforeSendRequest(request); if (retryCount == 0) { Assert.IsFalse(request.ClearSessionTokenOnSessionReadFailure); Assert.AreEqual(request.RequestContext.LocationEndpointToRoute, this.endpointManager.ReadEndpoints[0]); } else { Assert.Fail(); } retryCount++; StringKeyValueCollection headers = new StringKeyValueCollection(); headers[WFConstants.BackendHeaders.SubStatus] = ((int)SubStatusCodes.ReadSessionNotAvailable).ToString(); DocumentClientException notFoundException = new NotFoundException(RMResources.NotFound, headers); throw notFoundException; }, retryPolicy); Assert.Fail(); } catch (NotFoundException) { DefaultTrace.TraceInformation("Received expected notFoundException"); Assert.AreEqual(1, retryCount); } } }
public async Task AddPartitionKeyRangeToContinuationTokenOnSplit() { const string BackendToken = "backendToken"; StringKeyValueCollection headers = new StringKeyValueCollection(); List <CompositeContinuationToken> compositeContinuationTokensFromSplit = new List <CompositeContinuationToken> { new CompositeContinuationToken { Token = "someToken", Range = new Range <string>("A", "B", true, false) }, new CompositeContinuationToken { Token = "anotherToken", Range = new Range <string>("B", "C", true, false) } }; PartitionRoutingHelper partitionRoutingHelper = new PartitionRoutingHelper(); //With backend header headers.Add(HttpConstants.HttpHeaders.Continuation, BackendToken); ResolvedRangeInfo resolvedRangeInfo = new ResolvedRangeInfo(new PartitionKeyRange(), new List <CompositeContinuationToken>(compositeContinuationTokensFromSplit)); bool result = await partitionRoutingHelper.TryAddPartitionKeyRangeToContinuationTokenAsync( headers, null, null, null, resolvedRangeInfo, RntdbEnumerationDirection.Reverse); List <CompositeContinuationToken> compositeContinuationTokens = JsonConvert.DeserializeObject <List <CompositeContinuationToken> >(headers.Get(HttpConstants.HttpHeaders.Continuation)); Assert.IsTrue(result); Assert.AreEqual(compositeContinuationTokensFromSplit.Count, compositeContinuationTokens.Count); Assert.AreEqual(BackendToken, compositeContinuationTokens.First().Token); Assert.AreNotEqual(BackendToken, compositeContinuationTokens.Last().Token); //Without backend header headers.Remove(HttpConstants.HttpHeaders.Continuation); resolvedRangeInfo = new ResolvedRangeInfo(new PartitionKeyRange(), new List <CompositeContinuationToken>(compositeContinuationTokensFromSplit)); result = await partitionRoutingHelper.TryAddPartitionKeyRangeToContinuationTokenAsync( headers, null, null, null, resolvedRangeInfo, RntdbEnumerationDirection.Reverse); compositeContinuationTokens = JsonConvert.DeserializeObject <List <CompositeContinuationToken> >(headers.Get(HttpConstants.HttpHeaders.Continuation)); Assert.IsTrue(result); Assert.IsTrue(compositeContinuationTokens.Count == compositeContinuationTokensFromSplit.Count - 1); Assert.AreEqual(compositeContinuationTokensFromSplit.Last().Token, compositeContinuationTokens.First().Token); }
[Ignore] /* TODO: There is a TODO in PartitionRoutingHelper.ExtractPartitionKeyRangeFromContinuationToken that it's refering to some pending deployment */ public void TestExtractPartitionKeyRangeFromHeaders() { Func <string, INameValueCollection> getHeadersWithContinuation = (string continuationToken) => { INameValueCollection headers = new StringKeyValueCollection(); headers[HttpConstants.HttpHeaders.Continuation] = continuationToken; return(headers); }; using (Stream stream = new MemoryStream(Properties.Resources.BaselineTest_PartitionRoutingHelper_ExtractPartitionKeyRangeFromHeaders)) { using (StreamReader reader = new StreamReader(stream)) { TestSet <ExtractPartitionKeyRangeFromHeadersTestData> testSet = JsonConvert.DeserializeObject <TestSet <ExtractPartitionKeyRangeFromHeadersTestData> >(reader.ReadToEnd()); foreach (ExtractPartitionKeyRangeFromHeadersTestData testData in testSet.Postive) { INameValueCollection headers = getHeadersWithContinuation(testData.CompositeContinuationToken); List <CompositeContinuationToken> suppliedTokens; Range <string> range = this.partitionRoutingHelper.ExtractPartitionKeyRangeFromContinuationToken(headers, out suppliedTokens); if (suppliedTokens != null) { Assert.AreEqual(testData.ContinuationToken, headers[HttpConstants.HttpHeaders.Continuation]); Assert.AreEqual(JsonConvert.SerializeObject(testData.PartitionKeyRange), JsonConvert.SerializeObject(range)); } else { Assert.IsTrue(testData.ContinuationToken == headers[HttpConstants.HttpHeaders.Continuation] || testData.ContinuationToken == null); } } foreach (ExtractPartitionKeyRangeFromHeadersTestData testData in testSet.Negative) { INameValueCollection headers = getHeadersWithContinuation(testData.CompositeContinuationToken); try { List <CompositeContinuationToken> suppliedTokens; Range <string> rangeOrId = this.partitionRoutingHelper.ExtractPartitionKeyRangeFromContinuationToken(headers, out suppliedTokens); Assert.Fail("Expect BadRequestException"); } catch (BadRequestException) { } } } } }
private static string CreateRunAsAdminCommandLineArguments() { var commandLineArguments = new StringKeyValueCollection(); commandLineArguments.Add(new StringKeyValue(CLIArgs.runAsAdmin, "true")); if (ApplicationDeployment.IsNetworkDeployed) { var activationContext = AppDomain.CurrentDomain.ActivationContext; commandLineArguments.Add(new StringKeyValue(CLIArgs.version, ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString())); commandLineArguments.Add(new StringKeyValue(CLIArgs.identity, activationContext.Identity.FullName)); } return(string.Join(" ", commandLineArguments.Select(a => $"\"{a.Name}={a.Value}\""))); }
public InstallerDefinition(string latestTxtFileContent) { this.LatestTxtContent = latestTxtFileContent; var latestTxtProperties = StringKeyValueCollection.Parse(latestTxtFileContent); this.InstallerID = new Guid(latestTxtProperties[AntPropertyNames.InstallerUniqueID].Value); this.Version = new VersionNumber(latestTxtProperties[AntPropertyNames.InstallerVersion].Value); this.PublisherEmailAddress = latestTxtProperties[AntPropertyNames.TriggeredBy].Value; if (latestTxtProperties.Contains(AntPropertyNames.CustomizedInstaller)) { this.IsCustomizedInstaller = 0 == string.Compare("true", latestTxtProperties[AntPropertyNames.CustomizedInstaller].Value); } }
public static async Task <ICollection <T> > ListAllAsync <T>(this HttpClient client, Uri collectionUri, INameValueCollection headers = null) where T : CosmosResource, new() { Collection <T> responseCollection = new Collection <T>(); string responseContinuation = null; if (headers == null) { headers = new StringKeyValueCollection(); } do { if (responseContinuation != null) { headers[HttpConstants.HttpHeaders.Continuation] = responseContinuation; } HttpResponseMessage responseMessage; foreach (var header in headers.AllKeys()) { client.DefaultRequestHeaders.Add(header, headers[header]); } responseMessage = await client.GetAsync(collectionUri, HttpCompletionOption.ResponseHeadersRead); FeedResource <T> feedResource = await responseMessage.ToResourceAsync <FeedResource <T> >(); foreach (T resource in feedResource) { responseCollection.Add(resource); } IEnumerable <string> continuationToken = null; if (responseMessage.Headers.TryGetValues(HttpConstants.HttpHeaders.Continuation, out continuationToken)) { responseContinuation = continuationToken.SingleOrDefault(); } else { responseContinuation = null; } } while (!string.IsNullOrEmpty(responseContinuation)); return(responseCollection); }
public void CompositeContinuationTokenIsNotPassedToBackend() { Range <string> expectedRange = new Range <string>("A", "B", true, false); string expectedToken = "someToken"; CompositeContinuationToken compositeContinuationToken = new CompositeContinuationToken { Range = expectedRange, Token = expectedToken }; string continuation = JsonConvert.SerializeObject(compositeContinuationToken); PartitionRoutingHelper partitionRoutingHelper = new PartitionRoutingHelper(); StringKeyValueCollection headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.Continuation, continuation); Range <string> range = partitionRoutingHelper.ExtractPartitionKeyRangeFromContinuationToken(headers, out List <CompositeContinuationToken> compositeContinuationTokens); Assert.IsTrue(expectedRange.Equals(range)); Assert.AreEqual(expectedToken, headers.Get(HttpConstants.HttpHeaders.Continuation)); //not a composite token }
private async Task <CosmosAccountSettings> GetDatabaseAccountAsync(Uri serviceEndpoint) { HttpClient httpClient = this.messageHandler == null ? new HttpClient() : new HttpClient(this.messageHandler); httpClient.DefaultRequestHeaders.Add(HttpConstants.HttpHeaders.Version, HttpConstants.Versions.CurrentVersion); // Send client version. httpClient.AddUserAgentHeader(this.connectionPolicy.UserAgentContainer); httpClient.AddApiTypeHeader(this.apiType); string authorizationToken = string.Empty; if (this.hasAuthKeyResourceToken) { authorizationToken = HttpUtility.UrlEncode(this.authKeyResourceToken); } else { // Retrieve the document service properties. string xDate = DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture); httpClient.DefaultRequestHeaders.Add(HttpConstants.HttpHeaders.XDate, xDate); INameValueCollection headersCollection = new StringKeyValueCollection(); headersCollection.Add(HttpConstants.HttpHeaders.XDate, xDate); authorizationToken = AuthorizationHelper.GenerateKeyAuthorizationSignature( HttpConstants.HttpMethods.Get, serviceEndpoint, headersCollection, this.authKeyHashFunction); } httpClient.DefaultRequestHeaders.Add(HttpConstants.HttpHeaders.Authorization, authorizationToken); using (HttpResponseMessage responseMessage = await httpClient.GetHttpAsync( serviceEndpoint)) { using (DocumentServiceResponse documentServiceResponse = await ClientExtensions.ParseResponseAsync(responseMessage)) { CosmosAccountSettings databaseAccount = documentServiceResponse.GetInternalResource <CosmosAccountSettings>(CosmosAccountSettings.CreateNewInstance); return(databaseAccount); } } }
private void ValidateIndexingDirective(DocumentClient client) { //Will keep this as V2 OM, because we can pass invalid IndexingDirective from V3 onwarsds // Number out of range. INameValueCollection headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.IndexingDirective, "\"Invalid Value\""); try { CreateDocumentRequest(client, headers); Assert.Fail("Should throw an exception"); } catch (Exception ex) { var innerException = ex.InnerException as DocumentClientException; Assert.IsTrue(innerException.StatusCode == HttpStatusCode.BadRequest, "Invalid status code"); } headers = new StringKeyValueCollection(); headers.Add("indexAction", "\"Invalid Value\""); try { CreateDocumentScript(client, headers); Assert.Fail("Should throw an exception"); } catch (Exception ex) { var innerException = ex.InnerException as DocumentClientException; Assert.IsTrue(innerException.StatusCode == HttpStatusCode.BadRequest, "Invalid status code"); } // Valid Indexing Directive headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.IndexingDirective, IndexingDirective.Exclude.ToString()); var response = CreateDocumentRequest(client, headers); Assert.IsTrue(response.StatusCode == HttpStatusCode.Created); headers = new StringKeyValueCollection(); headers.Add("indexAction", "\"exclude\""); var result = CreateDocumentScript(client, headers); Assert.IsTrue(result.StatusCode == HttpStatusCode.OK, "Invalid status code"); }
private static INameValueCollection ExtractResponseHeaders(HttpResponseMessage responseMessage) { INameValueCollection headers = new StringKeyValueCollection(); foreach (KeyValuePair <string, IEnumerable <string> > headerPair in responseMessage.Headers) { if (string.Compare(headerPair.Key, HttpConstants.HttpHeaders.OwnerFullName, StringComparison.Ordinal) == 0) { foreach (string val in headerPair.Value) { headers.Add(headerPair.Key, Uri.UnescapeDataString(val)); } } else { foreach (string val in headerPair.Value) { headers.Add(headerPair.Key, val); } } } if (responseMessage.Content != null) { foreach (KeyValuePair <string, IEnumerable <string> > headerPair in responseMessage.Content.Headers) { if (string.Compare(headerPair.Key, HttpConstants.HttpHeaders.OwnerFullName, StringComparison.Ordinal) == 0) { foreach (string val in headerPair.Value) { headers.Add(headerPair.Key, Uri.UnescapeDataString(val)); } } else { foreach (string val in headerPair.Value) { headers.Add(headerPair.Key, val); } } } } return(headers); }
private void AppendInstallerContent(InstallerDefinition installerDefinition, IServerPath branchServerPath) { var installerContentTxtPath = branchServerPath.Subpath(Constants.Versions) .Subpath(installerDefinition.Version.ToString()) .Subpath(Constants.InstallerContentTxt); foreach (var keyValue in StringKeyValueCollection.Parse(_sourceControlAdapter.ReadTextFile(installerContentTxtPath))) { if (keyValue.Value.StartsWith("$/")) { installerDefinition.Components.Add(new InstallerDefinition.ComponentDefinition(keyValue.Name, _sourceControlAdapter.CreateServerPath(keyValue.Value))); } else //backward compatibility with the installers up to 1.5.x { installerDefinition.Components.Add(new InstallerDefinition.ComponentDefinition(keyValue.Name, _sourceControlAdapter.CreateServerPath(ConfigurationManager.AppSettings[ConfigurationKeys.oldDistributionPath]).Subpath(keyValue.Value))); } } }
public CommandLineArgs Parse(string[] args) { if (args.Length == 0) { throw new MissingCommandLineArgumentsException(); } var inputFilesArgs = args.Where(a => !a.Contains("=")).ToArray(); if (inputFilesArgs.Length == 0 || inputFilesArgs.Length > 2) { throw new InvalidCommandLineArgumentsException(); } var commandLineArgs = new CommandLineArgs(inputFilesArgs[0]); if (inputFilesArgs.Length == 2) { commandLineArgs.NavigationPlanFile = Optional <string> .Some(inputFilesArgs[1]); } var optionArgs = StringKeyValueCollection.Parse(args.Where(a => a.Contains("=")).ToArray()); var outpFolderOption = optionArgs.FirstOrDefault(o => 0 == string.Compare(o.Name, OptionNames.outputFolder, true)); if (outpFolderOption != null) { if (string.IsNullOrEmpty(outpFolderOption.Value)) { throw new InvalidCommandLineArgumentsException($"If you specify {OptionNames.outputFolder} paramters you must provide the path for the folder"); } commandLineArgs.OutputFolder = Optional <string> .Some(outpFolderOption.Value); } return(commandLineArgs); }
public static StringKeyValueCollection BuildComponentDescriptionProperties(StringKeyValue componentUniqueID, VersionNumber version, IEnumerable <IOutputFile> files, string friendlyName, IServerPath projectPath) { var properties = new StringKeyValueCollection(); properties.Add(new StringKeyValue(AntPropertyNames.major, version.Major.ToString())); properties.Add(new StringKeyValue(AntPropertyNames.minor, version.Minor.ToString())); properties.Add(new StringKeyValue(AntPropertyNames.revision, version.Revision.ToString())); properties.Add(new StringKeyValue(AntPropertyNames.build, version.Build.ToString())); properties.Add(componentUniqueID); properties.Add(new StringKeyValue(AntPropertyNames.ProjDir, projectPath.AsString())); properties.Add(new StringKeyValue(AntPropertyNames.FriendlyName, friendlyName)); properties.Add(new StringKeyValue(AntPropertyNames.TestingDeployFiles, string.Join(", ", files.Select(f => f.GetDeployableFileDefinition()).Where(f => f.Environment == DeployEnvironment.All || f.Environment == DeployEnvironment.QA).Select(f => f.RelativePath)))); properties.Add(new StringKeyValue(AntPropertyNames.ProductionDeployFiles, string.Join(", ", files.Select(f => f.GetDeployableFileDefinition()).Where(f => f.Environment == DeployEnvironment.All || f.Environment == DeployEnvironment.Production).Select(f => f.RelativePath)))); properties.Add(new StringKeyValue(AntPropertyNames.PublishDate, DateTime.Now.ToString())); return(properties); }
public async Task TestGetPartitionRoutingInfo() { using (Stream stream = new MemoryStream(Properties.Resources.BaselineTest_PartitionRoutingHelper_GetPartitionRoutingInfo)) { using (StreamReader reader = new StreamReader(stream)) { GetPartitionRoutingInfoTestData testData = JsonConvert.DeserializeObject <GetPartitionRoutingInfoTestData>(reader.ReadToEnd()); CollectionRoutingMap routingMap = CollectionRoutingMap.TryCreateCompleteRoutingMap( testData.RoutingMap.Select(range => Tuple.Create(range, (ServiceIdentity)null)), string.Empty); foreach (GetPartitionRoutingInfoTestCase testCase in testData.TestCases) { List <string> actualPartitionKeyRangeIds = new List <string>(); Range <string> startRange = Range <string> .GetEmptyRange(PartitionKeyInternal.MinimumInclusiveEffectivePartitionKey); for (Range <string> currentRange = startRange; currentRange != null;) { RoutingMapProvider routingMapProvider = new RoutingMapProvider(routingMap); PartitionRoutingHelper.ResolvedRangeInfo resolvedRangeInfo = await this.partitionRoutingHelper.TryGetTargetRangeFromContinuationTokenRangeAsync(testCase.ProvidedRanges, routingMapProvider, string.Empty, currentRange, null); actualPartitionKeyRangeIds.Add(resolvedRangeInfo.ResolvedRange.Id); INameValueCollection headers = new StringKeyValueCollection(); await this.partitionRoutingHelper.TryAddPartitionKeyRangeToContinuationTokenAsync(headers, testCase.ProvidedRanges, routingMapProvider, string.Empty, resolvedRangeInfo); List <CompositeContinuationToken> suppliedTokens; Range <string> nextRange = this.partitionRoutingHelper.ExtractPartitionKeyRangeFromContinuationToken(headers, out suppliedTokens); currentRange = nextRange.IsEmpty ? null : nextRange; } Assert.AreEqual(string.Join(", ", testCase.RoutingRangeIds), string.Join(", ", actualPartitionKeyRangeIds)); } } } }
private void ValidateCosistencyLevel(DocumentClient client) { //this is can be only tested with V2 OM, V3 doesnt allow to set invalid consistencty Database database = client.CreateDatabaseAsync(new Database { Id = Guid.NewGuid().ToString() }).Result; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition { Paths = new System.Collections.ObjectModel.Collection <string>(new[] { "/id" }), Kind = PartitionKind.Hash }; DocumentCollection collection = client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection { Id = Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition, }).Result; // Value not supported INameValueCollection headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.ConsistencyLevel, "Not a valid value"); try { ReadDocumentFeedRequest(client, collection.ResourceId, headers); Assert.Fail("Should throw an exception"); } catch (Exception ex) { var innerException = ex.InnerException as DocumentClientException; Assert.IsTrue(innerException.StatusCode == HttpStatusCode.BadRequest, "invalid status code"); } // Supported value headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.ConsistencyLevel, ConsistencyLevel.Eventual.ToString()); var response = ReadDocumentFeedRequest(client, collection.ResourceId, headers); Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, "Invalid status code"); }
private void RunAsAdmin(StringKeyValueCollection args) { if (args.Contains(CLIArgs.runAsAdmin)) { System.Threading.Thread.Sleep(100); Run(args); return; } if (IsCurrentUserAnAdmin()) { Run(args); } else { var processStartInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().CodeBase); processStartInfo.Arguments = CreateRunAsAdminCommandLineArguments(); processStartInfo.UseShellExecute = true; processStartInfo.Verb = "runas"; Process.Start(processStartInfo); } }
private void ValidateEnableLowPrecisionOrderBy(DocumentClient client, bool isHttps = false) { // Value not boolean INameValueCollection headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.EnableLowPrecisionOrderBy, "Not a boolean"); var document = CreateDocumentRequest(client, new StringKeyValueCollection()).GetResource <Document>(); try { var response = ReadDocumentRequest(client, document, headers); if (isHttps) { Assert.Fail("Should throw an exception"); } else { // Invalid boolean is treated as false by TCP" Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, "Invalid status code"); } } catch (Exception ex) { var innerException = ex.InnerException as DocumentClientException; Assert.IsTrue(innerException.StatusCode == HttpStatusCode.BadRequest, "Invalid status code"); } // Valid boolean document = CreateDocumentRequest(client, new StringKeyValueCollection()).GetResource <Document>(); headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.EnableLowPrecisionOrderBy, "true"); var response2 = ReadDocumentRequest(client, document, headers); Assert.IsTrue(response2.StatusCode == HttpStatusCode.OK, "Invalid status code"); }
private void ValidatePageSize(DocumentClient client) { // Invalid parsing INameValueCollection headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.PageSize, "\"Invalid header type\""); try { ReadDatabaseFeedRequest(client, headers); Assert.Fail("Should throw an exception"); } catch (Exception ex) { var innerException = ex.InnerException as DocumentClientException; Assert.IsTrue(innerException.StatusCode == HttpStatusCode.BadRequest, "Invalid status code"); } headers = new StringKeyValueCollection(); headers.Add("pageSize", "\"Invalid header type\""); try { ReadFeedScript(client, headers); Assert.Fail("Should throw an exception"); } catch (Exception ex) { var innerException = ex.InnerException as DocumentClientException; Assert.IsTrue(innerException.StatusCode == HttpStatusCode.BadRequest, "Invalid status code"); } // Invalid value headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.PageSize, "-2"); try { ReadDatabaseFeedRequest(client, headers); Assert.Fail("Should throw an exception"); } catch (Exception ex) { var innerException = ex.InnerException as DocumentClientException; Assert.IsTrue(innerException.StatusCode == HttpStatusCode.BadRequest, "Invalid status code"); } headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.PageSize, Int64.MaxValue.ToString(CultureInfo.InvariantCulture)); try { ReadFeedScript(client, headers); Assert.Fail("Should throw an exception"); } catch (Exception ex) { var innerException = ex.InnerException as DocumentClientException; Assert.IsTrue(innerException.StatusCode == HttpStatusCode.BadRequest, "Invalid status code"); } // Valid page size headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.PageSize, "20"); var response = ReadDatabaseFeedRequest(client, headers); Assert.IsTrue(response.StatusCode == HttpStatusCode.OK); headers = new StringKeyValueCollection(); headers.Add("pageSize", "20"); var result = ReadFeedScript(client, headers); Assert.IsTrue(result.StatusCode == HttpStatusCode.OK); // dynamic page size headers = new StringKeyValueCollection(); headers.Add(HttpConstants.HttpHeaders.PageSize, "-1"); response = ReadDatabaseFeedRequest(client, headers); Assert.IsTrue(response.StatusCode == HttpStatusCode.OK); headers = new StringKeyValueCollection(); headers.Add("pageSize", "-1"); result = ReadFeedScript(client, headers); Assert.IsTrue(result.StatusCode == HttpStatusCode.OK); }
static IDictionary<string, string> QueryString(string url) { string query = url.Substring(url.IndexOf('?') + 1); string[] queryItems = query.Split('&'); IDictionary<string, string> dic = new StringKeyValueCollection(); foreach (var qi in queryItems) { string[] qitem = qi.Split('='); if (qitem.Length == 2) { dic.Add(qitem[0], qitem[1]); } else { logger.Warning(qi); } } if (dic.Count != queryItems.Length) { logger.Warning(url); logger.Warning(query); } return dic; }