Пример #1
0
        public virtual GraphObject GetContainment(GraphObject parent, Type containmentType, string containmentObjectId)
        {
            Uri listUri = Utils.GetRequestUri(this, parent.GetType(), parent.ObjectId, containmentType, containmentObjectId);

            if (this.returnBatchItem.Value)
            {
                this.batchRequestItems.Value.Add(new BatchRequestItem(HttpVerb.GET, false, listUri, null, null));
                return(null);
            }

            Logger.Instance.Info("Retrieving {0}", listUri);

            byte[] rawResponse = this.ClientConnection.DownloadData(listUri, null);
            PagedResults <GraphObject> pagedResults = SerializationHelper.DeserializeJsonResponse <GraphObject>(
                Encoding.UTF8.GetString(rawResponse), listUri);

            return(pagedResults.Results.FirstOrDefault());
        }
Пример #2
0
        /// <summary>
        /// Add or update the directory object on the cloud.
        /// </summary>
        /// <param name="parent">Parent object type for containment type.</param>
        /// <param name="containment">Containment object.</param>
        /// <param name="isCreate">Is this create or update?</param>
        /// <returns>Created base entity object.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="parent"/> or <paramref name="containment"/> is <see langword="null" />
        /// </exception>
        private GraphObject AddOrUpdateContainment(GraphObject parent, GraphObject containment, bool isCreate)
        {
            Utils.ThrowIfNullOrEmpty(parent, "parent");
            Utils.ThrowIfNullOrEmpty(containment, "containment");

            containment.ValidateProperties(isCreate);

            Uri createUri = Utils.GetRequestUri(
                this,
                parent.GetType(),
                parent.ObjectId,
                containment.GetType(),
                isCreate ? String.Empty : containment.ObjectId);

            string requestJson = JsonConvert.SerializeObject(Utils.GetSerializableGraphObject(containment));

            string methodName = isCreate ? HttpVerb.POST : HttpVerb.PATCH;

            if (this.returnBatchItem.Value)
            {
                this.batchRequestItems.Value.Add(new BatchRequestItem(methodName, true, createUri, null, requestJson));
                return(null);
            }

            string responseJson = this.ClientConnection.UploadString(
                createUri, methodName, requestJson, null, null);

            PagedResults <GraphObject> pagedResults =
                SerializationHelper.DeserializeJsonResponse <GraphObject>(responseJson, createUri);

            if (pagedResults == null ||
                pagedResults.Results == null ||
                pagedResults.Results.Count != 1)
            {
                throw new InvalidOperationException("Unable to deserialize the response");
            }

            containment.ChangedProperties.Clear();
            pagedResults.Results[0].ChangedProperties.Clear();
            return(pagedResults.Results[0]);
        }
        /// <summary>
        /// Is the user member of the specified group? (transitive lookup)
        /// </summary>
        /// <param name="groupId">List of app ids.</param>
        /// <param name="memberId">Member object id.</param>
        /// <returns>
        /// <see langword="true"/> if the member is part of the group.
        /// <see langword="false"/> otherwise.
        /// </returns>
        public virtual bool IsMemberOf(string groupId, string memberId)
        {
            if (String.IsNullOrEmpty(groupId))
            {
                throw new ArgumentNullException("groupId");
            }

            if (String.IsNullOrEmpty(memberId))
            {
                throw new ArgumentNullException("memberId");
            }

            bool isMemberOf = false;

            Uri requestUri = Utils.GetRequestUri(this, null, null, Constants.ActionIsMemberOf);

            Logger.Instance.Info("POSTing to {0}", requestUri);

            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters["groupId"]  = groupId;
            parameters["memberId"] = memberId;

            string requestJson  = JsonConvert.SerializeObject(parameters);
            string responseJson = this.ClientConnection.UploadString(
                requestUri, HttpVerb.POST, requestJson, null, null);

            PagedResults <GraphObject> pagedResults =
                SerializationHelper.DeserializeJsonResponse <GraphObject>(responseJson, requestUri);

            if (pagedResults.MixedResults.Count > 0)
            {
                bool.TryParse(pagedResults.MixedResults[0].ToString(), out isMemberOf);
            }

            return(isMemberOf);
        }
        /// <summary>
        /// Assign license to a user.
        /// </summary>
        /// <param name="user">User whose licenses need to be manipulated.</param>
        /// <param name="addLicenses">List of licenses to be assigned.</param>
        /// <param name="removeLicenses">Licenses to be disabled.</param>
        /// <returns>Updated user object.</returns>
        public virtual User AssignLicense(User user, IList <AssignedLicense> addLicenses, IList <Guid> removeLicenses)
        {
            Utils.ValidateGraphObject(user, "user");

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

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

            Uri requestUri = Utils.GetRequestUri <User>(
                this, user.ObjectId, Constants.ActionAssignLicense);

            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters["addLicenses"]    = addLicenses;
            parameters["removeLicenses"] = removeLicenses;

            string requestJson  = JsonConvert.SerializeObject(parameters);
            string responseJson = this.ClientConnection.UploadString(
                requestUri, HttpVerb.POST, requestJson, null, null);

            PagedResults <User> pagedResults = SerializationHelper.DeserializeJsonResponse <User>(responseJson, requestUri);

            if (pagedResults != null && pagedResults.Results.Count > 0)
            {
                return(pagedResults.Results[0]);
            }

            // TODO: Should we throw an exception?
            return(null);
        }
Пример #5
0
        /// <summary>
        /// Deserialize JSON response
        /// </summary>
        /// <typeparam name="T">Graph object to be deserialized into.</typeparam>
        /// <param name="json">Serialized JSON string.</param>
        /// <param name="requestUri">Request uri that returned the results.</param>
        /// <returns>Paged collection of results.</returns>
        public static PagedResults <T> DeserializeJsonResponse <T>(string json, Uri requestUri) where T : GraphObject
        {
            if (String.IsNullOrEmpty(json))
            {
                return(null);
            }

            PopulateAvailableTypes();
            PagedResults <T> pagedResults = new PagedResults <T>();

            pagedResults.RequestUri = requestUri;

            JObject rootObject = JsonConvert.DeserializeObject(json) as JObject;

            if (rootObject == null)
            {
                throw new ArgumentException("Invalid json input.");
            }

            bool isGraphObject    = false;
            bool isCollection     = false;
            Type resultObjectType = null;

            if (rootObject[Constants.ODataMetadataKey] != null)
            {
                pagedResults.ODataMetadataType = rootObject[Constants.ODataMetadataKey].ToString();

                SerializationHelper.ParseMetadataType(
                    pagedResults.ODataMetadataType, out resultObjectType, out isGraphObject, out isCollection);
            }

            // Extract the next link if it exists
            JToken jtoken;

            if (rootObject.TryGetValue(Constants.ODataNextLink, out jtoken))
            {
                pagedResults.PageToken = jtoken.ToString();
            }

            // Check whether the json is an array or a single object.
            if (rootObject.TryGetValue(Constants.ODataValues, out jtoken))
            {
                // Even though a value attribute was found, there can be a single element inside the value
                if (isCollection)
                {
                    foreach (JToken valueItemToken in jtoken)
                    {
                        if (isGraphObject)
                        {
                            pagedResults.Results.Add(DeserializeGraphObject <T>(valueItemToken, resultObjectType));
                        }
                        else
                        {
                            // A collection of non directoryObject results.
                            pagedResults.MixedResults.Add(valueItemToken.ToString());
                        }
                    }
                }
                else
                {
                    pagedResults.MixedResults.Add(jtoken.ToString());
                }
            }
            else
            {
                if (isGraphObject)
                {
                    pagedResults.Results.Add(DeserializeGraphObject <T>(rootObject, resultObjectType));
                }
                else
                {
                    // Single value, non directoryObject result.
                    pagedResults.MixedResults.Add(rootObject.ToString());
                }
            }

            return(pagedResults);
        }
Пример #6
0
        /// <summary>
        /// Deserialize a batch response into individual response items.
        /// </summary>
        /// <param name="contentTypeHeader">Content type header.</param>
        /// <param name="responseString">Response string.</param>
        /// <param name="batchRequestItems">Batch request items.</param>
        /// <returns>Batch response items.</returns>
        public static List <BatchResponseItem> DeserializeBatchResponse(
            string contentTypeHeader, string responseString, IList <BatchRequestItem> batchRequestItems)
        {
            List <BatchResponseItem> batchResponseItems = new List <BatchResponseItem>();

            Utils.ThrowIfNullOrEmpty(contentTypeHeader, "contentTypeHeader");

            string[] splitContentTypeTokens = contentTypeHeader.Split(";".ToCharArray());
            string   boundaryMarker         = String.Empty;

            foreach (string contentTypeToken in splitContentTypeTokens)
            {
                if (contentTypeToken.Trim().StartsWith("boundary="))
                {
                    boundaryMarker = contentTypeToken.Trim().Substring("boundary=".Length);
                    break;
                }
            }

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(responseString)))
            {
                bool isCurrentBatchItemAFailure = false;
                int  itemIndex = 0;
                using (StreamReader sr = new StreamReader(ms))
                {
                    WebHeaderCollection headers = null;

                    while (!sr.EndOfStream)
                    {
                        string currentLine = sr.ReadLine();

                        if (String.IsNullOrWhiteSpace(currentLine))
                        {
                            continue;
                        }

                        if (currentLine.StartsWith("HTTP/1.1 "))
                        {
                            // In a batch item, the http status code for successful changesets is also 200 OK.
                            isCurrentBatchItemAFailure = !currentLine.Contains("200 OK");
                            continue;
                        }

                        if (currentLine.StartsWith("{\"odata.metadata"))
                        {
                            PagedResults <GraphObject> pagedResults = SerializationHelper.DeserializeJsonResponse <GraphObject>(
                                currentLine, batchRequestItems[itemIndex].RequestUri);
                            itemIndex++;
                            BatchResponseItem batchResponseItem = new BatchResponseItem();
                            batchResponseItem.Failed    = isCurrentBatchItemAFailure;
                            batchResponseItem.ResultSet = pagedResults;
                            batchResponseItems.Add(batchResponseItem);

                            // Add the response headers from the current batch to the response.
                            if (headers != null)
                            {
                                batchResponseItem.BatchHeaders.Add(headers);
                                headers = null;
                            }

                            continue;
                        }

                        if (currentLine.StartsWith("{\"odata.error"))
                        {
                            BatchResponseItem batchResponseItem = new BatchResponseItem();
                            batchResponseItem.Failed    = isCurrentBatchItemAFailure;
                            batchResponseItem.Exception = ErrorResolver.ParseErrorMessageString(
                                HttpStatusCode.BadRequest, currentLine);
                            batchResponseItem.Exception.ResponseUri = batchRequestItems[itemIndex].RequestUri.ToString();
                            batchResponseItems.Add(batchResponseItem);

                            if (headers != null)
                            {
                                batchResponseItem.BatchHeaders.Add(headers);
                                headers = null;
                            }
                        }

                        string[] tokens = currentLine.Split(":".ToCharArray());
                        if (tokens != null && tokens.Length == 2)
                        {
                            if (headers == null)
                            {
                                headers = new WebHeaderCollection();
                            }

                            headers[tokens[0]] = tokens[1];
                        }
                    }
                }
            }

            return(batchResponseItems);
        }