/// <summary>
        /// Utility method to test Patch request for Tags Operation within tracked resources and proxy resources, including Replace|Merge|Delete operations
        /// </summary>
        private void UpdateTagsTest(MockContext context, string resourceScope = "")
        {
            var handler = new RecordedDelegatingHandler()
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            var client            = GetResourceManagementClient(context, handler);
            var subscriptionScope = "/subscriptions/" + client.SubscriptionId;

            resourceScope = subscriptionScope + resourceScope;

            // using Tags.CreateOrUpdateAtScope to create two tags initially
            var tagsResource = new TagsResource(new Tags(
                                                    new Dictionary <string, string> {
                { "tagKey1", "tagValue1" },
                { "tagKey2", "tagValue2" }
            }
                                                    ));

            client.Tags.CreateOrUpdateAtScope(resourceScope, tagsResource);
            Thread.Sleep(3000);

            var putTags = new Tags(
                new Dictionary <string, string> {
                { "tagKey1", "tagValue3" },
                { "tagKey3", "tagValue3" }
            });

            { // test for Merge operation
                var tagPatchRequest = new TagsPatchResource("Merge", putTags);
                var patchResponse   = client.Tags.UpdateAtScope(resourceScope, tagPatchRequest);

                var expectedResponse = new TagsResource(new Tags(
                                                            new Dictionary <string, string> {
                    { "tagKey1", "tagValue3" },
                    { "tagKey2", "tagValue2" },
                    { "tagKey3", "tagValue3" }
                }
                                                            ));
                patchResponse.Properties.TagsProperty.Should().HaveCount(expectedResponse.Properties.TagsProperty.Count);
                this.CompareTagsResource(expectedResponse, patchResponse).Should().BeTrue();
            }

            { // test for Replace operation
                var tagPatchRequest = new TagsPatchResource("Replace", putTags);
                var patchResponse   = client.Tags.UpdateAtScope(resourceScope, tagPatchRequest);

                var expectedResponse = new TagsResource(putTags);
                patchResponse.Properties.TagsProperty.Should().HaveCount(expectedResponse.Properties.TagsProperty.Count);
                this.CompareTagsResource(expectedResponse, patchResponse).Should().BeTrue();
            }

            { // test for Delete operation
                var tagPatchRequest = new TagsPatchResource("Delete", putTags);
                var patchResponse   = client.Tags.UpdateAtScope(resourceScope, tagPatchRequest);
                patchResponse.Properties.TagsProperty.Should().BeEmpty();
            }
        }
Esempio n. 2
0
        static async Task Main(string[] args)
        {
            var resourceId = $"/subscriptions/{DefaultSubscription}/resourceGroups/XXX";

            var credentials = await ApplicationTokenProvider.LoginSilentAsync(
                TenantDomain,
                ClientId,
                ClientSecret);

            using (var client = new ResourceManagementClient(credentials))
            {
                client.SubscriptionId = DefaultSubscription;

                try
                {
                    // Create Predefined Tag name and value. Predefined Tags are not automatically
                    // applied to existing or newly created sub resources.
                    // Requires contributor permission at subscription level
                    //var t = await client.Tags.CreateOrUpdateAsync("PredefinedTag1");
                    //await client.Tags.CreateOrUpdateValueAsync("PredefinedTag1", "DefaultValue");

                    // Tags operations, only require Tags Contributor
                    // 1. Create/Update Tags on subscription,
                    var tags = new TagsResource(
                        new Tags(
                            new Dictionary <string, string>
                    {
                        { "environment", DateTimeOffset.Now.ToString() },
                        { "department", DateTimeOffset.Now.ToString() },
                        { "PredefinedTag1", "override" }
                    }));
                    var result = await client.Tags.CreateOrUpdateAtScopeAsync(resourceId, tags);

                    // 2. Update Tags on resource
                    var patchTags = new TagsPatchResource(
                        "Merge", // Replace, Delete
                        new Tags(
                            new Dictionary <string, string>
                    {
                        { "environment", DateTimeOffset.Now.ToString() },
                        { "department", DateTimeOffset.Now.ToString() },
                        { "newTag", DateTimeOffset.Now.ToString() },
                    }));

                    result = await client.Tags.UpdateAtScopeAsync(resourceId, patchTags);

                    // 3. Delete all Tags on the resource
                    await client.Tags.DeleteAtScopeAsync(resourceId);
                }
                catch (Exception e)
                {
                    System.Console.WriteLine(e.Message);
                }
            }
        }
Esempio n. 3
0
 public virtual Response <TagsResource> UpdateAtScope(string scope, TagsPatchResource parameters, CancellationToken cancellationToken = default)
 {
     using var scope0 = _clientDiagnostics.CreateScope("TagsClient.UpdateAtScope");
     scope0.Start();
     try
     {
         return(RestClient.UpdateAtScope(scope, parameters, cancellationToken));
     }
     catch (Exception e)
     {
         scope0.Failed(e);
         throw;
     }
 }
Esempio n. 4
0
        public static void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            log.LogInformation(eventGridEvent.Data.ToString());

            var dataJObject = (Newtonsoft.Json.Linq.JObject)eventGridEvent.Data;

            var data        = dataJObject.ToObject <CustomResourceWriteSuccessData>();
            var resourceUri = data.ResourceUri;

            log.LogInformation(resourceUri);

            //Update tags
            var resourceClient = new ResourcesManagementClient(data.SubscriptionId, new DefaultAzureCredential());
            var tags           = new TagsPatchResource
            {
                Operation  = TagsPatchResourceOperation.Merge,
                Properties = new Tags()
            };

            log.LogInformation("Add/Update Tag: ModifiedDate");
            tags.Properties.TagsValue.Add("ModifiedDate", DateTimeOffset.Now.ToString());

            log.LogInformation("Add/Update Tag: ModifiedBy");
            tags.Properties.TagsValue.Add("ModifiedBy", data.Claims["name"]);
            tags.Properties.TagsValue.Add("ModifiedById", data.Claims["http://schemas.microsoft.com/identity/claims/objectidentifier"]);

            //Add created by if they are not there
            log.LogInformation("Getting Current Tags");
            var currentTags = resourceClient.Tags.GetAtScope(resourceUri);

            if (!currentTags.Value.Properties.TagsValue.ContainsKey("CreatedBy"))
            {
                log.LogInformation("Add Tag: CreatedBy");
                tags.Properties.TagsValue.Add("CreatedBy", data.Claims["name"]);
                tags.Properties.TagsValue.Add("CreatedById", data.Claims["http://schemas.microsoft.com/identity/claims/objectidentifier"]);
            }
            if (!currentTags.Value.Properties.TagsValue.ContainsKey("CreatedDate"))
            {
                log.LogInformation("Add Tag: CreatedDate");
                tags.Properties.TagsValue.Add("CreatedDate", DateTimeOffset.Now.ToString());
            }

            log.LogInformation("Saving Tags");
            resourceClient.Tags.UpdateAtScope(resourceUri, tags);
        }
Esempio n. 5
0
        /// <summary>
        /// Utility method to test Patch request for Tags Operation within tracked resources and proxy resources, including Replace|Merge|Delete operations
        /// </summary>
        private async void UpdateTagsTest(string resourceScope = "")
        {
            var subscriptionScope = "/subscriptions/" + TestEnvironment.SubscriptionId;

            resourceScope = subscriptionScope + resourceScope;

            // using Tags.CreateOrUpdateAtScope to create two tags initially
            var tagsResource = new TagsResource(new Tags()
            {
                TagsValue = new Dictionary <string, string> {
                    { "tagKey1", "tagValue1" },
                    { "tagKey2", "tagValue2" }
                }
            }
                                                );
            await TagsOperations.CreateOrUpdateAtScopeAsync(resourceScope, tagsResource);

            SleepInTest(3 * 1000);

            var putTags = new Tags()
            {
                TagsValue = new Dictionary <string, string> {
                    { "tagKey1", "tagValue3" },
                    { "tagKey3", "tagValue3" }
                }
            };

            { // test for Merge operation
                var tagPatchRequest = new TagsPatchResource()
                {
                    Operation = TagsPatchResourceOperation.Merge, Properties = putTags
                };
                var patchResponse = (await TagsOperations.UpdateAtScopeAsync(resourceScope, tagPatchRequest)).Value;

                var expectedResponse = new TagsResource(new Tags()
                {
                    TagsValue = new Dictionary <string, string> {
                        { "tagKey1", "tagValue3" },
                        { "tagKey2", "tagValue2" },
                        { "tagKey3", "tagValue3" }
                    }
                }
                                                        );
                Assert.AreEqual(patchResponse.Properties.TagsValue.Count(), expectedResponse.Properties.TagsValue.Count());
                Assert.IsTrue(this.CompareTagsResource(expectedResponse, patchResponse));
            }

            { // test for Replace operation
                var tagPatchRequest = new TagsPatchResource()
                {
                    Operation = TagsPatchResourceOperation.Replace, Properties = putTags
                };
                var patchResponse = (await TagsOperations.UpdateAtScopeAsync(resourceScope, tagPatchRequest)).Value;

                var expectedResponse = new TagsResource(putTags);
                Assert.AreEqual(patchResponse.Properties.TagsValue.Count(), expectedResponse.Properties.TagsValue.Count());
                Assert.IsTrue(this.CompareTagsResource(expectedResponse, patchResponse));
            }

            { // test for Delete operation
                var tagPatchRequest = new TagsPatchResource()
                {
                    Operation = TagsPatchResourceOperation.Delete, Properties = putTags
                };
                var patchResponse = (await TagsOperations.UpdateAtScopeAsync(resourceScope, tagPatchRequest)).Value;
                Assert.IsEmpty(patchResponse.Properties.TagsValue);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Selectively updates the set of tags on a resource or subscription.
        /// </summary>
        /// <remarks>
        /// This operation allows replacing, merging or selectively deleting tags on
        /// the specified resource or subscription. The specified entity can have a
        /// maximum of 50 tags at the end of the operation. The 'replace' option
        /// replaces the entire set of existing tags with a new set. The 'merge' option
        /// allows adding tags with new names and updating the values of tags with
        /// existing names. The 'delete' option allows selectively deleting tags based
        /// on given names or name/value pairs.
        /// </remarks>
        /// <param name="scope"></param>
        /// <param name="operation"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public PSTagResource UpdateTagAtScope(string scope, TagPatchOperation operation, IDictionary <string, string> parameters)
        {
            var tagPatchResource = new TagsPatchResource(operation: operation.ToString(), properties: new SDKTagsObject(parameters));

            return(ResourceManagementClient.Tags.UpdateAtScope(scope: scope, parameters: tagPatchResource)?.ToPSTagResource());
        }
Esempio n. 7
0
 public virtual async Task <Response <TagsResource> > UpdateAtScopeAsync(string scope, TagsPatchResource parameters, CancellationToken cancellationToken = default)
 {
     using var scope0 = _clientDiagnostics.CreateScope("TagsOperations.UpdateAtScope");
     scope0.Start();
     try
     {
         return(await RestClient.UpdateAtScopeAsync(scope, parameters, cancellationToken).ConfigureAwait(false));
     }
     catch (Exception e)
     {
         scope0.Failed(e);
         throw;
     }
 }
 /// <summary>
 /// Selectively updates the set of tags on a resource or subscription.
 /// </summary>
 /// <remarks>
 /// This operation allows replacing, merging or selectively deleting tags on
 /// the specified resource or subscription. The specified entity can have a
 /// maximum of 50 tags at the end of the operation. The 'replace' option
 /// replaces the entire set of existing tags with a new set. The 'merge' option
 /// allows adding tags with new names and updating the values of tags with
 /// existing names. The 'delete' option allows selectively deleting tags based
 /// on given names or name/value pairs.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='scope'>
 /// The resource scope.
 /// </param>
 /// <param name='parameters'>
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <TagsResource> UpdateAtScopeAsync(this ITagsOperations operations, string scope, TagsPatchResource parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.UpdateAtScopeWithHttpMessagesAsync(scope, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Selectively updates the set of tags on a resource or subscription.
 /// </summary>
 /// <remarks>
 /// This operation allows replacing, merging or selectively deleting tags on
 /// the specified resource or subscription. The specified entity can have a
 /// maximum of 50 tags at the end of the operation. The 'replace' option
 /// replaces the entire set of existing tags with a new set. The 'merge' option
 /// allows adding tags with new names and updating the values of tags with
 /// existing names. The 'delete' option allows selectively deleting tags based
 /// on given names or name/value pairs.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='scope'>
 /// The resource scope.
 /// </param>
 /// <param name='parameters'>
 /// </param>
 public static TagsResource UpdateAtScope(this ITagsOperations operations, string scope, TagsPatchResource parameters)
 {
     return(operations.UpdateAtScopeAsync(scope, parameters).GetAwaiter().GetResult());
 }