public static async Task MainFunctions() { logger.Info("Starting example"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var command = Environment.GetEnvironmentVariable("OPERATION"); var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); var image = Environment.GetEnvironmentVariable("IMAGE"); var payload = Environment.GetEnvironmentVariable("PAYLOAD"); try { if (command.Equals(Setup, StringComparison.OrdinalIgnoreCase)) { await SetUpResources(provider, compartmentId, image); } if (command.Equals(Invoke, StringComparison.OrdinalIgnoreCase)) { await InvokeFunction(provider, compartmentId, payload); } if (command.Equals(TearDown, StringComparison.OrdinalIgnoreCase)) { await TearDownResources(provider, compartmentId); } } catch (Exception e) { logger.Error($"command {command} failed: {e}"); } }
public static async Task MainRegionAndRealm() { // Accepts profile name and creates a auth provider based on config file var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName); // Create a client for the service to enable using its APIs var client = new IdentityClient(provider, new ClientConfiguration()); // Assume a new region us-foo-1 is launched in OC2 realm // Register the new region var fooRegion = Region.Register("us-foo-1", Realm.OC2); // If the config file contains a value for region, then it will be picked up automatically by the SDK, // else set it up manually by calling setRegion logger.Info($"Setting region to {fooRegion.RegionId}"); client.SetRegion(fooRegion); // Use the client to make calls to the endpoint for the new region await ListAllRegions(client); // Now, assume a new region us-bar-1 is launched in OCX realm // (having secondLevelDomain oracle-baz-cloud.com) // Register the new region and realm var barRegion = Region.Register("us-bar-1", Realm.Register("ocx", "oracle-baz-cloud.com")); // Call setRegion to use the endpoint in the new region logger.Info($"Setting region to {barRegion.RegionId}"); client.SetRegion(barRegion); // Use the client to make calls to the endpoint for the new region await ListAllRegions(client); }
public static async Task MainCompartment() { logger.Info("Starting example"); // Create Identity Client var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var client = new IdentityClient(provider, new ClientConfiguration()); logger.Info("IdentityClient created"); try { var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); string sourceCompartmentId = await CreateCompartment(client, compartmentId, "source"); string targetCompartmentId = await CreateCompartment(client, compartmentId, "target"); await MoveCompartment(client, sourceCompartmentId, targetCompartmentId); } catch (Exception e) { logger.Error($"Failed to move compartments: {e}"); } finally { client.Dispose(); } }
public static async Task MainPagination() { string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); logger.Info("Starting Pagination example"); // Accepts profile name and creates a auth provider based on config file var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName); // Create a client for the service to enable using its APIs var identityClient = new IdentityClient(provider, new ClientConfiguration()); try { await DoManualPagination(identityClient, compartmentId); DoPaginateWithResponsePaginator(identityClient, compartmentId); DoPaginateWithRecordPaginator(identityClient, compartmentId); } catch (Exception e) { logger.Info($"Received exception due to {e.Message}"); } finally { logger.Info("ending Pagination example"); identityClient.Dispose(); } }
public static async Task MainRetry() { string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); // Configuring the AuthenticationDetailsProvider. It's assuming there is a default OCI config file // "~/.oci/config", and a profile in that config with the name OciConfigProfileName . Make changes to the following // line if needed and use ConfigFileAuthenticationDetailsProvider(configurationFilePath, profile); var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName); // Create a client for the service to enable using its APIs var client = new IdentityClient(provider, new ClientConfiguration()); try { await ListOciRegions(client); await ListOciRegionSubscriptions(client, compartmentId); } catch (Exception e) { logger.Info($"Received exception due to {e.Message}"); } finally { client.Dispose(); } }
public static async Task MainWaiters() { logger.Info("Starting example"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); var loadBalancerId = Environment.GetEnvironmentVariable("LOADBALANCER_ID"); var backendSetName = Environment.GetEnvironmentVariable("BACKEND_SET_NAME"); var loadBalancerClient = new LoadBalancerClient(provider); try { var ruleSet = await CreateRuleSet(loadBalancerClient, loadBalancerId); } catch (Exception e) { logger.Error($"Failed to add ruleset: {e}"); } finally { loadBalancerClient.Dispose(); } logger.Info("End example"); }
public LanguageWrapper() { // Create a default authentication provider that uses the DEFAULT // profile in the configuration file. // Refer to <see href="https://docs.cloud.oracle.com/en-us/iaas/Content/API/Concepts/sdkconfig.htm#SDK_and_CLI_Configuration_File>the public documentation</see> on how to prepare a configuration file. var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); client = new AIServiceLanguageClient(provider, new ClientConfiguration()); }
public static async Task MainNonRegionalClient() { logger.Info("Starting example"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); StreamAdminClient streamAdminClient = new StreamAdminClient(provider); StreamClient streamClient = new StreamClient(provider); string streamId = null; try { Stream stream = await GetOrCreateStream(streamAdminClient, compartmentId, STREAM_NAME, PARTITIONS); streamId = stream.Id; // Streams are assigned a specific endpoint url based on where they are provisioned. // Create a stream client using the provided message endpoint. streamClient.SetEndpoint(stream.MessagesEndpoint); // publish some messages to the stream await PublishExampleMessages(streamClient, streamId); // give the streaming service a second to propagate messages await Task.Delay(1000); // Use a cursor for getting messages // A cursor can be created at a given partition/offset. // This gives explicit offset management control to the consumer. logger.Info("Starting a simple message loop with a partition cursor"); string partitionCursor = await GetCursorByPartition(streamClient, streamId, "0"); await SimpleMessageLoop(streamClient, streamId, partitionCursor); } catch (Exception e) { logger.Error($"NonRegional client example failed: {e}"); } finally { // Cleanup; remember to delete streams which are not in use. await DeleteStream(streamAdminClient, streamId); // Stream deletion is an asynchronous operation, give it some time to complete. GetStreamRequest getStreamRequest = new GetStreamRequest { StreamId = streamId }; streamAdminClient.Waiters.ForStream(getStreamRequest, Stream.LifecycleStateEnum.Deleted).Execute(); streamAdminClient.Dispose(); logger.Info("End example"); } }
public static async Task MainAuthenticationPolicy() { string tenantId = Environment.GetEnvironmentVariable("OCI_TENANT_ID"); // Accepts profile name and creates a auth provider based on config file var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName); // Create a client for the service to enable using its APIs var client = new IdentityClient(provider, new ClientConfiguration()); await QueryAuthenticationPolicy(tenantId, client); await UpdateAuthenticationPolicy(tenantId, client); }
public static async Task MainPolymorphicObject() { logger.Info("Starting example"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var client = new ResourceSearchClient(provider); logger.Info("Search for resource by freetext search"); await FreeTextSearch(client, "admin"); logger.Info("Search for resource by structed query search"); await StructuredQuerySearch(client, "query all resources"); logger.Info("End example"); }
public static async Task MainChangeRegion() { logger.Info("Starting example"); AuditClient client = null; try { // Assumption: the compartment id has been set in environment variable. var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); logger.Info(compartmentId); // ListEvents var listEventsRequest = new ListEventsRequest { CompartmentId = compartmentId, StartTime = DateTime.Now.AddDays(-1), EndTime = DateTime.Now }; // Create AuditClient var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); using (client = new AuditClient(provider, new ClientConfiguration())) { logger.Info($"AuditClient created. Region is set to: {provider.Region}"); ListEventsResponse listEventsResp = await GetEvents(client, listEventsRequest); logger.Info($"Received {listEventsResp?.Items.Count} items"); } // Change the region to US_ASHBURN_1 using SetRegion Call // We cannot use the same client to change the region. See: // https://stackoverflow.com/questions/51478525/httpclient-this-instance-has-already-started-one-or-more-requests-properties-ca using (client = new AuditClient(provider, new ClientConfiguration())) { client.SetRegion(Region.US_ASHBURN_1); logger.Info("Changing region to US_ASHBURN_1"); ListEventsResponse listEventsRespDiffRegion = await GetEvents(client, listEventsRequest); logger.Info($"Received {listEventsRespDiffRegion?.Items.Count} items"); } } catch (Exception e) { logger.Error($"Failed Change Region example: {e.Message}"); } }
public static async Task MainUploadManager() { logger.Info("Starting Upload Manager Example"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var osClient = new ObjectStorageClient(provider, new ClientConfiguration() { TimeoutMillis = 1000 * 1000 // 1000 secs. Setting large timeouts is required for uploading large objects to avoid httpclient timeout exceptions. }); var putObjectRequest = new PutObjectRequest() { BucketName = Environment.GetEnvironmentVariable("BUCKET_NAME"), NamespaceName = Environment.GetEnvironmentVariable("NAMESPACE_NAME"), ObjectName = Environment.GetEnvironmentVariable("OBJECT_NAME"), PutObjectBody = System.IO.File.OpenRead(Environment.GetEnvironmentVariable("FILE_TO_UPLOAD")), ContentLength = Convert.ToInt64(Environment.GetEnvironmentVariable("CONTENT_LENGTH")), ContentType = Environment.GetEnvironmentVariable("CONTENT_TYPE") }; var uploadConfiguration = new UploadConfiguration() { AllowMultipartUploads = true }; var uploadManager = new UploadManager(osClient, uploadConfiguration); var uploadRequest = new UploadManager.UploadRequest(putObjectRequest) { AllowOverwrite = true, OnProgress = OnProgres }; var uploadResponse = await uploadManager.Upload(uploadRequest); logger.Info(uploadResponse); var headObject = await osClient.HeadObject(new HeadObjectRequest() { BucketName = Environment.GetEnvironmentVariable("BUCKET_NAME"), NamespaceName = Environment.GetEnvironmentVariable("NAMESPACE_NAME"), ObjectName = Environment.GetEnvironmentVariable("OBJECT_NAME") }); logger.Info($"{headObject.ETag}"); osClient.Dispose(); }
public void TestConfigProviderInstantiation(string profile, string tenancy, string user, string fingerprint) { string path = @".\testconfig" + DateTime.Now.ToFileTimeUtc(); try { File.WriteAllText(path, profile); var config = new ConfigFileAuthenticationDetailsProvider(path, "DEFAULT"); //Makes sure IAuthenticationDetailsProvider is instantiated if authentication_type is absent in config //Following values won't match if provider is not a configfileauthenticationdetail provider. Assert.Equal(config.TenantId, tenancy); Assert.Equal(config.UserId, user); Assert.Equal(config.Fingerprint, fingerprint); Assert.Null(config.GetDelegationToken()); } finally { File.Delete(path); } }
public static async Task MainOS() { logger.Info("Starting Object Storage Examples"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var osClient = new ObjectStorageClient(provider, new ClientConfiguration()); try { await PutObjectExample(osClient); await GetObjectExample(osClient); } catch (Exception e) { logger.Error($"Failed ObjectStorage example: {e.Message}"); } finally { osClient.Dispose(); } }
public static async Task MainLogging() { string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); string logGroupId = Environment.GetEnvironmentVariable("OCI_LOG_GROUP"); string logDisplayName = "oci-dotnet-sdk-example-log"; // Accepts profile name and creates a auth provider based on config file var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName); // Create clients for the service to enable using its APIs var logManagementClient = new LoggingManagementClient(provider, new ClientConfiguration()); var logIngestionclient = new LoggingClient(provider, new ClientConfiguration()); var logSearchClient = new LogSearchClient(provider, new ClientConfiguration()); try { string logId = await CreateLog(logManagementClient, logGroupId, logDisplayName); //string logId = "ocid1.log.oc1.phx.amaaaaaaogrv47iah6om32dahq3g4p6sleadbnsyptckvirmilizekvjptza"; await ListLogs(logManagementClient, logGroupId); await GetLog(logManagementClient, logGroupId, logId); // Wait for log to be accessible System.Threading.Thread.Sleep(50000); await PutLogDetails(logIngestionclient, logId); // Wait for PutLogs to ingest Logs System.Threading.Thread.Sleep(20000); await SearchLog(logSearchClient, compartmentId, logGroupId, logId); await DeleteLog(logManagementClient, logGroupId, logId); } catch (Exception e) { logger.Info($"Received exception due to {e.Message}"); } finally { logManagementClient.Dispose(); logIngestionclient.Dispose(); logSearchClient.Dispose(); } }
public static async Task MainResourcesearch() { logger.Info("Starting example"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var client = new ResourceSearchClient(provider); logger.Info("List all resource types"); await ListTypes(client); logger.Info("Get Group type details"); await GetTypeDetails(client, "Group"); logger.Info("Search for resource by freetext search"); await FreeTextSearch(client, "admin"); logger.Info("Search for resource by structed query search"); await StructuredQuerySearch(client, "query all resources"); logger.Info("End example"); }
public static async Task MainIdentity() { string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); // Accepts profile name and creates a auth provider based on config file var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName); // Create a client for the service to enable using its APIs var client = new IdentityClient(provider, new ClientConfiguration()); try { await ListOciRegions(client); await ListOciRegionSubscriptions(client, compartmentId); await UserAndGroupOps(client, compartmentId); } catch (Exception e) { logger.Info($"Received exception due to {e.Message}"); } finally { client.Dispose(); } }
public static async Task MainWaiter() { // Accepts profile name and creates a auth provider based on config file var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigSourceProfileName); string bootVolumeBackup = Environment.GetEnvironmentVariable("OCI_BOOT_VOLUME_BACKUP_ID"); string destinationRegion = Environment.GetEnvironmentVariable("OCI_DESTINATION_REGION"); // Create clients for the service to enable using its APIs var blockStorageClient = new BlockstorageClient(provider, new ClientConfiguration()); try { // Copy Boot Volume backup var backupCopyId = await CopyBootVolumeBackup(blockStorageClient, bootVolumeBackup, destinationRegion); logger.Info($"Create backup copy with OCID:{backupCopyId}"); // Create new client for making a retrying call for new backup copy in destination region var destinationProvider = new ConfigFileAuthenticationDetailsProvider(OciConfigDestinationProfileName); blockStorageClient = new BlockstorageClient(destinationProvider, new ClientConfiguration()); var state = GetBootVolumeBackup(blockStorageClient, backupCopyId); logger.Info($"Successfully create backup copy with Lifecyle State:{state}"); // Delete the backup copy for cleanup await DeleteBootVolumeBackup(blockStorageClient, backupCopyId); } catch (Exception e) { logger.Info($"Received exception due to {e.Message}"); } finally { blockStorageClient.Dispose(); } }
public static async Task MainKeyManagement() { logger.Info("Starting example"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); var vaultId = Environment.GetEnvironmentVariable("VAULT_ID"); KmsVaultClient kmsVaultClient = null; KmsManagementClient kmsManagementClient = null; KmsCryptoClient kmsCryptoClient = null; try { // Initialize the KMS Clients. KMS has three clients as following: // * KmsVaultClient: The client for Vault management // * KmsManagementClient: The client for Key management (ControlPlane) // * KmsCryptoClient: The client for data encryption and decryption (DataPlane) kmsVaultClient = new KmsVaultClient(provider); kmsManagementClient = new KmsManagementClient(provider); kmsCryptoClient = new KmsCryptoClient(provider); Vault vault = await GetVault(kmsVaultClient, vaultId); // The ManagementClient and CryptoClient use Vault specific endpoints; Set them now. kmsManagementClient.SetEndpoint(vault.ManagementEndpoint); kmsCryptoClient.SetEndpoint(vault.CryptoEndpoint); // Vault Operations await UpdateVaultResetTags(kmsVaultClient, vault.Id); await UpdateVault(kmsVaultClient, vault.Id); await ListVaults(kmsVaultClient, compartmentId); await ScheduleVaultDeletion(kmsVaultClient, vault.Id); var waiterConfiguration = new WaiterConfiguration { MaxAttempts = 10, GetNextDelayInSeconds = DelayStrategy.GetExponentialDelayInSeconds }; // After scheduling deletion, the Vault will stay in SCHEDULING_DELETION state shortly and then // transit to PENDING_DELETION state. Wait a bit for the transition to happen. logger.Info("Wait a bit for the deletion scheduling to finish"); GetVaultRequest getVaultRequest = new GetVaultRequest { VaultId = vault.Id }; kmsVaultClient.Waiters.ForVault(getVaultRequest, waiterConfiguration, Vault.LifecycleStateEnum.PendingDeletion).Execute(); await CancelVaultDeletion(kmsVaultClient, vault.Id); // After cancelling deletion, the Vault will stay in CANCELLING_DELETION state shortly and then // transit to ACTIVE state. Wait a bit for the transition to happen. logger.Info("Wait a bit for the deletion cancelling to finish"); kmsVaultClient.Waiters.ForVault(getVaultRequest, waiterConfiguration, Vault.LifecycleStateEnum.Active).Execute(); // Management / Key Operations string keyId = await CreateKey(kmsManagementClient, compartmentId); // After creating a Key, the Key will stay in CREATING state shortly and then // transit to ENABLED state. Wait a bit for the transition to happen. logger.Info("Wait a bit for Key creation to finish"); GetKeyRequest getKeyRequest = new GetKeyRequest { KeyId = keyId }; kmsManagementClient.Waiters.ForKey(getKeyRequest, waiterConfiguration, Key.LifecycleStateEnum.Enabled).Execute(); await GetKey(kmsManagementClient, keyId); await UpdateKeyResetTags(kmsManagementClient, keyId); kmsManagementClient.Waiters.ForKey(getKeyRequest, waiterConfiguration, Key.LifecycleStateEnum.Enabled).Execute(); await UpdateKey(kmsManagementClient, keyId); kmsManagementClient.Waiters.ForKey(getKeyRequest, waiterConfiguration, Key.LifecycleStateEnum.Enabled).Execute(); await ListKeys(kmsManagementClient, compartmentId); await DisableKey(kmsManagementClient, keyId); // After disabling a Key, the Key will stay in DISABLING state shortly and then // transit to DISABLED state. Wait a bit for the transition to happen. logger.Info("Wait a bit for Key disabling to finish"); kmsManagementClient.Waiters.ForKey(getKeyRequest, waiterConfiguration, Key.LifecycleStateEnum.Disabled).Execute(); await EnableKey(kmsManagementClient, keyId); // After enabling a Key, the Key will stay in ENABLING state shortly and then // transit to ENABLED state. Wait a bit for the transition to happen. logger.Info("Wait a bit for Key enabling to finish"); kmsManagementClient.Waiters.ForKey(getKeyRequest, waiterConfiguration, Key.LifecycleStateEnum.Enabled).Execute(); await ScheduleKeyDeletion(kmsManagementClient, keyId); // After scheduling deletion, the Key will stay in SCHEDULING_DELETION state shortly and then // transit to PENDING_DELETION state. Wait a bit for the transition to happen. logger.Info("Wait a bit for deletion scheduling to finish"); kmsManagementClient.Waiters.ForKey(getKeyRequest, waiterConfiguration, Key.LifecycleStateEnum.PendingDeletion).Execute(); await CancelKeyDeletion(kmsManagementClient, keyId); // After cancelling deletion, the Key will stay in CANCELLING_DELETION state shortly and then // transit to Enabled state. Wait a bit for the transition to happen. logger.Info("Wait a bit for deletion cancelling to finish"); kmsManagementClient.Waiters.ForKey(getKeyRequest, waiterConfiguration, Key.LifecycleStateEnum.Enabled).Execute(); await CreateKeyVersion(kmsManagementClient, keyId); await ListKeyVersions(kmsManagementClient, keyId); // Crypto Operations string cipherText = await Encrypt(kmsCryptoClient, keyId); await Decrypt(kmsCryptoClient, keyId, cipherText); await GenerateDataEncryptionKey(kmsCryptoClient, keyId); kmsManagementClient.Waiters.ForKey(getKeyRequest, waiterConfiguration, Key.LifecycleStateEnum.Enabled).Execute(); } catch (Exception e) { logger.Error($"Failed to perform operations on Vault: {e}"); } finally { if (kmsVaultClient != null) { kmsVaultClient.Dispose(); } if (kmsManagementClient != null) { kmsManagementClient.Dispose(); } if (kmsCryptoClient != null) { kmsCryptoClient.Dispose(); } } logger.Info("End example"); }
public static async Task MainContainerEngine(string[] args) { logger.Info("Starting example"); string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName); var containerEngineClient = new ContainerEngineClient(provider); var vcnClient = new VirtualNetworkClient(provider); var identityClient = new IdentityClient(provider); Vcn vcn = null; List <Subnet> subnets = null; Cluster cluster = null; try { IdentityModels.AvailabilityDomain availablityDomain = await GetAvailabilityDomain(identityClient, compartmentId); logger.Info($"availability domain is {availablityDomain.Name}"); vcn = await CreateVcn(vcnClient, compartmentId); subnets = await CreateSubnet(vcnClient, compartmentId, availablityDomain, vcn.Id); //Create a Container Engine Cluster List <string> subnetIds = new List <string>(); foreach (Subnet subnet in subnets) { subnetIds.Add(subnet.Id); } var kubernetesVersion = await GetKubernetesVersion(containerEngineClient); cluster = await CreateCluster(containerEngineClient, vcn.Id, subnetIds, kubernetesVersion, compartmentId); // Update the container engine cluster await UpdateCluster(containerEngineClient, cluster.Id, ClusterNewDisplayName); } catch (Exception e) { logger.Error($"Failed to create container engine cluster: {e}"); } finally { logger.Info("Cleaning up..."); if (cluster != null) { await DeleteCluster(containerEngineClient, cluster.Id); } for (int i = 0; i < 2; i++) { if (subnets[i] != null) { await DeleteSubnet(vcnClient, subnets[i]); } } if (vcn != null) { await DeleteVcn(vcnClient, vcn); } containerEngineClient.Dispose(); vcnClient.Dispose(); identityClient.Dispose(); } logger.Info("End example"); }
public static async Task MainContainerEngineNodePool() { logger.Info("Starting example"); string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName); var containerEngineClient = new ContainerEngineClient(provider); var vcnClient = new VirtualNetworkClient(provider); var identityClient = new IdentityClient(provider); Vcn vcn = null; List <Subnet> subnets = null; List <string> lbSubnetIds = new List <string>(); List <string> poolSubnetIds = new List <string>(); Cluster cluster = null; NodePool nodePool = null; try { List <IdentityModels.AvailabilityDomain> availablityDomains = await GetAvailabilityDomains(identityClient, compartmentId); vcn = await CreateVcn(vcnClient, compartmentId); subnets = await CreateSubnets(vcnClient, compartmentId, vcn); lbSubnetIds.Add(subnets[0].Id); poolSubnetIds.Add(subnets[1].Id); var kubernetesVersion = await GetKubernetesVersion(containerEngineClient); cluster = await CreateCluster(containerEngineClient, vcn.Id, lbSubnetIds, kubernetesVersion, compartmentId); // Add node pool in the cluster KeyValue keyValue = new KeyValue { Key = "key1", Value = "value1" }; List <KeyValue> initialNodeLabels = new List <KeyValue> { keyValue }; List <NodePoolPlacementConfigDetails> nodePoolPlacementConfigDetails = new List <NodePoolPlacementConfigDetails>(); foreach (var availabilityDomain in availablityDomains) { nodePoolPlacementConfigDetails.Add(new NodePoolPlacementConfigDetails { AvailabilityDomain = availabilityDomain.Name, SubnetId = poolSubnetIds[0] }); } ; var createNodePoolNodeConfigDetails = new CreateNodePoolNodeConfigDetails { Size = availablityDomains.Count, PlacementConfigs = nodePoolPlacementConfigDetails }; nodePool = await CreateNodePool(containerEngineClient, compartmentId, cluster.Id, NodePoolDisplayName, kubernetesVersion, NodeImageName, NodeShape, initialNodeLabels, createNodePoolNodeConfigDetails); logger.Info("Created node pool"); // Update the node pool await UpdateNodePool(containerEngineClient, nodePool.Id, NewNodePoolDisplayName); } catch (Exception e) { logger.Error($"Failed to create container engine cluster: {e}"); } finally { logger.Info("Cleaning up..."); if (nodePool != null) { await DeleteNodePool(containerEngineClient, nodePool.Id); } if (cluster != null) { await DeleteCluster(containerEngineClient, cluster.Id); } for (int i = 0; i < 2; i++) { if (subnets[i] != null) { await DeleteSubnet(vcnClient, subnets[i]); } } if (vcn != null) { await DeleteVcn(vcnClient, vcn); } containerEngineClient.Dispose(); vcnClient.Dispose(); identityClient.Dispose(); } logger.Info("End example"); }
public static async Task MainFileStorage() { logger.Info("Starting example"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); var fileSystemDisplayName = Environment.GetEnvironmentVariable("FILE_SYSTEM_DISPLAY_NAME"); var identityClient = new IdentityClient(provider); var fileStorageClient = new FileStorageClient(provider); var vcnClient = new VirtualNetworkClient(provider); Vcn vcn = null; Subnet subnet = null; FileSystem fileSystem = null; MountTarget mountTarget = null; Export export = null; Snapshot snapshot = null; try { var availablityDomain = await GetAvailabilityDomain(identityClient, compartmentId); logger.Info($"availability domain is {availablityDomain.Name}"); // A VCN and subnet is required to create a mount target vcn = await CreateVcn(vcnClient, compartmentId); subnet = await CreateSubnet(vcnClient, compartmentId, availablityDomain, vcn); fileSystem = await CreateFileSystem(fileStorageClient, compartmentId, fileSystemDisplayName, availablityDomain); mountTarget = await CreateMountTarget(fileStorageClient, vcnClient, compartmentId, fileSystemDisplayName + "-mnt", availablityDomain, subnet); await GetExportSet(fileStorageClient, mountTarget.ExportSetId); export = await CreateExport(fileStorageClient, fileSystem.Id, mountTarget.ExportSetId); ListExports(fileStorageClient, compartmentId, fileSystem, mountTarget); snapshot = await CreateSnapshot(fileStorageClient, fileSystem); } catch (Exception e) { logger.Error($"Failed to mount file system: {e}"); } finally { logger.Info("cleaning resources...."); if (snapshot != null) { await DeleteSnapshot(fileStorageClient, snapshot); } if (export != null) { await DeleteExport(fileStorageClient, export); } if (mountTarget != null) { await DeleteMountTarget(fileStorageClient, mountTarget); } if (fileSystem != null) { await DeleteFileSystem(fileStorageClient, fileSystem); } if (subnet != null) { await DeleteSubnet(vcnClient, subnet); } if (vcn != null) { await DeleteVcn(vcnClient, vcn); } identityClient.Dispose(); fileStorageClient.Dispose(); vcnClient.Dispose(); logger.Info("End example"); } }
static async Task MainDatabase(string[] args) { string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); string adminPassword = Environment.GetEnvironmentVariable("PASSWORD"); logger.Info("Starting example"); // Accepts profile name and creates a auth provider based on config file var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName); var identityClient = new IdentityClient(provider); var virtualNetworkClient = new VirtualNetworkClient(provider); var databaseClient = new DatabaseClient(provider); var networkCidrBlock = "10.0.1.0/24"; Vcn vcn = null; Subnet subnet = null; string dbSystemId = null; AvailabilityDomain availablityDomain = await getAvailabilityDomains(identityClient, compartmentId); logger.Info($"availability domain is {availablityDomain.Name}"); try { vcn = await createVcn(virtualNetworkClient, compartmentId, networkCidrBlock); subnet = await createSubnet(virtualNetworkClient, compartmentId, availablityDomain, networkCidrBlock, vcn); logger.Info("Launching Database...."); LaunchDbSystemDetails launchDbSystemDetails = new LaunchDbSystemDetails { AvailabilityDomain = availablityDomain.Name, CompartmentId = compartmentId, CpuCoreCount = 4, Shape = "BM.DenseIO2.52", SshPublicKeys = new List <string> { "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAyyA8wePstPC69PeuHFtOwyTecByonsHFAjHbVnZ+h0dpomvLZxUtbknNj3+c7MPYKqKBOx9gUKV/diR/mIDqsb405MlrI1kmNR9zbFGYAAwIH/Gxt0Lv5ffwaqsz7cECHBbMojQGEz3IH3twEvDfF6cu5p00QfP0MSmEi/eB+W+h30NGdqLJCziLDlp409jAfXbQm/4Yx7apLvEmkaYSrb5f/pfvYv1FEV1tS8/J7DgdHUAWo6gyGUUSZJgsyHcuJT7v9Tf0xwiFWOWL9WsWXa9fCKqTeYnYJhHlqfinZRnT/+jkz0OZ7YmXo6j4Hyms3RCOqenIX1W6gnIn+eQIkw== This is the key's comment" }, SubnetId = subnet.Id, DatabaseEdition = LaunchDbSystemDetails.DatabaseEditionEnum.EnterpriseEdition, DisplayName = "OCI DotNet SDK database", Hostname = "oci-dotnetsdk-host", Domain = "testdomain", DbHome = new CreateDbHomeDetails { DbVersion = "12.1.0.2", DisplayName = "Example DB Home", Database = new CreateDatabaseDetails { DbName = "dotnetdb", AdminPassword = adminPassword } } }; LaunchDbSystemRequest launchDbSystemRequest = new LaunchDbSystemRequest { LaunchDbSystemDetails = launchDbSystemDetails }; LaunchDbSystemResponse launchDbSystemResponse = await databaseClient.LaunchDbSystem(launchDbSystemRequest); logger.Info($"Database ID: {launchDbSystemResponse.DbSystem.Id} and Database display name: {launchDbSystemResponse.DbSystem.DisplayName}"); logger.Info("Waiting for Database to come to available state...."); GetDbSystemRequest getDbSystemRequest = new GetDbSystemRequest { DbSystemId = launchDbSystemResponse.DbSystem.Id }; WaiterConfiguration waiterConfiguration = new WaiterConfiguration { MaxAttempts = 20, GetNextDelayInSeconds = DelayStrategy.GetExponentialDelayInSeconds }; GetDbSystemResponse getDbSystemResponse = databaseClient.Waiters.ForDbSystem( getDbSystemRequest, waiterConfiguration, DbSystem.LifecycleStateEnum.Available).Execute(); logger.Info("Database is available"); logger.Info($"Database ID: {getDbSystemResponse.DbSystem.Id} and Database display name: {getDbSystemResponse.DbSystem.DisplayName}"); dbSystemId = getDbSystemResponse.DbSystem.Id; } catch (Exception e) { logger.Error($"failed to launch DbSystem: {e}"); } finally { if (dbSystemId != null) { await terminateDbSystem(databaseClient, dbSystemId); } if (subnet != null) { await deleteSubnet(virtualNetworkClient, subnet); } if (vcn != null) { await deleteVcn(virtualNetworkClient, vcn); } identityClient.Dispose(); virtualNetworkClient.Dispose(); databaseClient.Dispose(); logger.Info("End example"); } }
public static HttpClientHandler FromConfigFile(string configPath, string profile, SigningStrategy signingStrategy) { var provider = new ConfigFileAuthenticationDetailsProvider(configPath, profile); return(FromAuthProvider(provider, signingStrategy)); }
public static async Task Main() { logger.Info("Starting example"); AuditClient client = null; try { // Assumption: the compartment id has been set in environment variable. var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); logger.Info(compartmentId); // ListEvents var listEventsRequest = new ListEventsRequest { CompartmentId = compartmentId, StartTime = DateTime.Now.AddDays(-1), EndTime = DateTime.Now }; // Create AuditClient var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); using (client = new AuditClient(provider, new ClientConfiguration())) { logger.Info("AuditClient created."); ListEventsResponse listEventsResp = await NoRetryExample(client, listEventsRequest); logger.Info($"Received {listEventsResp?.Items.Count} items"); ListEventsResponse listEventsRespFromRetry = await RetryExample(client, listEventsRequest); logger.Info($"Received {listEventsRespFromRetry?.Items.Count} items"); await CancellationTokenExample(client, listEventsRequest); // GetConfiguration var getConfigurationRequest = new GetConfigurationRequest { CompartmentId = compartmentId }; logger.Info("GetConfigurationRequest created."); GetConfigurationResponse getConfigurationResp = await client.GetConfiguration(getConfigurationRequest); logger.Info($"Retention period days: {getConfigurationResp?.Configuration.RetentionPeriodDays}"); // UpdateConfiguration var updateConfigurationRequest = new UpdateConfigurationRequest { CompartmentId = compartmentId, UpdateConfigurationDetails = new UpdateConfigurationDetails { RetentionPeriodDays = 90 } }; logger.Info("UpdateConfigurationRequest created."); UpdateConfigurationResponse updateConfigurationResp = await client.UpdateConfiguration(updateConfigurationRequest); logger.Info($"opc work request id: {updateConfigurationResp.OpcRequestId}"); } } catch (Exception e) { logger.Error($"Failed Audit example: {e.Message}"); } }
public static async Task MainMonitoring() { logger.Info("Starting example"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); var metricCompartmentId = Environment.GetEnvironmentVariable("METRIC_COMPARTMENT_ID"); var destinations = Environment.GetEnvironmentVariable("DESTINATION"); var monitoringClient = new MonitoringClient(provider); string alarmId = null; var alarmDestinations = new List <string>(destinations.Split(',')); try { // Create a new alarm var createAlarmDetails = new CreateAlarmDetails { DisplayName = displayName, CompartmentId = compartmentId, MetricCompartmentId = metricCompartmentId, Namespace = ociNamespace, Query = metricQuery, Resolution = resolution, PendingDuration = pendingDuration, Severity = alertSeverity, Body = body, Destinations = alarmDestinations, RepeatNotificationDuration = repeatDuration, IsEnabled = true }; CreateAlarmRequest createAlarmRequest = new CreateAlarmRequest { CreateAlarmDetails = createAlarmDetails }; var createAlarmResponse = await monitoringClient.CreateAlarm(createAlarmRequest); logger.Info($"Created alarm: {displayName}"); alarmId = createAlarmResponse.Alarm.Id; Suppression suppression = new Suppression { Description = "suppress the alarm", TimeSuppressFrom = suppressFrom, TimeSuppressUntil = suppressUntil }; // Update the new alarm. UpdateAlarmDetails updateAlarmDetails = new UpdateAlarmDetails { Suppression = suppression }; UpdateAlarmRequest updateAlarmRequest = new UpdateAlarmRequest { AlarmId = alarmId, UpdateAlarmDetails = updateAlarmDetails }; UpdateAlarmResponse updateAlarmResponse = await monitoringClient.UpdateAlarm(updateAlarmRequest); logger.Info("Updated alarm"); RemoveAlarmSuppressionRequest removeAlarmSuppressionRequest = new RemoveAlarmSuppressionRequest { AlarmId = alarmId }; RemoveAlarmSuppressionResponse removeAlarmSuppressionResponse = await monitoringClient.RemoveAlarmSuppression(removeAlarmSuppressionRequest); logger.Info("removed suppression for the alarm"); // Get the new alarm GetAlarmRequest getAlarmRequest = new GetAlarmRequest { AlarmId = alarmId }; GetAlarmResponse getAlarmResponse = await monitoringClient.GetAlarm(getAlarmRequest); logger.Info($"Retrieved alarm for id: {getAlarmResponse.Alarm.Id}"); // Get alarm history GetAlarmHistoryRequest getAlarmHistoryRequest = new GetAlarmHistoryRequest { AlarmId = alarmId }; GetAlarmHistoryResponse getAlarmHistoryResponse = await monitoringClient.GetAlarmHistory(getAlarmHistoryRequest); logger.Info($"Alarm history for id: {alarmId}"); foreach (var alarmHistoryEntry in getAlarmHistoryResponse.AlarmHistoryCollection.Entries) { logger.Info($"summary: {alarmHistoryEntry.Summary}"); } // List alarms ListAlarmsRequest listAlarmsRequest = new ListAlarmsRequest { CompartmentId = compartmentId, DisplayName = displayName }; ListAlarmsResponse listAlarmsResponse = await monitoringClient.ListAlarms(listAlarmsRequest); logger.Info("Retrieved alarms"); logger.Info("================="); foreach (var alarmSummary in listAlarmsResponse.Items) { logger.Info($"Alarm: {alarmSummary.DisplayName}"); } // List alarm status ListAlarmsStatusRequest listAlarmsStatusRequest = new ListAlarmsStatusRequest { DisplayName = displayName, CompartmentId = compartmentId }; ListAlarmsStatusResponse listAlarmsStatusResponse = await monitoringClient.ListAlarmsStatus(listAlarmsStatusRequest); logger.Info("Retrieved alarms status"); logger.Info("======================="); foreach (var alarmsStatus in listAlarmsStatusResponse.Items) { logger.Info($"Status of the alarm: {alarmsStatus.DisplayName} is {alarmsStatus.Status}"); } } catch (Exception e) { logger.Error($"Exception: {e}"); } finally { if (alarmId != null) { DeleteAlarmRequest deleteAlarmRequest = new DeleteAlarmRequest { AlarmId = alarmId }; DeleteAlarmResponse deleteAlarmResponse = await monitoringClient.DeleteAlarm(deleteAlarmRequest); logger.Info($"Deleted alam: {displayName}"); } monitoringClient.Dispose(); } logger.Info("End example"); }
public static async Task MainInstance() { logger.Info("Starting example"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); var identityClient = new IdentityClient(provider); var computeClient = new ComputeClient(provider, new ClientConfiguration()); var virtualNetworkClient = new VirtualNetworkClient(provider); var blockStorageClient = new BlockstorageClient(provider); var networkCidrBlock = "10.0.1.0/24"; LaunchInstanceDetails launchInstanceDetails = null; Instance instance = null; BootVolume bootVolume = null; Instance instanceFromBootVolume = null; Vcn vcn = null; Subnet subnet = null; CreateVnicDetails createVnicDetails = null; InternetGateway internetGateway = null; AvailabilityDomain availablityDomain = await getAvailabilityDomains(identityClient, compartmentId); logger.Info($"availability domain is {availablityDomain.Name}"); Shape shape = await getShape(computeClient, compartmentId, availablityDomain); if (shape == null) { logger.Error($"No Shapes available in the availability domain: {availablityDomain.Name}"); return; } logger.Info($"shape is {shape.ShapeProp}"); Image image = await getImage(computeClient, compartmentId, shape); try { vcn = await createVcn(virtualNetworkClient, compartmentId, networkCidrBlock); // The Internet Gateway with updated Route Rules will enable the instance to connect to the public // internet. If it is not desired, remove the following two lines below that create an internet // gateway and add that internet gateway to the VCN route table. internetGateway = await createInternalGateway(virtualNetworkClient, compartmentId, vcn); await addInternetGatewayToDefaultRouteTable(virtualNetworkClient, vcn, internetGateway); subnet = await createSubnet(virtualNetworkClient, compartmentId, availablityDomain, networkCidrBlock, vcn); createVnicDetails = new CreateVnicDetails { SubnetId = subnet.Id }; launchInstanceDetails = new LaunchInstanceDetails { AvailabilityDomain = availablityDomain.Name, CompartmentId = compartmentId, Shape = shape.ShapeProp, CreateVnicDetails = createVnicDetails, ImageId = image.Id }; instance = await createInstance(computeClient, launchInstanceDetails); await printInstance(computeClient, virtualNetworkClient, instance); logger.Info("Instance is being created via boot volume ..."); // This boot volume is created based on the boot volume of previous instance which needs to be running bootVolume = await createBootVolume(blockStorageClient, compartmentId, availablityDomain, image); launchInstanceDetails = createLaunchInstanceDetailsFromBootVolume(launchInstanceDetails, bootVolume); instanceFromBootVolume = await createInstance(computeClient, launchInstanceDetails); await printInstance(computeClient, virtualNetworkClient, instanceFromBootVolume); } catch (Exception e) { logger.Error($"Failed to call LaunchInstance API: {e.Message}"); } finally { logger.Info("cleaning up resources"); if (instanceFromBootVolume != null) { await terminateInstance(computeClient, instanceFromBootVolume); } if (instance != null) { await terminateInstance(computeClient, instance); } if (internetGateway != null) { await clearRouteRulesFromDefaultRouteTable(virtualNetworkClient, vcn); await deleteInternetGateway(virtualNetworkClient, internetGateway); } if (subnet != null) { await deleteSubnet(virtualNetworkClient, subnet); } if (vcn != null) { await deleteVcn(virtualNetworkClient, vcn); } identityClient.Dispose(); computeClient.Dispose(); virtualNetworkClient.Dispose(); blockStorageClient.Dispose(); logger.Info("End example"); } }
public static async Task MainOSBucketTagging() { string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); string bucketName = Environment.GetEnvironmentVariable("BUCKET_NAME"); string tagNamespace = Environment.GetEnvironmentVariable("TAG_NAMESPACE"); string tagName = Environment.GetEnvironmentVariable("TAG_NAME"); logger.Info("Starting example"); // Create Object Storage Client var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var osClient = new ObjectStorageClient(provider, new ClientConfiguration()); logger.Info("Object Storage client created."); GetNamespaceRequest getNamespaceRequest = new GetNamespaceRequest { CompartmentId = compartmentId }; GetNamespaceResponse getNamespaceResponse = await osClient.GetNamespace(getNamespaceRequest); string nSpace = getNamespaceResponse.Value.Trim('"'); logger.Info($"namespace is {nSpace}"); /* * We can assign tags to a bucket at creation time. Like other taggable resources, we can * assign freeform and defined tags to a bucket. Freeform tags are a dictionary of * string-to-string, where the key is the tag name and the value is the tag value. * * Defined tags are a dictionary where the key is the tag namespace (string) and the value is another dictionary. In * this second dictionary, the key is the tag name (string) and the value is the tag value. The tag names have to * correspond to the name of a tag within the specified namespace (and the namespace must exist). */ try { Dictionary <string, string> freeformTags = new Dictionary <string, string>() { { "free", "form" }, { "another", "item" } }; Dictionary <string, object> definedTagsMap = new Dictionary <string, object>() { { tagName, "original value" } }; Dictionary <string, Dictionary <string, object> > definedTags = new Dictionary <string, Dictionary <string, object> >() { { tagNamespace, definedTagsMap } }; CreateBucketDetails createBucketDetails = new CreateBucketDetails { Name = bucketName, CompartmentId = compartmentId, FreeformTags = freeformTags, DefinedTags = definedTags, ObjectEventsEnabled = false }; CreateBucketRequest createBucketRequest = new CreateBucketRequest { CreateBucketDetails = createBucketDetails, NamespaceName = nSpace }; CreateBucketResponse createBucketResponse = await osClient.CreateBucket(createBucketRequest); logger.Info($"Created a bucket with tags Bucket name: {createBucketResponse.Bucket.Name}"); logger.Info("========================================"); definedTags = createBucketResponse.Bucket.DefinedTags; foreach (KeyValuePair <string, Dictionary <string, object> > kvp in definedTags) { foreach (KeyValuePair <string, object> tags in kvp.Value) { logger.Info($"tag key name: {tags.Key} and tag value is {tags.Value}"); } } // Tags come back when retrieving the bucket GetBucketRequest getBucketRequest = new GetBucketRequest { NamespaceName = nSpace, BucketName = bucketName }; GetBucketResponse getBucketResponse = await osClient.GetBucket(getBucketRequest); logger.Info($"Retrieved a bucket with tags Bucket name: {getBucketResponse.Bucket.Name}"); logger.Info("=========================================="); definedTags = getBucketResponse.Bucket.DefinedTags; foreach (KeyValuePair <string, Dictionary <string, object> > kvp in definedTags) { foreach (KeyValuePair <string, object> tags in kvp.Value) { logger.Info($"tag key name: {tags.Key} and tag value is {tags.Value}"); } } /* * Unlike other resources (e.g. instances, VCNs, and block volumes), when listing buckets * tags are not returned by default. Instead, you need to provide a value to the fields * parameter when listing buckets in order to have those tags returned. * * Here we can see the result of providing and not providing that parameter. */ ListBucketsRequest listBucketsRequest = new ListBucketsRequest { CompartmentId = compartmentId, NamespaceName = nSpace }; IEnumerable <BucketSummary> bucketSummaries = osClient.Paginators.ListBucketsRecordEnumerator(listBucketsRequest); foreach (BucketSummary bucketSummary in bucketSummaries) { if (bucketSummary.Name.Equals(bucketName)) { logger.Info($"Bucket summary without tags: Bucket Name: {bucketSummary.Name}"); logger.Info("========================================="); if (bucketSummary.DefinedTags != null) { logger.Error($"expected tags to be zero but got: {bucketSummary.DefinedTags.Count}"); } break; } } List <ListBucketsRequest.FieldsEnum> fields = new List <ListBucketsRequest.FieldsEnum>() { ListBucketsRequest.FieldsEnum.Tags }; listBucketsRequest = new ListBucketsRequest { CompartmentId = compartmentId, NamespaceName = nSpace, Fields = fields }; bucketSummaries = osClient.Paginators.ListBucketsRecordEnumerator(listBucketsRequest); foreach (BucketSummary bucketSummary in bucketSummaries) { if (bucketSummary.Name.Equals(bucketName)) { logger.Info($"Bucket summary with tags: Bucket Name: {bucketSummary.Name}"); logger.Info("======================================"); definedTags = bucketSummary.DefinedTags; foreach (KeyValuePair <string, Dictionary <string, object> > kvp in definedTags) { foreach (KeyValuePair <string, object> tags in kvp.Value) { logger.Info($"tag key name: {tags.Key} and tag value is {tags.Value}"); } } } } /* * We can also update tags on a bucket. Note that this is a total replacement for any * previously set freeform or defined tags. */ Dictionary <string, string> updateFreeformTags = new Dictionary <string, string>() { { "new", "freeform" } }; Dictionary <string, object> updateDefinedTagsMap = new Dictionary <string, object>() { { tagName, "replaced" } }; Dictionary <string, Dictionary <string, object> > updateDefinedTags = new Dictionary <string, Dictionary <string, object> >() { { tagNamespace, updateDefinedTagsMap } }; UpdateBucketDetails updateBucketDetails = new UpdateBucketDetails { Name = bucketName, FreeformTags = updateFreeformTags, DefinedTags = updateDefinedTags }; UpdateBucketRequest updateBucketRequest = new UpdateBucketRequest { NamespaceName = nSpace, BucketName = bucketName, UpdateBucketDetails = updateBucketDetails }; UpdateBucketResponse updateBucketResponse = await osClient.UpdateBucket(updateBucketRequest); logger.Info($"Updated the bucket with new tags Bucket name: {updateBucketResponse.Bucket.Name}"); logger.Info("=============================================="); definedTags = updateBucketResponse.Bucket.DefinedTags; foreach (KeyValuePair <string, Dictionary <string, object> > kvp in definedTags) { foreach (KeyValuePair <string, object> tags in kvp.Value) { logger.Info($"tag key name: {tags.Key} and tag value is {tags.Value}"); } } updateBucketDetails = new UpdateBucketDetails { Name = bucketName, FreeformTags = new Dictionary <string, string>(), DefinedTags = new Dictionary <string, Dictionary <string, object> >() }; updateBucketRequest = new UpdateBucketRequest { NamespaceName = nSpace, BucketName = bucketName, UpdateBucketDetails = updateBucketDetails }; updateBucketResponse = await osClient.UpdateBucket(updateBucketRequest); logger.Info($"cleared the tags for the bucket: {updateBucketResponse.Bucket.Name}"); logger.Info("================================="); // Clean up DeleteBucketRequest deleteBucketRequest = new DeleteBucketRequest { NamespaceName = nSpace, BucketName = bucketName }; await osClient.DeleteBucket(deleteBucketRequest); logger.Info("Deleted the bucket"); logger.Info("Ending example."); } catch (Exception e) { logger.Error($"Failed Object Storage example: {e.Message}"); } finally { osClient.Dispose(); } }
static async Task MainEncryptedKeyAuthentication(string[] args) { string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); DatabaseClient databaseClient = null; logger.Info("Starting example"); try { // Instead of hardcoding the values here, // keyPath and passPhrase should be obtained through environment variables or // parameters to this function. // The caller is responsible for securely providing the values. string keyPath = "/path/to/some/api_key_with_passphrase.pem"; char[] chars = { 's', 'o', 'm', 'e', 'p', 'a', 's', 's', 'p', 'h', 'r', 'a', 's', 'e' }; SecureString passPhrase = new SecureString(); foreach (char c in chars) { passPhrase.AppendChar(c); } // Build FileSecurePrivateKeySupplier // It ensures that private key length is at least 2048, // private key is encrypted with a passphrase, and // only CBC chaining mode is allowed FileSecurePrivateKeySupplier keySupplier = new FileSecurePrivateKeySupplier(keyPath, passPhrase); // There are a few ways to provide config information. // 1. In addition to normal profile parameter, also provide the keySupplier. var providerFromFileAndSupplier = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName, keySupplier); // 2. Provide a custom config path plus keySupplier. var providerFromCustomFileAndSupplier = new ConfigFileAuthenticationDetailsProvider("/some/custom/path/to/config", OciConfigProfileName, keySupplier); // 3. Build a ConfigFile object plus keySupplier. ConfigFile.ConfigAccumulator accumulator = new ConfigFile.ConfigAccumulator(); Dictionary <string, string> entries = new Dictionary <string, string>(); entries.Add("user", "ocid1.user.oc1..somefakeuserocid"); entries.Add("fingerprint", "somefakefingerprint"); entries.Add("tenancy", "ocid1.tenancy.oc1..somefaketenancyocid"); entries.Add("region", "us-phoenix-1"); accumulator.configurationByProfile.Add(OciConfigProfileName, entries);; ConfigFile configFile = new ConfigFile(accumulator, OciConfigProfileName); var providerFromConfigAndSupplier = new ConfigFileAuthenticationDetailsProvider(configFile, keySupplier); // Create Database service client with any of the authentication details providers above databaseClient = new DatabaseClient(providerFromFileAndSupplier); // databaseClient = new DatabaseClient(providerFromCustomFileAndSupplier); // databaseClient = new DatabaseClient(providerFromConfigAndSupplier); // Call ListDbSystems Operation ListDbSystemsRequest listDbSystemsRequest = new ListDbSystemsRequest { CompartmentId = compartmentId }; ListDbSystemsResponse listDbSystemsResponse = await databaseClient.ListDbSystems(listDbSystemsRequest); logger.Info($"Found {listDbSystemsResponse.Items.Count} DbSystems"); foreach (var dbSystem in listDbSystemsResponse.Items) { logger.Info($"DbSystem Name: {dbSystem.DisplayName}"); } } catch (Exception e) { logger.Error($"Got exception: {e.Message}"); } finally { if (databaseClient != null) { databaseClient.Dispose(); } } logger.Info("End Example"); }