コード例 #1
0
        public GetAzureRmUsageTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            //ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            insightsUsageMetricOperationsMock = new Mock<IUsageMetricsOperations>();
            insightsClientMock = new Mock<InsightsClient>();
            commandRuntimeMock = new Mock<ICommandRuntime>();
            cmdlet = new GetAzureRmUsageCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                InsightsClient = insightsClientMock.Object
            };

            response = new Microsoft.Rest.Azure.AzureOperationResponse<IEnumerable<UsageMetric>>()
            {
                Body = new List<UsageMetric>()
            };

            insightsUsageMetricOperationsMock
                .Setup(f => f.ListWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ODataQuery<UsageMetric>>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult<Microsoft.Rest.Azure.AzureOperationResponse<IEnumerable<UsageMetric>>>(response))
                .Callback((string r, string api, ODataQuery<UsageMetric> q, Dictionary<string, List<string>> headers, CancellationToken t) =>
                {
                    resourceId = r;
                    filter = q;
                    apiVersion = api;
                });

            insightsClientMock
                .SetupGet(f => f.UsageMetrics)
                .Returns(this.insightsUsageMetricOperationsMock.Object);
        }
コード例 #2
0
        public ODataQuery Parse(Uri query)
        {
            var result = new ODataQuery();

            var queryString = Uri.UnescapeDataString(query.Query);

            //var matches = Regex.Matches(queryString, @"[?&]([^=]+)=([^&]+)").Cast<Match>();
            var matches = Regex.Matches(queryString, @"[?&]([^=&]+)(?:=([^&]+))?").Cast<Match>();

            foreach (var match in matches)
            {
                var groups = match.Groups.Cast<Group>().Skip(1).ToList();

                var parameterName = groups[0].Value;
                var parameterValue = groups[1].Value;

                var queryPartType = parameterName.GetFromUrlParameterName();

                var parsedPart = _strategy.Parse(queryPartType, parameterValue);

                switch (queryPartType)
                {
                    case ODataQueryPartType.Count:
                        result.CountPredicate = (CountQueryPart) parsedPart;
                        break;
                    case ODataQueryPartType.Expand:
                        result.ExpandPredicate = (ExpandQueryPart) parsedPart;
                        break;
                    case ODataQueryPartType.Filter:
                        result.FilterPredicate = (FilterQueryPart) parsedPart;
                        break;
                    case ODataQueryPartType.Format:
                        result.FormatPredicate = (FormatQueryPart) parsedPart;
                        break;
                    case ODataQueryPartType.InlineCount:
                        result.InlineCountPredicate = (InlineCountQueryPart) parsedPart;
                        break;
                    case ODataQueryPartType.OrderBy:
                        result.OrderByPredicate = (OrderByQueryPart) parsedPart;
                        break;
                    case ODataQueryPartType.Select:
                        result.SelectPredicate = (SelectQueryPart) parsedPart;
                        break;
                    case ODataQueryPartType.Skip:
                        result.SkipPredicate = (SkipQueryPart) parsedPart;
                        break;
                    case ODataQueryPartType.SkipToken:
                        result.SkipTokenPredicate = (SkipTokenQueryPart) parsedPart;
                        break;
                    case ODataQueryPartType.Top:
                        result.TopPredicate = (TopQueryPart) parsedPart;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            return result;
        }
コード例 #3
0
        public GetAzureRmAutoscaleSettingTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            //ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            insightsAutoscaleOperationsMock = new Mock<IAutoscaleSettingsOperations>();
            insightsManagementClientMock = new Mock<InsightsManagementClient>();
            commandRuntimeMock = new Mock<ICommandRuntime>();
            cmdlet = new GetAzureRmAutoscaleSettingCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                InsightsManagementClient = insightsManagementClientMock.Object
            };

            var responseObject = new AutoscaleSettingResource(id: "", location: "", profiles: null, autoscaleSettingResourceName: "")
                {
                    Name = "",
                    Tags = null,
                };

            responseSimple = new Microsoft.Rest.Azure.AzureOperationResponse<AutoscaleSettingResource>()
            {
                Body = responseObject
            };

            responsePage = new AzureOperationResponse<IPage<AutoscaleSettingResource>>()
            {
                Body = JsonConvert.DeserializeObject<Microsoft.Azure.Management.Insights.Models.Page<AutoscaleSettingResource>>(JsonConvert.SerializeObject(responseObject))
            };

            insightsAutoscaleOperationsMock.Setup(f => f.GetWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult<Microsoft.Rest.Azure.AzureOperationResponse<AutoscaleSettingResource>>(responseSimple))
                .Callback((string resourceGrp, string settingNm, Dictionary<string, List<string>> headers, CancellationToken t) =>
                {
                    resourceGroup = resourceGrp;
                    settingName = settingNm;
                });

            insightsAutoscaleOperationsMock.Setup(f => f.ListByResourceGroupWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<ODataQuery<AutoscaleSettingResource>>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult<Microsoft.Rest.Azure.AzureOperationResponse<IPage<AutoscaleSettingResource>>>(responsePage))
                .Callback((string resourceGrp, ODataQuery<AutoscaleSettingResource> qry, Dictionary<string, List<string>> headers, CancellationToken t) =>
                {
                    resourceGroup = resourceGrp;
                    query = qry;
                });

            insightsManagementClientMock.SetupGet(f => f.AutoscaleSettings).Returns(this.insightsAutoscaleOperationsMock.Object);
        }
コード例 #4
0
        public void Translate_SkipThree_ReturnsLastThreeResult()
        {
            var query = new ODataQuery
            {
                SkipPredicate = ODataQueryPart.Skip(3)
            };

            var expression = _translator.Translate<TestModel>(query);

            var fn = (Func<IQueryable<TestModel>, IQueryable<TestModel>>)expression.Compile();

            var result = fn(_source).ToList();

            Assert.That(result.Count, Is.EqualTo(3));
            Assert.That(result[0].TestInt, Is.EqualTo(6));
            Assert.That(result[1].TestInt, Is.EqualTo(7));
            Assert.That(result[2].TestInt, Is.EqualTo(8));
        }
コード例 #5
0
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            if (string.IsNullOrWhiteSpace(this.Name))
            {
                // Retrieve all the AlertRules for a ResourceGroup
                ODataQuery<AlertRuleResource> query = new ODataQuery<AlertRuleResource>(this.TargetResourceId);
                IEnumerable<AlertRuleResource> result = this.InsightsManagementClient.AlertRules.ListByResourceGroupAsync(resourceGroupName: this.ResourceGroup, odataQuery: query).Result;

                var records = result.Select(e => this.DetailedOutput.IsPresent ? (PSManagementItemDescriptor)new PSAlertRule(e) : new PSAlertRuleNoDetails(e));
                WriteObject(sendToPipeline: records.ToList());
            }
            else
            {
                // Retrieve a single AlertRule determined by the ResourceGroup and the rule name
                AlertRuleResource result = this.InsightsManagementClient.AlertRules.GetAsync(resourceGroupName: this.ResourceGroup, ruleName: this.Name).Result;

                var finalResult = new List<PSManagementItemDescriptor> { this.DetailedOutput.IsPresent ? (PSManagementItemDescriptor)new PSAlertRule(result) : new PSAlertRuleNoDetails(result) };
                WriteObject(sendToPipeline: finalResult);
            }
        }
コード例 #6
0
        public void Translate_TestIntEqualsThree_ReturnsOneResult()
        {
            var left = FilterExpression.MemberAccess("TestInt");
            var right = FilterExpression.Constant(3);

            var filterExpression = FilterExpression.Binary(left, FilterExpressionOperator.Equal, right);

            var query = new ODataQuery
            {
                FilterPredicate = ODataQueryPart.Filter(filterExpression)
            };

            var expression = _translator.Translate<TestModel>(query);

            var fn = (Func<IQueryable<TestModel>, IQueryable<TestModel>>) expression.Compile();

            var result = fn(_source).ToList();

            Assert.That(result.Count, Is.EqualTo(1));
            Assert.That(result[0].TestInt, Is.EqualTo(3));
        }
コード例 #7
0
        protected virtual ODataQuery VisitODataQuery(ODataQuery query)
        {
            var result = new ODataQuery();

            if (query.FilterPredicate != null)
            {
                result.FilterPredicate = VisitFilter(query.FilterPredicate);
            }

            if (query.OrderByPredicate != null)
            {
                result.OrderByPredicate = VisitOrderBy(query.OrderByPredicate);
            }

            if (query.CountPredicate != null)
            {
                result.CountPredicate = VisitCount(query.CountPredicate);
            }
            else
            {
                if (query.SkipPredicate != null)
                {
                    result.SkipPredicate = VisitSkip(query.SkipPredicate);
                }

                if (query.TopPredicate != null)
                {
                    result.TopPredicate = VisitTop(query.TopPredicate);
                }

                if (query.SelectPredicate != null)
                {
                    result.SelectPredicate = VisitSelect(query.SelectPredicate);
                }
            }

            return result;
        }
コード例 #8
0
        /// <summary>
        /// List jobs.
        /// </summary>
        /// <param name="resourceGroupName">Name of the resource group.</param>
        /// <param name="jobCollectionName">job collection name.</param>
        /// <param name="jobName">Name of the job.</param>
        /// <param name="jobState">State of the job.</param>
        /// <returns>List of Job definition.</returns>
        internal IList<JobDefinition> ListJobs(string resourceGroupName, string jobCollectionName, JobState? jobState)
        {
            var listOfJobs = new List<JobDefinition>();

            var oDataQuery = new ODataQuery<JobStateFilter>();

            if (jobState != null)
            {
                Expression<Func<JobStateFilter, bool>> jobFilterExpression = (jobStateFilter) => jobStateFilter.State == jobState;
                oDataQuery.SetFilter(jobFilterExpression);
            }

            IPage<JobDefinition> jobsPage = this.SchedulerManagementClient.Jobs.List(resourceGroupName, jobCollectionName, oDataQuery);

            listOfJobs.AddRange(jobsPage);

            while (!string.IsNullOrWhiteSpace(jobsPage.NextPageLink))
            {
                jobsPage = this.SchedulerManagementClient.Jobs.ListNext(jobsPage.NextPageLink);
                listOfJobs.AddRange(jobsPage);
            }

            return listOfJobs;
        }
コード例 #9
0
        public GetAzureRmAlertHistoryTests(ITestOutputHelper output)
        {
            //XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
            insightsEventOperationsMock = new Mock<IEventsOperations>();
            insightsClientMock = new Mock<InsightsClient>();
            commandRuntimeMock = new Mock<ICommandRuntime>();
            cmdlet = new GetAzureRmAlertHistoryCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                InsightsClient = insightsClientMock.Object
            };

            response = Test.Utilities.InitializeResponse();

            insightsEventOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(It.IsAny<ODataQuery<EventData>>(), It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult<AzureOperationResponse<IPage<EventData>>>(response))
                .Callback((ODataQuery<EventData> f, string s, Dictionary<string, List<string>> headers, CancellationToken t) =>
                {
                    filter = f;
                    selected = s;
                });

            insightsClientMock.SetupGet(f => f.Events).Returns(this.insightsEventOperationsMock.Object);
        }
コード例 #10
0
 private void CleanParamVariables()
 {
     resourceId = null;
     filter = null;
     apiVersion = null;
 }
コード例 #11
0
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            var queryFilter = new ODataQuery<UsageMetric>(this.ProcessParameters());
            string apiVersion = this.ApiVersion ?? DefaultApiVersion;

            // Call the proper API methods to return a list of raw records.
            // If fullDetails is present full details of the records displayed, otherwise only a summary of the values is displayed
            IEnumerable<UsageMetric> response = this.InsightsClient.UsageMetrics
                .ListAsync(resourceUri: this.ResourceId, apiVersion: apiVersion, odataQuery: queryFilter, cancellationToken: CancellationToken.None)
                .Result;

            var records = ExtractCollectionFromResult(response.GetEnumerator()).ToArray();

            WriteObject(sendToPipeline: records);
        }
コード例 #12
0
 /// <summary>
 /// Get Employee Work Types
 /// </summary>
 /// <remarks>
 /// Lists all the work types for the employee.
 /// This operation supports OData queries.
 /// </remarks>
 public List <AuWorkTypeModel> GetEmployeeWorkTypes(int businessId, int employeeId, ODataQuery oDataQuery = null)
 {
     return(ApiRequest <List <AuWorkTypeModel> >($"/business/{businessId}/employee/{employeeId}/worktype{ODataQuery.ToQueryString(oDataQuery, "?")}", Method.GET));
 }
 /// <summary>
 /// Provides the details of the backed up item. This is an asynchronous
 /// operation. To know the status of the operation,
 /// call the GetItemOperationResult API.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='vaultName'>
 /// The name of the recovery services vault.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group where the recovery services vault is
 /// present.
 /// </param>
 /// <param name='fabricName'>
 /// Fabric name associated with the backed up item.
 /// </param>
 /// <param name='containerName'>
 /// Container name associated with the backed up item.
 /// </param>
 /// <param name='protectedItemName'>
 /// Backed up item name whose details are to be fetched.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 public static ProtectedItemResource Get(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ODataQuery <GetProtectedItemQueryObject> odataQuery = default(ODataQuery <GetProtectedItemQueryObject>))
 {
     return(operations.GetAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, odataQuery).GetAwaiter().GetResult());
 }
コード例 #14
0
 protected void Visit(ODataQuery query)
 {
     VisitODataQuery(query);
 }
コード例 #15
0
ファイル: ODataTests.cs プロジェクト: Ranjana1996/autorest
 public void ODataQuerySupportsEmptyState()
 {
     var query = new ODataQuery<Param1>();
     Assert.Equal("", query.ToString());
     query = new ODataQuery<Param1>(p => p.Foo == null);
     Assert.Equal("", query.ToString());
     var param = new InputParam1
     {
         Value = null
     };
     var paramEncoded = new InputParam1
     {
         Value = "bar/car"
     };
     query = new ODataQuery<Param1>(p => p.Foo == param.Value);
     Assert.Equal("", query.ToString());
     query = new ODataQuery<Param1>(p => p.Foo == param.Value && p.AssignedTo(param.Value));
     Assert.Equal("", query.ToString());
     query = new ODataQuery<Param1>(p => p.AssignedTo(param.Value));
     Assert.Equal("", query.ToString());
     query = new ODataQuery<Param1>(p => p.AssignedTo(paramEncoded.Value));
     Assert.Equal("$filter=assignedTo('bar%2Fcar')", query.ToString());
 }
コード例 #16
0
 /// <summary>
 /// List notificationchannels in a given lab.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='labName'>
 /// The name of the lab.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <IPage <NotificationChannel> > ListAsync(this INotificationChannelsOperations operations, string resourceGroupName, string labName, ODataQuery <NotificationChannel> odataQuery = default(ODataQuery <NotificationChannel>), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, labName, odataQuery, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #17
0
        /// <summary>
        /// Specify filter parameter with value '$filter=id gt 5 and name eq
        /// 'foo'&amp;$orderby=id&amp;$top=10'
        /// </summary>
        /// <param name='odataQuery'>
        /// OData parameters to apply to the operation.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse> GetWithFilterWithHttpMessagesAsync(ODataQuery <OdataFilterInner> odataQuery = default(ODataQuery <OdataFilterInner>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("odataQuery", odataQuery);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetWithFilter", tracingParameters);
            }
            // Construct URL
            var           _baseUrl         = Client.BaseUri.AbsoluteUri;
            var           _url             = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/odata/filter").ToString();
            List <string> _queryParameters = new List <string>();

            if (odataQuery != null)
            {
                var _odataFilter = odataQuery.ToString();
                if (!string.IsNullOrEmpty(_odataFilter))
                {
                    _queryParameters.Add(_odataFilter);
                }
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new System.Net.Http.HttpRequestMessage();

            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
コード例 #18
0
        /// <summary>
        /// Lists the collection of subscriptions of the specified user.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// The name of the API Management service.
        /// </param>
        /// <param name='userId'>
        /// User identifier. Must be unique in the current API Management service
        /// instance.
        /// </param>
        /// <param name='odataQuery'>
        /// OData parameters to apply to the operation.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <IPage <SubscriptionContract> > > ListWithHttpMessagesAsync(string resourceGroupName, string serviceName, string userId, ODataQuery <SubscriptionContract> odataQuery = default(ODataQuery <SubscriptionContract>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (serviceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
            }
            if (serviceName != null)
            {
                if (serviceName.Length > 50)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
                }
                if (serviceName.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
                }
            }
            if (userId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "userId");
            }
            if (userId != null)
            {
                if (userId.Length > 80)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "userId", 80);
                }
                if (userId.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "userId", 1);
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(userId, "^[^*#&+:<>?]+$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "userId", "^[^*#&+:<>?]+$");
                }
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("odataQuery", odataQuery);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serviceName", serviceName);
                tracingParameters.Add("userId", userId);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/users/{userId}/subscriptions").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
            _url = _url.Replace("{userId}", System.Uri.EscapeDataString(userId));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            List <string> _queryParameters = new List <string>();

            if (odataQuery != null)
            {
                var _odataFilter = odataQuery.ToString();
                if (!string.IsNullOrEmpty(_odataFilter))
                {
                    _queryParameters.Add(_odataFilter);
                }
            }
            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <IPage <SubscriptionContract> >();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Page <SubscriptionContract> >(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
コード例 #19
0
 /// <summary>
 /// List notificationchannels in a given lab.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='labName'>
 /// The name of the lab.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 public static IPage <NotificationChannel> List(this INotificationChannelsOperations operations, string resourceGroupName, string labName, ODataQuery <NotificationChannel> odataQuery = default(ODataQuery <NotificationChannel>))
 {
     return(operations.ListAsync(resourceGroupName, labName, odataQuery).GetAwaiter().GetResult());
 }
コード例 #20
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            ExecuteClientAction(() =>
            {
                if (this.ParameterSetName.Equals(ListVMImageParamSetName))
                {
                    var filter = new ODataQuery <VirtualMachineImageResource>(this.FilterExpression);

                    var result = this.VirtualMachineImageClient.ListWithHttpMessagesAsync(
                        this.Location.Canonicalize(),
                        this.PublisherName,
                        this.Offer,
                        this.Skus,
                        odataQuery: filter).GetAwaiter().GetResult();

                    var images = from r in result.Body
                                 select new PSVirtualMachineImage
                    {
                        RequestId        = result.RequestId,
                        StatusCode       = result.Response.StatusCode,
                        Id               = r.Id,
                        Location         = r.Location,
                        Version          = r.Name,
                        PublisherName    = this.PublisherName,
                        Offer            = this.Offer,
                        Skus             = this.Skus,
                        FilterExpression = this.FilterExpression
                    };

                    WriteObject(images, true);
                }
                else
                {
                    var response = this.VirtualMachineImageClient.GetWithHttpMessagesAsync(
                        this.Location.Canonicalize(),
                        this.PublisherName,
                        this.Offer,
                        this.Skus,
                        version: this.Version).GetAwaiter().GetResult();

                    var image = new PSVirtualMachineImageDetail
                    {
                        RequestId      = response.RequestId,
                        StatusCode     = response.Response.StatusCode,
                        Id             = response.Body.Id,
                        Location       = response.Body.Location,
                        Name           = response.Body.Name,
                        Version        = this.Version,
                        PublisherName  = this.PublisherName,
                        Offer          = this.Offer,
                        Skus           = this.Skus,
                        OSDiskImage    = response.Body.OsDiskImage,
                        DataDiskImages = response.Body.DataDiskImages,
                        PurchasePlan   = response.Body.Plan,
                    };

                    WriteObject(image);
                }
            });
        }
コード例 #21
0
 /// <summary>
 /// Retrieves all the alerts in a manager.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The resource group name
 /// </param>
 /// <param name='managerName'>
 /// The manager name
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <IPage <Alert> > ListByManagerAsync(this IAlertsOperations operations, string resourceGroupName, string managerName, ODataQuery <AlertFilter> odataQuery = default(ODataQuery <AlertFilter>), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ListByManagerWithHttpMessagesAsync(resourceGroupName, managerName, odataQuery, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #22
0
 /// <summary>
 /// Retrieves all the alerts in a manager.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The resource group name
 /// </param>
 /// <param name='managerName'>
 /// The manager name
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 public static IPage <Alert> ListByManager(this IAlertsOperations operations, string resourceGroupName, string managerName, ODataQuery <AlertFilter> odataQuery = default(ODataQuery <AlertFilter>))
 {
     return(operations.ListByManagerAsync(resourceGroupName, managerName, odataQuery).GetAwaiter().GetResult());
 }
コード例 #23
0
 public RestQueryModelVisitor(IODataQueryFactory queryFactory)
 {
     _query = queryFactory.Create();
     _filterExpressionTranslator = new ODataFilterExpressionVisitor(new FilterExpressionParserStrategy(), new TypeFormatter());
 }
コード例 #24
0
        /// <summary>
        /// Gets job history.
        /// </summary>
        /// <param name="resourceGroupName">The name of the resource.</param>
        /// <param name="jobCollectionName">The job collection name.</param>
        /// <param name="jobName">The name of the job.</param>
        /// <param name="jobStatus">The status of the job.</param>
        /// <returns>List of job history definition.</returns>
        public IList<PSJobHistory> GetJobHistory(string resourceGroupName, string jobCollectionName, string jobName, string jobStatus)
        {
            if (string.IsNullOrWhiteSpace(resourceGroupName))
            {
                throw new PSManagement.PSArgumentNullException(paramName: "ResourceGroupName");
            }

            if (string.IsNullOrWhiteSpace(jobCollectionName))
            {
                throw new PSManagement.PSArgumentNullException(paramName: "JobCollectionName");
            }

            if(string.IsNullOrWhiteSpace(jobName))
            {
                throw new PSManagement.PSArgumentNullException(paramName: "JobName");
            }

            var oDataQuery = new ODataQuery<JobHistoryFilter>(); 

            JobExecutionStatus? executionStatus = jobStatus.GetValueOrDefaultEnum<JobExecutionStatus?>(defaultValue: null);

            if (executionStatus != null)
            {
                Expression<Func<JobHistoryFilter, bool>> jobHistoryFilterExpression = (jobHistoryFilter) => jobHistoryFilter.Status == executionStatus;
                oDataQuery.SetFilter(jobHistoryFilterExpression);
            }

            var listOfJobHistory = new List<JobHistoryDefinition>();

            IPage<JobHistoryDefinition> jobHistoryPage = this.SchedulerManagementClient.Jobs.ListJobHistory(resourceGroupName, jobCollectionName, jobName, oDataQuery);

            listOfJobHistory.AddRange(jobHistoryPage);

            while (!string.IsNullOrWhiteSpace(jobHistoryPage.NextPageLink))
            {
                jobHistoryPage = this.SchedulerManagementClient.Jobs.ListJobHistoryNext(jobHistoryPage.NextPageLink);
                listOfJobHistory.AddRange(jobHistoryPage);
            }

            return Converter.ConvertJobHistoryListToPSList(listOfJobHistory);
        }
コード例 #25
0
ファイル: ODataTests.cs プロジェクト: jkonecki/autorest
 public void ODataQuerySupportsEmptyState()
 {
     var query = new ODataQuery<Param1>();
     Assert.Equal("", query.ToString());
     query = new ODataQuery<Param1>(p => p.Foo == null);
     Assert.Equal("", query.ToString());
     var param = new InputParam1
     {
         Value = null
     };
     query = new ODataQuery<Param1>(p => p.Foo == param.Value);
     Assert.Equal("", query.ToString());
     query = new ODataQuery<Param1>(p => p.Foo == param.Value && p.AssignedTo(param.Value));
     Assert.Equal("", query.ToString());
     query = new ODataQuery<Param1>(p => p.AssignedTo(param.Value));
     Assert.Equal("", query.ToString());
 }
コード例 #26
0
 /// <summary>
 /// List basic details for employees
 /// </summary>
 /// <remarks>
 /// This endpoint returns a list of employees. The details are a subset of the 'unstructured' employee endpoint.
 /// This data can be filtered much more efficiently though so if you only need the basic employee details, this endpoint is preferred.
 /// This operation supports OData queries (only $filter, $orderby, $top, $skip).
 /// </remarks>
 public List <EmployeeDetailsModel> ListBasicDetailsForEmployees(int businessId, ODataQuery oDataQuery = null)
 {
     return(ApiRequest <List <EmployeeDetailsModel> >($"/business/{businessId}/employee/details{ODataQuery.ToQueryString(oDataQuery, "?")}", Method.GET));
 }
コード例 #27
0
        public List<DataLakeStoreAccount> ListAccounts(string resourceGroupName, string filter, int? top, int? skip)
        {
            var parameters = new ODataQuery<DataLakeStoreAccount>
            {
                Filter = filter,
                Top = top,
                Skip = skip
            };

            var accountList = new List<DataLakeStoreAccount>();
            var response = string.IsNullOrEmpty(resourceGroupName) ?
                _client.Account.List(parameters) :
                _client.Account.ListByResourceGroup(resourceGroupName, parameters);

            accountList.AddRange(response);

            while (!string.IsNullOrEmpty(response.NextPageLink))
            {
                response = ListAccountsWithNextLink(response.NextPageLink);
                accountList.AddRange(response);
            }

            return accountList;
        }
コード例 #28
0
 /// <summary>
 /// List Employees
 /// </summary>
 /// <remarks>
 /// This endpoint returns the unstructured employee details for all matching employees.
 /// <p>
 /// See also: List basic details for employees (which is much more efficient if that is all the information that is required)
 /// </p>
 /// This operation supports OData queries (only $filter, $orderby, $top, $skip).
 /// </remarks>
 public List <AuUnstructuredEmployeeModel> ListEmployees(int businessId, ListEmployeesQueryModel request, ODataQuery oDataQuery = null)
 {
     return(ApiRequest <List <AuUnstructuredEmployeeModel> >($"/business/{businessId}/employee/unstructured?payScheduleId={request.PayScheduleId}&locationId={request.LocationId}{ODataQuery.ToQueryString(oDataQuery, "&")}", Method.GET));
 }
コード例 #29
0
ファイル: ODataTests.cs プロジェクト: Ranjana1996/autorest
 public void ODataQuerySupportsPartialState()
 {
     var query = new ODataQuery<Param1>(p => p.Foo == "bar")
     {
         Top = 100
     };
     Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString());
 }
コード例 #30
0
 /// <summary>
 /// Gets a list of all virtual machine image versions for the specified
 /// location, publisher, offer, and SKU.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='location'>
 /// The name of a supported Azure region.
 /// </param>
 /// <param name='publisherName'>
 /// A valid image publisher.
 /// </param>
 /// <param name='offer'>
 /// A valid image publisher offer.
 /// </param>
 /// <param name='skus'>
 /// A valid image SKU.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <IList <VirtualMachineImageResourceInner> > ListAsync(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, ODataQuery <VirtualMachineImageResourceInner> odataQuery = default(ODataQuery <VirtualMachineImageResourceInner>), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ListWithHttpMessagesAsync(location, publisherName, offer, skus, odataQuery, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #31
0
        public void ODataQuerySupportsImplicitConversionFromQueryString()
        {
            ODataQuery <Param1> query = "$filter=foo eq 'bar'&$top=100";

            Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString());
        }
コード例 #32
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            ExecuteClientAction(() =>
            {
                if (this.ParameterSetName.Equals(ListVMImageParamSetName))
                {
                    var filter = new ODataQuery<VirtualMachineImageResource>(this.FilterExpression);

                    var result = this.VirtualMachineImageClient.ListWithHttpMessagesAsync(
                        this.Location.Canonicalize(),
                        this.PublisherName,
                        this.Offer,
                        this.Skus,
                        odataQuery: filter).GetAwaiter().GetResult();

                    var images = from r in result.Body
                                 select new PSVirtualMachineImage
                                 {
                                     RequestId = result.RequestId,
                                     StatusCode = result.Response.StatusCode,
                                     Id = r.Id,
                                     Location = r.Location,
                                     Version = r.Name,
                                     PublisherName = this.PublisherName,
                                     Offer = this.Offer,
                                     Skus = this.Skus,
                                     FilterExpression = this.FilterExpression
                                 };

                    WriteObject(images, true);
                }
                else
                {
                    var response = this.VirtualMachineImageClient.GetWithHttpMessagesAsync(
                        this.Location.Canonicalize(),
                        this.PublisherName,
                        this.Offer,
                        this.Skus,
                        version: this.Version).GetAwaiter().GetResult();

                    var image = new PSVirtualMachineImageDetail
                    {
                        RequestId = response.RequestId,
                        StatusCode = response.Response.StatusCode,
                        Id = response.Body.Id,
                        Location = response.Body.Location,
                        Name = response.Body.Name,
                        Version = this.Version,
                        PublisherName = this.PublisherName,
                        Offer = this.Offer,
                        Skus = this.Skus,
                        OSDiskImage = response.Body.OsDiskImage,
                        DataDiskImages = response.Body.DataDiskImages,
                        PurchasePlan = response.Body.Plan,
                    };

                    WriteObject(image);
                }
            });
        }
 /// <summary>
 /// Provides the details of the backed up item. This is an asynchronous
 /// operation. To know the status of the operation,
 /// call the GetItemOperationResult API.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='vaultName'>
 /// The name of the recovery services vault.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group where the recovery services vault is
 /// present.
 /// </param>
 /// <param name='fabricName'>
 /// Fabric name associated with the backed up item.
 /// </param>
 /// <param name='containerName'>
 /// Container name associated with the backed up item.
 /// </param>
 /// <param name='protectedItemName'>
 /// Backed up item name whose details are to be fetched.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <ProtectedItemResource> GetAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ODataQuery <GetProtectedItemQueryObject> odataQuery = default(ODataQuery <GetProtectedItemQueryObject>), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, odataQuery, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #34
0
 /// <summary>
 /// Specify filter parameter with value '$filter=id gt 5 and name eq
 /// 'foo'&amp;$orderby=id&amp;$top=10'
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task GetWithFilterAsync( this IOdataOperations operations, ODataQuery<OdataFilter> odataQuery = default(ODataQuery<OdataFilter>), CancellationToken cancellationToken = default(CancellationToken))
 {
     await operations.GetWithFilterWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false);
 }
コード例 #35
0
 /// <summary>
 /// Get Employee Work Types
 /// </summary>
 /// <remarks>
 /// Lists all the work types for the employee.
 /// This operation supports OData queries.
 /// </remarks>
 public Task <List <AuWorkTypeModel> > GetEmployeeWorkTypesAsync(int businessId, int employeeId, ODataQuery oDataQuery = null, CancellationToken cancellationToken = default)
 {
     return(ApiRequestAsync <List <AuWorkTypeModel> >($"/business/{businessId}/employee/{employeeId}/worktype{ODataQuery.ToQueryString(oDataQuery, "?")}", Method.GET, cancellationToken));
 }
コード例 #36
0
        private WorkloadProtectableItemResource GetAzureFileShareProtectableObject(
            string azureFileShareName,
            string storageAccountName,
            string vaultName = null,
            string vaultResourceGroupName = null)
        {
            //Trigger Discovery
            ODataQuery <BMSRefreshContainersQueryObject> queryParam = new ODataQuery <BMSRefreshContainersQueryObject>(
                q => q.BackupManagementType
                == ServiceClientModel.BackupManagementType.AzureStorage);

            AzureWorkloadProviderHelper.RefreshContainer(vaultName, vaultResourceGroupName, queryParam);

            //get registered storage accounts
            bool   isRegistered         = false;
            string storageContainerName = null;
            List <ContainerBase> registeredStorageAccounts = GetRegisteredStorageAccounts(vaultName, vaultResourceGroupName);
            ContainerBase        registeredStorageAccount  = registeredStorageAccounts.Find(
                storageAccount => string.Compare(storageAccount.Name.Split(';').Last(),
                                                 storageAccountName, true) == 0);

            if (registeredStorageAccount != null)
            {
                isRegistered         = true;
                storageContainerName = "StorageContainer;" + registeredStorageAccount.Name;
            }

            //get unregistered storage account
            if (!isRegistered)
            {
                List <ProtectableContainerResource> unregisteredStorageAccounts =
                    GetUnRegisteredStorageAccounts(vaultName, vaultResourceGroupName);
                ProtectableContainerResource unregisteredStorageAccount = unregisteredStorageAccounts.Find(
                    storageAccount => string.Compare(storageAccount.Name.Split(';').Last(),
                                                     storageAccountName, true) == 0);
                if (unregisteredStorageAccount != null)
                {
                    //unregistered
                    //check for source Id for storageAccountId in ProtectionContainerResource
                    storageContainerName = unregisteredStorageAccount.Name;
                    ProtectionContainerResource protectionContainerResource =
                        new ProtectionContainerResource(unregisteredStorageAccount.Id,
                                                        unregisteredStorageAccount.Name);
                    AzureStorageContainer azureStorageContainer = new AzureStorageContainer(
                        friendlyName: storageAccountName,
                        backupManagementType: ServiceClientModel.BackupManagementType.AzureStorage,
                        sourceResourceId: unregisteredStorageAccount.Properties.ContainerId,
                        resourceGroup: vaultResourceGroupName);
                    protectionContainerResource.Properties = azureStorageContainer;
                    AzureWorkloadProviderHelper.RegisterContainer(unregisteredStorageAccount.Name,
                                                                  protectionContainerResource,
                                                                  vaultName,
                                                                  vaultResourceGroupName);
                }
            }

            //inquiry
            AzureWorkloadProviderHelper.TriggerInquiry(vaultName, vaultResourceGroupName,
                                                       storageContainerName, ServiceClientModel.WorkloadType.AzureFileShare);

            //get protectable item
            WorkloadProtectableItemResource protectableObjectResource = null;

            protectableObjectResource = GetProtectableItem(vaultName, vaultResourceGroupName, azureFileShareName, storageAccountName);

            if (protectableObjectResource == null)
            {
                // Container is not discovered. Throw exception
                string errorMessage = string.Format(
                    Resources.AFSDiscoveryFailure,
                    azureFileShareName,
                    vaultResourceGroupName);
                Logger.Instance.WriteDebug(errorMessage);
                Logger.Instance.WriteError(
                    new ErrorRecord(new Exception(Resources.FileShareNotDiscovered),
                                    string.Empty, ErrorCategory.InvalidArgument, null));
            }

            return(protectableObjectResource);
        }
コード例 #37
0
 /// <summary>
 /// List basic details for employees
 /// </summary>
 /// <remarks>
 /// This endpoint returns a list of employees. The details are a subset of the 'unstructured' employee endpoint.
 /// This data can be filtered much more efficiently though so if you only need the basic employee details, this endpoint is preferred.
 /// This operation supports OData queries (only $filter, $orderby, $top, $skip).
 /// </remarks>
 public Task <List <EmployeeDetailsModel> > ListBasicDetailsForEmployeesAsync(int businessId, ODataQuery oDataQuery = null, CancellationToken cancellationToken = default)
 {
     return(ApiRequestAsync <List <EmployeeDetailsModel> >($"/business/{businessId}/employee/details{ODataQuery.ToQueryString(oDataQuery, "?")}", Method.GET, cancellationToken));
 }
コード例 #38
0
 /// <summary>
 /// Get a list of all virtual networks.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='inlineCount'>
 /// OData inline count parameter.
 /// </param>
 public static IPage <VirtualNetwork> List(this IVirtualNetworksOperations operations, ODataQuery <VirtualNetwork> odataQuery = default(ODataQuery <VirtualNetwork>), string inlineCount = default(string))
 {
     return(operations.ListAsync(odataQuery, inlineCount).GetAwaiter().GetResult());
 }
コード例 #39
0
 /// <summary>
 /// List Employees
 /// </summary>
 /// <remarks>
 /// This endpoint returns the unstructured employee details for all matching employees.
 /// <p>
 /// See also: List basic details for employees (which is much more efficient if that is all the information that is required)
 /// </p>
 /// This operation supports OData queries (only $filter, $orderby, $top, $skip).
 /// </remarks>
 public Task <List <AuUnstructuredEmployeeModel> > ListEmployeesAsync(int businessId, ListEmployeesQueryModel request, ODataQuery oDataQuery = null, CancellationToken cancellationToken = default)
 {
     return(ApiRequestAsync <List <AuUnstructuredEmployeeModel> >($"/business/{businessId}/employee/unstructured?payScheduleId={request.PayScheduleId}&locationId={request.LocationId}{ODataQuery.ToQueryString(oDataQuery, "&")}", Method.GET, cancellationToken));
 }
コード例 #40
0
 /// <summary>
 /// Get a list of all virtual networks.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='inlineCount'>
 /// OData inline count parameter.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <IPage <VirtualNetwork> > ListAsync(this IVirtualNetworksOperations operations, ODataQuery <VirtualNetwork> odataQuery = default(ODataQuery <VirtualNetwork>), string inlineCount = default(string), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, inlineCount, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #41
0
        IEnumerator StorageAsync()
        {
            Log.text = string.Empty;
            Debug.Log("Storage Tests");

            var storage = StorageService.Instance;

            //Make sure you are logged in.
            yield return StartCoroutine(SignIn());

            // make objects
            List<DemoObject> _demoObjects = new List<DemoObject>();
            for (int i = 0; i < 10; i++)
            {
                _demoObjects.Add(DemoObject.Create());
            }

            // post 1
            Debug.Log("Post 1...");
            yield return StartCoroutine(TaskAsync(storage.Update(_demoObjects.First())));

            // post 9
            Debug.Log("Post Set...");
            yield return StartCoroutine(TaskAsync(storage.UpdateSet(_demoObjects.ToArray())));

            // get 1
            Debug.Log("Get 1...");
            yield return StartCoroutine(TaskAsync(storage.Get<DemoObject>(_demoObjects.First().Id)));

            // getset
            Debug.Log("Get Set...");
            yield return StartCoroutine(TaskAsync(storage.GetSet<DemoObject>(_demoObjects.Select(o => o.Id).ToArray())));

            // query
            Debug.Log("Query Set...");
            var query = new ODataQuery<DemoObject>().WhereGreaterThan("Id", 5).OrderBy("String").Take(5);
            yield return StartCoroutine(TaskAsync(storage.Query(query)));

            var first = _demoObjects.First();

            // update prop
            Debug.Log("Update Prop...");
            yield return StartCoroutine(TaskAsync(storage.UpdateProperty(first.Id, "String", UnityEngine.Random.value.ToString())));

            // delta
            Debug.Log("Update Delta...");
            yield return StartCoroutine(TaskAsync(storage.UpdateDelta(first.Id, "Number", 1)));

            // delta
            Debug.Log("Sync...");
            yield return StartCoroutine(TaskAsync(storage.Sync(first)));

            // delete
            Debug.Log("Delete...");
            yield return StartCoroutine(TaskAsync(storage.Delete(first)));

            Debug.Log("Done");
        }
 /// <summary>
 /// Lists all comments for the Issue associated with the specified API.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='serviceName'>
 /// The name of the API Management service.
 /// </param>
 /// <param name='apiId'>
 /// API identifier. Must be unique in the current API Management service
 /// instance.
 /// </param>
 /// <param name='issueId'>
 /// Issue identifier. Must be unique in the current API Management service
 /// instance.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 public static IPage <IssueCommentContract> ListByService(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, ODataQuery <IssueCommentContract> odataQuery = default(ODataQuery <IssueCommentContract>))
 {
     return(operations.ListByServiceAsync(resourceGroupName, serviceName, apiId, issueId, odataQuery).GetAwaiter().GetResult());
 }
コード例 #43
0
 /// <summary>
 /// Specify filter parameter with value '$filter=id gt 5 and name eq
 /// 'foo'&amp;$orderby=id&amp;$top=10'
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 public static void GetWithFilter(this IOdataOperations operations, ODataQuery<OdataFilter> odataQuery = default(ODataQuery<OdataFilter>))
 {
     Task.Factory.StartNew(s => ((IOdataOperations)s).GetWithFilterAsync(odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 /// Lists all comments for the Issue associated with the specified API.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='serviceName'>
 /// The name of the API Management service.
 /// </param>
 /// <param name='apiId'>
 /// API identifier. Must be unique in the current API Management service
 /// instance.
 /// </param>
 /// <param name='issueId'>
 /// Issue identifier. Must be unique in the current API Management service
 /// instance.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <IPage <IssueCommentContract> > ListByServiceAsync(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, ODataQuery <IssueCommentContract> odataQuery = default(ODataQuery <IssueCommentContract>), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ListByServiceWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, issueId, odataQuery, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #45
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            ExecuteClientAction(() =>
            {
                if (string.IsNullOrEmpty(this.Version))
                {
                    var filter = new ODataQuery<VirtualMachineImageResource>(this.FilterExpression);

                    var result = this.VirtualMachineExtensionImageClient.ListVersionsWithHttpMessagesAsync(
                        this.Location.Canonicalize(),
                        this.PublisherName,
                        this.Type,
                        odataQuery: filter).GetAwaiter().GetResult();

                    var images = from r in result.Body
                                 select new PSVirtualMachineExtensionImage
                                 {
                                     RequestId = result.RequestId,
                                     StatusCode = result.Response.StatusCode,
                                     Id = r.Id,
                                     Location = r.Location,
                                     Version = r.Name,
                                     PublisherName = this.PublisherName,
                                     Type = this.Type,
                                     FilterExpression = this.FilterExpression
                                 };

                    WriteObject(images, true);
                }
                else
                {
                    var result = this.VirtualMachineExtensionImageClient.GetWithHttpMessagesAsync(
                        this.Location.Canonicalize(),
                        this.PublisherName,
                        this.Type,
                        this.Version).GetAwaiter().GetResult();


                    var image = new PSVirtualMachineExtensionImageDetails
                    {
                        RequestId = result.RequestId,
                        StatusCode = result.Response.StatusCode,
                        Id = result.Body.Id,
                        Location = result.Body.Location,
                        HandlerSchema = result.Body.HandlerSchema,
                        OperatingSystem = result.Body.OperatingSystem,
                        ComputeRole = result.Body.ComputeRole,
                        SupportsMultipleExtensions = result.Body.SupportsMultipleExtensions,
                        VMScaleSetEnabled = result.Body.VmScaleSetEnabled,
                        Version = result.Body.Name,
                        PublisherName = this.PublisherName,
                        Type = this.Type,
                        FilterExpression = this.FilterExpression
                    };

                    WriteObject(image);
                }
            });
        }
コード例 #46
0
 /// <summary>
 /// Gets a list of integration account schemas.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The resource group name.
 /// </param>
 /// <param name='integrationAccountName'>
 /// The integration account name.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 public static IPage <IntegrationAccountSchema> List(this IIntegrationAccountSchemasOperations operations, string resourceGroupName, string integrationAccountName, ODataQuery <IntegrationAccountSchemaFilter> odataQuery = default(ODataQuery <IntegrationAccountSchemaFilter>))
 {
     return(Task.Factory.StartNew(s => ((IIntegrationAccountSchemasOperations)s).ListAsync(resourceGroupName, integrationAccountName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
コード例 #47
0
        public void GetAutoscaleSettingCommandParametersProcessing()
        {
            // Calling ListSettingsAsync
            cmdlet.ResourceGroup = Utilities.ResourceGroup;
            cmdlet.ExecuteCmdlet();

            Assert.Equal(Utilities.ResourceGroup, this.resourceGroup);
            Assert.Null(this.settingName);
            Assert.True(this.query == null || string.IsNullOrWhiteSpace(this.query.Filter));

            // Calling GetSettingAsync
            this.resourceGroup = null;
            this.query = "";
            cmdlet.Name = Utilities.Name;
            cmdlet.ExecuteCmdlet();

            Assert.Equal(Utilities.ResourceGroup, this.resourceGroup);
            Assert.Equal(Utilities.Name, this.settingName);
            // Assert.Equal(Utilities.ResourceUri, this.targetResourceUri);

            // Test deatiled output flag calling GetSettingAsync
            this.resourceGroup = null;
            this.settingName = null;
            cmdlet.DetailedOutput = true;
            cmdlet.ExecuteCmdlet();

            Assert.Equal(Utilities.ResourceGroup, this.resourceGroup);
            Assert.Equal(Utilities.Name, this.settingName);
            //Assert.Equal(Utilities.ResourceUri, this.targetResourceUri);
        }
コード例 #48
0
 /// <summary>
 /// Gets a list of integration account schemas.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The resource group name.
 /// </param>
 /// <param name='integrationAccountName'>
 /// The integration account name.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <IPage <IntegrationAccountSchema> > ListAsync(this IIntegrationAccountSchemasOperations operations, string resourceGroupName, string integrationAccountName, ODataQuery <IntegrationAccountSchemaFilter> odataQuery = default(ODataQuery <IntegrationAccountSchemaFilter>), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, integrationAccountName, odataQuery, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #49
0
ファイル: ODataTests.cs プロジェクト: jkonecki/autorest
 public void ODataQuerySupportsAllParameters()
 {
     var queryString = "foo eq 'bar'";
     var query = new ODataQuery<Param1>(p => p.Foo == "bar")
     {
         Expand = "param1",
         OrderBy = "d",
         Skip = 10,
         Top = 100
     };
     Assert.Equal(string.Format("$filter={0}&$orderby=d&$expand=param1&$top=100&$skip=10", Uri.EscapeDataString(queryString)), query.ToString());
 }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            HttpRequest req, ILogger log, Microsoft.Azure.WebJobs.ExecutionContext execContext)
        {
            MediaServicesHelpers.LogInformation(log, "C# HTTP trigger function processed a request.");

            dynamic data;

            try
            {
                data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd());
            }
            catch (Exception ex)
            {
                return(IrdetoHelpers.ReturnErrorException(log, ex));
            }

            var assetNameStartsWith = (string)data.assetNameStartsWith;

            if (assetNameStartsWith == null)
            {
                return(IrdetoHelpers.ReturnErrorException(log, "Error - please pass assetNameStartsWith in the JSON"));
            }

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

            // Azure region management
            var azureRegions = new List <string>();

            if ((string)data.azureRegion != null)
            {
                azureRegions = ((string)data.azureRegion).Split(',').ToList();
            }
            else
            {
                azureRegions.Add((string)null);
            }


            foreach (var region in azureRegions)
            {
                ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder()
                                                         .SetBasePath(Directory.GetCurrentDirectory())
                                                         .AddEnvironmentVariables()
                                                         .Build(),
                                                         region
                                                         );

                MediaServicesHelpers.LogInformation(log, "config loaded.", region);
                MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, region);

                var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config);

                // Set the polling interval for long running operations to 2 seconds.
                // The default value is 30 seconds for the .NET client SDK
                client.LongRunningOperationRetryTimeout = 2;

                MediaServicesHelpers.LogInformation(log, "asset name starts : " + assetNameStartsWith, region);

                try
                {
                    ODataQuery <Asset> query  = new ODataQuery <Asset>();
                    string             search = "'" + assetNameStartsWith + "'";
                    query.Filter  = "name gt " + search.Substring(0, search.Length - 2) + char.ConvertFromUtf32(char.ConvertToUtf32(search, search.Length - 2) - 1) + new string('z', 262 - search.Length) + "'" + " and name lt " + search.Substring(0, search.Length - 1) + new string('z', 262 - search.Length) + "'";
                    query.OrderBy = "Properties/Created";
                    var assetsResult = client.Assets.List(config.ResourceGroup, config.AccountName, query);

                    assets = assetsResult.Select(a => a.Name).ToList();
                }
                catch (Exception ex)
                {
                    return(IrdetoHelpers.ReturnErrorException(log, ex));
                }
            }

            var response = new JObject
            {
                { "success", true },
                { "assetNames", new JArray(assets) },
                {
                    "operationsVersion",
                    AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().Location).Version.ToString()
                }
            };

            return(new OkObjectResult(
                       response
                       ));
        }
コード例 #51
0
ファイル: ODataTests.cs プロジェクト: jkonecki/autorest
 public void ODataQuerySupportsPartialState()
 {
     var queryString = "foo eq 'bar'";
     var query = new ODataQuery<Param1>(p => p.Foo == "bar")
     {
         Top = 100
     };
     Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString());
 }
コード例 #52
0
 /// <summary>
 /// Gets the first page of Data Lake Store accounts linked to the specified
 /// Data Lake Analytics account. The response includes a link to the next page,
 /// if any.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the Azure resource group.
 /// </param>
 /// <param name='accountName'>
 /// The name of the Data Lake Analytics account.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='select'>
 /// OData Select statement. Limits the properties on each entry to just those
 /// requested, e.g. Categories?$select=CategoryName,Description. Optional.
 /// </param>
 /// <param name='count'>
 /// The Boolean value of true or false to request a count of the matching
 /// resources included with the resources in the response, e.g.
 /// Categories?$count=true. Optional.
 /// </param>
 public static IPage <DataLakeStoreAccountInformation> ListByAccount(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, ODataQuery <DataLakeStoreAccountInformation> odataQuery = default(ODataQuery <DataLakeStoreAccountInformation>), string select = default(string), bool?count = default(bool?))
 {
     return(operations.ListByAccountAsync(resourceGroupName, accountName, odataQuery, select, count).GetAwaiter().GetResult());
 }
コード例 #53
0
        public List<JobInformation> ListJobs(string accountName, string filter, int? top,
            int? skip)
        {
            var parameters = new ODataQuery<JobInformation>
            {
                Filter = filter,
                Top = top,
                Skip = skip
            };

            var jobList = new List<JobInformation>();
            var response = _jobClient.Job.List(accountName, parameters);

            jobList.AddRange(response);
            while (!string.IsNullOrEmpty(response.NextPageLink))
            {
                response = ListJobsWithNextLink(response.NextPageLink);
                jobList.AddRange(response);
            }

            return jobList;
        }
コード例 #54
0
 /// <summary>
 /// Gets the first page of Data Lake Store accounts linked to the specified
 /// Data Lake Analytics account. The response includes a link to the next page,
 /// if any.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the Azure resource group.
 /// </param>
 /// <param name='accountName'>
 /// The name of the Data Lake Analytics account.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='select'>
 /// OData Select statement. Limits the properties on each entry to just those
 /// requested, e.g. Categories?$select=CategoryName,Description. Optional.
 /// </param>
 /// <param name='count'>
 /// The Boolean value of true or false to request a count of the matching
 /// resources included with the resources in the response, e.g.
 /// Categories?$count=true. Optional.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <IPage <DataLakeStoreAccountInformation> > ListByAccountAsync(this IDataLakeStoreAccountsOperations operations, string resourceGroupName, string accountName, ODataQuery <DataLakeStoreAccountInformation> odataQuery = default(ODataQuery <DataLakeStoreAccountInformation>), string select = default(string), bool?count = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ListByAccountWithHttpMessagesAsync(resourceGroupName, accountName, odataQuery, select, count, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #55
0
ファイル: ODataTests.cs プロジェクト: Ranjana1996/autorest
 public void ODataQuerySupportsAllParameters()
 {
     var query = new ODataQuery<Param1>(p => p.Foo == "bar")
     {
         Expand = "param1",
         OrderBy = "d",
         Skip = 10,
         Top = 100
     };
     Assert.Equal("$filter=foo eq 'bar'&$orderby=d&$expand=param1&$top=100&$skip=10", query.ToString());
 }
コード例 #56
0
        /// <summary>
        /// Lists the backup copies for the backed up item.
        /// </summary>
        /// <param name='vaultName'>
        /// The name of the recovery services vault.
        /// </param>
        /// <param name='resourceGroupName'>
        /// The name of the resource group where the recovery services vault is
        /// present.
        /// </param>
        /// <param name='fabricName'>
        /// Fabric name associated with the backed up item.
        /// </param>
        /// <param name='containerName'>
        /// Container name associated with the backed up item.
        /// </param>
        /// <param name='protectedItemName'>
        /// Backed up item whose backup copies are to be fetched.
        /// </param>
        /// <param name='odataQuery'>
        /// OData parameters to apply to the operation.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <IPage <RecoveryPointResource> > > ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ODataQuery <BMSRPQueryObject> odataQuery = default(ODataQuery <BMSRPQueryObject>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (vaultName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (fabricName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "fabricName");
            }
            if (containerName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "containerName");
            }
            if (protectedItemName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "protectedItemName");
            }
            string apiVersion = "2019-06-15";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("odataQuery", odataQuery);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("vaultName", vaultName);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("fabricName", fabricName);
                tracingParameters.Add("containerName", containerName);
                tracingParameters.Add("protectedItemName", protectedItemName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints").ToString();

            _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
            _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName));
            _url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName));
            List <string> _queryParameters = new List <string>();

            if (odataQuery != null)
            {
                var _odataFilter = odataQuery.ToString();
                if (!string.IsNullOrEmpty(_odataFilter))
                {
                    _queryParameters.Add(_odataFilter);
                }
            }
            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <IPage <RecoveryPointResource> >();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Page <RecoveryPointResource> >(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
コード例 #57
0
ファイル: ODataTests.cs プロジェクト: Ranjana1996/autorest
        public void ODataQuerySupportsCustomDateTimeOffsetFilter()
        {
            var param = new Param1
            {
                SubmitTime = DateTimeOffset.Parse("2016-03-28T08:15:00.0971693+00:00"),
                State = "Ended"

            };

            var filter = new List<string>();
            filter.Add(string.Format("submitTime lt datetimeoffset'{0}'", Uri.EscapeDataString(param.SubmitTime.Value.ToString("O"))));
            filter.Add(string.Format("state ne '{0}'", param.State));
            var filterString = string.Join(" and ", filter.ToArray());


            var query = new ODataQuery<Param1>
            {
                Filter = filterString
            };
            Assert.Equal("$filter=submitTime lt datetimeoffset'2016-03-28T08%3A15%3A00.0971693%2B00%3A00' and state ne 'Ended'", query.ToString());
        }
コード例 #58
0
        /// <summary>
        /// Lists protected items protected by the recovery services vault according to the provider data
        /// </summary>
        /// <returns>List of protected items</returns>
        public List <ItemBase> ListProtectedItems()
        {
            string               vaultName         = (string)ProviderData[VaultParams.VaultName];
            string               resourceGroupName = (string)ProviderData[VaultParams.ResourceGroupName];
            ContainerBase        container         = (ContainerBase)ProviderData[ItemParams.Container];
            string               name             = (string)ProviderData[ItemParams.AzureVMName];
            ItemProtectionStatus protectionStatus =
                (ItemProtectionStatus)ProviderData[ItemParams.ProtectionStatus];
            ItemProtectionState status =
                (ItemProtectionState)ProviderData[ItemParams.ProtectionState];

            CmdletModel.WorkloadType workloadType =
                (CmdletModel.WorkloadType)ProviderData[ItemParams.WorkloadType];
            PolicyBase policy = (PolicyBase)ProviderData[PolicyParams.ProtectionPolicy];

            ODataQuery <ProtectedItemQueryObject> queryParams = policy != null ?
                                                                new ODataQuery <ProtectedItemQueryObject>(
                q => q.BackupManagementType
                == ServiceClientModel.BackupManagementType.AzureSql &&
                q.ItemType == DataSourceType.AzureSqlDb &&
                q.PolicyName == policy.Name) :
                                                                new ODataQuery <ProtectedItemQueryObject>(
                q => q.BackupManagementType
                == ServiceClientModel.BackupManagementType.AzureSql &&
                q.ItemType == DataSourceType.AzureSqlDb);

            List <ProtectedItemResource> protectedItems = new List <ProtectedItemResource>();
            string skipToken    = null;
            var    listResponse = ServiceClientAdapter.ListProtectedItem(
                queryParams,
                skipToken,
                vaultName: vaultName,
                resourceGroupName: resourceGroupName);

            protectedItems.AddRange(listResponse);

            // 1. Filter by container
            if (container != null)
            {
                protectedItems = protectedItems.Where(protectedItem =>
                {
                    Dictionary <UriEnums, string> dictionary =
                        HelperUtils.ParseUri(protectedItem.Id);
                    string containerUri =
                        HelperUtils.GetContainerUri(dictionary, protectedItem.Id);
                    return(containerUri.Contains(container.Name));
                }).ToList();
            }

            List <ProtectedItemResource> protectedItemGetResponses =
                new List <ProtectedItemResource>();

            // 2. Filter by item's friendly name
            if (!string.IsNullOrEmpty(name))
            {
                protectedItems = protectedItems.Where(protectedItem =>
                {
                    Dictionary <UriEnums, string> dictionary =
                        HelperUtils.ParseUri(protectedItem.Id);
                    string protectedItemUri =
                        HelperUtils.GetProtectedItemUri(dictionary, protectedItem.Id);
                    return(protectedItemUri.ToLower().Contains(name.ToLower()));
                }).ToList();

                ODataQuery <GetProtectedItemQueryObject> getItemQueryParams =
                    new ODataQuery <GetProtectedItemQueryObject>(q => q.Expand == extendedInfo);

                for (int i = 0; i < protectedItems.Count; i++)
                {
                    Dictionary <UriEnums, string> dictionary =
                        HelperUtils.ParseUri(protectedItems[i].Id);
                    string containerUri =
                        HelperUtils.GetContainerUri(dictionary, protectedItems[i].Id);
                    string protectedItemUri =
                        HelperUtils.GetProtectedItemUri(dictionary, protectedItems[i].Id);

                    var getResponse = ServiceClientAdapter.GetProtectedItem(
                        containerUri,
                        protectedItemUri,
                        getItemQueryParams,
                        vaultName: vaultName,
                        resourceGroupName: resourceGroupName);
                    protectedItemGetResponses.Add(getResponse.Body);
                }
            }

            List <ItemBase> itemModels = ConversionHelpers.GetItemModelList(protectedItems);

            if (!string.IsNullOrEmpty(name))
            {
                for (int i = 0; i < itemModels.Count; i++)
                {
                    AzureSqlProtectedItem azureSqlProtectedItem =
                        (AzureSqlProtectedItem)protectedItemGetResponses[i].Properties;
                    AzureSqlItemExtendedInfo extendedInfo = new AzureSqlItemExtendedInfo();
                    var hydraExtendedInfo = azureSqlProtectedItem.ExtendedInfo;
                    if (hydraExtendedInfo.OldestRecoveryPoint.HasValue)
                    {
                        extendedInfo.OldestRecoveryPoint = hydraExtendedInfo.OldestRecoveryPoint;
                    }
                    extendedInfo.PolicyState                   = hydraExtendedInfo.PolicyState;
                    extendedInfo.RecoveryPointCount            = hydraExtendedInfo.RecoveryPointCount;
                    ((AzureSqlItem)itemModels[i]).ExtendedInfo = extendedInfo;
                }
            }

            // 3. Filter by item's Protection Status
            if (protectionStatus != 0)
            {
                throw new Exception(
                          string.Format(
                              Resources.ProtectionStatusNotAllowedForAzureSqlItem,
                              protectionStatus.ToString()));
            }

            // 4. Filter by item's Protection State
            if (status != 0)
            {
                if (status != ItemProtectionState.Protected)
                {
                    throw new Exception(
                              string.Format(
                                  Resources.ProtectionStateInvalidForAzureSqlItem,
                                  status.ToString()));
                }

                itemModels = itemModels.Where(itemModel =>
                {
                    return(((AzureSqlItem)itemModel).ProtectionState == status.ToString());
                }).ToList();
            }

            // 5. Filter by workload type
            if (workloadType != 0)
            {
                itemModels = itemModels.Where(itemModel =>
                {
                    return(itemModel.WorkloadType == workloadType);
                }).ToList();
            }

            return(itemModels);
        }
コード例 #59
0
ファイル: ODataTests.cs プロジェクト: Ranjana1996/autorest
 public void ODataQuerySupportsPartialStateWithSlashes()
 {
     var queryString = "$filter=foo eq 'bar%2Fclub'&$top=100";
     var query = new ODataQuery<Param1>(p => p.Foo == "bar/club")
     {
         Top = 100
     };
     Assert.Equal(queryString, query.ToString());
 }
コード例 #60
0
        public async Task RefreshAssetsAsync(int pagetodisplay) // all assets are refreshed
        {
            if (!_initialized)
            {
                return;
            }
            if (pagetodisplay == 1)
            {
                _currentPageNumberIsMax = false;
            }
            Debug.WriteLine("RefreshAssets Start");

            if (WorkerAnalyzeAssets.IsBusy)
            {
                // cancel the analyze.
                WorkerAnalyzeAssets.CancelAsync();
            }
            this.BeginInvoke(new Action(() => this.FindForm().Cursor = Cursors.WaitCursor));

            /*
             *
             *
             * Property
             * Name	Filtering	Ordering
             * Equals	Greater than	Less Than	Ascending	Descending
             * Name	✓	✓	✓	✓	✓
             * Properties/AssetId	✓
             * Properties/Created	✓	✓	✓	✓	✓
             * Properties/LastModified
             * Properties/AlternateId	✓
             * Properties/Description
             * Properties/Container
             * Properties/StorageId
             *
             *
             */


            ///////////////////////
            // SORTING
            ///////////////////////
            var odataQuery = new ODataQuery <Asset>();

            switch (_orderassets)
            {
            case OrderAssets.CreatedDescending:
                odataQuery.OrderBy = "Properties/Created desc";
                break;

            case OrderAssets.CreatedAscending:
                odataQuery.OrderBy = "Properties/Created";
                break;

            case OrderAssets.NameAscending:
                odataQuery.OrderBy = "Name";
                break;

            case OrderAssets.NameDescending:
                odataQuery.OrderBy = "Name desc";
                break;

            default:
                odataQuery.OrderBy = "Properties/Created desc";
                break;
            }



            ///////////////////////
            // SEARCH
            ///////////////////////
            if (_searchinname != null && !string.IsNullOrEmpty(_searchinname.Text))
            {
                string search = _searchinname.Text;

                switch (_searchinname.SearchType)
                {
                // Search on Asset name Equals
                case SearchIn.AssetNameEquals:
                    search            = "'" + search + "'";
                    odataQuery.Filter = "name eq " + search;
                    break;

                // Search on Asset name starts with
                case SearchIn.AssetNameStartsWith:
                    search            = "'" + search + "'";
                    odataQuery.Filter = "name gt " + search.Substring(0, search.Length - 2) + char.ConvertFromUtf32(char.ConvertToUtf32(search, search.Length - 2) - 1) + new String('z', 262 - search.Length) + "'" + " and name lt " + search.Substring(0, search.Length - 2) + char.ConvertFromUtf32(char.ConvertToUtf32(search, search.Length - 2) + 1) + "'";
                    break;

                // Search on Asset name Greater than
                case SearchIn.AssetNameGreaterThan:
                    search            = "'" + search + "'";
                    odataQuery.Filter = "name gt " + search;
                    break;

                // Search on Asset name Less than
                case SearchIn.AssetNameLessThan:
                    search            = "'" + search + "'";
                    odataQuery.Filter = "name lt " + search;
                    break;

                // Search on Asset aternate id
                case SearchIn.AssetAltId:
                    search            = "'" + search + "'";
                    odataQuery.Filter = "properties/alternateid eq " + search;
                    break;

                case SearchIn.AssetId:
                    odataQuery.Filter = "properties/assetid eq " + search;
                    break;

                default:
                    break;
                }
            }

            // DAYS
            bool filterStartDate = false;
            bool filterEndDate   = false;

            DateTime dateTimeStart    = DateTime.UtcNow;
            DateTime dateTimeRangeEnd = DateTime.UtcNow.AddDays(1);

            int days = FilterTime.ReturnNumberOfDays(_timefilter);

            if (days > 0)
            {
                filterStartDate = true;
                dateTimeStart   = (DateTime.UtcNow.Add(-TimeSpan.FromDays(days)));
            }
            else if (days == -1) // TimeRange
            {
                filterStartDate = true;
                filterEndDate   = true;
                dateTimeStart   = _timefilterTimeRange.StartDate;
                if (_timefilterTimeRange.EndDate != null) // there is an end time
                {
                    dateTimeRangeEnd = (DateTime)_timefilterTimeRange.EndDate;
                }
            }
            if (filterStartDate)
            {
                if (odataQuery.Filter != null)
                {
                    odataQuery.Filter = odataQuery.Filter + " and ";
                }
                odataQuery.Filter = odataQuery.Filter + $"properties/created gt {dateTimeStart.ToString("o")}";
            }
            if (filterEndDate)
            {
                if (odataQuery.Filter != null)
                {
                    odataQuery.Filter = odataQuery.Filter + " and ";
                }
                odataQuery.Filter = odataQuery.Filter + $"properties/created lt {dateTimeRangeEnd.ToString("o")}";
            }

            IPage <Asset> currentPage = null;
            await _client.RefreshTokenIfNeededAsync();

            if (pagetodisplay == 1)
            {
                firstpage = await _client.AMSclient.Assets.ListAsync(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName, odataQuery);

                currentPage = firstpage;
            }
            else
            {
                currentPage        = firstpage;
                _currentPageNumber = 1;
                while (currentPage.NextPageLink != null && pagetodisplay > _currentPageNumber)
                {
                    _currentPageNumber++;
                    currentPage = await _client.AMSclient.Assets.ListNextAsync(currentPage.NextPageLink);
                }
                if (currentPage.NextPageLink == null)
                {
                    _currentPageNumberIsMax = true;                                   // we reached max
                }
            }



            /*
             * var assets = currentPage.Select(a => new AssetEntryV3
             * {
             *  Name = a.Name,
             *  Description = a.Description,
             *  AssetId = a.AssetId,
             *  AlternateId = a.AlternateId,
             *  Created = ((DateTime)a.Created).ToLocalTime().ToString("G"),
             *  StorageAccountName = a.StorageAccountName
             * }
             * );
             */


            var assets = currentPage.Select(a =>
                                            (cacheAssetentriesV3.ContainsKey(a.Name) &&
                                             cacheAssetentriesV3[a.Name].LastModified != null &&
                                             (cacheAssetentriesV3[a.Name].LastModified == a.LastModified.ToLocalTime().ToString("G")) ?
                                             cacheAssetentriesV3[a.Name] :
                                             new AssetEntryV3
            {
                Name = a.Name,
                Description = a.Description,
                AssetId = a.AssetId,
                AlternateId = a.AlternateId,
                Created = ((DateTime)a.Created).ToLocalTime().ToString("G"),
                LastModified = ((DateTime)a.LastModified).ToLocalTime().ToString("G"),
                StorageAccountName = a.StorageAccountName
            }
                                            ));

            _MyObservAssetV3 = new BindingList <AssetEntryV3>(assets.ToList());

            this.BeginInvoke(new Action(() => this.DataSource = _MyObservAssetV3));

            Debug.WriteLine("RefreshAssets End");
            AnalyzeItemsInBackground();

            this.BeginInvoke(new Action(() => this.FindForm().Cursor = Cursors.Default));
        }