public void NoProfile()
 {
     Assert.Throws<Exception>(
         delegate
         {
             ConfigFile config = ConfigFileReader.Parse(ConfigPath, "USER_A");
         }
     );
 }
 public void NoLeadingFile()
 {
     Assert.Throws<FileNotFoundException>(
         delegate
         {
             ConfigFile config = ConfigFileReader.Parse("abc");
         }
     );
 }
        public void ProfiletestMyProfile()
        {
            ConfigFile config = ConfigFileReader.Parse(ConfigPath, "myProfile");

            Assert.Equal("ocid1.tenancy.oc1..test", config.Get("tenancy"));
            Assert.Equal("ocid1.user.oc1..myProfile", config.Get("user"));
            Assert.Equal("7g:8h:9i:0j:1k:2l", config.Get("fingerprint"));
            Assert.Equal("~/.oci/my_key.pem", config.Get("key_file"));
            Assert.Equal("ocid1.compartment.oc1..Mytest", config.Get("custom_compartment_id"));
        }
        public void ProfiletestDEFAULT()
        {
            ConfigFile config = ConfigFileReader.Parse(ConfigPath, "DEFAULT");

            Assert.Equal("ocid1.tenancy.oc1..test", config.Get("tenancy"));
            Assert.Equal("ocid1.user.oc1..test", config.Get("user"));
            Assert.Equal("1a:2b:3c:4d:5e:6f", config.Get("fingerprint"));
            Assert.Equal("~/.oci/api_key.pem", config.Get("key_file"));
            Assert.Equal("ocid1.compartment.oc1..test", config.Get("custom_compartment_id"));
        }
 public void LineWithNoValue()
 {
     Assert.Throws<KeyNotFoundException>(
         delegate
         {
             ConfigFile config = ConfigFileReader.Parse(ConfigPath);
             string tenancy = config.Get("unit_test_no_value_config");
         }
     );
 }
        private string ValidateProfileName(string profileName)
        {
            string valid = null;

            try
            {
                profileName = profileName.ToUpperInvariant();
                ConfigFileReader.Parse(ConfigPath, profileName);
                WriteWarning($"Profile {profileName} already exists!! Can't specify a profile that exists.");
            }
            catch (ArgumentException ex)
            {
                if (ex.Message.Contains(profileName))
                {
                    valid = profileName;
                }
            }
            return(valid);
        }
Example #7
0
        public void SetRegionTest(string profile, string expectedRegionId)
        {
            string path = @".\testconfig" + DateTime.Now.ToFileTimeUtc();

            try
            {
                File.WriteAllText(path, profile);
                Region region;
                var    config = ConfigFileReader.Parse(path);
                //test retrieving region not present in config but from env variable.
                if (String.IsNullOrEmpty(config.GetValue("region")))
                {
                    Environment.SetEnvironmentVariable(ConfigUtils.REGION_ENV_VAR_NAME, expectedRegionId);
                }
                ConfigUtils.SetRegion(config, out region);
                Assert.Equal(region.RegionId, expectedRegionId);
            }
            finally
            {
                File.Delete(path);
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("+----------------------------------------+");
            Console.WriteLine("|                                        |");
            Console.WriteLine("|             OCISDK Example             |");
            Console.WriteLine("|                                        |");
            Console.WriteLine("+----------------------------------------+");

            string configPath = ".oci/config";

            System.OperatingSystem os = System.Environment.OSVersion;
            // windows
            if (os.Platform == PlatformID.Win32NT)
            {
                string rootPath = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
                configPath = $"{rootPath}/{configPath}";
                if (!Directory.Exists($"{rootPath}/.oci"))
                {
                    Directory.CreateDirectory($"{rootPath}/.oci");
                }
            }
            else
            {
                configPath = $"/home/user/{configPath}";
            }

            string     profile;
            ConfigFile configReader;

            if (File.Exists(configPath))
            {
                Console.Write("Connection ProfileName(Empty Input is DEFAULT): ");
                profile = Console.ReadLine();
                if (string.IsNullOrEmpty(profile))
                {
                    profile = "DEFAULT";
                }

                // load connection file
                configReader = ConfigFileReader.Parse(configPath, profile);
            }
            else
            {
                profile = "DEFAULT";

                // create connection file
                Console.WriteLine("Create connection settings to Oracle Cloud Infrastructure");

                Console.Write("TenancyId (Required): ");
                string tenancyId = OCIDInput();

                Console.Write("UserId (Required): ");
                string userId = OCIDInput();

                Console.Write("Fingerprint (Required): ");
                string fingerprint = KeyInput();

                Console.Write("PrivateKeyPath (Required): ");
                string privateKeyPath = KeyInput();

                Console.Write("PrivateKeyPassphrase: ");
                string privateKeyPassphrase = InputPassword();

                string testFileContentsMyProfile = $"[{profile}]\n" +
                                                   $"tenancy={tenancyId}\n" +
                                                   $"user={userId}\n" +
                                                   $"fingerprint={fingerprint}\n" +
                                                   $"key_file={privateKeyPath}\n" +
                                                   $"pass_phrase={privateKeyPassphrase}\n";

                File.WriteAllText(configPath, testFileContentsMyProfile);

                configReader = ConfigFileReader.Parse(configPath, profile);
            }

            // ClientConfig settings
            var config = new ClientConfig
            {
                TenancyId            = configReader.Get("tenancy"),
                UserId               = configReader.Get("user"),
                Fingerprint          = configReader.Get("fingerprint"),
                PrivateKey           = configReader.Get("key_file"),
                PrivateKeyPassphrase = configReader.Get("pass_phrase"),
                HomeRegion           = configReader.Get("home_region"),
            };

            while (true)
            {
                Console.WriteLine("");
                Console.WriteLine("Mode Selection....");
                Console.WriteLine("[1]: All Example run");
                Console.WriteLine("[2]: Display TenatcyInfomation and Compartment Example");
                Console.WriteLine("[3]: Display VirtualNetwork List Example");
                Console.WriteLine("[4]: Display Instance List Example");
                Console.WriteLine("[5]: Display BlockStorage List Example");
                Console.WriteLine("[6]: Display Audit List Example");
                Console.WriteLine("[7]: Display ObjectStorage List Example");
                Console.WriteLine("[8]: SearchResouces Example");
                Console.WriteLine("[9]: Monitoring Example");
                Console.WriteLine("[a]: Database Example");
                Console.WriteLine("[b]: DNS Example");
                Console.WriteLine("[c]: LoadBalancer Example");
                Console.WriteLine("[d]: Users Example");
                Console.WriteLine("[e]: Notification Example");
                Console.WriteLine("[f]: Budgets Example");
                Console.WriteLine("[g]: ObjectStorageDirectoryInfo Example");
                Console.WriteLine("[h]: Usage Example");
                Console.WriteLine("[i]: SupportManagement Example");
                Console.WriteLine("[ESC]: Exit Example");
                Console.WriteLine("");

                var presskey = Console.ReadKey(true);
                if (presskey.Key == ConsoleKey.Escape)
                {
                    Console.WriteLine("Exit....");
                    return;
                }
                var mode = presskey.KeyChar;

                // Indentity
                // Compartment
                if (mode == '1' || mode == '2')
                {
                    IdentityCompartmentExample.CompartmentConsoleDisplay(config);
                }

                // Core
                // VirtualNetworks
                if (mode == '1' || mode == '3')
                {
                    CoreVirtualNetworkExample.VirtualNetworkExample(config);
                }

                // Instances
                if (mode == '1' || mode == '4')
                {
                    CoreInstanceExample.InstanceConsoleDisplay(config);
                }

                // BlockStorage
                // BootVolumes
                if (mode == '1' || mode == '5')
                {
                    BlockStorageExample.BlockStoragesConsoleDisplay(config);
                }

                // Audit
                if (mode == '1' || mode == '6')
                {
                    AuditExample.AuditDisplay(config);
                }

                // ObjectStorage
                if (mode == '1' || mode == '7')
                {
                    ObjectStorageExample.DisplayObjectStorage(config);
                }

                // search
                if (mode == '1' || mode == '8')
                {
                    SearchExample.SearchResourcesExample(config);
                }

                // monitoring
                if (mode == '1' || mode == '9')
                {
                    MonitoringExample.MonitoringResourceExample(config);
                }

                //database
                if (mode == '1' || mode == 'a')
                {
                    DatabaseExample.DatabaseConsoleDisplay(config);
                }

                //dns
                if (mode == '1' || mode == 'b')
                {
                    DNSExample.DNSConsoleDisplay(config);
                }

                //loadbalancer
                if (mode == '1' || mode == 'c')
                {
                    LoadBalancerExample.ConsoleDisplay(config);
                }

                //users
                if (mode == '1' || mode == 'd')
                {
                    IdentityUsersExample.ConsoleDisplay(config);
                }

                // notification
                if (mode == '1' || mode == 'e')
                {
                    NotificationExample.ResourcesExample(config);
                }

                // budget
                if (mode == '1' || mode == 'f')
                {
                    BudgetsExample.ConsoleDisplay(config);
                }

                //objectstorage directory info
                if (mode == '1' || mode == 'g')
                {
                    ObjectStorageDirectoryInfoExample.Example(config);
                }

                // usage
                if (mode == '1' || mode == 'h')
                {
                    UsageExample.Example(config);
                }

                // SupportManagement
                if (mode == '1' || mode == 'i')
                {
                    SupportManagementExample.Example(config);
                }
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("+----------------------------------------+");
            Console.WriteLine("|                                        |");
            Console.WriteLine("|         OCISDK SessionExample          |");
            Console.WriteLine("|                                        |");
            Console.WriteLine("+----------------------------------------+");

            string configPath = ".oci/config";

            System.OperatingSystem os = System.Environment.OSVersion;
            // windows
            if (os.Platform == PlatformID.Win32NT)
            {
                string rootPath = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
                configPath = $"{rootPath}/{configPath}";
                if (!Directory.Exists($"{rootPath}/.oci"))
                {
                    Directory.CreateDirectory($"{rootPath}/.oci");
                }
            }
            else
            {
                configPath = $"/home/user/{configPath}";
            }

            string     profile;
            ConfigFile configReader;

            if (File.Exists(configPath))
            {
                Console.Write("Connection ProfileName(Empty Input is DEFAULT): ");
                profile = Console.ReadLine();
                if (string.IsNullOrEmpty(profile))
                {
                    profile = "DEFAULT";
                }

                // load connection file
                configReader = ConfigFileReader.Parse(configPath, profile);
            }
            else
            {
                profile = "DEFAULT";

                // create connection file
                Console.WriteLine("Create connection settings to Oracle Cloud Infrastructure");

                Console.Write("TenancyId (Required): ");
                string tenancyId = OCIDInput();

                Console.Write("UserId (Required): ");
                string userId = OCIDInput();

                Console.Write("Fingerprint (Required): ");
                string fingerprint = KeyInput();

                Console.Write("PrivateKeyPath (Required): ");
                string privateKeyPath = KeyInput();

                Console.Write("PrivateKeyPassphrase: ");
                string privateKeyPassphrase = InputPassword();

                string testFileContentsMyProfile = $"[{profile}]\n" +
                                                   $"tenancy={tenancyId}\n" +
                                                   $"user={userId}\n" +
                                                   $"fingerprint={fingerprint}\n" +
                                                   $"key_file={privateKeyPath}\n" +
                                                   $"pass_phrase={privateKeyPassphrase}\n";

                File.WriteAllText(configPath, testFileContentsMyProfile);

                configReader = ConfigFileReader.Parse(configPath, profile);
            }

            // ClientConfig settings
            var         configSt = new ClientConfigStream();
            IOciSession session;

            using (var st = File.OpenText(configReader.Get("key_file")))
            {
                configSt = new ClientConfigStream
                {
                    TenancyId            = configReader.Get("tenancy"),
                    UserId               = configReader.Get("user"),
                    Fingerprint          = configReader.Get("fingerprint"),
                    PrivateKey           = st,
                    PrivateKeyPassphrase = configReader.Get("pass_phrase"),
                    AccountId            = configReader.Get("accountId"),
                    IdentityDomain       = configReader.Get("domain"),
                    UserName             = configReader.Get("user"),
                    Password             = configReader.Get("password"),
                    HomeRegion           = configReader.Get("home_region")
                };

                session = new OciSession(configSt);
            }

            var comClient = session.GetCommercialClient();
            var listPurchaseEntitlementsRequest = new ListPurchaseEntitlementsRequest
            {
                CompartmentId = configSt.TenancyId
            };
            var purchase = comClient.ListPurchaseEntitlements(listPurchaseEntitlementsRequest);

            var getServiceEntitlementRegistrationsRequest = new ListServiceEntitlementRegistrationsRequest()
            {
                CompartmentId = configSt.TenancyId
            };
            var services = comClient.ListServiceEntitlementRegistrations(getServiceEntitlementRegistrationsRequest);

            var costClient = session.GetUsageCostsClient();
            var getSubscriptionInfoRequest = new GetSubscriptionInfoRequest
            {
                TenancyId = configSt.TenancyId
            };
            var subsc = costClient.GetSubscriptionInfo(getSubscriptionInfoRequest);

            // get Client
            var identityClient = session.GetIdentityClient();

            var getTenancyRequest = new GetTenancyRequest()
            {
                TenancyId = configSt.TenancyId
            };
            var getTenacy = identityClient.GetTenancy(getTenancyRequest);

            Console.WriteLine($"tenantName: {getTenacy.Tenancy.Name}");

            // get compute
            var computeClient = session.GetComputeClient();

            IDictionary <string, IDictionary <string, string> > tags = new Dictionary <string, IDictionary <string, string> >();

            tags.Add("CostTracking", new Dictionary <string, string> {
                { "cost-trakcerA", "aaaa" }
            });

            var dbClient = session.GetDatabaseClient();
            GetDbSystemRequest getDbSystemRequest = new GetDbSystemRequest()
            {
                DbSystemId = "ocid1.dbsystem.oc1.iad.abuwcljrbukbjzlameegvsn3u7qb3qcqvtcdvl74jxfth7xjsya7cxkdpibq"
            };
            var dbSystem = dbClient.GetDbSystem(getDbSystemRequest);

            UpdateDbSystemRequest updateDbSystemRequest = new UpdateDbSystemRequest()
            {
                DbSystemId            = "ocid1.dbsystem.oc1.iad.abuwcljrbukbjzlameegvsn3u7qb3qcqvtcdvl74jxfth7xjsya7cxkdpibq",
                UpdateDbSystemDetails = new OCISDK.Core.Database.Model.UpdateDbSystemDetails()
                {
                    DefinedTags = tags
                }
            };

            dbClient.UpdateDbSystem(updateDbSystemRequest);

            var listCompartmentRequest = new ListCompartmentRequest()
            {
                CompartmentId          = getTenacy.Tenancy.Id,
                CompartmentIdInSubtree = true
            };
            var cmparts = identityClient.ListCompartment(listCompartmentRequest);

            foreach (var com in cmparts.Items)
            {
                Console.WriteLine($"compartmentName: {com.Name}");

                var listInstanceRequest = new ListInstancesRequest()
                {
                    CompartmentId = com.Id,
                    Limit         = 10,
                    SortOrder     = SortOrder.ASC
                };
                var instances = computeClient.ListInstances(listInstanceRequest);
                foreach (var ins in instances.Items)
                {
                    Console.WriteLine($"rootCompartmentInstanceName: {ins.DisplayName}");


                    var workReqestClient        = session.GetWorkRequestClient();
                    var listWorkRequestsRequest = new OCISDK.Core.Core.Request.WorkRequest.ListWorkRequestsRequest()
                    {
                        CompartmentId = ins.CompartmentId,
                        ResourceId    = ins.Id
                    };
                    var workreqs = workReqestClient.ListWorkRequests(listWorkRequestsRequest);
                    foreach (var wq in workreqs.Items)
                    {
                        Console.WriteLine($"\tWorkRequest: {wq.OperationType}, state:{wq.Status}");

                        var getWorkRequestRequest = new OCISDK.Core.Core.Request.WorkRequest.GetWorkRequestRequest()
                        {
                            WorkRequestId = wq.Id
                        };
                        var gw = workReqestClient.GetWorkRequest(getWorkRequestRequest);
                        Console.WriteLine($"\taccepted:{gw.WorkRequest.TimeAccepted}, finished:{gw.WorkRequest.TimeFinished}");

                        var listWorkRequestErrorsRequest = new OCISDK.Core.Core.Request.WorkRequest.ListWorkRequestErrorsRequest()
                        {
                            WorkRequestId = wq.Id,
                            Limit         = 100,
                            SortOrder     = SortOrder.ASC
                        };
                        var wqErrors = workReqestClient.ListWorkRequestErrors(listWorkRequestErrorsRequest);
                        foreach (var error in wqErrors.Items)
                        {
                            Console.WriteLine($"\tErrorCode: {error.Code}, ErrorMessage:{error.Message}, ErrorTimeStamp:{error.Timestamp}");
                        }

                        var listWorkRequestLogsRequest = new OCISDK.Core.Core.Request.WorkRequest.ListWorkRequestLogsRequest()
                        {
                            WorkRequestId = wq.Id,
                            Limit         = 100,
                            SortOrder     = SortOrder.ASC
                        };
                        var wqLogs = workReqestClient.ListWorkRequestLogs(listWorkRequestLogsRequest);
                        foreach (var log in wqLogs.Items)
                        {
                            Console.WriteLine($"\tLogMessage:{log.Message}, LogTimeStamp:{log.Timestamp}");
                        }
                    }
                }
            }

            Console.WriteLine("Exit with key press...");
            Console.ReadLine();
        }
 public ConfigFileAuthenticationDetailsProvider(string configurationFilePath, string profile) : this(ConfigFileReader.Parse(configurationFilePath, profile))
 {
 }
 /// <summary>Constructor. Reads from the config file at given location.</summary>
 public ConfigFileAuthenticationDetailsProvider(string configurationFilePath, string profile, FilePrivateKeySupplier keySupplier = null) : this(ConfigFileReader.Parse(configurationFilePath, profile), keySupplier)
 {
 }
        static async Task Main(string[] args)
        {
            Console.WriteLine("+----------------------------------------+");
            Console.WriteLine("|                                        |");
            Console.WriteLine("|       OCISDK SessionAsyncExample       |");
            Console.WriteLine("|                                        |");
            Console.WriteLine("+----------------------------------------+");

            string configPath = ".oci/config";

            System.OperatingSystem os = System.Environment.OSVersion;
            // windows
            if (os.Platform == PlatformID.Win32NT)
            {
                string rootPath = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
                configPath = $"{rootPath}/{configPath}";
                if (!Directory.Exists($"{rootPath}/.oci"))
                {
                    Directory.CreateDirectory($"{rootPath}/.oci");
                }
            }
            else
            {
                configPath = $"/home/user/{configPath}";
            }

            string     profile;
            ConfigFile configReader;

            if (File.Exists(configPath))
            {
                Console.Write("Connection ProfileName(Empty Input is DEFAULT): ");
                profile = Console.ReadLine();
                if (string.IsNullOrEmpty(profile))
                {
                    profile = "DEFAULT";
                }

                // load connection file
                configReader = ConfigFileReader.Parse(configPath, profile);
            }
            else
            {
                profile = "DEFAULT";

                // create connection file
                Console.WriteLine("Create connection settings to Oracle Cloud Infrastructure");

                Console.Write("TenancyId (Required): ");
                string tenancyId = OCIDInput();

                Console.Write("UserId (Required): ");
                string userId = OCIDInput();

                Console.Write("Fingerprint (Required): ");
                string fingerprint = KeyInput();

                Console.Write("PrivateKeyPath (Required): ");
                string privateKeyPath = KeyInput();

                Console.Write("PrivateKeyPassphrase: ");
                string privateKeyPassphrase = InputPassword();

                string testFileContentsMyProfile = $"[{profile}]\n" +
                                                   $"tenancy={tenancyId}\n" +
                                                   $"user={userId}\n" +
                                                   $"fingerprint={fingerprint}\n" +
                                                   $"key_file={privateKeyPath}\n" +
                                                   $"pass_phrase={privateKeyPassphrase}\n";

                File.WriteAllText(configPath, testFileContentsMyProfile);

                configReader = ConfigFileReader.Parse(configPath, profile);
            }

            // ClientConfig settings
            var         configSt = new ClientConfigStream();
            IOciSession session;
            var         stt = File.ReadAllText(configReader.Get("key_file"));


            using (var st = File.OpenText(configReader.Get("key_file")))
            {
                configSt = new ClientConfigStream
                {
                    TenancyId            = configReader.Get("tenancy"),
                    UserId               = configReader.Get("user"),
                    Fingerprint          = configReader.Get("fingerprint"),
                    PrivateKey           = st,
                    PrivateKeyPassphrase = configReader.Get("pass_phrase"),
                    AccountId            = configReader.Get("accountId"),
                    DomainName           = configReader.Get("domain_name"),
                    IdentityDomain       = configReader.Get("identity_domain"),
                    UserName             = configReader.Get("user_name"),
                    Password             = configReader.Get("password"),
                    HomeRegion           = configReader.Get("home_region")
                };

                session = new OciSession(configSt);
            }

            // get Client
            var identityClientAsync       = session.GetIdentityClientAsync();
            var computeClientAsync        = session.GetComputeClientAsync();
            var virtualNetworkClientAsync = session.GetVirtualNetworkClientAsync();

            // get tenant
            var getTenancyRequest = new GetTenancyRequest()
            {
                TenancyId = configSt.TenancyId
            };
            var getTenacy = await identityClientAsync.GetTenancy(getTenancyRequest);

            Console.WriteLine($"tenantName: {getTenacy.Tenancy.Name}");

            // get compartments
            var listCompartmentRequest = new ListCompartmentRequest()
            {
                CompartmentId          = configSt.TenancyId,
                AccessLevel            = ListCompartmentRequest.AccessLevels.ACCESSIBLE,
                CompartmentIdInSubtree = true
            };
            var compartments = await identityClientAsync.ListCompartment(listCompartmentRequest);

            // loop get compartments async
            var infoTasks = new List <Task>();

            foreach (var com in compartments.Items)
            {
                if (com.LifecycleState != "ACTIVE")
                {
                    continue;
                }

                infoTasks.Add(LoadCompartmentDetail(com, identityClientAsync));
                infoTasks.Add(LoadInstances(com, computeClientAsync));
                infoTasks.Add(LoadVcn(com, virtualNetworkClientAsync));
            }

            await Task.WhenAll(infoTasks);

            Console.WriteLine();
            Console.WriteLine("Exit with key press...");
            Console.ReadLine();
        }