Exemplo n.º 1
0
        /// <summary>
        /// Called when resource is deleted.
        /// </summary>
        /// <remarks>
        /// A request context is not necessary to delete a resource.
        /// </remarks>
        /// <param name="deletedResource">The deleted resource.</param>
        Task <ResourceOperationStatus> IManagedResourceGroupWideResourceTypeRequestHandler.OnDeleteResource(IResourceEntity deletedResource)
        {
            ArgumentValidator.ValidateNotNull("deletedResource", deletedResource);

            // TODO: Add custom nested resource deletion logic here.

            return(Task.FromResult(ResourceOperationStatus.CompleteSynchronously(deletedResource)));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Called before a resource is updated in the storage layer.
        /// </summary>
        /// <remarks>
        /// Use requestContext.ApiVersion to get the API version of the request.
        /// </remarks>
        /// <param name="requestContext">The request context.</param>
        /// <param name="subscription">The subscription.</param>
        /// <param name="existingResource">The existing resource.</param>
        /// <param name="updatedResourceDefinition">The updated resource definition.</param>
        Task <ResourceOperationStatus> IManagedResourceGroupWideResourceTypeRequestHandler.OnUpdateResource(
            RequestContext requestContext,
            SubscriptionNotificationDefinition subscription,
            IResourceEntity existingResource,
            ResourceDefinition updatedResourceDefinition)
        {
            ArgumentValidator.ValidateNotNull("requestContext", requestContext);
            ArgumentValidator.ValidateNotNull("subscription", subscription);
            ArgumentValidator.ValidateNotNull("existingResource", existingResource);
            ArgumentValidator.ValidateNotNull("updatedResourceDefinition", updatedResourceDefinition);

            // TODO: Implement custom logic to update the resource.

            return(Task.FromResult(ResourceOperationStatus.CompleteSynchronously(existingResource)));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Called after a resource is created in the storage layer.
        /// </summary>
        /// <remarks>
        /// Use requestContext.ApiVersion to get the API version of the request.
        /// </remarks>
        /// <param name="requestContext">The request context.</param>
        /// <param name="subscription">The subscription.</param>
        /// <param name="createdResource">The created resource.</param>
        async Task <ResourceOperationStatus> IManagedResourceGroupWideResourceTypeRequestHandler.OnAfterInsertResource(
            RequestContext requestContext,
            SubscriptionNotificationDefinition subscription,
            IResourceEntity createdResource)
        {
            ArgumentValidator.ValidateNotNull("requestContext", requestContext);
            ArgumentValidator.ValidateNotNull("subscription", subscription);
            ArgumentValidator.ValidateNotNull("createdResource", createdResource);

            // Enforce quotas for nested resources.
            ServiceQuota[] quotas = ServiceQuota.CreateSubscriptionQuotaFromSubscriptionNotification(
                createdResource.SubscriptionId,
                subscription);

            // Count aggregated quota for nested resources for the entire subscription.
            int nestedResourceCountLimit = 0;

            quotas.ToList().ForEach(quota => nestedResourceCountLimit += quota.NestedResourceCountLimit);

            int resourceCount = 0;
            DataContinuationToken continuationToken = null;

            do
            {
                var result = await this.resourceProviderStorage
                             .ResourceDataProvider
                             .FindResources(
                    createdResource.SubscriptionId,
                    createdResource.QualifiedTypeName,
                    continuationToken : continuationToken);

                resourceCount    += result.Entities.Length;
                continuationToken = result.ContinuationToken;
            } while (continuationToken != null);

            // TODO: Apply custom quota enforcement logic here.

            // Check that there is sufficient quota to create additional resources (enforce the resource count)
            if (nestedResourceCountLimit < resourceCount)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, ResponseErrorMessages.InsufficientResourceQuota, createdResource.Name);
                throw new ResourceProviderException(errorMessage, ResponseErrorCode.InsufficientQuota.ToString(), HttpStatusCode.BadRequest);
            }

            // TODO: Add custom nested resource creation logic here.

            return(ResourceOperationStatus.CompleteSynchronously(createdResource));
        }
        /// <summary>
        /// Retrieve a list of Cloud services
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the list cloud service operation.
        /// </returns>
        public async Task <CloudServiceListResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/cloudservices";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-04-10");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/xml");
                httpRequest.Headers.Add("x-ms-version", "2013-03-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    CloudServiceListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new CloudServiceListResponse();
                        XDocument responseDoc = XDocument.Parse(responseContent);

                        XElement cloudServicesSequenceElement = responseDoc.Element(XName.Get("CloudServices", "http://schemas.microsoft.com/windowsazure"));
                        if (cloudServicesSequenceElement != null)
                        {
                            foreach (XElement cloudServicesElement in cloudServicesSequenceElement.Elements(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure")))
                            {
                                CloudService cloudServiceInstance = new CloudService();
                                result.CloudServices.Add(cloudServiceInstance);

                                XElement descriptionElement = cloudServicesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
                                if (descriptionElement != null)
                                {
                                    string descriptionInstance = descriptionElement.Value;
                                    cloudServiceInstance.Description = descriptionInstance;
                                }

                                XElement geoRegionElement = cloudServicesElement.Element(XName.Get("GeoRegion", "http://schemas.microsoft.com/windowsazure"));
                                if (geoRegionElement != null)
                                {
                                    string geoRegionInstance = geoRegionElement.Value;
                                    cloudServiceInstance.GeoRegion = geoRegionInstance;
                                }

                                XElement labelElement = cloudServicesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
                                if (labelElement != null)
                                {
                                    string labelInstance = labelElement.Value;
                                    cloudServiceInstance.Label = labelInstance;
                                }

                                XElement nameElement = cloudServicesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                                if (nameElement != null)
                                {
                                    string nameInstance = nameElement.Value;
                                    cloudServiceInstance.Name = nameInstance;
                                }

                                XElement resourcesSequenceElement = cloudServicesElement.Element(XName.Get("Resources", "http://schemas.microsoft.com/windowsazure"));
                                if (resourcesSequenceElement != null)
                                {
                                    foreach (XElement resourcesElement in resourcesSequenceElement.Elements(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure")))
                                    {
                                        Vault resourceInstance = new Vault();
                                        cloudServiceInstance.Resources.Add(resourceInstance);

                                        XElement resourceProviderNamespaceElement = resourcesElement.Element(XName.Get("ResourceProviderNamespace", "http://schemas.microsoft.com/windowsazure"));
                                        if (resourceProviderNamespaceElement != null)
                                        {
                                            string resourceProviderNamespaceInstance = resourceProviderNamespaceElement.Value;
                                            resourceInstance.ResourceProviderNamespace = resourceProviderNamespaceInstance;
                                        }

                                        XElement eTagElement = resourcesElement.Element(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure"));
                                        if (eTagElement != null)
                                        {
                                            string eTagInstance = eTagElement.Value;
                                            resourceInstance.ETag = eTagInstance;
                                        }

                                        XElement labelElement2 = resourcesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
                                        if (labelElement2 != null)
                                        {
                                            string labelInstance2 = labelElement2.Value;
                                            resourceInstance.Label = labelInstance2;
                                        }

                                        XElement nameElement2 = resourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                                        if (nameElement2 != null)
                                        {
                                            string nameInstance2 = nameElement2.Value;
                                            resourceInstance.Name = nameInstance2;
                                        }

                                        XElement operationStatusElement = resourcesElement.Element(XName.Get("OperationStatus", "http://schemas.microsoft.com/windowsazure"));
                                        if (operationStatusElement != null)
                                        {
                                            ResourceOperationStatus operationStatusInstance = new ResourceOperationStatus();
                                            resourceInstance.OperationStatus = operationStatusInstance;

                                            XElement resultElement = operationStatusElement.Element(XName.Get("Result", "http://schemas.microsoft.com/windowsazure"));
                                            if (resultElement != null)
                                            {
                                                string resultInstance = resultElement.Value;
                                                operationStatusInstance.Result = resultInstance;
                                            }

                                            XElement typeElement = operationStatusElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
                                            if (typeElement != null)
                                            {
                                                string typeInstance = typeElement.Value;
                                                operationStatusInstance.Type = typeInstance;
                                            }

                                            XElement errorElement = operationStatusElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
                                            if (errorElement != null)
                                            {
                                                ResourceErrorInfo errorInstance = new ResourceErrorInfo();
                                                operationStatusInstance.Error = errorInstance;

                                                XElement extendedCodeElement = errorElement.Element(XName.Get("ExtendedCode", "http://schemas.microsoft.com/windowsazure"));
                                                if (extendedCodeElement != null)
                                                {
                                                    string extendedCodeInstance = extendedCodeElement.Value;
                                                    errorInstance.ExtendedCode = extendedCodeInstance;
                                                }

                                                XElement httpCodeElement = errorElement.Element(XName.Get("HttpCode", "http://schemas.microsoft.com/windowsazure"));
                                                if (httpCodeElement != null)
                                                {
                                                    int httpCodeInstance = int.Parse(httpCodeElement.Value, CultureInfo.InvariantCulture);
                                                    errorInstance.HttpCode = httpCodeInstance;
                                                }

                                                XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
                                                if (messageElement != null)
                                                {
                                                    string messageInstance = messageElement.Value;
                                                    errorInstance.Message = messageInstance;
                                                }
                                            }
                                        }

                                        XElement outputItemsSequenceElement = resourcesElement.Element(XName.Get("OutputItems", "http://schemas.microsoft.com/windowsazure"));
                                        if (outputItemsSequenceElement != null)
                                        {
                                            foreach (XElement outputItemsElement in outputItemsSequenceElement.Elements(XName.Get("OutputItem", "http://schemas.microsoft.com/windowsazure")))
                                            {
                                                OutputItem outputItemInstance = new OutputItem();
                                                resourceInstance.OutputItems.Add(outputItemInstance);

                                                XElement keyElement = outputItemsElement.Element(XName.Get("Key", "http://schemas.microsoft.com/windowsazure"));
                                                if (keyElement != null)
                                                {
                                                    string keyInstance = keyElement.Value;
                                                    outputItemInstance.Key = keyInstance;
                                                }

                                                XElement valueElement = outputItemsElement.Element(XName.Get("Value", "http://schemas.microsoft.com/windowsazure"));
                                                if (valueElement != null)
                                                {
                                                    string valueInstance = valueElement.Value;
                                                    outputItemInstance.Value = valueInstance;
                                                }
                                            }
                                        }

                                        XElement planElement = resourcesElement.Element(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
                                        if (planElement != null)
                                        {
                                            string planInstance = planElement.Value;
                                            resourceInstance.Plan = planInstance;
                                        }

                                        XElement schemaVersionElement = resourcesElement.Element(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure"));
                                        if (schemaVersionElement != null)
                                        {
                                            string schemaVersionInstance = schemaVersionElement.Value;
                                            resourceInstance.SchemaVersion = schemaVersionInstance;
                                        }

                                        XElement stateElement = resourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
                                        if (stateElement != null)
                                        {
                                            string stateInstance = stateElement.Value;
                                            resourceInstance.State = stateInstance;
                                        }

                                        XElement subStateElement = resourcesElement.Element(XName.Get("SubState", "http://schemas.microsoft.com/windowsazure"));
                                        if (subStateElement != null)
                                        {
                                            string subStateInstance = subStateElement.Value;
                                            resourceInstance.SubState = subStateInstance;
                                        }

                                        XElement typeElement2 = resourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
                                        if (typeElement2 != null)
                                        {
                                            string typeInstance2 = typeElement2.Value;
                                            resourceInstance.Type = typeInstance2;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }