Ejemplo n.º 1
0
        /// <inheritdoc/>
        public async Task <ClaimPermissions> UpdateAsync(ClaimPermissions claimPermissions)
        {
            if (claimPermissions is null)
            {
                throw new ArgumentNullException(nameof(claimPermissions));
            }

            if (string.IsNullOrWhiteSpace(claimPermissions.ETag))
            {
                throw new ArgumentException(
                          "There is no ETag on this ClaimPermissions. Updates are not safe without an ETag.");
            }

            BlobClient blob = this.Container.GetBlobClient(claimPermissions.Id);
            string     serializedPermissions    = JsonConvert.SerializeObject(claimPermissions, this.serializerSettings);
            Response <BlobContentInfo> response = await blob.UploadAsync(
                BinaryData.FromString(serializedPermissions),
                new BlobUploadOptions { Conditions = new BlobRequestConditions {
                                            IfMatch = new ETag(claimPermissions.ETag)
                                        } })
                                                  .ConfigureAwait(false);

            claimPermissions.ETag = response.Value.ETag.ToString("G");
            return(claimPermissions);
        }
        public void SampleToStream()
        {
            using MemoryStream ms = new();

#if SNIPPET
            KeyVaultKey key = null;
#endif

            #region Snippet:KeyReleasePolicy_ToStream
#if SNIPPET
            KeyReleasePolicy policy = key.Properties.ReleasePolicy;
#else
            KeyReleasePolicy policy = new KeyReleasePolicy(BinaryData.FromString("test"));
#endif
            using (Stream stream = policy.EncodedPolicy.ToStream())
            {
#if SNIPPET
                using FileStream file = File.OpenWrite("policy.dat");
#else
                using Stream file = ms;
#endif
                stream.CopyTo(file);
            }
            #endregion

            Assert.AreEqual("test", Encoding.UTF8.GetString(ms.ToArray()));
        }
Ejemplo n.º 3
0
        public void CanConvertArrays()
        {
            var expected = File.ReadAllText(GetFileName("PropertiesWithArrays.json")).TrimEnd();
            var model    = BinaryData.FromString(expected);

            var properties = model.ToDictionaryFromJson();

            Assert.IsTrue(AllValuesAreType(typeof(string), properties["stringArray"]));
            Assert.IsTrue(AllValuesAreType(typeof(string), properties["dateTimeArray"]));
            Assert.IsTrue(AllValuesAreType(typeof(int), properties["intArray"]));
            Assert.IsTrue(AllValuesAreType(typeof(long), properties["longArray"]));
            Assert.IsTrue(AllValuesAreType(typeof(double), properties["doubleArray"]));
            Assert.IsTrue(AllValuesAreType(typeof(bool), properties["boolArray"]));
            foreach (var item in properties["nullArray"] as object[])
            {
                Assert.IsNull(item);
            }
            var mixList = properties["mixedNullArray"] as object[];

            for (int i = 0; i < 2; i++)
            {
                if (i == 0)
                {
                    Assert.IsNull(mixList[i]);
                }
                else
                {
                    Assert.IsNotNull(mixList[i]);
                }
            }
            Assert.AreEqual(expected, GetSerializedString(model));
        }
Ejemplo n.º 4
0
        public void BatchSetAccessTierCool()
        {
            string connectionString = ConnectionString;
            string containerName    = Randomize("sample-container");

            #region Snippet:SampleSnippetsBatch_AccessTier
            // Get a connection string to our Azure Storage account.
            //@@ string connectionString = "<connection_string>";
            //@@ string containerName = "sample-container";

            // Get a reference to a container named "sample-container" and then create it
            BlobServiceClient   service   = new BlobServiceClient(connectionString);
            BlobContainerClient container = service.GetBlobContainerClient(containerName);
            container.Create();
            // Create three blobs named "foo", "bar", and "baz"
            BlobClient foo = container.GetBlobClient("foo");
            BlobClient bar = container.GetBlobClient("bar");
            BlobClient baz = container.GetBlobClient("baz");
            foo.Upload(BinaryData.FromString("Foo!"));
            bar.Upload(BinaryData.FromString("Bar!"));
            baz.Upload(BinaryData.FromString("Baz!"));

            // Set the access tier for all three blobs at once
            BlobBatchClient batch = service.GetBlobBatchClient();
            batch.SetBlobsAccessTier(new Uri[] { foo.Uri, bar.Uri, baz.Uri }, AccessTier.Cool);
            #endregion

            foreach (BlobItem blob in container.GetBlobs())
            {
                Assert.AreEqual(AccessTier.Cool, blob.Properties.AccessTier);
            }
            // Clean up after the test when we're finished
        }
Ejemplo n.º 5
0
        internal static ColumnTransformer DeserializeColumnTransformer(JsonElement element)
        {
            Optional <IList <string> > fields     = default;
            Optional <BinaryData>      parameters = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("fields"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        fields = null;
                        continue;
                    }
                    List <string> array = new List <string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    fields = array;
                    continue;
                }
                if (property.NameEquals("parameters"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        parameters = null;
                        continue;
                    }
                    parameters = BinaryData.FromString(property.Value.GetRawText());
                    continue;
                }
            }
            return(new ColumnTransformer(Optional.ToList(fields), parameters.Value));
        }
 public static void BindToICollectorBinaryData(
     [Queue(OutputQueueName)] ICollector <BinaryData> output)
 {
     output.Add(BinaryData.FromString("test1"));
     output.Add(BinaryData.FromString("test2"));
     output.Add(BinaryData.FromString("test3"));
 }
Ejemplo n.º 7
0
        public void BatchErrors()
        {
            string connectionString = ConnectionString;
            string containerName    = Randomize("sample-container");

            #region Snippet:SampleSnippetsBatch_Troubleshooting
            // Get a connection string to our Azure Storage account.
            //@@ string connectionString = "<connection_string>";
            //@@ string containerName = "sample-container";

            // Get a reference to a container named "sample-container" and then create it
            BlobServiceClient   service   = new BlobServiceClient(connectionString);
            BlobContainerClient container = service.GetBlobContainerClient(containerName);
            container.Create();

            // Create a blob named "valid"
            BlobClient valid = container.GetBlobClient("valid");
            valid.Upload(BinaryData.FromString("Valid!"));

            // Get a reference to a blob named "invalid", but never create it
            BlobClient invalid = container.GetBlobClient("invalid");

            // Delete both blobs at the same time
            BlobBatchClient batch = service.GetBlobBatchClient();
            try
            {
                batch.DeleteBlobs(new Uri[] { valid.Uri, invalid.Uri });
            }
            catch (AggregateException)
            {
                // An aggregate exception is thrown for all the individual failures
                // Check ex.InnerExceptions for RequestFailedException instances
            }
            #endregion
        }
Ejemplo n.º 8
0
        internal static KeyValuePairStringObject DeserializeKeyValuePairStringObject(JsonElement element)
        {
            Optional <string>     key   = default;
            Optional <BinaryData> value = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("key"))
                {
                    key = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("value"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    value = BinaryData.FromString(property.Value.GetRawText());
                    continue;
                }
            }
            return(new KeyValuePairStringObject(key.Value, value.Value));
        }
        private async Task UploadBlobAsync(string containerName, string blobName, string blobContent, bool isRetry = false)
        {
            BlobContainerClient containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
            BlobClient          blobClient      = containerClient.GetBlobClient(blobName);

            try
            {
                await blobClient.UploadAsync(
                    BinaryData.FromString(blobContent),
                    new BlobUploadOptions
                {
                    HttpHeaders = new BlobHttpHeaders
                    {
                        ContentType = MediaTypeNames.Application.Json
                    }
                });
            }
            catch (RequestFailedException ex) when(ex.ErrorCode == BlobErrorCode.ContainerNotFound)
            {
                if (!isRetry)
                {
                    await containerClient.CreateAsync();
                    await UploadBlobAsync(containerName, blobName, blobContent, isRetry : true);
                }
            }
        }
Ejemplo n.º 10
0
        public void AuthWithSasCredential()
        {
            //setup blob
            string containerName = Randomize("sample-container");
            string blobName      = Randomize("sample-file");
            var    container     = new BlobContainerClient(ConnectionString, containerName);

            try
            {
                container.Create();
                BlobClient blobClient = container.GetBlobClient(blobName);
                blobClient.Upload(BinaryData.FromString("hello world"));

                // build SAS URI for sample
                Uri sasUri = blobClient.GenerateSasUri(BlobSasPermissions.All, DateTimeOffset.UtcNow.AddHours(1));

                #region Snippet:SampleSnippetsBlobMigration_SasUri
                BlobClient blob = new BlobClient(sasUri);
                #endregion

                var stream = new MemoryStream();
                blob.DownloadTo(stream);
                Assert.Greater(stream.Length, 0);
            }
            finally
            {
                container.Delete();
            }
        }
Ejemplo n.º 11
0
        public async Task BatchSetAccessTierAsync()
        {
            // Get a connection string to our Azure Storage account.
            string connectionString = ConnectionString;

            // Get a reference to a container named "sample-container" and then create it
            BlobServiceClient   service   = new BlobServiceClient(connectionString);
            BlobContainerClient container = service.GetBlobContainerClient(Randomize("sample-container"));
            await container.CreateAsync();

            try
            {
                // Create three blobs named "foo", "bar", and "baz"
                BlobClient foo = container.GetBlobClient("foo");
                BlobClient bar = container.GetBlobClient("bar");
                BlobClient baz = container.GetBlobClient("baz");
                await foo.UploadAsync(BinaryData.FromString("Foo!"));

                await bar.UploadAsync(BinaryData.FromString("Bar!"));

                await baz.UploadAsync(BinaryData.FromString("Baz!"));

                // Set the access tier for all three blobs at once
                BlobBatchClient batch = service.GetBlobBatchClient();
                await batch.SetBlobsAccessTierAsync(new Uri[] { foo.Uri, bar.Uri, baz.Uri }, AccessTier.Cool);
            }
            finally
            {
                // Clean up after the test when we're finished
                await container.DeleteAsync();
            }
        }
Ejemplo n.º 12
0
        public async Task MaximumExecutionTime()
        {
            string connectionString = this.ConnectionString;

            string data = "hello world";

            //setup blob
            string containerName   = Randomize("sample-container");
            string blobName        = Randomize("sample-file");
            var    containerClient = new BlobContainerClient(ConnectionString, containerName);

            try
            {
                await containerClient.CreateIfNotExistsAsync();

                await containerClient.GetBlobClient(blobName).UploadAsync(BinaryData.FromString(data));

                #region Snippet:SampleSnippetsBlobMigration_MaximumExecutionTime
                BlobClient blobClient = containerClient.GetBlobClient(blobName);
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(30));
                Stream targetStream = new MemoryStream();
                await blobClient.DownloadToAsync(targetStream, cancellationTokenSource.Token);

                #endregion
            }
            finally
            {
                await containerClient.DeleteIfExistsAsync();
            }

            Assert.Pass();
        }
Ejemplo n.º 13
0
        internal static DataPolicyManifestEffect DeserializeDataPolicyManifestEffect(JsonElement element)
        {
            Optional <string>     name          = default;
            Optional <BinaryData> detailsSchema = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("detailsSchema"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    detailsSchema = BinaryData.FromString(property.Value.GetRawText());
                    continue;
                }
            }
            return(new DataPolicyManifestEffect(name.Value, detailsSchema.Value));
        }
        public async Task BlobTrigger_ProvidesBlobTriggerBindingData()
        {
            // Arrange
            var container = CreateContainer(blobServiceClient, ContainerName);
            var blob      = container.GetBlobClient(BlobName);

            var metadata = new Dictionary <string, string>()
            {
                { "foo", "bar" }
            };

            await blob.UploadAsync(BinaryData.FromString("ignore"),
                                   new BlobUploadOptions
            {
                Metadata = metadata,
            });

            // Act
            BlobBaseClient result = await RunTriggerAsync <BlobBaseClient>(typeof(BlobTriggerBindingDataProgram),
                                                                           (s) => BlobTriggerBindingDataProgram.TaskSource = s);

            // Assert
            Assert.AreEqual(blob.Uri, result.Uri);
            Assert.AreEqual($"{ContainerName}/{BlobName}", BlobTriggerBindingDataProgram.BlobTrigger);
            Assert.AreEqual(blob.Uri, BlobTriggerBindingDataProgram.Uri);
            Assert.AreEqual(metadata, BlobTriggerBindingDataProgram.Metadata);
            Assert.AreEqual(BlobType.Block, BlobTriggerBindingDataProgram.Properties.BlobType);
        }
Ejemplo n.º 15
0
    public async virtual Task <ArmDeploymentPropertiesExtended> DeployLocalTemplateAsync <TParameters>(
        string templateName,
        TParameters parameters,
        ResourceIdentifier scope,
        CancellationToken cancellationToken)
    {
        var armClient = new ArmClient(_credential);
        var rgClient  = armClient.GetResourceGroupResource(scope);

        var template = File.ReadAllText(Path.Combine(Assembly.GetExecutingAssembly().Location, "..", templateName + ".json"));
        var props    = new ArmDeploymentProperties(ArmDeploymentMode.Incremental)
        {
            Template   = BinaryData.FromString(template),
            Parameters = BinaryData.FromObjectAsJson(parameters),
        };

        _logger.LogInformation("Beginning deployment of {}.json", templateName);
        var deploymentOperation = await rgClient.GetArmDeployments().CreateOrUpdateAsync(WaitUntil.Completed, templateName, new ArmDeploymentContent(props), cancellationToken);

        var deployment = await deploymentOperation.WaitForCompletionAsync(cancellationToken);

        var result = deployment.Value.Data.Properties;

        if (result.ProvisioningState != ResourcesProvisioningState.Succeeded)
        {
            throw new Exception();
        }
        return(result);
    }
Ejemplo n.º 16
0
        public async Task AuthWithConnectionStringDirectToBlob()
        {
            // setup blob
            string containerName = Randomize("sample-container");
            string blobName      = Randomize("sample-file");
            var    container     = new BlobContainerClient(ConnectionString, containerName);

            try
            {
                await container.CreateAsync();

                await container.GetBlobClient(blobName).UploadAsync(BinaryData.FromString("hello world"));

                string connectionString = this.ConnectionString;

                #region Snippet:SampleSnippetsBlobMigration_ConnectionStringDirectBlob
                BlobClient blob = new BlobClient(connectionString, containerName, blobName);
                #endregion

                var stream = new MemoryStream();
                blob.DownloadTo(stream);
                Assert.Greater(stream.Length, 0);
            }
            finally
            {
                await container.DeleteAsync();
            }
        }
Ejemplo n.º 17
0
        internal static MetricAlertCriteria DeserializeMetricAlertCriteria(JsonElement element)
        {
            if (element.TryGetProperty("odata.type", out JsonElement discriminator))
            {
                switch (discriminator.GetString())
                {
                case "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria": return(MetricAlertMultipleResourceMultipleMetricCriteria.DeserializeMetricAlertMultipleResourceMultipleMetricCriteria(element));

                case "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria": return(MetricAlertSingleResourceMultipleMetricCriteria.DeserializeMetricAlertSingleResourceMultipleMetricCriteria(element));

                case "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria": return(WebtestLocationAvailabilityCriteria.DeserializeWebtestLocationAvailabilityCriteria(element));
                }
            }
            Odatatype odataType = default;
            IDictionary <string, BinaryData> additionalProperties           = default;
            Dictionary <string, BinaryData>  additionalPropertiesDictionary = new Dictionary <string, BinaryData>();

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("odata.type"))
                {
                    odataType = new Odatatype(property.Value.GetString());
                    continue;
                }
                additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText()));
            }
            additionalProperties = additionalPropertiesDictionary;
            return(new MetricAlertCriteria(odataType, additionalProperties));
        }
Ejemplo n.º 18
0
        public async Task DownloadBlobToStream()
        {
            string data = "hello world";

            //setup blob
            string containerName    = Randomize("sample-container");
            string blobName         = Randomize("sample-file");
            var    containerClient  = new BlobContainerClient(ConnectionString, containerName);
            string downloadFilePath = this.CreateTempPath();

            try
            {
                containerClient.Create();
                containerClient.GetBlobClient(blobName).Upload(BinaryData.FromString(data));

                #region Snippet:SampleSnippetsBlobMigration_DownloadBlobToStream
                BlobClient blobClient = containerClient.GetBlobClient(blobName);
                using (Stream target = File.OpenWrite(downloadFilePath))
                {
                    await blobClient.DownloadToAsync(target);
                }
                #endregion

                FileStream fs             = File.OpenRead(downloadFilePath);
                string     downloadedData = await new StreamReader(fs).ReadToEndAsync();
                fs.Close();

                Assert.AreEqual(data, downloadedData);
            }
            finally
            {
                await containerClient.DeleteIfExistsAsync();
            }
        }
        internal static ModelWithBinaryData DeserializeModelWithBinaryData(JsonElement element)
        {
            Optional <string>     a          = default;
            Optional <BinaryData> properties = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("a"))
                {
                    a = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    properties = BinaryData.FromString(property.Value.GetRawText());
                    continue;
                }
            }
            return(new ModelWithBinaryData(a.Value, properties.Value));
        }
Ejemplo n.º 20
0
        public async Task DownloadBlobText()
        {
            string data = "hello world";

            //setup blob
            string containerName   = Randomize("sample-container");
            string blobName        = Randomize("sample-file");
            var    containerClient = new BlobContainerClient(ConnectionString, containerName);

            try
            {
                containerClient.Create();
                containerClient.GetBlobClient(blobName).Upload(BinaryData.FromString(data));

                #region Snippet:SampleSnippetsBlobMigration_DownloadBlobText
                BlobClient         blobClient     = containerClient.GetBlobClient(blobName);
                BlobDownloadResult downloadResult = await blobClient.DownloadContentAsync();

                string downloadedData = downloadResult.Content.ToString();
                #endregion

                Assert.AreEqual(data, downloadedData);
            }
            finally
            {
                await containerClient.DeleteIfExistsAsync();
            }
        }
Ejemplo n.º 21
0
        public void BatchDelete()
        {
            string connectionString = ConnectionString;
            string containerName    = Randomize("sample-container");

            #region Snippet:SampleSnippetsBatch_DeleteBatch

            // Get a connection string to our Azure Storage account.
            //@@ string connectionString = "<connection_string>";
            //@@ string containerName = "sample-container";

            // Get a reference to a container named "sample-container" and then create it
            BlobServiceClient   service   = new BlobServiceClient(connectionString);
            BlobContainerClient container = service.GetBlobContainerClient(containerName);
            container.Create();

            // Create three blobs named "foo", "bar", and "baz"
            BlobClient foo = container.GetBlobClient("foo");
            BlobClient bar = container.GetBlobClient("bar");
            BlobClient baz = container.GetBlobClient("baz");
            foo.Upload(BinaryData.FromString("Foo!"));
            bar.Upload(BinaryData.FromString("Bar!"));
            baz.Upload(BinaryData.FromString("Baz!"));

            // Delete all three blobs at once
            BlobBatchClient batch = service.GetBlobBatchClient();
            batch.DeleteBlobs(new Uri[] { foo.Uri, bar.Uri, baz.Uri });
            #endregion

            Assert.AreEqual(0, container.GetBlobs().ToList().Count);
            // Clean up after we're finished
            container.Delete();
        }
Ejemplo n.º 22
0
        public async Task RetryPolicy()
        {
            string connectionString = this.ConnectionString;

            string data = "hello world";

            //setup blob
            string containerName   = Randomize("sample-container");
            string blobName        = Randomize("sample-file");
            var    containerClient = new BlobContainerClient(ConnectionString, containerName);
            await containerClient.GetBlobClient(blobName).UploadAsync(BinaryData.FromString(data));

            #region Snippet:SampleSnippetsBlobMigration_RetryPolicy
            BlobClientOptions blobClientOptions = new BlobClientOptions();
            blobClientOptions.Retry.Mode       = RetryMode.Exponential;
            blobClientOptions.Retry.Delay      = TimeSpan.FromSeconds(10);
            blobClientOptions.Retry.MaxRetries = 6;
            BlobServiceClient service      = new BlobServiceClient(connectionString, blobClientOptions);
            BlobClient        blobClient   = service.GetBlobContainerClient(containerName).GetBlobClient(blobName);
            Stream            targetStream = new MemoryStream();
            await blobClient.DownloadToAsync(targetStream);

            #endregion

            Assert.Pass();
        }
        internal static MetricAlertSingleResourceMultipleMetricCriteria DeserializeMetricAlertSingleResourceMultipleMetricCriteria(JsonElement element)
        {
            Optional <IList <MetricCriteria> > allOf = default;
            Odatatype odataType = default;
            IDictionary <string, BinaryData> additionalProperties           = default;
            Dictionary <string, BinaryData>  additionalPropertiesDictionary = new Dictionary <string, BinaryData>();

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("allOf"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List <MetricCriteria> array = new List <MetricCriteria>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(MetricCriteria.DeserializeMetricCriteria(item));
                    }
                    allOf = array;
                    continue;
                }
                if (property.NameEquals("odata.type"))
                {
                    odataType = new Odatatype(property.Value.GetString());
                    continue;
                }
                additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText()));
            }
            additionalProperties = additionalPropertiesDictionary;
            return(new MetricAlertSingleResourceMultipleMetricCriteria(odataType, additionalProperties, Optional.ToList(allOf)));
        }
Ejemplo n.º 24
0
        private static void PerformWriteFlushReadSeek(DataLakeFileSystemClient client)
        {
            string fileName = "/Test/dir1/testFilename1.txt";

            DataLakeFileClient file = client.GetFileClient(fileName);

            // Create the file
            Stream stream = BinaryData.FromString("This is the first line.\nThis is the second line.\n").ToStream();
            long   length = stream.Length;

            file.Upload(stream, true);

            // Append to the file
            stream = BinaryData.FromString("This is the third line.\nThis is the fourth line.\n").ToStream();
            file.Append(stream, length);
            file.Flush(length + stream.Length);

            // Read the file
            using (var readStream = file.OpenRead())
            {
                byte[] readData = new byte[1024];

                // Read 40 bytes at this offset
                int readBytes = readStream.Read(readData, 25, 40);
                Console.WriteLine("Read output of 40 bytes from offset 25: " + Encoding.UTF8.GetString(readData, 0, readBytes));
            }
        }
        public async Task CreateDeploymentsUsingJsonElement()
        {
            #region Snippet:Managing_Deployments_CreateADeploymentUsingJsonElement
            // First we need to get the deployment collection from the resource group
            ArmDeploymentCollection ArmDeploymentCollection = resourceGroup.GetArmDeployments();
            // Use the same location as the resource group
            string deploymentName = "myDeployment";
            // Create a parameter object
            var parametersObject = new { storageAccountType = new { value = "Standard_GRS" } };
            //convert this object to JsonElement
            var parametersString = JsonSerializer.Serialize(parametersObject);
            var parameters       = JsonDocument.Parse(parametersString).RootElement;
            var input            = new ArmDeploymentInput(new ArmDeploymentProperties(ArmDeploymentMode.Incremental)
            {
                TemplateLink = new ArmDeploymentTemplateLink()
                {
                    Uri = new Uri("https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.storage/storage-account-create/azuredeploy.json")
                },
                Parameters = BinaryData.FromString(parameters.GetRawText())
            });
            ArmOperation <ArmDeploymentResource> lro = await ArmDeploymentCollection.CreateOrUpdateAsync(WaitUntil.Completed, deploymentName, input);

            ArmDeploymentResource deployment = lro.Value;
            #endregion Snippet:Managing_Deployments_CreateADeployment
        }
Ejemplo n.º 26
0
        internal static ModelWithBinaryDataInDictionary DeserializeModelWithBinaryDataInDictionary(JsonElement element)
        {
            Optional <string> a = default;
            Optional <IReadOnlyDictionary <string, BinaryData> > details = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("a"))
                {
                    a = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("details"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary <string, BinaryData> dictionary = new Dictionary <string, BinaryData>();
                    foreach (var property1 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property1.Name, BinaryData.FromString(property1.Value.GetRawText()));
                    }
                    details = dictionary;
                    continue;
                }
            }
            return(new ModelWithBinaryDataInDictionary(a.Value, details.Value));
        }
Ejemplo n.º 27
0
        internal static ResourceGroupExportResult DeserializeResourceGroupExportResult(JsonElement element)
        {
            Optional <BinaryData>    template = default;
            Optional <ResponseError> error    = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("template"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    template = BinaryData.FromString(property.Value.GetRawText());
                    continue;
                }
                if (property.NameEquals("error"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    error = ResponseError.DeserializeResponseError(property.Value);
                    continue;
                }
            }
            return(new ResourceGroupExportResult(template.Value, error.Value));
        }
        /// <summary>
        /// Extracting event from the json.
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public CallingServerEventBase ExtractEvent(string content)
        {
            CloudEvent cloudEvent = CloudEvent.Parse(BinaryData.FromString(content));

            if (cloudEvent != null && cloudEvent.Data != null)
            {
                if (cloudEvent.Type.Equals(CallingServerEventType.CallConnectionStateChangedEvent.ToString()))
                {
                    return(CallConnectionStateChangedEvent.Deserialize(cloudEvent.Data.ToString()));
                }
                else if (cloudEvent.Type.Equals(CallingServerEventType.ToneReceivedEvent.ToString()))
                {
                    return(ToneReceivedEvent.Deserialize(cloudEvent.Data.ToString()));
                }
                else if (cloudEvent.Type.Equals(CallingServerEventType.PlayAudioResultEvent.ToString()))
                {
                    return(PlayAudioResultEvent.Deserialize(cloudEvent.Data.ToString()));
                }
                else if (cloudEvent.Type.Equals(CallingServerEventType.AddParticipantResultEvent.ToString()))
                {
                    return(AddParticipantResultEvent.Deserialize(cloudEvent.Data.ToString()));
                }
            }

            return(null);
        }
        internal static ErrorAdditionalInfo DeserializeErrorAdditionalInfo(JsonElement element)
        {
            Optional <string>     type = default;
            Optional <BinaryData> info = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("info"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    info = BinaryData.FromString(property.Value.GetRawText());
                    continue;
                }
            }
            return(new ErrorAdditionalInfo(type.Value, info.Value));
        }
Ejemplo n.º 30
0
        /// <inheritdoc/>
        public async Task <ClaimPermissions> CreateAsync(ClaimPermissions claimPermissions)
        {
            if (claimPermissions is null)
            {
                throw new ArgumentNullException(nameof(claimPermissions));
            }

            BlockBlobClient blob = this.Container.GetBlockBlobClient(claimPermissions.Id);
            string          serializedPermissions = JsonConvert.SerializeObject(claimPermissions, this.serializerSettings);

            try
            {
                using var content = BinaryData.FromString(serializedPermissions).ToStream();
                Response <BlobContentInfo> response = await blob.UploadAsync(
                    content,
                    new BlobUploadOptions { Conditions = new BlobRequestConditions {
                                                IfNoneMatch = ETag.All
                                            } })
                                                      .ConfigureAwait(false);

                claimPermissions.ETag = response.Value.ETag.ToString("G");
                return(claimPermissions);
            }
            catch (RequestFailedException x)
            {
                System.Diagnostics.Debug.WriteLine(x.ToString());
                throw new InvalidOperationException();
            }
        }