Exemple #1
0
        /// <inheritdoc />
        public override ParameterDefinition[] ToParameterDefinition()
        {
            var result = new List <ParameterDefinition>();

            if (PartUuids != null && PartUuids.Length > 0)
            {
                result.Add(ParameterDefinition.Create(PartUuidsParamName, RestClientHelper.ConvertGuidListToString(PartUuids)));
            }

            if (Deep)
            {
                result.Add(ParameterDefinition.Create(DeepParamName, Deep.ToString()));
            }

            if (LimitResult >= 0)
            {
                result.Add(ParameterDefinition.Create(LimitResultParamName, LimitResult.ToString()));
            }

            if (MeasurementUuids != null && MeasurementUuids.Length > 0)
            {
                result.Add(ParameterDefinition.Create(MeasurementUuidsParamName, RestClientHelper.ConvertGuidListToString(MeasurementUuids)));
            }

            if (RequestedMeasurementAttributes != null && RequestedMeasurementAttributes.AllAttributes != AllAttributeSelectionDto.True && RequestedMeasurementAttributes.Attributes != null)
            {
                result.Add(ParameterDefinition.Create(RequestedMeasurementAttributesParamName, RestClientHelper.ConvertUshortArrayToString(RequestedMeasurementAttributes.Attributes)));
            }

            if (OrderBy != null && OrderBy.Length > 0)
            {
                result.Add(ParameterDefinition.Create(OrderByParamName, OrderByToString(OrderBy)));
            }

            if (SearchCondition != null)
            {
                result.Add(ParameterDefinition.Create(SearchConditionParamName, SearchConditionParser.GenericConditionToString(SearchCondition)));
            }

            if (Statistics != MeasurementStatisticsDto.None)
            {
                result.Add(ParameterDefinition.Create(StatisticsParamName, Statistics.ToString()));
            }

            if (AggregationMeasurements != AggregationMeasurementSelectionDto.Default)
            {
                result.Add(ParameterDefinition.Create(AggregationParamName, AggregationMeasurements.ToString()));
            }

            if (FromModificationDate.HasValue)
            {
                result.Add(ParameterDefinition.Create(FromModificationDateParamName, XmlConvert.ToString(FromModificationDate.Value, XmlDateTimeSerializationMode.RoundtripKind)));
            }

            if (ToModificationDate.HasValue)
            {
                result.Add(ParameterDefinition.Create(ToModificationDateParamName, XmlConvert.ToString(ToModificationDate.Value, XmlDateTimeSerializationMode.RoundtripKind)));
            }

            if (MergeAttributes != null && MergeAttributes.Length > 0)
            {
                result.Add(ParameterDefinition.Create(MergeAttributesParamName, RestClientHelper.ConvertUshortArrayToString(MergeAttributes)));
            }

            if (MergeCondition != MeasurementMergeConditionDto.MeasurementsInAllParts)
            {
                result.Add(ParameterDefinition.Create(MergeConditionParamName, MergeCondition.ToString()));
            }

            if (MergeMasterPart != null)
            {
                result.Add(ParameterDefinition.Create(MergeMasterPartParamName, MergeMasterPart.ToString()));
            }

            return(result.ToArray());
        }
Exemple #2
0
        /// <summary>
        /// Parses the filter and returns a <see cref="MeasurementValueFilterAttributes"/> object that represents the filter values.
        /// If the parse operation was not successful, an <see cref="InvalidOperationException"/> will be thrown.
        /// </summary>
        /// <returns>The <see cref="MeasurementValueFilterAttributes"/> with the parsed information.</returns>
        public static MeasurementValueFilterAttributes Parse(string measurementUuids, string characteristicUuids, string deep, string limitResult, string order, string requestedMeasurementAttributes, string requestedValueAttributes, string searchCondition, string aggregation, string fromModificationDate, string toModificationDate)
        {
            var items = new[]
            {
                Tuple.Create(MeasurementUuidsParamName, measurementUuids),
                Tuple.Create(CharacteristicsUuidListParamName, characteristicUuids),
                Tuple.Create(DeepParamName, deep),
                Tuple.Create(LimitResultParamName, limitResult),
                Tuple.Create(OrderByParamName, order),
                Tuple.Create(RequestedValueAttributesParamName, requestedValueAttributes),
                Tuple.Create(RequestedMeasurementAttributesParamName, requestedMeasurementAttributes),
                Tuple.Create(SearchConditionParamName, searchCondition),
                Tuple.Create(AggregationParamName, aggregation),
                Tuple.Create(FromModificationDateParamName, fromModificationDate),
                Tuple.Create(ToModificationDateParamName, toModificationDate)
            };

            var result = new MeasurementValueFilterAttributes();

            foreach (var item in items)
            {
                var key   = item.Item1;
                var value = item.Item2;

                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }

                try
                {
                    switch (key)
                    {
                    case DeepParamName:
                        result.Deep = bool.Parse(value);
                        break;

                    case MeasurementUuidsParamName:
                        result.MeasurementUuids = RestClientHelper.ConvertStringToGuidList(value);
                        break;

                    case CharacteristicsUuidListParamName:
                        result.CharacteristicsUuidList = RestClientHelper.ConvertStringToGuidList(value);
                        break;

                    case LimitResultParamName:
                        result.LimitResult = short.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
                        break;

                    case RequestedValueAttributesParamName:
                        result.RequestedValueAttributes = new AttributeSelector(RestClientHelper.ConvertStringToUInt16List(value));
                        break;

                    case RequestedMeasurementAttributesParamName:
                        result.RequestedMeasurementAttributes = new AttributeSelector(RestClientHelper.ConvertStringToUInt16List(value));
                        break;

                    case OrderByParamName:
                        result.OrderBy = value.Split(',').Select(MeasurementFilterAttributes.ParseOrderBy).ToArray();
                        break;

                    case SearchConditionParamName:
                        result.SearchCondition = SearchConditionParser.Parse(value);
                        break;

                    case AggregationParamName:
                        result.AggregationMeasurements = (AggregationMeasurementSelection)Enum.Parse(typeof(AggregationMeasurementSelection), value);
                        break;

                    case ToModificationDateParamName:
                        result.ToModificationDate = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind);
                        break;

                    case FromModificationDateParamName:
                        result.FromModificationDate = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException(string.Format("Invalid filter value '{0}' for parameter '{1}'. The can be specified via url parameter in the form of 'key=value'. The following keys are valid: {2}",
                                                                      value, key,
                                                                      "deep = [True|False]\r\n" +
                                                                      "limitResult = [short]\r\n" +
                                                                      "measurementUuids = [list of measurement uuids]\r\n" +
                                                                      "characteristicUuids = [list of characteristic uuids]\r\n" +
                                                                      "valueAttributes = [attribute keys csv|Empty for all attributes]\r\n" +
                                                                      "measurementAttributes = [attribute keys csv|Empty for all attributes]\r\n" +
                                                                      "orderBy:[ushort asc|desc, ushort asc|desc, ...]\r\n" +
                                                                      "searchCondition:[search filter string]\r\n" +
                                                                      "aggregation:[Measurements|AggregationMeasurements|Default|All]\r\n" +
                                                                      "fromModificationDate:[Date]\r\n" +
                                                                      "toModificationDate:[Date]"), ex);
                }
            }
            return(result);
        }
        /// <summary>
        /// Fetches a single characteristic by its uuid.
        /// </summary>
        /// <param name="charUuid">The characteristic's uuid</param>
        /// <param name="withHistory">Determines whether to return the version history for the characteristic.</param>
        /// <param name="requestedCharacteristicAttributes">The attribute selector to determine which attributes to return.</param>
        /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
        public async Task <InspectionPlanCharacteristic> GetCharacteristicByUuid(Guid charUuid, AttributeSelector requestedCharacteristicAttributes = null, bool withHistory = false, CancellationToken cancellationToken = default(CancellationToken))
        {
            var parameter = RestClientHelper.ParseToParameter(requestedCharacteristicAttributes: requestedCharacteristicAttributes, withHistory: withHistory);

            return(await Get <InspectionPlanCharacteristic>(string.Format("characteristics/{0}", charUuid), cancellationToken, parameter.ToArray()).ConfigureAwait(false));
        }
 /// <summary>
 /// Deletes the measurements that are part of the <paramref name="measurementUuids"/> list.
 /// </summary>
 /// <param name="measurementUuids">The list of uuids of the measurements to delete.</param>
 /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
 public Task DeleteMeasurements(Guid[] measurementUuids, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(Delete(string.Format("measurements?measurementUuids={0}", RestClientHelper.ConvertGuidListToString(measurementUuids)), cancellationToken));
 }
        public void TestPutWithXmlData()
        {
            int id = random.Next(1000);

            string xmlData = "<Laptop>" +
                             "<BrandName>Alienware</BrandName>" +
                             "<Features>" +
                             "<Feature>8th Generation Intel® Core™ i5 - 8300H</Feature>" +
                             "<Feature>Windows 10 Home 64 - bit English</Feature>" +
                             "<Feature>NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6</Feature>" +
                             "<Feature>8GB, 2x4GB, DDR4, 2666MHz</Feature>" +
                             "</Features>" +
                             "<Id> " + id + "</Id>" +
                             "<LaptopName>Alienware M17</LaptopName>" +
                             "</Laptop>";

            Dictionary <string, string> headers = new Dictionary <string, string>()
            {
                { "Content-Type", "application/xml" },
                { "Accept", "application/xml" }
            };

            RestClientHelper restClientHelper = new RestClientHelper();
            IRestResponse    restResponse     = restClientHelper.PerformPostRequest(postUrl, headers, xmlData, RestSharp.DataFormat.Xml);

            Assert.Equal(200, (int)restResponse.StatusCode);

            xmlData = "<Laptop>" +
                      "<BrandName>Alienware</BrandName>" +
                      "<Features>" +
                      "<Feature>8th Generation Intel® Core™ i5 - 8300H</Feature>" +
                      "<Feature>Windows 10 Home 64 - bit English</Feature>" +
                      "<Feature>NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6</Feature>" +
                      "<Feature>8GB, 2x4GB, DDR4, 2666MHz</Feature>" +
                      "<Feature>Updated Feature</Feature>" +
                      "</Features>" +
                      "<Id> " + id + "</Id>" +
                      "<LaptopName>Alienware M17</LaptopName>" +
                      "</Laptop>";

            IRestClient  restClient  = new RestClient();
            IRestRequest restRequest = new RestRequest()
            {
                Resource = putUrl
            };

            restRequest.AddHeader("Content-Type", "application/xml");
            restRequest.AddHeader("Accept", "application/xml");
            restRequest.AddParameter("xmlBody", xmlData, ParameterType.RequestBody);

            IRestResponse restResponse1 = restClient.Put(restRequest);
            var           deserializer  = new RestSharp.Deserializers.DotNetXmlDeserializer();

            var laptop = deserializer.Deserialize <Laptop>(restResponse1);

            Assert.True(laptop.Features.Feature.Contains("Updated Feature"), "Feature did not got updated");

            headers = new Dictionary <string, string>()
            {
                { "Accept", "application/xml" }
            };

            var restResponse2 = restClientHelper.PerformGetRequest <Laptop>(getUrl + id, headers);

            Assert.Equal(200, (int)restResponse2.StatusCode);
            Assert.True(restResponse2.Data.Features.Feature.Contains("Updated Feature"), "Feature did not got updated");
        }
        /// <summary>
        /// Fetches a single part by its uuid.
        /// </summary>
        /// <param name="partUuid">The part's uuid</param>
        /// <param name="withHistory">Determines whether to return the version history for the part.</param>
        /// <param name="requestedPartAttributes">The attribute selector to determine which attributes to return.</param>
        /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
        public async Task <InspectionPlanPart> GetPartByUuid(Guid partUuid, AttributeSelector requestedPartAttributes = null, bool withHistory = false, CancellationToken cancellationToken = default(CancellationToken))
        {
            var parameter = RestClientHelper.ParseToParameter(requestedPartAttributes: requestedPartAttributes, withHistory: withHistory);

            return(await Get <InspectionPlanPart>(String.Format("parts/{0}", partUuid), cancellationToken, parameter.ToArray()).ConfigureAwait(false));
        }
 public IncreaseTimeOperation()
 {
     _restClientHelper = new RestClientHelper();
 }
        public void TestPutWithXmlData()
        {
            int    id      = random.Next(1000);
            string xmlData = "<Laptop>" +
                             "<BrandName>Alienware</BrandName>" +
                             "<Features>" +
                             "<Feature>8th Generation Intel® Core™ i5-8300H</Feature>" +
                             "<Feature>Windows 10 Home 64-bit English</Feature>" +
                             "<Feature>NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6</Feature>" +
                             "<Feature>8GB, 2x4GB, DDR4, 2666MHz</Feature>" +
                             "</Features>" +
                             "<Id>" + id + "</Id>" +
                             "<LaptopName>Alienware M17</LaptopName>" +
                             "</Laptop>";

            Dictionary <string, string> httpHeader = new Dictionary <string, string>()
            {
                { "Content-Type", "application/xml" },
                { "Accept", "application/xml" }
            };
            RestClientHelper restClientHelper = new RestClientHelper();
            IRestResponse    restResponse     = restClientHelper.PerformPostRequest(postUrl, httpHeader, xmlData, DataFormat.Xml);

            Assert.AreEqual(200, (int)restResponse.StatusCode);

            xmlData = "<Laptop>" +
                      "<BrandName>Alienware</BrandName>" +
                      "<Features>" +
                      "<Feature>8th Generation Intel® Core™ i5-8300H</Feature>" +
                      "<Feature>Windows 10 Home 64-bit English</Feature>" +
                      "<Feature>NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6</Feature>" +
                      "<Feature>8GB, 2x4GB, DDR4, 2666MHz</Feature>" +
                      "<Feature>1TB of RAM</Feature>" +
                      "</Features>" +
                      "<Id>" + id + "</Id>" +
                      "<LaptopName>Alienware M17</LaptopName>" +
                      "</Laptop>";

            IRestClient  restClient  = new RestClient();
            IRestRequest restRequest = new RestRequest()
            {
                Resource = putUrl
            };

            restRequest.AddHeader("Content-Type", "application/xml");
            restRequest.AddHeader("Accept", "application/xml");
            restRequest.RequestFormat = DataFormat.Xml;
            restRequest.AddParameter("xmlData", xmlData, ParameterType.RequestBody);

            IRestResponse putRestResponse = restClient.Put(restRequest);
            var           deserializer    = new RestSharp.Deserializers.DotNetXmlDeserializer();
            Laptop        laptop          = deserializer.Deserialize <Laptop>(restResponse);

            Assert.AreEqual(laptop.Id, id);

            Dictionary <string, string> getHttpHeadr = new Dictionary <string, string>()
            {
                { "Accept", "application/xml" }
            };
            IRestResponse <Laptop> getRestResponse = restClientHelper.PerformGetRequest <Laptop>(getUrl + id, getHttpHeadr);

            Assert.AreEqual(200, (int)getRestResponse.StatusCode);
            Assert.IsTrue(getRestResponse.Data.Features.Feature.Contains("1TB of RAM"));
        }
        public void Testputendpointwithjson()
        {
            string jsondata = "{" +
                              "\"BrandName\": \"Alienware\"," +
                              "\"Features\": {" +
                              "\"Feature\": [" +
                              "\"8th Generation Intel® Core™ i5-8300H\"," +
                              "\"Windows 10 Home 64-bit English\"," +
                              "\"NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6\"," +
                              "\"8GB, 2x4GB, DDR4, 2666MHz\"" +
                              "]" +
                              "}," +
                              "\"Id\": " + id + "," +
                              "\"LaptopName\": \"Alienware M16\"" +
                              "}";
            Dictionary <string, string> header = new Dictionary <string, string>()
            {
                { "Content-Type", "application/json" },
                { "Accept", "application/json" }
            };

            RestClientHelper restClientHelper = new RestClientHelper();
            IRestResponse    restresponse     = restClientHelper.PerformPostRequest(posturl, header, jsondata, DataFormat.Json);

            Assert.AreEqual(200, (int)restresponse.StatusCode);


            jsondata = "{" +
                       "\"BrandName\": \"Alienware\"," +
                       "\"Features\": {" +
                       "\"Feature\": [" +
                       "\"8th Generation Intel® Core™ i5-8300H\"," +
                       "\"Windows 10 Home 64-bit English\"," +
                       "\"NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6\"," +
                       "\"8GB, 2x4GB, DDR4, 2666MHz\"," +
                       "\"New feature added\"" +
                       "]" +
                       "}," +
                       "\"Id\": " + id + "," +
                       "\"LaptopName\": \"Alienware M16\"" +
                       "}";
            IRestClient  restClient  = new RestClient();
            IRestRequest restRequest = new RestRequest()
            {
                Resource = puturl
            };

            restRequest.AddHeader("Content-Type", "application/json");
            restRequest.AddHeader("Accept", "application/json");
            restRequest.RequestFormat = DataFormat.Json;
            restRequest.AddJsonBody(jsondata);
            IRestResponse <JsonRootObject> restResponse = restClient.Put <JsonRootObject>(restRequest);

            Assert.IsTrue(restResponse.Data.Features.Feature.Contains("New feature added"), "Data is not present");

            header = new Dictionary <string, string>
            {
                { "Accept", "application/json" }
            };
            restClientHelper = new RestClientHelper();
            restResponse     = restClientHelper.PerformGetRequest <JsonRootObject>(geturl + id, header);
            Assert.AreEqual(200, (int)restResponse.StatusCode);
            Assert.IsTrue(restResponse.Data.Features.Feature.Contains("New feature added"), "Data is not present");
        }
        public void Testputendpointwithxml()
        {
            string contentxml = "<Laptop>" +
                                "<BrandName>Alienware</BrandName>" +
                                "<Features>" +
                                "<Feature>8th Generation Intel® Core™ i5-8300H</Feature>" +
                                "<Feature>Windows 10 Home 64-bit English</Feature>" +
                                "<Feature>NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6</Feature>" +
                                "<Feature>8GB, 2x4GB, DDR4, 2666MHz</Feature>" +
                                "</Features>" +
                                "<Id>" + id.ToString() + "</Id>" +
                                "<LaptopName>Alienware M16</LaptopName>" +
                                "</Laptop>";
            Dictionary <string, string> header = new Dictionary <string, string>()
            {
                { "Content-Type", "application/xml" },
                { "Accept", "application/xml" }
            };

            RestClientHelper restClientHelper = new RestClientHelper();
            IRestResponse    restresponse     = restClientHelper.PerformPostRequest(posturl, header, contentxml, DataFormat.Xml);

            Assert.AreEqual(200, (int)restresponse.StatusCode);

            contentxml = "<Laptop>" +
                         "<BrandName>Alienware</BrandName>" +
                         "<Features>" +
                         "<Feature>8th Generation Intel® Core™ i5-8300H</Feature>" +
                         "<Feature>Windows 10 Home 64-bit English</Feature>" +
                         "<Feature>NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6</Feature>" +
                         "<Feature>8GB, 2x4GB, DDR4, 2666MHz</Feature>" +
                         "<Feature>New Feature</Feature>" +
                         "</Features>" +
                         "<Id>" + id.ToString() + "</Id>" +
                         "<LaptopName>Alienware M16</LaptopName>" +
                         "</Laptop>";
            IRestClient  restClient  = new RestClient();
            IRestRequest restRequest = new RestRequest()
            {
                Resource = puturl
            };

            restRequest.AddHeader("Content-Type", "application/xml");
            restRequest.AddHeader("Accept", "application/xml");
            restRequest.RequestFormat = DataFormat.Xml;
            restRequest.AddParameter("xmlbody", contentxml, ParameterType.RequestBody);
            IRestResponse restResponse1 = restClient.Put(restRequest);
            var           deserializer  = new RestSharp.Deserializers.DotNetXmlDeserializer();
            var           laptop        = deserializer.Deserialize <Laptop>(restResponse1);

            Assert.IsTrue(laptop.Features.Feature.Contains("New Feature"), "Data is not updated");

            header = new Dictionary <string, string>
            {
                { "Accept", "application/xml" }
            };
            restClientHelper = new RestClientHelper();
            IRestResponse <Laptop> restResponse2 = restClientHelper.PerformGetRequest <Laptop>(geturl + id, header);

            Assert.AreEqual(200, (int)restResponse2.StatusCode);
            Assert.IsTrue(restResponse2.Data.Features.Feature.Contains("New Feature"), "Data is not present");
        }
Exemple #11
0
        private async Task <TResult> SendAsyncImpl <TBody, TResult>(HttpMethod method, string urlTemplate, object[] urlParameters,
                                                                    TBody body, string acceptMediaType = null)
        {
            var start    = GetTimestamp();
            var callData = new RestCallData()
            {
                StartedAtUtc      = RestClientHelper.GetUtc(),
                HttpMethod        = method,
                UrlTemplate       = urlTemplate,
                UrlParameters     = urlParameters,
                Url               = FormatUrl(urlTemplate, urlParameters),
                RequestBodyType   = typeof(TBody),
                ResponseBodyType  = typeof(TResult),
                RequestBodyObject = body,
                AcceptMediaType   = acceptMediaType ?? Settings.ExplicitAcceptList ?? Settings.Serializer.ContentTypes,
            };

            // Create RequestMessage, setup headers, serialize body
            callData.Request = new HttpRequestMessage(callData.HttpMethod, callData.Url);
            var headers = callData.Request.Headers;

            headers.Add("accept", callData.AcceptMediaType);
            foreach (var kv in this.DefaultRequestHeaders)
            {
                headers.Add(kv.Key, kv.Value);
            }
            BuildHttpRequestContent(callData);

            Settings.Events.OnSendingRequest(this, callData);

            //actually make a call
            callData.Response = await HttpClient.SendAsync(callData.Request, this.CancellationToken);

            callData.TimeElapsed = GetTimeSince(start); //measure time in case we are about to cancel and throw

            //check error
            if (callData.Response.IsSuccessStatusCode)
            {
                Settings.Events.OnReceivedResponse(this, callData);
                await ReadResponseBodyAsync(callData).ConfigureAwait(false);
            }
            else
            {
                callData.Exception = await this.ReadErrorResponseAsync(callData);

                Settings.Events.OnReceivedError(this, callData);
            }
            // get time again to include deserialization time
            callData.TimeElapsed = GetTimeSince(start);
            // Log
            // args: operationContext, clientName, urlTemplate, urlArgs, request, response, requestBody, responseBody, timeMs, exc
            var timeMs = (int)callData.TimeElapsed.TotalMilliseconds;

            Settings.LogAction?.Invoke(this.AppContext, this.ClientName, callData.UrlTemplate, callData.UrlParameters,
                                       callData.Request, callData.Response, callData.RequestBodyString, callData.ResponseBodyString,
                                       timeMs, callData.Exception);
            Settings.Events.OnCompleted(this, callData);
            if (callData.Exception != null)
            {
                throw callData.Exception;
            }
            return((TResult)callData.ResponseBodyObject);
        }//method
Exemple #12
0
 /// <summary>
 /// Formats the query part of URL from properties (fields) of an object (names and values).
 /// Null-value parameters are skipped. All values are URL-escaped.
 /// </summary>
 /// <param name="queryParams">Query parameters object.</param>
 /// <returns>Constructed query part.</returns>
 public string BuildUrlQuery(object queryParams)
 {
     return(RestClientHelper.BuildUrlQuery(queryParams));
 }
Exemple #13
0
 public CampaignOperation()
 {
     _restClientHelper = new RestClientHelper();
 }
Exemple #14
0
        /// <summary>
        /// Creates a <see cref="ParameterDefinition"/> list that represents this filter.
        /// </summary>
        public ParameterDefinition[] ToParameterDefinition()
        {
            var result = new List <ParameterDefinition>();

            if (Deep)
            {
                result.Add(ParameterDefinition.Create(DeepParamName, Deep.ToString()));
            }

            if (LimitResult >= 0)
            {
                result.Add(ParameterDefinition.Create(LimitResultParamName, LimitResult.ToString()));
            }

            if (MeasurementUuids != null && MeasurementUuids.Length > 0)
            {
                result.Add(ParameterDefinition.Create(MeasurementUuidsParamName, RestClientHelper.ConvertGuidListToString(MeasurementUuids)));
            }

            if (CharacteristicsUuidList != null && CharacteristicsUuidList.Length > 0)
            {
                result.Add(ParameterDefinition.Create(CharacteristicsUuidListParamName, RestClientHelper.ConvertGuidListToString(CharacteristicsUuidList)));
            }

            if (RequestedValueAttributes != null && RequestedValueAttributes.AllAttributes != AllAttributeSelection.True && RequestedValueAttributes.Attributes != null)
            {
                result.Add(ParameterDefinition.Create(RequestedValueAttributesParamName, RestClientHelper.ConvertUInt16ListToString(RequestedValueAttributes.Attributes)));
            }

            if (RequestedMeasurementAttributes != null && RequestedMeasurementAttributes.AllAttributes != AllAttributeSelection.True && RequestedMeasurementAttributes.Attributes != null)
            {
                result.Add(ParameterDefinition.Create(RequestedMeasurementAttributesParamName, RestClientHelper.ConvertUInt16ListToString(RequestedMeasurementAttributes.Attributes)));
            }

            if (OrderBy != null && OrderBy.Length > 0)
            {
                result.Add(ParameterDefinition.Create(OrderByParamName, MeasurementFilterAttributes.OrderByToString(OrderBy)));
            }

            if (SearchCondition != null)
            {
                result.Add(ParameterDefinition.Create(SearchConditionParamName, SearchConditionParser.GenericConditionToString(SearchCondition)));
            }

            if (AggregationMeasurements != AggregationMeasurementSelection.Default)
            {
                result.Add(ParameterDefinition.Create(AggregationParamName, AggregationMeasurements.ToString()));
            }

            if (FromModificationDate.HasValue)
            {
                result.Add(ParameterDefinition.Create(FromModificationDateParamName, XmlConvert.ToString(FromModificationDate.Value, XmlDateTimeSerializationMode.RoundtripKind)));
            }

            if (ToModificationDate.HasValue)
            {
                result.Add(ParameterDefinition.Create(ToModificationDateParamName, XmlConvert.ToString(ToModificationDate.Value, XmlDateTimeSerializationMode.RoundtripKind)));
            }

            return(result.ToArray());
        }
Exemple #15
0
 public SiteBetBase(string domain)
 {
     _restHelper = new RestClientHelper(domain);
 }
        public void TestPutWithJsonData()
        {
            int    id       = random.Next(1000);
            string jsonData = "{" +
                              "\"BrandName\": \"Alienware\"," +
                              "\"Features\": {" +
                              "\"Feature\": [" +
                              "\"8th Generation Intel® Core™ i5-8300H\"," +
                              "\"Windows 10 Home 64-bit English\"," +
                              "\"NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6\"," +
                              "\"8GB, 2x4GB, DDR4, 2666MHz\"" +
                              "]" +
                              "}," +
                              "\"Id\": " + id + "," +
                              "\"LaptopName\": \"Alienware M17\"" +
                              "}";

            Dictionary <string, string> httpHeader = new Dictionary <string, string>()
            {
                { "Content-Type", "application/json" },
                { "Accept", "application/xml" }
            };
            RestClientHelper restClientHelper = new RestClientHelper();
            IRestResponse    restResponse     = restClientHelper.PerformPostRequest(postUrl, httpHeader, jsonData, DataFormat.Json);

            Assert.AreEqual(200, (int)restResponse.StatusCode);


            jsonData = "{" +
                       "\"BrandName\": \"Alienware\"," +
                       "\"Features\": {" +
                       "\"Feature\": [" +
                       "\"8th Generation Intel® Core™ i5-8300H\"," +
                       "\"Windows 10 Home 64-bit English\"," +
                       "\"NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6\"," +
                       "\"8GB, 2x4GB, DDR4, 2666MHz\"," +
                       "\"1TB Of RAM\"" +
                       "]" +
                       "}," +
                       "\"Id\": " + id + "," +
                       "\"LaptopName\": \"Alienware M17\"" +
                       "}";

            IRestClient  restClient  = new RestClient();
            IRestRequest restRequest = new RestRequest()
            {
                Resource = putUrl
            };

            restRequest.AddHeader("Content-Type", "application/json");
            restRequest.AddHeader("Accept", "application/json");
            restRequest.RequestFormat = DataFormat.Json;
            restRequest.AddJsonBody(jsonData);

            IRestResponse <Root> putRestResponse = restClient.Put <Root>(restRequest);

            Assert.IsTrue(putRestResponse.Data.Features.Feature.Contains("1TB Of RAM"));

            Dictionary <string, string> getHttpHeadr = new Dictionary <string, string>()
            {
                { "Accept", "application/json" }
            };
            IRestResponse <Root> getRestResponse = restClientHelper.PerformGetRequest <Root>(getUrl + id, getHttpHeadr);

            Assert.AreEqual(200, (int)getRestResponse.StatusCode);
            Assert.IsTrue(getRestResponse.Data.Features.Feature.Contains("1TB Of RAM"));
        }
 /// <summary>
 /// Adds the required authentication and timestamp headers to the request
 /// </summary>
 /// <param name="request"></param>
 private void SignRequest(HttpWebRequest request)
 {
     request.Headers.Add(HttpRequestHeader.Authorization,
                         "SharedKey " + _accountId + ":" + RestClientHelper.GenerateSignature(request, SignatureType.SharedKey, _key));
 }
        public void TestPutWithJsonData()
        {
            int    id       = random.Next(1000);
            string jsonData = "{" +
                              "\"BrandName\": \"Alienware\"," +
                              "\"Features\": {" +
                              "\"Feature\": [" +
                              "\"8th Generation Intel® Core™ i5-8300H\"," +
                              "\"Windows 10 Home 64-bit English\"," +
                              "\"NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6\"," +
                              "\"8GB, 2x4GB, DDR4, 2666MHz\"" +
                              "]" +
                              "}," +
                              "\"Id\": " + id + "," +
                              "\"LaptopName\": \"Alienware M17\"" +
                              "}";

            Dictionary <string, string> headers = new Dictionary <string, string>()
            {
                { "Content-Type", "application/json" },
                { "Accept", "application/json" }
            };


            RestClientHelper restClientHelper = new RestClientHelper();
            IRestResponse    restResponse     = restClientHelper.PerformPostRequest(postUrl, headers, jsonData, RestSharp.DataFormat.Json);

            Assert.Equal(200, (int)restResponse.StatusCode);

            jsonData = "{" +
                       "\"BrandName\": \"Alienware\"," +
                       "\"Features\": {" +
                       "\"Feature\": [" +
                       "\"8th Generation Intel® Core™ i5-8300H\"," +
                       "\"Windows 10 Home 64-bit English\"," +
                       "\"NVIDIA® GeForce® GTX 1660 Ti 6GB GDDR6\"," +
                       "\"8GB, 2x4GB, DDR4, 2666MHz\"," +
                       "\"New Feature\"" +
                       "]" +
                       "}," +
                       "\"Id\": " + id + "," +
                       "\"LaptopName\": \"Alienware M17\"" +
                       "}";

            IRestClient  restClient  = new RestClient();
            IRestRequest restRequest = new RestRequest()
            {
                Resource = putUrl
            };

            restRequest.AddHeader("Content-Type", "application/json");
            restRequest.AddHeader("Accept", "application/json");
            restRequest.AddJsonBody(jsonData);

            IRestResponse <JsonRootObject> restResponse1 = restClient.Put <JsonRootObject>(restRequest);

            Assert.Equal(200, (int)restResponse1.StatusCode);
            Assert.True(restResponse1.Data.Features.Feature.Contains("New Feature"), "Feature did not got updated");

            headers = new Dictionary <string, string>()
            {
                { "Accept", "application/json" }
            };

            restClientHelper.PerformGetRequest <JsonRootObject>(getUrl, headers);
            Assert.Contains("New Feature", restResponse1.Data.Features.Feature);
        }
Exemple #19
0
        /// <inheritdoc />
        public async Task <IEnumerable <InspectionPlanCharacteristicDto> > GetCharacteristics(PathInformationDto partPath = null, ushort?depth = null, AttributeSelector requestedCharacteristicAttributes = null, bool withHistory = false, CancellationToken cancellationToken = default)
        {
            var parameter = RestClientHelper.ParseToParameter(partPath, null, null, depth, null, requestedCharacteristicAttributes, withHistory);

            return(await _RestClient.Request <InspectionPlanCharacteristicDto[]>(RequestBuilder.CreateGet("characteristics", parameter.ToArray()), cancellationToken).ConfigureAwait(false));
        }
 /// <summary>
 /// Removes the catalog entries with the specified <paramref name="keys"/> from the catalog <paramref name="catalogUuid"/>. If the list of keys
 /// is empty, all catalog entries will be removed.
 /// </summary>
 /// <param name="catalogUuid">The uuid of the catalog to remove the entries from.</param>
 /// <param name="keys">The keys of the catalog entries to delete.</param>
 /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
 public Task DeleteCatalogEntries(Guid catalogUuid, ushort[] keys = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(Delete(string.Format("catalogs/{0}/{1}", catalogUuid, RestClientHelper.ConvertUInt16ListToString(keys)), cancellationToken));
 }
Exemple #21
0
        /// <inheritdoc />
        public async Task <InspectionPlanCharacteristicDto> GetCharacteristicByUuid(Guid charUuid, AttributeSelector requestedCharacteristicAttributes = null, bool withHistory = false, CancellationToken cancellationToken = default)
        {
            var parameter = RestClientHelper.ParseToParameter(requestedCharacteristicAttributes: requestedCharacteristicAttributes, withHistory: withHistory);

            return(await _RestClient.Request <InspectionPlanCharacteristicDto>(RequestBuilder.CreateGet($"characteristics/{charUuid}", parameter.ToArray()), cancellationToken).ConfigureAwait(false));
        }
 /// <summary>
 /// Deletes all parts and child parts below the parts specified by <paramref name="partUuids"/> from the database. Since parts act as the parent
 /// of characteristics and measurements, this call will delete all characteristics and measurements including the measurement
 /// values that are a child of the specified parent part.
 /// </summary>
 /// <param name="partUuids">The uuid list of the parent part for the delete operation.</param>
 /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
 public Task DeleteParts(Guid[] partUuids, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(Delete(string.Format("parts?partUuids={0}", RestClientHelper.ConvertGuidListToString(partUuids)), cancellationToken));
 }
Exemple #23
0
        /// <summary>
        /// Parses the filter and returns a <see cref="InspectionPlanFilterAttributes"/> object that represents the filter values.
        /// If the parse operation was not successful, an <see cref="InvalidOperationException"/> will be thrown.
        /// </summary>
        /// <returns>The <see cref="InspectionPlanFilterAttributes"/> with the parsed information.</returns>
        public static InspectionPlanFilterAttributes Parse(string depth, string partUuids, string withHistory, string requestedPartAttributes, string requestedCharacteristicsAttributes)
        {
            var items = new[]
            {
                Tuple.Create(DepthParamName, depth),
                Tuple.Create(PartUuidsParamName, partUuids),
                Tuple.Create(WithHistoryParamName, withHistory),
                Tuple.Create(RequestedPartAttributesParamName, requestedPartAttributes),
                Tuple.Create(RequestedCharacteristicsAttributesParamName, requestedCharacteristicsAttributes),
            };

            var result = new InspectionPlanFilterAttributes();

            foreach (var item in items)
            {
                var key   = item.Item1;
                var value = item.Item2;

                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }

                try
                {
                    switch (key)
                    {
                    case DepthParamName:
                        result.Depth = ushort.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
                        break;

                    case PartUuidsParamName:
                        result.PartUuids = RestClientHelper.ConvertStringToGuidList(value);
                        break;

                    case WithHistoryParamName:
                        result.WithHistory = bool.Parse(value);
                        break;

                    case RequestedPartAttributesParamName:
                        if (string.Equals(value, "None", StringComparison.OrdinalIgnoreCase))
                        {
                            result.RequestedPartAttributes = new AttributeSelector(AllAttributeSelection.False);
                        }
                        else if (string.Equals(value, "All", StringComparison.OrdinalIgnoreCase))
                        {
                            result.RequestedPartAttributes = new AttributeSelector(AllAttributeSelection.True);
                        }
                        else
                        {
                            result.RequestedPartAttributes = new AttributeSelector(RestClientHelper.ConvertStringToUInt16List(value));
                        }
                        break;

                    case RequestedCharacteristicsAttributesParamName:
                        if (string.Equals(value, "None", StringComparison.OrdinalIgnoreCase))
                        {
                            result.RequestedCharacteristicAttributes = new AttributeSelector(AllAttributeSelection.False);
                        }
                        else if (string.Equals(value, "All", StringComparison.OrdinalIgnoreCase))
                        {
                            result.RequestedCharacteristicAttributes = new AttributeSelector(AllAttributeSelection.True);
                        }
                        else
                        {
                            result.RequestedCharacteristicAttributes = new AttributeSelector(RestClientHelper.ConvertStringToUInt16List(value));
                        }
                        break;
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException(string.Format("Invalid filter value '{0}' for parameter '{1}'. The can be specified via url parameter in the form of 'key=value'. The following keys are valid: {2}",
                                                                      value, key,
                                                                      "withHistory = [True|False]\r\n" +
                                                                      "depth = [short]\r\n" +
                                                                      "partUuids = [list of part uuids]\r\n" +
                                                                      "partAttributes = [All|None|Attribute keys csv|Empty for all attributes]\r\n" +
                                                                      "characteristicAttributes = [All|None|Attribute keys csv|Empty for all attributes]\r\n"), ex);
                }
            }
            return(result);
        }
 /// <summary>
 /// Deletes the characteristics <paramref name="charUuid"/> and their sub characteristics from the database.
 /// </summary>
 /// <param name="charUuid">The characteristic uuid list for the delete operation.</param>
 /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
 public Task DeleteCharacteristics(Guid[] charUuid, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(Delete(string.Format("characteristics?charUuids={0}", RestClientHelper.ConvertGuidListToString(charUuid)), cancellationToken));
 }
Exemple #25
0
        /// <summary>
        /// Creates a <see cref="ParameterDefinition"/> list that represents this filter.
        /// </summary>
        public IEnumerable <ParameterDefinition> ToParameterDefinition()
        {
            var result = new List <ParameterDefinition>();

            if (Depth.HasValue)
            {
                result.Add(ParameterDefinition.Create(DepthParamName, Depth.ToString()));
            }

            if (WithHistory)
            {
                result.Add(ParameterDefinition.Create(WithHistoryParamName, WithHistory.ToString()));
            }

            if (PartUuids != null && PartUuids.Length > 0)
            {
                result.Add(ParameterDefinition.Create(PartUuidsParamName, RestClientHelper.ConvertGuidListToString(PartUuids)));
            }

            if (RequestedPartAttributes != null && RequestedPartAttributes.AllAttributes != AllAttributeSelection.True && RequestedPartAttributes.Attributes != null)
            {
                result.Add(ParameterDefinition.Create(RequestedPartAttributesParamName, RestClientHelper.ConvertUInt16ListToString(RequestedPartAttributes.Attributes)));
            }

            if (RequestedCharacteristicAttributes != null && RequestedCharacteristicAttributes.AllAttributes != AllAttributeSelection.True && RequestedCharacteristicAttributes.Attributes != null)
            {
                result.Add(ParameterDefinition.Create(RequestedCharacteristicsAttributesParamName, RestClientHelper.ConvertUInt16ListToString(RequestedCharacteristicAttributes.Attributes)));
            }

            return(result);
        }
 public AggregatorCloudService(RestClientHelper restHelper)
 {
     RestHelper = restHelper;
 }
Exemple #27
0
        /// <summary>
        /// Parses the filter and returns a <see cref="MeasurementFilterAttributesDto"/> object that represents the filter values.
        /// If the parse operation was not successful, an <see cref="InvalidOperationException"/> will be thrown.
        /// </summary>
        /// <returns>The <see cref="MeasurementFilterAttributesDto"/> with the parsed information.</returns>
        public static MeasurementFilterAttributesDto Parse(
            string partUuids,
            string measurementUuids,
            string deep,
            string limitResult,
            string order,
            string requestedMeasurementAttributes,
            string searchCondition,
            string statistics,
            string aggregation,
            string fromModificationDate,
            string toModificationDate,
            string mergeAttributes,
            string mergeCondition,
            string mergeMasterPart)
        {
            var items = new[]
            {
                Tuple.Create(PartUuidsParamName, partUuids),
                Tuple.Create(MeasurementUuidsParamName, measurementUuids),
                Tuple.Create(DeepParamName, deep),
                Tuple.Create(LimitResultParamName, limitResult),
                Tuple.Create(OrderByParamName, order),
                Tuple.Create(RequestedMeasurementAttributesParamName, requestedMeasurementAttributes),
                Tuple.Create(SearchConditionParamName, searchCondition),
                Tuple.Create(StatisticsParamName, statistics),
                Tuple.Create(AggregationParamName, aggregation),
                Tuple.Create(FromModificationDateParamName, fromModificationDate),
                Tuple.Create(ToModificationDateParamName, toModificationDate),
                Tuple.Create(MergeAttributesParamName, mergeAttributes),
                Tuple.Create(MergeConditionParamName, mergeCondition),
                Tuple.Create(MergeMasterPartParamName, mergeMasterPart)
            };

            var result = new MeasurementFilterAttributesDto();

            foreach (var(key, value) in items)
            {
                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }

                try
                {
                    switch (key)
                    {
                    case PartUuidsParamName:
                        result.PartUuids = RestClientHelper.ConvertStringToGuidList(value);
                        break;

                    case DeepParamName:
                        result.Deep = bool.Parse(value);
                        break;

                    case MeasurementUuidsParamName:
                        result.MeasurementUuids = RestClientHelper.ConvertStringToGuidList(value);
                        break;

                    case LimitResultParamName:
                        result.LimitResult = int.Parse(value, CultureInfo.InvariantCulture);
                        break;

                    case RequestedMeasurementAttributesParamName:
                        result.RequestedMeasurementAttributes = new AttributeSelector(RestClientHelper.ConvertStringToUInt16List(value));
                        break;

                    case OrderByParamName:
                        result.OrderBy = value.Split(',').Select(ParseOrderBy).ToArray();
                        break;

                    case SearchConditionParamName:
                        result.SearchCondition = SearchConditionParser.Parse(value);
                        break;

                    case StatisticsParamName:
                        result.Statistics = (MeasurementStatisticsDto)Enum.Parse(typeof(MeasurementStatisticsDto), value);
                        break;

                    case AggregationParamName:
                        result.AggregationMeasurements = (AggregationMeasurementSelectionDto)Enum.Parse(typeof(AggregationMeasurementSelectionDto), value);
                        break;

                    case ToModificationDateParamName:
                        result.ToModificationDate = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind);
                        break;

                    case FromModificationDateParamName:
                        result.FromModificationDate = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind);
                        break;

                    case MergeAttributesParamName:
                        result.MergeAttributes = RestClientHelper.ConvertStringToUInt16List(value);
                        break;

                    case MergeConditionParamName:
                        result.MergeCondition = (MeasurementMergeConditionDto)Enum.Parse(typeof(MeasurementMergeConditionDto), value);
                        break;

                    case MergeMasterPartParamName:
                        result.MergeMasterPart = string.IsNullOrWhiteSpace(value) ? (Guid?)null : Guid.Parse(value);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException($"Invalid filter value '{value}' for parameter '{key}'. The can be specified via url parameter in the form of 'key=value'. The following keys are valid: {"partUuids: [list of part uuids]\r\n" + "deep: [True|False]\r\n" + "limitResult: [short]\r\n" + "measurementUuids: [list of measurement uuids]\r\n" + "measurementAttributes: [attribute keys csv|Empty for all attributes]\r\n" + "orderBy:[ushort asc|desc, ushort asc|desc, ...]\r\n" + "searchCondition:[search filter string]\r\n" + "aggregation:[Measurements|AggregationMeasurements|Default|All]\r\n" + "statistics:[None|Simple|Detailed]\r\n" + "mergeAttributes:[list of measurement attributes]\r\n" + "mergeCondition: [None|MeasurementsInAtLeastTwoParts|MeasurementsInAllParts]\r\n" + "mergeMasterPart: [part uuid]\r\n" + "fromModificationDate:[Date]\r\n" + "toModificationDate:[Date]"}", ex);
                }
            }

            return(result);
        }