Beispiel #1
0
        /// <summary>
        /// Converts a <see cref="Resource{JToken}"/> object into a <see cref="PSObject"/> object.
        /// </summary>
        /// <param name="resource">The <see cref="Resource{JToken}"/> object.</param>
        internal static PSObject ToPsObject(this Resource <JToken> resource)
        {
            var resourceType          = ResourceIdUtility.GetResourceType(resource.Id);
            var extensionResourceType = ResourceIdUtility.GetExtensionResourceType(resource.Id);

            var objectDefinition = new Dictionary <string, object>
            {
                { "Name", resource.Name },
                { "ResourceId", resource.Id },
                { "ResourceName", ResourceIdUtility.GetResourceName(resource.Id) },
                { "ResourceType", resourceType },
                { "ExtensionResourceName", ResourceIdUtility.GetExtensionResourceName(resource.Id) },
                { "ExtensionResourceType", extensionResourceType },
                { "Kind", resource.Kind },
                { "ResourceGroupName", ResourceIdUtility.GetResourceGroup(resource.Id) },
                { "Location", resource.Location },
                { "SubscriptionId", ResourceIdUtility.GetSubscriptionId(resource.Id) },
                { "Tags", TagsHelper.GetTagsHashtables(resource.Tags) },
                { "Plan", resource.Plan.ToJToken().ToPsObject() },
                { "Properties", resource.Properties.ToPsObject() },
                { "PropertiesText", resource.Properties == null ? null : resource.Properties.ToString() },
                { "CreatedTime", resource.CreatedTime },
                { "ChangedTime", resource.ChangedTime },
                { "ETag", resource.ETag },
            };

            return(PowerShellUtilities.ConstructPSObject(
                       (resourceType + extensionResourceType).Replace('/', '.'),
                       objectDefinition.Where(kvp => kvp.Value != null).SelectManyArray(kvp => new[] { kvp.Key, kvp.Value })));
        }
Beispiel #2
0
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        protected override void OnProcessRecord()
        {
            base.OnProcessRecord();

            var resourceId = this.GetResourceId();

            var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result;

            var parameters = new ExportTemplateParameters
            {
                Resources = new string [] { "*" },
                Options   = this.GetExportOptions() ?? null
            };

            var operationResult = this.GetResourcesClient()
                                  .InvokeActionOnResource <JObject>(
                resourceId: resourceId,
                action: Constants.ExportTemplate,
                parameters: parameters.ToJToken(),
                apiVersion: apiVersion,
                cancellationToken: this.CancellationToken.Value)
                                  .Result;

            var managementUri = this.GetResourcesClient()
                                .GetResourceManagementRequestUri(
                resourceId: resourceId,
                apiVersion: apiVersion,
                action: Constants.ExportTemplate);

            var activity     = string.Format("POST {0}", managementUri.PathAndQuery);
            var resultString = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false)
                               .WaitOnOperation(operationResult: operationResult);

            var template = JToken.FromObject(JObject.Parse(resultString)["template"]);

            if (JObject.Parse(resultString)["error"] != null)
            {
                ExtendedErrorInfo error;
                if (JObject.Parse(resultString)["error"].TryConvertTo(out error))
                {
                    WriteWarning(string.Format("{0} : {1}", error.Code, error.Message));
                    foreach (var detail in error.Details)
                    {
                        WriteWarning(string.Format("{0} : {1}", detail.Code, detail.Message));
                    }
                }
            }

            string path = FileUtility.SaveTemplateFile(
                templateName: this.ResourceGroupName,
                contents: template.ToString(),
                outputPath: string.IsNullOrEmpty(this.Path) ? System.IO.Path.Combine(CurrentPath(), this.ResourceGroupName) : this.TryResolvePath(this.Path),
                overwrite: this.Force,
                confirmAction: ConfirmAction);

            WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path));
        }
        public override void ExecuteCmdlet()
        {
            string path = GalleryTemplatesClient.DownloadGalleryTemplateFile(
                Identity,
                string.IsNullOrEmpty(Path) ? System.IO.Path.Combine(CurrentPath(), Identity) : this.TryResolvePath(Path),
                Force,
                ConfirmAction);

            WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path));
        }
 public static PSObject GetNamespacePSObject(ExtendedAuthorizationRule rule)
 {
     return(null == rule? null : PowerShellUtilities.ConstructPSObject(
                typeof(ExtendedAuthorizationRule).FullName,
                "Namespace", rule.Namespace,
                "Name", rule.Name,
                "ConnectionString", rule.ConnectionString,
                "Permission", rule.Permission,
                "Rule", rule.Rule));
 }
        public override void ExecuteCmdlet()
        {
            WriteWarning("This cmdlet is being deprecated and will be removed in a future release.");
            string path = GalleryTemplatesClient.DownloadGalleryTemplateFile(
                Identity,
                string.IsNullOrEmpty(Path) ? System.IO.Path.Combine(CurrentPath(), Identity) : this.TryResolvePath(Path),
                Force,
                ConfirmAction);

            WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path));
        }
Beispiel #6
0
        public override void ExecuteCmdlet()
        {
            try
            {
                ResourceIdentifier resourceIdentifier = (ResourceId != null)
                    ? new ResourceIdentifier(ResourceId)
                    : null;

                ResourceGroupName = ResourceGroupName ?? resourceIdentifier.ResourceGroupName;
                Name = Name ?? ResourceIdUtility.GetResourceName(ResourceId);

                // Get the template spec version model from the SDK:
                TemplateSpecVersion specificVersion =
                    TemplateSpecsSdkClient.TemplateSpecsClient.TemplateSpecVersions.Get(
                        ResourceGroupName,
                        Name,
                        Version
                        );

                // Get the parent template spec from the SDK. We do this because we want to retrieve the
                // template spec name with its proper casing for naming our main template output file (the
                // Name parameter may have mismatched casing):
                TemplateSpec parentTemplateSpec =
                    TemplateSpecsSdkClient.TemplateSpecsClient.TemplateSpecs.Get(ResourceGroupName, Name);

                PackagedTemplate packagedTemplate = new PackagedTemplate(specificVersion);

                // TODO: Handle overwriting prompts...

                // Ensure our output path is resolved based on the current powershell working
                // directory instead of the current process directory:
                OutputFolder = ResolveUserPath(OutputFolder);

                string mainTemplateFileName     = $"{parentTemplateSpec.Name}.{specificVersion.Name}.json";
                string uiFormDefinitionFileName = $"{parentTemplateSpec.Name}.{specificVersion.Name}.uiformdefinition.json";
                string fullRootTemplateFilePath = Path.GetFullPath(
                    Path.Combine(OutputFolder, mainTemplateFileName)
                    );

                if (ShouldProcess(specificVersion.Id, $"Export to '{fullRootTemplateFilePath}'"))
                {
                    TemplateSpecPackagingEngine.Unpack(
                        packagedTemplate, OutputFolder, mainTemplateFileName, uiFormDefinitionFileName);
                }

                WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", fullRootTemplateFilePath));
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }
        /// <summary>
        /// Converts a <see cref="Resource{JToken}"/> object into a <see cref="PSObject"/> object.
        /// </summary>
        /// <param name="resource">The <see cref="Resource{JToken}"/> object.</param>
        internal static PSObject ToPsObject(this Resource <JToken> resource)
        {
            var resourceType = string.IsNullOrEmpty(resource.Id)
                ? null
                : ResourceIdUtility.GetResourceType(resource.Id);

            var extensionResourceType = string.IsNullOrEmpty(resource.Id)
                ? null
                : ResourceIdUtility.GetExtensionResourceType(resource.Id);

            var objectDefinition = new Dictionary <string, object>
            {
                { "Name", resource.Name },
                { "ResourceId", string.IsNullOrEmpty(resource.Id) ? null : resource.Id },
                { "ResourceName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceName(resource.Id) },
                { "ResourceType", resourceType },
                { "ExtensionResourceName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetExtensionResourceName(resource.Id) },
                { "ExtensionResourceType", extensionResourceType },
                { "Kind", resource.Kind },
                { "ResourceGroupName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceGroupName(resource.Id) },
                { "Location", resource.Location },
                { "SubscriptionId", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetSubscriptionId(resource.Id) },
                { "Tags", TagsHelper.GetTagsHashtable(resource.Tags) },
                { "Plan", resource.Plan.ToJToken().ToPsObject() },
                { "Properties", ResourceExtensions.GetProperties(resource) },
                { "CreatedTime", resource.CreatedTime },
                { "ChangedTime", resource.ChangedTime },
                { "ETag", resource.ETag },
                { "Sku", resource.Sku.ToJToken().ToPsObject() },
                { "Zones", resource.Zones },
            };

            var resourceTypeName = resourceType == null && extensionResourceType == null
                ? null
                : (resourceType + extensionResourceType).Replace('/', '.');

            var psObject =
                PowerShellUtilities.ConstructPSObject(
                    resourceTypeName,
                    objectDefinition.Where(kvp => kvp.Value != null).SelectManyArray(kvp => new[] { kvp.Key, kvp.Value }));

            psObject.TypeNames.Add(Constants.MicrosoftAzureResource);
            return(psObject);
        }
Beispiel #8
0
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        protected override void OnProcessRecord()
        {
            base.OnProcessRecord();
            if (ShouldProcess(DeploymentName, VerbsData.Save))
            {
                var resourceId = this.GetResourceId();

                var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result;

                var operationResult = this.GetResourcesClient()
                                      .InvokeActionOnResource <JObject>(
                    resourceId: resourceId,
                    action: Constants.ExportTemplate,
                    apiVersion: apiVersion,
                    cancellationToken: this.CancellationToken.Value)
                                      .Result;

                var managementUri = this.GetResourcesClient()
                                    .GetResourceManagementRequestUri(
                    resourceId: resourceId,
                    apiVersion: apiVersion,
                    action: Constants.ExportTemplate);

                var activity     = string.Format("POST {0}", managementUri.PathAndQuery);
                var resultString = this.GetLongRunningOperationTracker(activityName: activity,
                                                                       isResourceCreateOrUpdate: false)
                                   .WaitOnOperation(operationResult: operationResult);

                var template = JToken.FromObject(JObject.Parse(resultString)["template"]);

                string path = FileUtility.SaveTemplateFile(
                    templateName: this.DeploymentName,
                    contents: template.ToString(),
                    outputPath:
                    string.IsNullOrEmpty(this.Path)
                            ? System.IO.Path.Combine(CurrentPath(), this.DeploymentName)
                            : this.TryResolvePath(this.Path),
                    overwrite: this.Force,
                    shouldContinue: ShouldContinue);

                WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path));
            }
        }
Beispiel #9
0
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        protected override void OnProcessRecord()
        {
            base.OnProcessRecord();
            if (ShouldProcess(DeploymentName, VerbsData.Save))
            {
                var template = ResourceManagerSdkClient.GetDeploymentTemplateAtResourceGroup(ResourceGroupName, DeploymentName);

                string path = FileUtility.SaveTemplateFile(
                    templateName: this.DeploymentName,
                    contents: template.ToString(),
                    outputPath:
                    string.IsNullOrEmpty(this.Path)
                            ? System.IO.Path.Combine(CurrentPath(), this.DeploymentName)
                            : this.TryResolvePath(this.Path),
                    overwrite: this.Force,
                    shouldContinue: ShouldContinue);

                WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path));
            }
        }
        internal static PSObject ConstructPolicyOutputPSObject <T>(IDictionary <string, T> sharedAccessPolicies, string policyName)
        {
            if (!(typeof(T) == typeof(SharedAccessTablePolicy) ||
                  typeof(T) == typeof(SharedAccessBlobPolicy) ||
                  (typeof(T) == typeof(SharedAccessQueuePolicy))))
            {
                throw new ArgumentException(Resources.InvalidAccessPolicyType);
            }

            return(PowerShellUtilities.ConstructPSObject(
                       typeof(PSObject).FullName,
                       "Policy",
                       policyName,
                       "Permissions",
                       (sharedAccessPolicies[policyName]).GetType().GetProperty("Permissions").GetValue(sharedAccessPolicies[policyName]),
                       "StartTime",
                       (sharedAccessPolicies[policyName]).GetType().GetProperty("SharedAccessStartTime").GetValue(sharedAccessPolicies[policyName]),
                       "ExpiryTime",
                       (sharedAccessPolicies[policyName]).GetType().GetProperty("SharedAccessExpiryTime").GetValue(sharedAccessPolicies[policyName])));
        }
        internal static PSObject ConstructPolicyOutputPSObject <T>(T identifier)
        {
            if (!(typeof(T) == typeof(BlobSignedIdentifier) ||
                  typeof(T) == typeof(ShareSignedIdentifier) ||
                  (typeof(T) == typeof(QueueSignedIdentifier))))
            {
                throw new ArgumentException("Access policy type is invalid, only BlobSignedIdentifier, ShareSignedIdentifier, and QueueSignedIdentifier are supported.");
            }

            var accessPolicy = (identifier).GetType().GetProperty("AccessPolicy").GetValue(identifier);

            return(PowerShellUtilities.ConstructPSObject(
                       typeof(PSObject).FullName,
                       "Policy",
                       (identifier).GetType().GetProperty("Id").GetValue(identifier),
                       "Permissions",
                       (accessPolicy).GetType().GetProperty("Permissions").GetValue(accessPolicy) is null ? null: (accessPolicy).GetType().GetProperty("Permissions").GetValue(accessPolicy).ToString(),
                       "StartTime",
                       (accessPolicy).GetType().GetProperty("PolicyStartsOn").GetValue(accessPolicy),
                       "ExpiryTime",
                       (accessPolicy).GetType().GetProperty("PolicyExpiresOn").GetValue(accessPolicy)));
        }
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        protected override void OnProcessRecord()
        {
            base.OnProcessRecord();
            string contents;

            if (ShouldProcess(ResourceGroupName, VerbsData.Export))
            {
                var resourceGroupId = this.GetResourceGroupId();

                if (this.IsParameterBound(c => c.ApiVersion))
                {
                    var parameters = new Management.ResourceManager.Models.ExportTemplateRequest
                    {
                        Resources = this.GetResourcesFilter(resourceGroupId: resourceGroupId),
                        Options   = this.GetExportOptions(),
                    };

                    var exportedTemplate = ResourceManagerSdkClient.ExportResourceGroup(ResourceGroupName, parameters);

                    var template = exportedTemplate.Template;
                    contents = template.ToString();

                    var error = exportedTemplate.Error;

                    if (error != null)
                    {
                        WriteWarning(string.Format("{0} : {1}", error.Code, error.Message));
                        foreach (var detail in error.Details)
                        {
                            WriteWarning(string.Format("{0} : {1}", detail.Code, detail.Message));
                        }
                    }
                }
                else
                {
                    var parameters = new ExportTemplateParameters
                    {
                        Resources = this.GetResourcesFilter(resourceGroupId: resourceGroupId),
                        Options   = this.GetExportOptions(),
                    };
                    var apiVersion      = this.ApiVersion ?? DefaultApiVersion;
                    var operationResult = this.GetResourcesClient()
                                          .InvokeActionOnResource <JObject>(
                        resourceId: resourceGroupId,
                        action: Constants.ExportTemplate,
                        parameters: parameters.ToJToken(),
                        apiVersion: apiVersion,
                        cancellationToken: this.CancellationToken.Value)
                                          .Result;

                    var managementUri = this.GetResourcesClient()
                                        .GetResourceManagementRequestUri(
                        resourceId: resourceGroupId,
                        apiVersion: apiVersion,
                        action: Constants.ExportTemplate);

                    var activity     = string.Format("POST {0}", managementUri.PathAndQuery);
                    var resultString = this.GetLongRunningOperationTracker(activityName: activity,
                                                                           isResourceCreateOrUpdate: false)
                                       .WaitOnOperation(operationResult: operationResult);

                    var template = JToken.FromObject(JObject.Parse(resultString)["template"]);
                    contents = template.ToString();

                    if (JObject.Parse(resultString)["error"] != null)
                    {
                        if (JObject.Parse(resultString)["error"].TryConvertTo(out ExtendedErrorInfo error))
                        {
                            WriteWarning(string.Format("{0} : {1}", error.Code, error.Message));
                            foreach (var detail in error.Details)
                            {
                                WriteWarning(string.Format("{0} : {1}", detail.Code, detail.Message));
                            }
                        }
                    }
                }

                string path = FileUtility.SaveTemplateFile(
                    templateName: this.ResourceGroupName,
                    contents: contents,
                    outputPath:
                    string.IsNullOrEmpty(this.Path)
                            ? System.IO.Path.Combine(CurrentPath(), this.ResourceGroupName)
                            : this.TryResolvePath(this.Path),
                    overwrite: Force.IsPresent,
                    shouldContinue: ShouldContinue);

                WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", path));
            }
        }