private NameValueCollection Get(INameValueCollection coll)
        {
            var nv = new NameValueCollection(StringComparer.OrdinalIgnoreCase);

            foreach (var key in coll.AllKeys)
            {
                nv[key] = coll[key];
            }

            return nv;
            //return coll.ToNameValueCollection();
        }
        public TestAuthorizationRequest(AuthorizationContext authorizationContext, WebServerRequestType requestType, string url, INameValueCollection queryString, string resource = null)
        {
            UserIsInRole = false;
            AuthorizationContext = authorizationContext;
            Resource = resource;
            RequestType = requestType;
            Url = new Uri(url);
            QueryString = queryString;

            var principal = new Mock<IPrincipal>();
            principal.Setup(p => p.Identity.Name).Returns("User");
            principal.Setup(p => p.IsInRole(It.Is<string>(role => UserRoles.Contains(role)))).Returns(true);
            principal.Setup(p => p.IsInRole(It.Is<string>(role => !UserRoles.Contains(role)))).Returns(false);

            User = principal.Object;
        }
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               string resourceId,
                                                               string resourceType,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               out MemoryStream payload)
        {
            string authorizationToken = AuthorizationHelper.GenerateAuthorizationTokenWithHashCore(
                verb,
                resourceId,
                resourceType,
                headers,
                stringHMACSHA256Helper,
                out payload);

            return(HttpUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, Constants.Properties.AuthorizationFormat,
                                                       Constants.Properties.MasterToken,
                                                       Constants.Properties.TokenVersion,
                                                       authorizationToken)));
        }
Beispiel #4
0
 internal DocumentFeedResponse(
     IEnumerable <T> result,
     int count,
     INameValueCollection responseHeaders,
     bool useETagAsContinuation = false,
     IReadOnlyDictionary <string, QueryMetrics> queryMetrics = null,
     IClientSideRequestStatistics requestStats = null,
     string disallowContinuationTokenMessage   = null,
     long responseLengthBytes = 0)
     : this(result)
 {
     this.Count                            = count;
     this.responseHeaders                  = (INameValueCollection)responseHeaders.Clone();
     this.usageHeaders                     = new Dictionary <string, long>();
     this.quotaHeaders                     = new Dictionary <string, long>();
     this.useETagAsContinuation            = useETagAsContinuation;
     this.queryMetrics                     = queryMetrics;
     this.disallowContinuationTokenMessage = disallowContinuationTokenMessage;
     this.ResponseLengthBytes              = responseLengthBytes;
 }
        public static void SerializeMessagePayload(
            MemoryStream stream,
            string verb,
            string resourceId,
            string resourceType,
            INameValueCollection headers,
            bool bUseUtcNowForMissingXDate = false)
        {
            string xDate = AuthorizationHelper.GetHeaderValue(headers, HttpConstants.HttpHeaders.XDate);
            string date  = AuthorizationHelper.GetHeaderValue(headers, HttpConstants.HttpHeaders.HttpDate);

            // At-least one of date header should present
            // https://docs.microsoft.com/en-us/rest/api/documentdb/access-control-on-documentdb-resources
            if (string.IsNullOrEmpty(xDate) && string.IsNullOrWhiteSpace(date))
            {
                if (!bUseUtcNowForMissingXDate)
                {
                    throw new UnauthorizedException(RMResources.InvalidDateHeader);
                }

                headers[HttpConstants.HttpHeaders.XDate] = DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture);
                xDate = AuthorizationHelper.GetHeaderValue(headers, HttpConstants.HttpHeaders.XDate);
            }

            // for name based, it is case sensitive, we won't use the lower case
            if (!PathsHelper.IsNameBased(resourceId))
            {
                resourceId = resourceId.ToLowerInvariant();
            }

            stream.Write(verb.ToLowerInvariant());
            stream.Write("\n");
            stream.Write(resourceType.ToLowerInvariant());
            stream.Write("\n");
            stream.Write(resourceId);
            stream.Write("\n");
            stream.Write(xDate.ToLowerInvariant());
            stream.Write("\n");
            stream.Write(xDate.Equals(string.Empty, StringComparison.OrdinalIgnoreCase) ? date.ToLowerInvariant() : string.Empty);
            stream.Write("\n");
        }
        // This API is a helper method to create auth header based on client request.
        // Uri is split into resourceType/resourceId -
        // For feed/post/put requests, resourceId = parentId,
        // For point get requests,     resourceId = last segment in URI
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               Uri uri,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               string clientVersion = "")
        {
            if (string.IsNullOrEmpty(verb))
            {
                throw new ArgumentException(RMResources.StringArgumentNullOrEmpty, "verb");
            }

            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            if (stringHMACSHA256Helper == null)
            {
                throw new ArgumentNullException("stringHMACSHA256Helper");
            }

            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            string resourceType    = string.Empty;
            string resourceIdValue = string.Empty;
            bool   isNameBased     = false;

            AuthorizationHelper.GetResourceTypeAndIdOrFullName(uri, out isNameBased, out resourceType, out resourceIdValue, clientVersion);

            string payload;

            return(AuthorizationHelper.GenerateKeyAuthorizationSignature(verb,
                                                                         resourceIdValue,
                                                                         resourceType,
                                                                         headers,
                                                                         stringHMACSHA256Helper,
                                                                         out payload));
        }
        public static bool CheckPayloadUsingKey(string inputToken,
                                                string verb,
                                                string resourceId,
                                                string resourceType,
                                                INameValueCollection headers,
                                                string key)
        {
            string payload;
            string requestBasedToken = AuthorizationHelper.GenerateKeyAuthorizationSignature(
                verb,
                resourceId,
                resourceType,
                headers,
                key,
                out payload);

            requestBasedToken = HttpUtility.UrlDecode(requestBasedToken);
            requestBasedToken = requestBasedToken.Substring(requestBasedToken.IndexOf("sig=", StringComparison.OrdinalIgnoreCase) + 4);

            return(inputToken.Equals(requestBasedToken, StringComparison.OrdinalIgnoreCase));
        }
Beispiel #8
0
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               string resourceId,
                                                               string resourceType,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               out string payload)
        {
            string authorizationToken = AuthorizationHelper.GenerateUrlEncodedAuthorizationTokenWithHashCore(
                verb,
                resourceId,
                resourceType,
                headers,
                stringHMACSHA256Helper,
                out ArrayOwner payloadStream);

            using (payloadStream)
            {
                payload = AuthorizationHelper.AuthorizationEncoding.GetString(payloadStream.Buffer.Array, payloadStream.Buffer.Offset, (int)payloadStream.Buffer.Count);
                return(AuthorizationHelper.AuthorizationFormatPrefixUrlEncoded + authorizationToken);
            }
        }
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               string resourceId,
                                                               string resourceType,
                                                               INameValueCollection headers,
                                                               string key,
                                                               bool bUseUtcNowForMissingXDate = false)
        {
            string authorizationToken = AuthorizationHelper.GenerateKeyAuthorizationCore(
                verb,
                resourceId,
                resourceType,
                headers,
                key,
                out _,
                bUseUtcNowForMissingXDate);

            return(HttpUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, Constants.Properties.AuthorizationFormat,
                                                       Constants.Properties.MasterToken,
                                                       Constants.Properties.TokenVersion,
                                                       authorizationToken)));
        }
Beispiel #10
0
        // This API is a helper method to create auth header based on client request.
        // Uri is split into resourceType/resourceId -
        // For feed/post/put requests, resourceId = parentId,
        // For point get requests,     resourceId = last segment in URI
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               Uri uri,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               string clientVersion = "")
        {
            if (string.IsNullOrEmpty(verb))
            {
                throw new ArgumentException(RMResources.StringArgumentNullOrEmpty, nameof(verb));
            }

            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (stringHMACSHA256Helper == null)
            {
                throw new ArgumentNullException(nameof(stringHMACSHA256Helper));
            }

            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            AuthorizationHelper.GetResourceTypeAndIdOrFullName(uri, out _, out string resourceType, out string resourceIdValue, clientVersion);

            string authorizationToken = AuthorizationHelper.GenerateKeyAuthorizationSignature(verb,
                                                                                              resourceIdValue,
                                                                                              resourceType,
                                                                                              headers,
                                                                                              stringHMACSHA256Helper,
                                                                                              out ArrayOwner arrayOwner);

            using (arrayOwner)
            {
                return(authorizationToken);
            }
        }
        public override Task <HttpResponseMessage> GetAsync(
            Uri uri,
            INameValueCollection additionalHeaders,
            ResourceType resourceType,
            HttpTimeoutPolicy timeoutPolicy,
            CosmosDiagnosticsContext diagnosticsContext,
            CancellationToken cancellationToken)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            // GetAsync doesn't let clients to pass in additional headers. So, we are
            // internally using SendAsync and add the additional headers to requestMessage.
            ValueTask <HttpRequestMessage> CreateRequestMessage()
            {
                HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, uri);

                if (additionalHeaders != null)
                {
                    foreach (string header in additionalHeaders)
                    {
                        if (GatewayStoreClient.IsAllowedRequestHeader(header))
                        {
                            requestMessage.Headers.TryAddWithoutValidation(header, additionalHeaders[header]);
                        }
                    }
                }

                return(new ValueTask <HttpRequestMessage>(requestMessage));
            }

            return(this.SendHttpAsync(
                       CreateRequestMessage,
                       resourceType,
                       timeoutPolicy,
                       diagnosticsContext,
                       cancellationToken));
        }
Beispiel #12
0
        private void CaptureSessionToken(DocumentServiceRequest request, INameValueCollection responseHeaders)
        {
            if (request.ResourceType == ResourceType.Collection && request.OperationType == OperationType.Delete)
            {
                string resourceId;

                if (request.IsNameBased)
                {
                    resourceId = responseHeaders[HttpConstants.HttpHeaders.OwnerId];
                }
                else
                {
                    resourceId = request.ResourceId;
                }

                this.sessionContainer.ClearTokenByResourceId(resourceId);
            }
            else
            {
                this.sessionContainer.SetSessionToken(request, responseHeaders);
            }
        }
 private DocumentServiceRequest CreateReadFeedDocumentServiceRequest(INameValueCollection requestHeaders)
 {
     if (this.resourceTypeEnum == Microsoft.Azure.Cosmos.Internal.ResourceType.Database ||
         this.resourceTypeEnum == Microsoft.Azure.Cosmos.Internal.ResourceType.Offer)
     {
         return(DocumentServiceRequest.Create(
                    OperationType.ReadFeed,
                    null,
                    this.resourceTypeEnum,
                    AuthorizationTokenType.PrimaryMasterKey,
                    requestHeaders));
     }
     else
     {
         return(DocumentServiceRequest.Create(
                    OperationType.ReadFeed,
                    this.resourceTypeEnum,
                    this.resourceLink,
                    AuthorizationTokenType.PrimaryMasterKey,
                    requestHeaders));
     }
 }
        // This API is a helper method to create auth header based on client request.
        // Uri is split into resourceType/resourceId -
        // For feed/post/put requests, resourceId = parentId,
        // For point get requests,     resourceId = last segment in URI
        public static string GenerateGatewayAuthSignatureWithAddressResolution(string verb,
                                                                               Uri uri,
                                                                               INameValueCollection headers,
                                                                               IComputeHash stringHMACSHA256Helper,
                                                                               string clientVersion = "")
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            // Address request has the URI fragment (dbs/dbid/colls/colId...) as part of
            // either $resolveFor 'or' $generate queries of the context.RequestUri.
            // Extracting out the URI in the form https://localhost/dbs/dbid/colls/colId/docs to generate the signature.
            // Authorizer uses the same URI to verify signature.
            if (uri.AbsolutePath.Equals(Paths.Address_Root, StringComparison.OrdinalIgnoreCase))
            {
                uri = AuthorizationHelper.GenerateUriFromAddressRequestUri(uri);
            }

            return(GenerateKeyAuthorizationSignature(verb, uri, headers, stringHMACSHA256Helper, clientVersion));
        }
Beispiel #15
0
        protected ServiceClientBase()
        {
            this.HttpMethod = DefaultHttpMethod;
            this.Headers    = PclExportClient.Instance.NewNameValueCollection();

            asyncClient = new AsyncServiceClient
            {
                ContentType        = ContentType,
                StreamSerializer   = AsyncSerializeToStream,
                StreamDeserializer = AsyncDeserializeFromStream,
                UserName           = this.UserName,
                Password           = this.Password,
                RequestFilter      = this.RequestFilter,
                ResponseFilter     = this.ResponseFilter,
                Headers            = this.Headers,
            };
            this.CookieContainer = new CookieContainer();
            this.StoreCookies    = true; //leave
            this.UserAgent       = DefaultUserAgent;

            asyncClient.HandleCallbackOnUiThread = this.HandleCallbackOnUiThread = true;
            asyncClient.ShareCookiesWithBrowser  = this.ShareCookiesWithBrowser = true;
        }
Beispiel #16
0
        public void TestSetAndGetKnownProperties(HeaderType headerType)
        {
            string value1 = Guid.NewGuid().ToString();
            string value2 = Guid.NewGuid().ToString();
            string value3 = Guid.NewGuid().ToString();
            INameValueCollection headers = this.CreateHeaders(headerType);

            headers.Add(HttpConstants.HttpHeaders.Continuation, value1);
            headers.Add(HttpConstants.HttpHeaders.PartitionKey, value2);
            headers.Add(WFConstants.BackendHeaders.PartitionKeyRangeId, value3);

            Assert.AreEqual(value1, headers[HttpConstants.HttpHeaders.Continuation]);
            Assert.AreEqual(value2, headers[HttpConstants.HttpHeaders.PartitionKey]);
            Assert.AreEqual(value3, headers[WFConstants.BackendHeaders.PartitionKeyRangeId]);
            value1 = Guid.NewGuid().ToString();
            value2 = Guid.NewGuid().ToString();
            value3 = Guid.NewGuid().ToString();
            headers[HttpConstants.HttpHeaders.Continuation]         = value1;
            headers[HttpConstants.HttpHeaders.PartitionKey]         = value2;
            headers[WFConstants.BackendHeaders.PartitionKeyRangeId] = value3;
            Assert.AreEqual(value1, headers[HttpConstants.HttpHeaders.Continuation]);
            Assert.AreEqual(value2, headers[HttpConstants.HttpHeaders.PartitionKey]);
            Assert.AreEqual(value3, headers[WFConstants.BackendHeaders.PartitionKeyRangeId]);
        }
Beispiel #17
0
        public override ValueTask <string> GetUserAuthorizationTokenAsync(
            string resourceAddress,
            string resourceType,
            string requestVerb,
            INameValueCollection headers,
            AuthorizationTokenType tokenType,
            ITrace trace)
        {
            // this is masterkey authZ
            headers[HttpConstants.HttpHeaders.XDate] = DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture);

            string authorizationToken = AuthorizationHelper.GenerateKeyAuthorizationSignature(
                requestVerb,
                resourceAddress,
                resourceType,
                headers,
                this.authKeyHashFunction,
                out AuthorizationHelper.ArrayOwner arrayOwner);

            using (arrayOwner)
            {
                return(new ValueTask <string>(authorizationToken));
            }
        }
        internal static async Task <DocumentServiceResponse> ParseResponseAsync(HttpResponseMessage responseMessage, JsonSerializerSettings serializerSettings = null, DocumentServiceRequest request = null)
        {
            using (responseMessage)
            {
                IClientSideRequestStatistics requestStatistics = request?.RequestContext?.ClientRequestStatistics;
                if ((int)responseMessage.StatusCode < 400)
                {
                    INameValueCollection headers = GatewayStoreClient.ExtractResponseHeaders(responseMessage);
                    Stream contentStream         = await GatewayStoreClient.BufferContentIfAvailableAsync(responseMessage);

                    return(new DocumentServiceResponse(
                               body: contentStream,
                               headers: headers,
                               statusCode: responseMessage.StatusCode,
                               clientSideRequestStatistics: requestStatistics,
                               serializerSettings: serializerSettings));
                }
                else if (request != null &&
                         request.IsValidStatusCodeForExceptionlessRetry((int)responseMessage.StatusCode))
                {
                    INameValueCollection headers = GatewayStoreClient.ExtractResponseHeaders(responseMessage);
                    Stream contentStream         = await GatewayStoreClient.BufferContentIfAvailableAsync(responseMessage);

                    return(new DocumentServiceResponse(
                               body: contentStream,
                               headers: headers,
                               statusCode: responseMessage.StatusCode,
                               clientSideRequestStatistics: requestStatistics,
                               serializerSettings: serializerSettings));
                }
                else
                {
                    throw await GatewayStoreClient.CreateDocumentClientExceptionAsync(responseMessage, requestStatistics);
                }
            }
        }
Beispiel #19
0
        ValueTask <string> ICosmosAuthorizationTokenProvider.GetUserAuthorizationTokenAsync(
            string resourceAddress,
            string resourceType,
            string requestVerb,
            INameValueCollection headers,
            AuthorizationTokenType tokenType,
            CosmosDiagnosticsContext diagnosticsContext) // unused, use token based upon what is passed in constructor
        {
            // this is masterkey authZ
            headers[HttpConstants.HttpHeaders.XDate] = DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture);

            string authorization = AuthorizationHelper.GenerateKeyAuthorizationSignature(
                verb: requestVerb,
                resourceId: resourceAddress,
                resourceType: resourceType,
                headers: headers,
                stringHMACSHA256Helper: this.authKeyHashFunction,
                payload: out AuthorizationHelper.ArrayOwner payload);

            using (payload)
            {
                return(new ValueTask <string>(authorization));
            }
        }
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               string resourceId,
                                                               string resourceType,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               out string payload)
        {
            string authorizationToken = AuthorizationHelper.GenerateAuthorizationTokenWithHashCore(
                verb,
                resourceId,
                resourceType,
                headers,
                stringHMACSHA256Helper,
                out ArrayOwner payloadStream);

            using (payloadStream)
            {
                payload = AuthorizationHelper.AuthorizationEncoding.GetString(payloadStream.Buffer.Array, payloadStream.Buffer.Offset, (int)payloadStream.Buffer.Count);
                return(HttpUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, Constants.Properties.AuthorizationFormat,
                                                           Constants.Properties.MasterToken,
                                                           Constants.Properties.TokenVersion,
                                                           authorizationToken)));
            }
        }
Beispiel #21
0
 private static string ToQueryString(INameValueCollection queryStringCollection)
 {
     return(ToQueryString((NameValueCollection)queryStringCollection.Original));
 }
Beispiel #22
0
 public JsonHttpClient()
 {
     this.Headers         = PclExportClient.Instance.NewNameValueCollection();
     this.CookieContainer = new CookieContainer();
 }
Beispiel #23
0
        private async Task <DocumentServiceResponse> ExecutePartitionKeyRangeReadChangeFeedAsync(string collectionRid,
                                                                                                 INameValueCollection headers,
                                                                                                 ITrace trace,
                                                                                                 IClientSideRequestStatistics clientSideRequestStatistics)
        {
            using (ITrace childTrace = trace.StartChild("Read PartitionKeyRange Change Feed", TraceComponent.Transport, Tracing.TraceLevel.Info))
            {
                using (DocumentServiceRequest request = DocumentServiceRequest.Create(
                           OperationType.ReadFeed,
                           collectionRid,
                           ResourceType.PartitionKeyRange,
                           AuthorizationTokenType.PrimaryMasterKey,
                           headers))
                {
                    string authorizationToken = null;
                    try
                    {
                        authorizationToken = await this.authorizationTokenProvider.GetUserAuthorizationTokenAsync(
                            request.ResourceAddress,
                            PathsHelper.GetResourcePath(request.ResourceType),
                            HttpConstants.HttpMethods.Get,
                            request.Headers,
                            AuthorizationTokenType.PrimaryMasterKey,
                            childTrace);
                    }
                    catch (UnauthorizedException)
                    {
                    }

                    if (authorizationToken == null)
                    {
                        // User doesn't have rid based resource token. Maybe he has name based.
                        throw new NotSupportedException("Resource tokens are not supported");

                        ////CosmosContainerSettings collection = await this.collectionCache.ResolveCollectionAsync(request, CancellationToken.None);
                        ////authorizationToken =
                        ////    this.authorizationTokenProvider.GetUserAuthorizationTokenAsync(
                        ////        collection.AltLink,
                        ////        PathsHelper.GetResourcePath(request.ResourceType),
                        ////        HttpConstants.HttpMethods.Get,
                        ////        request.Headers,
                        ////        AuthorizationTokenType.PrimaryMasterKey);
                    }

                    request.Headers[HttpConstants.HttpHeaders.Authorization] = authorizationToken;
                    request.RequestContext.ClientRequestStatistics           = clientSideRequestStatistics ?? new ClientSideRequestStatisticsTraceDatum(DateTime.UtcNow);
                    if (clientSideRequestStatistics == null)
                    {
                        childTrace.AddDatum("Client Side Request Stats", request.RequestContext.ClientRequestStatistics);
                    }

                    using (new ActivityScope(Guid.NewGuid()))
                    {
                        try
                        {
                            return(await this.storeModel.ProcessMessageAsync(request));
                        }
                        catch (DocumentClientException ex)
                        {
                            childTrace.AddDatum("Exception Message", ex.Message);
                            throw;
                        }
                    }
                }
            }
        }
 public static NameValueCollection ToNameValueCollection(this INameValueCollection nvc)
 {
     return((NameValueCollection)nvc.Original);
 }
Beispiel #25
0
        private DocumentServiceResponse ReadDocumentRequest(DocumentClient client, Document doc, INameValueCollection headers)
        {
            DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, ResourceType.Document, doc.SelfLink, AuthorizationTokenType.PrimaryMasterKey, headers);

            request.Headers.Set(HttpConstants.HttpHeaders.PartitionKey, (new PartitionKey(doc.Id)).InternalKey.ToJsonString());
            var retrievedDocResponse = client.ReadAsync(request, null).Result;

            return(retrievedDocResponse);
        }
Beispiel #26
0
        private StoredProcedureResponse <string> CreateDocumentScript(DocumentClient client, INameValueCollection headers)
        {
            var headersIterator = headers.AllKeys().SelectMany(headers.GetValues, (k, v) => new { key = k, value = v });
            var scriptOptions   = "{";
            var headerIndex     = 0;

            foreach (var header in headersIterator)
            {
                if (headerIndex != 0)
                {
                    scriptOptions += ", ";
                }

                headerIndex++;
                scriptOptions += header.key + ":" + header.value;
            }

            scriptOptions += "}";
            var guid = Guid.NewGuid().ToString();

            var script = @" function() {
                var client = getContext().getCollection();                
                client.createDocument(client.getSelfLink(), { id: ""TestDoc"" }," + scriptOptions + @", function(err, docCreated, options) { 
                   if(err) throw new Error('Error while creating document: ' + err.message); 
                   else {
                     getContext().getResponse().setBody(JSON.stringify(docCreated));  
                   }
                });}";

            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;
            var sproc = new StoredProcedure()
            {
                Id = Guid.NewGuid().ToString(), Body = script
            };
            var            createdSproc   = client.CreateStoredProcedureAsync(collection, sproc).Result.Resource;
            RequestOptions requestOptions = new RequestOptions();

            requestOptions.PartitionKey = new PartitionKey("TestDoc");
            var result = client.ExecuteStoredProcedureAsync <string>(createdSproc, requestOptions).Result;

            return(result);
        }
 public static Dictionary<string, string> ToDictionary(INameValueCollection nvc)
 {
     var map = new Dictionary<string, string>();
     for (var i = 0; i < nvc.Count; i++)
     {
         map[nvc.GetKey(i)] = nvc.Get(i);
     }
     return map;
 }
Beispiel #28
0
        private DocumentServiceResponse ReadDatabaseFeedRequest(DocumentClient client, INameValueCollection headers)
        {
            DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.ReadFeed, null, ResourceType.Database, AuthorizationTokenType.PrimaryMasterKey, headers);
            var response = client.ReadFeedAsync(request, null).Result;

            return(response);
        }
Beispiel #29
0
        private DocumentServiceResponse ReadDocumentFeedRequest(DocumentClient client, string collectionId, INameValueCollection headers)
        {
            DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.ReadFeed, collectionId, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, headers);

            Range <string> fullRange = new Range <string>(
                PartitionKeyInternal.MinimumInclusiveEffectivePartitionKey,
                PartitionKeyInternal.MaximumExclusiveEffectivePartitionKey,
                true,
                false);
            IRoutingMapProvider routingMapProvider   = client.GetPartitionKeyRangeCacheAsync().Result;
            IReadOnlyList <PartitionKeyRange> ranges = routingMapProvider.TryGetOverlappingRangesAsync(collectionId, fullRange).Result;

            request.RouteTo(new PartitionKeyRangeIdentity(collectionId, ranges.First().Id));

            var response = client.ReadFeedAsync(request, null).Result;

            return(response);
        }
Beispiel #30
0
        public static string ToString(INameValueCollection nvc)
        {
            var map = ToDictionary(nvc);

            return(TypeSerializer.SerializeToString(map));
        }
 public static Dictionary <string, string> ToDictionary(this INameValueCollection nameValues)
 {
     return(ToDictionary((NameValueCollection)nameValues.Original));
 }
        private static string GenerateKeyAuthorizationCore(
            string verb,
            string resourceId,
            string resourceType,
            INameValueCollection headers,
            string key,
            out ArraySegment <byte> payload,
            bool bUseUtcNowForMissingXDate = false)
        {
            string authorizationToken;

            // resourceId can be null for feed-read of /dbs
            if (string.IsNullOrEmpty(verb))
            {
                throw new ArgumentException(RMResources.StringArgumentNullOrEmpty, nameof(verb));
            }

            if (resourceType == null)
            {
                throw new ArgumentNullException(nameof(resourceType)); // can be empty
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException(RMResources.StringArgumentNullOrEmpty, nameof(key));
            }

            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            byte[] keyBytes = Convert.FromBase64String(key);
            using (HMACSHA256 hmacSha256 = new HMACSHA256(keyBytes))
            {
                // Order of the values included in the message payload is a protocol that clients/BE need to follow exactly.
                // More headers can be added in the future.
                // If any of the value is optional, it should still have the placeholder value of ""
                // OperationType -> ResourceType -> ResourceId/OwnerId -> XDate -> Date
                string verbInput         = verb ?? string.Empty;
                string resourceIdInput   = resourceId ?? string.Empty;
                string resourceTypeInput = resourceType ?? string.Empty;

                string authResourceId       = AuthorizationHelper.GetAuthorizationResourceIdOrFullName(resourceTypeInput, resourceIdInput);
                int    memoryStreamCapacity = AuthorizationHelper.ComputeMemoryCapacity(verbInput, authResourceId, resourceTypeInput);
                byte[] buffer = ArrayPool <byte> .Shared.Rent(memoryStreamCapacity);

                using ArrayOwner owner = new ArrayOwner(ArrayPool <byte> .Shared, new ArraySegment <byte>(buffer, 0, buffer.Length));
                Span <byte> payloadBytes = buffer;
                int         length       = AuthorizationHelper.SerializeMessagePayload(
                    payloadBytes,
                    verbInput,
                    authResourceId,
                    resourceTypeInput,
                    headers);

                byte[] hashPayLoad = hmacSha256.ComputeHash(buffer, 0, length);
                authorizationToken = Convert.ToBase64String(hashPayLoad);
            }

            return(authorizationToken);
        }
 public object CreateFromMap(INameValueCollection nameValues)
 {
     return PopulateFromMap(null, nameValues, null);
 }
        public object PopulateFromMap(object instance, INameValueCollection nameValues, List<string> ignoredWarningsOnPropertyNames = null)
        {
            var errors = new List<RequestBindingError>();

            PropertySerializerEntry propertySerializerEntry = null;

            if (instance == null)
                instance = type.CreateInstance();

            foreach (var key in nameValues.AllKeys)
            {
                string value = nameValues[key];
                if (!string.IsNullOrEmpty(value))
                {
                    instance = PopulateFromKeyValue(instance, key, value, 
                            out propertySerializerEntry, errors, ignoredWarningsOnPropertyNames);
                }
            }

            if (errors.Count > 0)
            {
                var serializationException = new SerializationException($"Unable to bind to request '{type.Name}'");
                serializationException.Data.Add("errors", errors);
                throw serializationException;
            }

            return instance;
        }
Beispiel #35
0
        private StoredProcedureResponse <string> ReadFeedScript(DocumentClient client, INameValueCollection headers)
        {
            var headersIterator = headers.AllKeys().SelectMany(headers.GetValues, (k, v) => new { key = k, value = v });
            var scriptOptions   = "{";
            var headerIndex     = 0;

            foreach (var header in headersIterator)
            {
                if (headerIndex != 0)
                {
                    scriptOptions += ", ";
                }

                headerIndex++;
                scriptOptions += header.key + ":" + header.value;
            }

            scriptOptions += "}";

            var script = @"function() {
                var client = getContext().getCollection();
                function callback(err, docFeed, responseOptions) {
                    if(err) throw 'Error while reading documents';
                    docFeed.forEach(function(doc, i, arr) { getContext().getResponse().appendBody(JSON.stringify(doc));  });
                };
                client.readDocuments(client.getSelfLink()," + scriptOptions + @", callback);}";

            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;
            var sproc = new StoredProcedure()
            {
                Id = Guid.NewGuid().ToString(), Body = script
            };
            var            createdSproc   = client.CreateStoredProcedureAsync(collection, sproc).Result.Resource;
            RequestOptions requestOptions = new RequestOptions();

            requestOptions.PartitionKey = new PartitionKey("test");
            var result = client.ExecuteStoredProcedureAsync <string>(createdSproc, requestOptions).Result;

            return(result);
        }
 private static string ToQueryString(INameValueCollection queryStringCollection)
 {
     return ToQueryString((NameValueCollection)queryStringCollection.Original);
 }
 public static string ToString(INameValueCollection nvc)
 {
     var map = ToDictionary(nvc);
     return TypeSerializer.SerializeToString(map);
 }