private async Task CreateDeviceCollection()
        {
            string response;

            string  endpoint = string.Format("{0}dbs/{1}/colls", _docDbEndpoint, _dbId);
            JObject body     = new JObject();

            body.Add("id", _collectionName);
            using (WebClient client = new WebClient())
            {
                BuildHeaders(client);

                client.Headers.Add(AUTHORIZATION_HEADER_KEY, GetAuthorizationToken("POST", COLLECTION_RESOURCE_TYPE, _dbId));
                response = await AzureRetryHelper.OperationWithBasicRetryAsync <string>(async() =>
                                                                                        await client.UploadStringTaskAsync(endpoint, "POST", body.ToString()));

                object json = JObject.Parse(response);

                _collectionId =
                    ReflectionHelper.GetNamedPropertyValue(
                        json,
                        "_rid",
                        true,
                        false).ToString();
            }
        }
        public async Task InitializeDeviceCollection()
        {
            IEnumerable collections;
            string      topResponse;

            string endpoint = string.Format("{0}dbs/{1}/colls", _docDbEndpoint, _dbId);

            using (WebClient client = new WebClient())
            {
                BuildHeaders(client);
                client.Headers.Add(AUTHORIZATION_HEADER_KEY, GetAuthorizationToken("GET", COLLECTION_RESOURCE_TYPE, _dbId));
                topResponse = await AzureRetryHelper.OperationWithBasicRetryAsync <string>(async() =>
                                                                                           await client.DownloadStringTaskAsync(endpoint));
            }

            object topJson = JObject.Parse(topResponse);

            collections =
                ReflectionHelper.GetNamedPropertyValue(
                    topJson,
                    "DocumentCollections",
                    true,
                    false) as IEnumerable;

            if (collections != null)
            {
                foreach (object col in collections)
                {
                    object id =
                        ReflectionHelper.GetNamedPropertyValue(
                            col,
                            "id",
                            true,
                            false);

                    if ((id != null) &&
                        (id.ToString() == this._collectionName))
                    {
                        object rid =
                            ReflectionHelper.GetNamedPropertyValue(
                                col,
                                "_rid",
                                true,
                                false);

                        if (rid != null)
                        {
                            this._collectionId = rid.ToString();
                            return;
                        }
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(_collectionId))
            {
                await CreateDeviceCollection();
            }
        }
        /// <summary>
        /// Update the record for an existing device.
        /// </summary>
        /// <param name="updatedDevice"></param>
        /// <returns></returns>
        public async Task <JObject> UpdateDeviceAsync(dynamic updatedDevice)
        {
            string rid = DeviceSchemaHelper.GetDocDbRid(updatedDevice);

            WebClient client = new WebClient();

            BuildHeaders(client);
            client.Headers.Add(AUTHORIZATION_HEADER_KEY, GetAuthorizationToken("PUT", DOCUMENTS_RESOURCE_TYPE, rid));

            string endpoint = string.Format("{0}dbs/{1}/colls/{2}/docs/{3}", _docDbEndpoint, _dbId, _collectionId, rid);

            string response = await AzureRetryHelper.OperationWithBasicRetryAsync <string>(async() =>
                                                                                           await client.UploadStringTaskAsync(endpoint, "PUT", updatedDevice.ToString()));

            return(JObject.Parse(response));
        }
        public async Task <JObject> SaveNewDeviceAsync(dynamic device)
        {
            WebClient client = new WebClient();

            BuildHeaders(client);
            client.Headers.Add(AUTHORIZATION_HEADER_KEY, GetAuthorizationTokenForDeviceManagementCollectionQuery("POST"));

            string endpoint = string.Format("{0}dbs/{1}/colls/{2}/docs", _docDbEndpoint, _dbId, _collectionId);

            if (device.id == null)
            {
                device.id = Guid.NewGuid().ToString();
            }

            string response = await AzureRetryHelper.OperationWithBasicRetryAsync <string>(async() =>
                                                                                           await client.UploadStringTaskAsync(endpoint, "POST", device.ToString()));

            return(JObject.Parse(response));
        }
        /// <summary>
        ///
        /// https://msdn.microsoft.com/en-us/library/azure/dn783363.aspx
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="queryParameters"></param>
        /// <returns></returns>
        public async Task <DocDbRestQueryResult> QueryDeviceDbAsync(
            string queryString, Dictionary <string, Object> queryParams, int pageSize = -1, string continuationToken = null)
        {
            WebClient client = new WebClient();

            BuildHeaders(client);
            client.Headers.Set("Content-Type", "application/query+json");
            client.Headers.Add(AUTHORIZATION_HEADER_KEY, GetAuthorizationTokenForDeviceManagementCollectionQuery("POST"));
            client.Headers.Add("x-ms-documentdb-isquery", "true");

            if (pageSize >= 0)
            {
                client.Headers.Add("x-ms-max-item-count", pageSize.ToString());
            }
            if (continuationToken != null && continuationToken.Length > 0)
            {
                client.Headers.Add("x-ms-continuation", continuationToken);
            }

            JObject body = new JObject();

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

            string endpoint = string.Format("{0}dbs/{1}/colls/{2}/docs", _docDbEndpoint, _dbId, _collectionId);

            DocDbRestQueryResult result = new DocDbRestQueryResult();

            string response = await AzureRetryHelper.OperationWithBasicRetryAsync <string>(async() =>
                                                                                           await client.UploadStringTaskAsync(endpoint, "POST", body.ToString()));

            JObject responseJobj = JObject.Parse(response);
            JToken  documents    = responseJobj.GetValue("Documents");

            if (documents != null)
            {
                result.Documents = (JArray)documents;
            }

            WebHeaderCollection responseHeaders = client.ResponseHeaders;
            string count = responseHeaders["x-ms-item-count"];

            if (!string.IsNullOrEmpty(count))
            {
                result.TotalDocuments = int.Parse(count);
            }
            result.ContinuationToken = responseHeaders["x-ms-continuation"];

            return(result);
        }