Beispiel #1
0
 /// <summary>
 /// Visits the children of the given payload element and replaces it with a copy if any child changes
 /// </summary>
 /// <param name="payloadElement">The payload element to potentially replace</param>
 /// <returns>The original element or a copy to replace it with</returns>
 public virtual ODataPayloadElement Visit(BatchRequestPayload payloadElement)
 {
     ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");
     return(this.VisitBatch <BatchRequestPayload, BatchRequestChangeset, IHttpRequest>(
                payloadElement,
                this.VisitRequestOperation));
 }
        /// <summary>
        /// Serializes a batch request payload
        /// </summary>
        /// <param name="payload">The batch payload</param>
        /// <param name="boundary">The batch payload boundary</param>
        /// <param name="encodingName">Optional name of an encoding to use if it is relevant to the current format. May be null if no character-set information was known.</param>
        /// <returns>The serialized batch payload</returns>
        public byte[] SerializeBatchPayload(BatchRequestPayload payload, string boundary, string encodingName)
        {
            ExceptionUtilities.CheckArgumentNotNull(payload, "payload");

            var encoding = HttpUtilities.GetEncodingOrDefault(encodingName);

            return(WriteBatchParts <IHttpRequest, BatchRequestChangeset>(payload, boundary, encoding, this.WriteRequest));
        }
 /// <summary>
 /// Visits the entity set and removes the title and entity set annotations
 /// </summary>
 /// <param name="payloadElement">The payload element to visit</param>
 public override void Visit(BatchRequestPayload payloadElement)
 {
     ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");
     
     var annotation = payloadElement.Annotations.Where(a => a is BatchBoundaryAnnotation).SingleOrDefault();
     payloadElement.Annotations.Remove(annotation);
     base.Visit(payloadElement);
 }
Beispiel #4
0
        /// <summary>
        /// Visits the entity set and removes the title and entity set annotations
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(BatchRequestPayload payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            var annotation = payloadElement.Annotations.Where(a => a is BatchBoundaryAnnotation).SingleOrDefault();

            payloadElement.Annotations.Remove(annotation);
            base.Visit(payloadElement);
        }
Beispiel #5
0
            /// <summary>
            /// Visits the payload element.
            /// </summary>
            /// <param name="payloadElement">The payload element to visit.</param>
            public override void Visit(BatchRequestPayload payloadElement)
            {
                var observed = this.GetNextObservedElement <BatchRequestPayload>();

                this.WrapAccept(
                    payloadElement,
                    observed,
                    (e) => this.VisitBatch <IHttpRequest, BatchRequestChangeset, BatchRequestPayload>((BatchRequestPayload)e, this.VisitRequestOperation));
            }
            /// <summary>
            /// Visits a payload element whose root is a BatchRequestPayload.
            /// </summary>
            /// <param name="expected">The root node of payload element being visited.</param>
            public void Visit(BatchRequestPayload expected)
            {
                ExceptionUtilities.CheckArgumentNotNull(expected, "expected");
                var observed = this.GetNextObservedElement <BatchRequestPayload>();

                using (this.Assert.WithMessage("Batch request did not match expectation"))
                {
                    this.batchComparer.CompareBatchPayload(expected, observed);
                }
            }
        /// <summary>
        /// Puts payload in a batch request.
        /// </summary>
        /// <typeparam name="T">T must be a PayloadTestDescriptor.</typeparam>
        /// <param name="originalPayload">Payload to put into batch.</param>
        /// <param name="verb">HttpVerb associated with payload.</param>
        /// <param name="random">Use of random makes this method non deterministic.</param>
        /// <param name="requestManager">Used to construct requests.</param>
        /// <param name="operationsBefore">Number of operations/changesets to go before payload.</param>
        /// <param name="operationsAfter">Number of operations/changesets to go after payload.</param>
        /// <param name="version">Maximum version for extra payloads</param>
        /// <returns>The test descriptor for the new BatchRequestPayload</returns>
        public static T InBatchRequest <T>(
            this T originalPayload,
            HttpVerb verb,
            IRandomNumberGenerator random,
            IODataRequestManager requestManager,
            int operationsBefore = 0,
            int operationsAfter  = 0,
            ODataVersion version = ODataVersion.V4
            ) where T : PayloadTestDescriptor
        {
            ExceptionUtilities.CheckArgumentNotNull(originalPayload, "originalPayload");
            ExceptionUtilities.CheckArgumentNotNull(verb, "verb");
            ExceptionUtilities.CheckArgumentNotNull(random, "random");
            ExceptionUtilities.CheckArgumentNotNull(requestManager, "requestManager");
            var payload = (T)originalPayload.Clone();

            var baseUri = new ODataUri(ODataUriBuilder.Root(new Uri("http://www.odata.org/service.svc")));

            IMimePart[] extraOperations = BatchUtils.ExtraRequestChangesets(random, requestManager, (EdmModel)payload.PayloadEdmModel, baseUri, version);  // add extraChangesets methods
            extraOperations.Concat(BatchUtils.ExtraRequestChangesets(random, requestManager, (EdmModel)payload.PayloadEdmModel, baseUri, version));

            //Work out the operations and changesets to go before the payload
            var parts = Enumerable.Range(0, operationsBefore).Select(i => random.ChooseFrom(extraOperations));

            if (verb != HttpVerb.Get)
            {
                extraOperations.ConcatSingle(payload.InRequestOperation(HttpVerb.Get, baseUri, requestManager));
            }
            else
            {
                extraOperations.ConcatSingle(payload.InRequestChangeset(verb, random, requestManager, random.NextFromRange(0, 2), random.NextFromRange(0, 2), version));
            }

            parts.Concat(Enumerable.Range(0, operationsAfter).Select(i => random.ChooseFrom(extraOperations)));

            var batchRequest = new BatchRequestPayload();

            foreach (var part in parts)
            {
                IHttpRequest operation = part as IHttpRequest;
                if (operation != null)
                {
                    batchRequest.Add(operation.AsBatchFragment());
                }
                BatchRequestChangeset changeset = part as BatchRequestChangeset;
                if (changeset != null)
                {
                    batchRequest.Add(changeset);
                }
            }

            //payload.PayloadEdmModel.Fixup();
            payload.PayloadElement = batchRequest;
            return(payload);
        }
Beispiel #8
0
        /// <summary>
        /// Deserializes the given response's binary payload into a batch payload
        /// </summary>
        /// <param name="requestPayload">The batch request payload that corresponds to the request</param>
        /// <param name="response">The response to deserialize</param>
        /// <returns>The deserialized batch response payload</returns>
        public BatchResponsePayload DeserializeBatchResponse(BatchRequestPayload requestPayload, HttpResponseData response)
        {
            var    encoding = HttpUtilities.DefaultEncoding;
            string charset;

            if (response.TryGetMimeCharset(out charset))
            {
                encoding = Encoding.GetEncoding(charset);
            }

            MultipartMimeData <MimePartData <byte[]> > split;

            ExceptionUtilities.Assert(TrySplitMimePart(response, encoding, out split), "Failed to split batch response body");

            var batchResponse = new BatchResponsePayload();

            var requestPartQueue = new Queue <IMimePart>(requestPayload.Parts);

            foreach (var subPart in split.ToList())
            {
                MultipartMimeData <MimePartData <byte[]> > splitChangeset;
                if (TrySplitMimePart(subPart, encoding, out splitChangeset))
                {
                    ExceptionUtilities.Assert(requestPartQueue.Count > 0, "Response changeset did not line up anything in request");
                    var requestChangeset = requestPartQueue.Dequeue() as BatchRequestChangeset;
                    ExceptionUtilities.CheckObjectNotNull(requestChangeset, "Response changeset did not line up with a request changeset");

                    var requestsQueue = new Queue <IHttpRequest>(requestChangeset.Operations);

                    var changeset = new BatchResponseChangeset();
                    changeset.Headers.AddRange(splitChangeset.Headers);

                    foreach (var changesetPart in splitChangeset)
                    {
                        ExceptionUtilities.Assert(requestsQueue.Count > 0, "Response did not line up anything in request changeset");
                        changeset.Add(this.BuildResponseFromPart(changesetPart, requestsQueue.Dequeue(), encoding));
                    }

                    batchResponse.Add(changeset);
                }
                else
                {
                    ExceptionUtilities.Assert(requestPartQueue.Count > 0, "Response did not line up anything in request");
                    var requestOperation = requestPartQueue.Dequeue() as MimePartData <IHttpRequest>;
                    ExceptionUtilities.CheckObjectNotNull(requestOperation, "Response operation did not line up with request operation");

                    batchResponse.Add(this.BuildResponseFromPart(subPart, requestOperation.Body, encoding));
                }
            }

            return(batchResponse);
        }
Beispiel #9
0
        /// <summary>
        /// Gets group members for AD group.
        /// </summary>
        /// <param name="groupIds">Group ids.</param>
        /// <param name="accessToken">accessToken to get Graph API data.</param>
        /// <returns>List of members.</returns>
        public async Task <List <Models.ADGroup> > GetBatchADGroupsInfoAsync(
            IEnumerable <string> groupIds,
            string accessToken)
        {
            var allRequests             = new BatchRequestCreator().CreateBatchRequestPayloadForGroupsDetails(groupIds);
            BatchRequestPayload payload = new BatchRequestPayload()
            {
                Requests = allRequests,
            };
            List <Models.ADGroup> responses = await this.CallGraphApiBatchPostToGetGroupsAsync(accessToken, this.graphQuery, JsonConvert.SerializeObject(payload));

            return(responses);
        }
Beispiel #10
0
        /// <summary>
        /// To Call GraphApi to get AD Group members.
        /// </summary>
        /// <param name="accessToken">Access Token.</param>
        /// <param name="payload">input JSON.</param>
        /// <returns>A <see cref="T"/> representing the result of operation.</returns>
        public async Task <dynamic> CallGraphApiBatchPostAsync(string accessToken, string payload)
        {
            List <ADGroupMembers> users = new List <ADGroupMembers>();

            HttpClient.DefaultRequestHeaders.Clear();
            HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var request = new StringContent(payload, Encoding.UTF8, "application/json");
            Uri myUri   = new Uri(this.graphQuery);
            HttpResponseMessage response = await HttpClient.PostAsync(myUri, request).ConfigureAwait(true);

            string content = await response.Content.ReadAsStringAsync();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var           responses        = this.GetValue <dynamic>(content, "responses");
                List <string> pagingResultURLs = new List <string>();

                foreach (var res in responses)
                {
                    var userlist = this.GetValue <dynamic>(JsonConvert.SerializeObject(res), "body");
                    var result   = this.GetValue <List <ADGroupMembers> >(JsonConvert.SerializeObject(userlist), "value");
                    users.AddRange(result);

                    string query = this.GetValue <string>(JsonConvert.SerializeObject(userlist), "@odata.nextLink");
                    if (query != null)
                    {
                        pagingResultURLs.Add(query);
                    }
                }

                if (pagingResultURLs.Count > 0)
                {
                    var allRequests = new BatchRequestCreator().CreatePagingBatchRequestPayloadForDetails(pagingResultURLs);
                    BatchRequestPayload payloadPagingRequests = new BatchRequestPayload()
                    {
                        Requests = allRequests,
                    };

                    users.AddRange(await this.CallGraphApiBatchPostAsync(accessToken, JsonConvert.SerializeObject(payloadPagingRequests)));
                }

                return(users);
            }

            return(content);

            throw new Exception(content);
        }
Beispiel #11
0
        /// <summary>
        /// Gets group members for AD group.
        /// </summary>
        /// <param name="groupIds">Group ids.</param>
        /// <param name="accessToken">accessToken to get Graph API data.</param>
        /// <returns>List of members.</returns>
        public async Task <List <ADGroupMembers> > GetBatchADGroupMembersAsync(
            IEnumerable <string> groupIds,
            string accessToken)
        {
            List <ADGroupMembers> adGroupMembers = new List <ADGroupMembers>();

            try
            {
                var allRequests = new BatchRequestCreator().CreateBatchRequestPayloadForDetails(groupIds);

                BatchRequestPayload payload = new BatchRequestPayload()
                {
                    Requests = allRequests,
                };
                List <ADGroupMembers> responses = await this.CallGraphApiBatchPostAsync(accessToken, JsonConvert.SerializeObject(payload));

                List <string> nestedGroupIds = new List <string>();

                for (int i = 0; i < responses.Count; i++)
                {
                    if (responses[i].Type == "#microsoft.graph.group")
                    {
                        nestedGroupIds.Add(responses[i].Id);
                    }
                    else
                    {
                        adGroupMembers.Add(responses[i]);
                    }
                }

                if (nestedGroupIds.Count > 0)
                {
                    adGroupMembers.AddRange(await this.GetBatchADGroupMembersAsync(nestedGroupIds, accessToken));
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(adGroupMembers);
        }
        /// <summary>
        /// Generates a dummy request based on the supplied response and model
        /// </summary>
        /// <param name="batchResponse">Response to build the request for.</param>
        /// <param name="model">Model to get the types from.</param>
        /// <returns></returns>
        public BatchRequestPayload GenerateRequestPayload(BatchResponsePayload batchResponse, EntityModelSchema model)
        {
            ExceptionUtilities.CheckArgumentNotNull(batchResponse, "batchResponse");
            ExceptionUtilities.CheckArgumentNotNull(model, "model");
            var batchRequest = new BatchRequestPayload();
            foreach (var part in batchResponse.Parts)
            {
                var operation = part as MimePartData<HttpResponseData>;
                if (operation != null)
                {
                    batchRequest.Add(this.GenerateRequestOperation(operation.Body as ODataResponse, model).AsBatchFragment());
                }

                BatchResponseChangeset changeset = part as BatchResponseChangeset;
                if (changeset != null)
                {
                    batchRequest.Add(this.GenerateRequestChangeset(changeset, model));
                }
            }

            return batchRequest;
        }
Beispiel #13
0
        /// <summary>
        /// Deserializes the given request's binary payload into a batch payload
        /// </summary>
        /// <param name="request">The request to deserialize</param>
        /// <returns>The deserialized batch request payload</returns>
        public BatchRequestPayload DeserializeBatchRequest(HttpRequestData request)
        {
            var encoding = request.GetEncodingFromHeadersOrDefault();

            MultipartMimeData <MimePartData <byte[]> > split;

            ExceptionUtilities.Assert(TrySplitMimePart(request, encoding, out split), "Failed to split batch response body");

            var batchRequest = new BatchRequestPayload();

            foreach (var subPart in split.ToList())
            {
                MultipartMimeData <MimePartData <byte[]> > splitChangeset;
                if (TrySplitMimePart(subPart, encoding, out splitChangeset))
                {
                    var changeset = new BatchRequestChangeset();
                    changeset.Headers.AddRange(splitChangeset.Headers);

                    foreach (var changesetPart in splitChangeset)
                    {
                        if (changesetPart.Body != null)
                        {
                            if (changesetPart.Body.Length > 0)
                            {
                                changeset.Add(this.BuildRequestFromPart(changesetPart, encoding));
                            }
                        }
                    }

                    batchRequest.Add(changeset);
                }
                else
                {
                    batchRequest.Add(this.BuildRequestFromPart(subPart, encoding));
                }
            }

            return(batchRequest);
        }
        /// <summary>
        /// Deserializes the given request's binary payload into a batch payload
        /// </summary>
        /// <param name="request">The request to deserialize</param>
        /// <returns>The deserialized batch request payload</returns>
        public BatchRequestPayload DeserializeBatchRequest(HttpRequestData request)
        {
            var encoding = request.GetEncodingFromHeadersOrDefault();

            MultipartMimeData<MimePartData<byte[]>> split;
            ExceptionUtilities.Assert(TrySplitMimePart(request, encoding, out split), "Failed to split batch response body");

            var batchRequest = new BatchRequestPayload();

            foreach (var subPart in split.ToList())
            {
                MultipartMimeData<MimePartData<byte[]>> splitChangeset;
                if (TrySplitMimePart(subPart, encoding, out splitChangeset))
                {
                    var changeset = new BatchRequestChangeset();
                    changeset.Headers.AddRange(splitChangeset.Headers);

                    foreach (var changesetPart in splitChangeset)
                    {
                        if (changesetPart.Body != null)
                        {
                            if (changesetPart.Body.Length > 0)
                            {
                                changeset.Add(this.BuildRequestFromPart(changesetPart, encoding));
                            }
                        }
                    }

                    batchRequest.Add(changeset);
                }
                else
                {
                    batchRequest.Add(this.BuildRequestFromPart(subPart, encoding));    
                }
            }

            return batchRequest;
        }
        /// <summary>
        /// Generates a dummy request based on the supplied response and model
        /// </summary>
        /// <param name="batchResponse">Response to build the request for.</param>
        /// <param name="model">Model to get the types from.</param>
        /// <returns></returns>
        public BatchRequestPayload GenerateRequestPayload(BatchResponsePayload batchResponse, EntityModelSchema model)
        {
            ExceptionUtilities.CheckArgumentNotNull(batchResponse, "batchResponse");
            ExceptionUtilities.CheckArgumentNotNull(model, "model");
            var batchRequest = new BatchRequestPayload();

            foreach (var part in batchResponse.Parts)
            {
                var operation = part as MimePartData <HttpResponseData>;
                if (operation != null)
                {
                    batchRequest.Add(this.GenerateRequestOperation(operation.Body as ODataResponse, model).AsBatchFragment());
                }

                BatchResponseChangeset changeset = part as BatchResponseChangeset;
                if (changeset != null)
                {
                    batchRequest.Add(this.GenerateRequestChangeset(changeset, model));
                }
            }

            return(batchRequest);
        }
 /// <summary>
 /// Visits a payload element whose root is a BatchRequestPayload.
 /// </summary>
 /// <param name="payloadElement">The root node of payload element being visited.</param>
 public void Visit(BatchRequestPayload payloadElement)
 {
     throw new TaupoNotSupportedException("Batch payloads are not supported");
 }
 /// <summary>
 /// Visits a BatchRequestPayload
 /// </summary>
 /// <param name="payloadElement">payload Element</param>
 public override void Visit(BatchRequestPayload payloadElement)
 {
     throw new TaupoNotSupportedException("Batch payloads are not supported");
 }
        /// <summary>
        /// Deserializes the given response's binary payload into a batch payload
        /// </summary>
        /// <param name="requestPayload">The batch request payload that corresponds to the request</param>
        /// <param name="response">The response to deserialize</param>
        /// <returns>The deserialized batch response payload</returns>
        public BatchResponsePayload DeserializeBatchResponse(BatchRequestPayload requestPayload, HttpResponseData response)
        {
            var encoding = HttpUtilities.DefaultEncoding;
            string charset;
            if (response.TryGetMimeCharset(out charset))
            {
                encoding = Encoding.GetEncoding(charset);
            }

            MultipartMimeData<MimePartData<byte[]>> split;
            ExceptionUtilities.Assert(TrySplitMimePart(response, encoding, out split), "Failed to split batch response body");

            var batchResponse = new BatchResponsePayload();
            
            var requestPartQueue = new Queue<IMimePart>(requestPayload.Parts);

            foreach (var subPart in split.ToList())
            {
                MultipartMimeData<MimePartData<byte[]>> splitChangeset;
                if (TrySplitMimePart(subPart, encoding, out splitChangeset))
                {
                    ExceptionUtilities.Assert(requestPartQueue.Count > 0, "Response changeset did not line up anything in request");
                    var requestChangeset = requestPartQueue.Dequeue() as BatchRequestChangeset;
                    ExceptionUtilities.CheckObjectNotNull(requestChangeset, "Response changeset did not line up with a request changeset");

                    var requestsQueue = new Queue<IHttpRequest>(requestChangeset.Operations);

                    var changeset = new BatchResponseChangeset();
                    changeset.Headers.AddRange(splitChangeset.Headers);

                    foreach (var changesetPart in splitChangeset)
                    {
                        ExceptionUtilities.Assert(requestsQueue.Count > 0, "Response did not line up anything in request changeset");
                        changeset.Add(this.BuildResponseFromPart(changesetPart, requestsQueue.Dequeue(), encoding));
                    }

                    batchResponse.Add(changeset);
                }
                else
                {
                    ExceptionUtilities.Assert(requestPartQueue.Count > 0, "Response did not line up anything in request");
                    var requestOperation = requestPartQueue.Dequeue() as MimePartData<IHttpRequest>;
                    ExceptionUtilities.CheckObjectNotNull(requestOperation, "Response operation did not line up with request operation");

                    batchResponse.Add(this.BuildResponseFromPart(subPart, requestOperation.Body, encoding));
                }
            }

            return batchResponse;
        }
Beispiel #19
0
 /// <summary>
 /// Visits the payload element
 /// </summary>
 /// <param name="payloadElement">The payload element to visit</param>
 public virtual void Visit(BatchRequestPayload payloadElement)
 {
     this.VisitBatch <IHttpRequest, BatchRequestChangeset, BatchRequestPayload>(payloadElement, this.VisitRequestOperation);
 }