Example #1
0
        /// <summary>
        /// Queries the DocumentDB and retrieves the device based on its deviceId
        /// </summary>
        /// <param name="deviceId">DeviceID of the device to retrieve</param>
        /// <returns>Device instance if present, null if a device was not found with the provided deviceId</returns>
        public async Task <dynamic> GetDeviceAsync(string deviceId)
        {
            dynamic result = null;

            Dictionary <string, Object> queryParams = new Dictionary <string, Object>();

            queryParams.Add("@id", deviceId);
            DocDbRestQueryResult response = await _docDbRestUtil.QueryCollectionAsync("SELECT VALUE root FROM root WHERE (root.DeviceProperties.DeviceID = @id)", queryParams);

            JArray foundDevices = response.ResultSet;

            if (foundDevices != null && foundDevices.Count > 0)
            {
                result = foundDevices.Children().ElementAt(0);
            }

            return(result);
        }
Example #2
0
        /// <summary>
        /// Queries the DocumentDB and retrieves all documents in the collection
        /// </summary>
        /// <returns>All documents in the collection</returns>
        private async Task <List <dynamic> > GetAllDevicesAsync()
        {
            IEnumerable    docs;
            List <dynamic> deviceList = new List <dynamic>();

            string query             = "SELECT VALUE root FROM root";
            string continuationToken = null;
            int    pageSize          = 500;

            do
            {
                DocDbRestQueryResult result = await _docDbRestUtil.QueryCollectionAsync(query, null, pageSize, continuationToken);

                docs =
                    ReflectionHelper.GetNamedPropertyValue(
                        result,
                        "ResultSet",
                        true,
                        false) as IEnumerable;

                if (docs != null)
                {
                    foreach (object doc in docs)
                    {
                        if (doc != null)
                        {
                            deviceList.Add(doc);
                        }
                    }
                }

                continuationToken = result.ContinuationToken;
            } while (!String.IsNullOrEmpty(continuationToken));

            return(deviceList);
        }
        private async Task<DocDbRestQueryResult> QueryDocDbInternal(string endpoint, string queryString, Dictionary<string, Object> queryParams,
            DocDbResourceType resourceType, string resourceId, int pageSize = -1, string continuationToken = null)
        {
            if (string.IsNullOrWhiteSpace(endpoint))
            {
                throw new ArgumentException("endpoint is null or whitespace");
            }

            if (string.IsNullOrWhiteSpace(queryString))
            {
                throw new ArgumentException("queryString is null or whitespace");
            }

            using (WebClient client = new WebClient())
            {
                client.Encoding = System.Text.Encoding.UTF8;
                client.Headers.Add(CONTENT_TYPE_HEADER_KEY, APPLICATION_QUERY_JSON);
                client.Headers.Add(ACCEPT_HEADER_KEY, APPLICATION_JSON);
                client.Headers.Add(VERSION_HEADER_KEY, X_MS_VERSION);

                // https://msdn.microsoft.com/en-us/library/azure/dn783368.aspx
                // The date of the request, as specified in RFC 1123. The date format is expressed in
                // Coordinated Universal Time (UTC), for example. Fri, 08 Apr 2015 03:52:31 GMT.
                string formattedTimeString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture).ToLowerInvariant();
                client.Headers.Add(DATE_HEADER_KEY, formattedTimeString);
                client.Headers.Add(AUTHORIZATION_HEADER_KEY, GetAuthorizationToken(POST_VERB, DocDbResourceTypeHelper.GetResourceTypeString(resourceType), resourceId, formattedTimeString));
                client.Headers.Add(IS_QUERY_HEADER_KEY, "true");

                if (pageSize >= 0)
                {
                    client.Headers.Add(MAX_ITEMS_HEADER_KEY, pageSize.ToString());
                }
                if (continuationToken != null && continuationToken.Length > 0)
                {
                    client.Headers.Add(CONTINUATION_HEADER_KEY, continuationToken);
                }

                var body = new JObject();
                body.Add("query", queryString);
                if (queryParams != null && queryParams.Count > 0)
                {
                    var paramsArray = new JArray();
                    foreach (string key in queryParams.Keys)
                    {
                        var param = new JObject();
                        param.Add("name", key);
                        param.Add("value", JToken.FromObject(queryParams[key]));
                        paramsArray.Add(param);
                    }
                    body.Add("parameters", paramsArray);
                }

                var result = new DocDbRestQueryResult();
                string response = await AzureRetryHelper.OperationWithBasicRetryAsync<string>(async () => await client.UploadStringTaskAsync(endpoint, POST_VERB, body.ToString()));
                JObject responseJobj = JObject.Parse(response);
                JToken jsonResultSet = responseJobj.GetValue(DocDbResourceTypeHelper.GetResultSetKey(resourceType));
                if (jsonResultSet != null)
                {
                    result.ResultSet = (JArray)jsonResultSet;
                }

                WebHeaderCollection responseHeaders = client.ResponseHeaders;

                string count = responseHeaders[ITEM_COUNT_RESPONSE_HEADER_KEY];
                if (!string.IsNullOrEmpty(count))
                {
                    result.TotalResults = int.Parse(count);
                }
                result.ContinuationToken = responseHeaders[CONTINUATION_HEADER_KEY];

                return result;
            }
        }