Inheritance: IArguments
Example #1
0
        internal static void Main(string[] args)
        {
            Console.WriteLine(@"KonfDBRC : KonfDB Remote Console");
            Console.WriteLine(@"KonfDBRC : Initializing..");
            var arguments = new CommandArgs(args);

            if (arguments.ContainsKey("configFile"))
            {
                var configFile = arguments.GetValue("configFile", "konfdbc.json");
                var instance = ConnectionFactory.GetInstance(new FileInfo(configFile));

                RunFromConfig(instance);
            }
            else if (File.Exists("konfdbc.json"))
            {
                var configFile = arguments.GetValue("configFile", "konfdbc.json");
                var instance = ConnectionFactory.GetInstance(new FileInfo(configFile));

                RunFromConfig(instance);
            }
            else
            {
                Console.WriteLine(@" ");
            }

            Console.WriteLine(@"Thanks for using KonfDBRC. Press any key to exit.");
            Console.ReadKey();
            Console.WriteLine();
        }
Example #2
0
 public void TestSplitOnStartupArgs()
 {
     CommandArgs args = new CommandArgs("-console -port:8080 -dbconfig:dbproviders.json -dbprovider:mydb");
     Assert.AreEqual("console", args[0]);
     Assert.AreEqual("8080", args["port"]);
     Assert.AreEqual("dbproviders.json", args["dbconfig"]);
     Assert.AreEqual("mydb", args["dbprovider"]);
 }
Example #3
0
        internal static BaseLogger CreateInstance(LogElement logElement)
        {
            if (_instance == null)
            {
                Type providerType = Type.GetType(logElement.ProviderType);
                if (providerType == null)
                    throw new InvalidConfigurationException("Could not locate Log Provider :" + logElement.ProviderType);

                if (!providerType.ImplementsClass<BaseLogger>())
                    throw new InvalidConfigurationException("Log Provider does not implement ILogger:" +
                                                            logElement.ProviderType);

                var args = new CommandArgs(logElement.Parameters);
                _instance = (BaseLogger) Activator.CreateInstance(providerType, args);
            }

            return _instance;
        }
Example #4
0
        internal static void Main(string[] args)
        {
            IArguments argsDictionary = new CommandArgs(args);
            var backgroundService = new KonfDBH(argsDictionary);
            var services = new ServiceBase[] {backgroundService};

            if (argsDictionary.ContainsKey("install"))
            {
                ManagedInstallerClass.InstallHelper(new[]
                {
                    Assembly.GetExecutingAssembly().Location
                });
            }
            else if (argsDictionary.ContainsKey("uninstall"))
            {
                ManagedInstallerClass.InstallHelper(new[]
                {
                    "/u",
                    Assembly.GetExecutingAssembly().Location
                });
            }
            else if (argsDictionary.ContainsKey("console")) // console mode
            {
                #region Console

                var contextSettings = new ContextSettings
                {
                    CommandFactory = new CommandFactory()
                };
                HostContext.CreateFrom(argsDictionary.GetValue("configPath", "konfdb.json"), contextSettings);
                CurrentHostContext.Default.Log.Debug("Running in Console Mode");
                Console.SetWindowPosition(0, 0);
                Console.BackgroundColor = ConsoleColor.DarkGray;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Clear();

                services.RunService();

                var shutdown = new ManualResetEvent(false);
                var thread = new Thread(() =>
                {
                    while (!shutdown.WaitOne(0))
                    {
                        Thread.Sleep(1000);
                    }
                });
                thread.Start();

                bool exitLoop = false;
                var commandService = backgroundService.ServiceFacade;
                string internalSessionId = Guid.NewGuid().ToString();
                while (!exitLoop)
                {
                    Console.Write(">");
                    string line = Console.ReadLine();

                    if (string.IsNullOrEmpty(line)) continue;

                    var commandOutput = commandService.ExecuteCommand(new ServiceRequestContext
                    {
                        Command = line,
                        Token = backgroundService.AuthenticationToken,
                        SessionId = internalSessionId
                    });
                    if (commandOutput == null) continue;

                    if (commandOutput.MessageType == CommandOutput.DisplayMessageType.Message)
                        Console.WriteLine(commandOutput.Data != null
                            ? commandOutput.Data.ToJson()
                            : commandOutput.DisplayMessage);
                    else if (commandOutput.MessageType == CommandOutput.DisplayMessageType.Error)
                        Console.WriteLine(commandOutput.DisplayMessage);

                    if (commandOutput.PostAction == CommandOutput.PostCommandAction.ExitApplication)
                    {
                        shutdown.Set();
                        thread.Join();

                        services.StopService();

                        CurrentHostContext.Default.Log.Info("Exiting...");

                        Thread.Sleep(500);

                        exitLoop = true;
                    }
                }

                #endregion
            }
            else
            {
                ServiceBase.Run(services);
            }
        }
Example #5
0
        public void TestAzureDatabaseConnectionString()
        {
            var args =
                new CommandArgs(
                    "-providerType=AzureSqlProvider -host=tcp:host.database.windows.net -port=1433 -instanceName=konfdb -username=userid@host -password=dBPassword");

            Assert.AreEqual("AzureSqlProvider", args["providerType"]);
            Assert.AreEqual("tcp:host.database.windows.net", args["host"]);
            Assert.AreEqual("1433", args["port"]);
            Assert.AreEqual("konfdb", args["instanceName"]);
            Assert.AreEqual("userid@host", args["username"]);
            Assert.AreEqual("dBPassword", args["password"]);
        }
Example #6
0
 public void TestAzureUserConnectionString()
 {
     var args = new CommandArgs("-username=myuser -password=pwd");
     Assert.AreEqual("myuser", args["username"]);
     Assert.AreEqual("pwd", args["password"]);
 }
Example #7
0
 public void TestSplitOnGetSuiteWithQuotesDifferentSeparator()
 {
     CommandArgs args = new CommandArgs(String.Format("GetSuite /name:{0}", StringWithQuotes));
     Assert.AreEqual(StringWithQuotes, args["name"]);
 }
Example #8
0
 public void TestSplitOnGetSuite()
 {
     CommandArgs args = new CommandArgs("GetSuite /name=Suite");
     Assert.AreEqual("Suite", args["name"]);
 }
Example #9
0
 public void TestSplitOnCreateSuiteWithQuotes()
 {
     CommandArgs args = new CommandArgs(String.Format("NewSuite /name={0}", StringWithQuotes));
     StringAssert.Contains(StringWithQuotes, args["name"]);
 }
        private CurrentHostContext(IHostConfig configuration, ContextSettings settings)
        {
            Audit = configuration.Runtime.Audit;
            Config = configuration;
            UserTokens = new List<string>();

            var logger = LogFactory.CreateInstance(configuration.Runtime.LogInfo);
            var commandArgs = new CommandArgs(configuration.Runtime.Parameters);
            var cache = CacheFactory.Create(configuration.Caching);
            cache.ItemRemoved += (sender, args) =>
            {
                Log.Debug("Item removed from cache: " + args.CacheKey + " Reason : " + args.RemoveReason);
                if (args.Value is AuthenticationOutput)
                {
                    // User has been removed from cache. Login expired
                    UserTokens.Remove(args.CacheKey);
                }
            };

            CurrentContext.CreateDefault(logger, commandArgs, cache);

            //override the passwords if encrypted
            if (configuration.Certificate.Encryption != null)
            {
                var certificate = configuration.Certificate.Encryption.GetX509Certificate();
                if (certificate != null)
                {
                    DecryptPasswords(configuration, certificate);
                }
            }

            CommandFactory = settings.CommandFactory;
            Provider = GetDatabaseProviderInstance(configuration);
        }
Example #11
0
        private IHostConfig LoadConfigurationFromAzureUI()
        {
            var userConnectionString = RoleEnvironment.GetConfigurationSettingValue("konfdb.runtime.superuser");
            var databaseConnectionString = RoleEnvironment.GetConfigurationSettingValue("konfdb.database");
            var defaultCertificateSettings = RoleEnvironment.GetConfigurationSettingValue("konfdb.certificate.default");
            var encryptionCertificateSettings =
                RoleEnvironment.GetConfigurationSettingValue("konfdb.certificate.encryption");

            var superuserArgs = new CommandArgs(userConnectionString);
            var databaseArgs = new CommandArgs(databaseConnectionString);
            var defaultCertificateArgs = new CommandArgs(defaultCertificateSettings);
            var encryptionCertificateArgs = new CommandArgs(encryptionCertificateSettings);


            IHostConfig hostConfig = new HostConfig();
            hostConfig.Caching.ProviderType = typeof (InRoleCacheStore).AssemblyQualifiedName;
            hostConfig.Caching.Enabled = true;

            hostConfig.Runtime.Audit = new AuditElement {Enabled = true};
            hostConfig.Runtime.LogInfo = new LogElement
            {
                ProviderType = typeof (AzureLogger).AssemblyQualifiedName
            };

            if (string.IsNullOrEmpty(defaultCertificateSettings))
            {
                hostConfig.Runtime.ServiceSecurity = ServiceSecurityMode.None;
            }
            else
            {
                hostConfig.Runtime.ServiceSecurity = ServiceSecurityMode.BasicSSL;
                hostConfig.Certificate.DefaultKey = "default";
                var certificateConfig = new CertificateProviderConfiguration
                {
                    CertificateKey = "default",
                    FindBy =
                        defaultCertificateArgs.GetValue("findBy", X509FindType.FindByThumbprint.ToString())
                            .FromJsonToObject<X509FindType>(),
                    StoreLocation =
                        defaultCertificateArgs.GetValue("storeLocation", StoreLocation.CurrentUser.ToString())
                            .FromJsonToObject<StoreLocation>(),
                    StoreName =
                        defaultCertificateArgs.GetValue("storeName", StoreName.My.ToString())
                            .FromJsonToObject<StoreName>(),
                    Value = defaultCertificateArgs.GetValue("value", string.Empty)
                };
                hostConfig.Certificate.Certificates.Add(certificateConfig);
            }

            if (string.IsNullOrEmpty(encryptionCertificateSettings))
            {
                hostConfig.Certificate.EncryptionKey = "default";
            }
            else
            {
                hostConfig.Certificate.EncryptionKey = "encryption";
                var certificateConfig = new CertificateProviderConfiguration
                {
                    CertificateKey = "encryption",
                    FindBy =
                        encryptionCertificateArgs.GetValue("findBy", X509FindType.FindByThumbprint.ToString())
                            .FromJsonToObject<X509FindType>(),
                    StoreLocation =
                        encryptionCertificateArgs.GetValue("storeLocation", StoreLocation.CurrentUser.ToString())
                            .FromJsonToObject<StoreLocation>(),
                    StoreName =
                        encryptionCertificateArgs.GetValue("storeName", StoreName.My.ToString())
                            .FromJsonToObject<StoreName>(),
                    Value = encryptionCertificateArgs.GetValue("value", string.Empty)
                };
                hostConfig.Certificate.Certificates.Add(certificateConfig);
            }

            hostConfig.Runtime.SuperUser = new UserElement
            {
                Username = superuserArgs.GetValue("username", "azureuser"),
                Password = superuserArgs.GetValue("password", "aZuReu$rpWd"),
                IsEncrypted = bool.Parse(databaseArgs.GetValue("isEncrypted", bool.FalseString.ToLower()))
            };

            hostConfig.Database.DefaultKey = "default";
            hostConfig.Database.Databases.Add(new DatabaseProviderConfiguration
            {
                Key = "default",
                Host = databaseArgs["host"],
                Port = int.Parse(databaseArgs["port"]),
                InstanceName = databaseArgs["instanceName"],
                Username = databaseArgs["username"],
                Password = databaseArgs["password"],
                IsEncrypted = bool.Parse(databaseArgs.GetValue("isEncrypted", bool.FalseString.ToLower())),
                ProviderType = GetProvider(databaseArgs["providerType"]),
                Location = databaseArgs.GetValue("location", string.Empty)
            });

            foreach (var endPoint in RoleEnvironment.CurrentRoleInstance.InstanceEndpoints)
            {
                Debug.WriteLine(endPoint.Key + " " + endPoint.Value.IPEndpoint.Port + " " + endPoint.Value.Protocol);

                if (!endPoint.Key.StartsWith("KonfDB"))
                    continue;

                hostConfig.Runtime.Server.Add(new ServiceTypeConfiguration
                {
                    Port = endPoint.Value.IPEndpoint.Port,
                    Type = ConvertAzureProtocol(endPoint.Key, endPoint.Value.Protocol)
                });
            }

            return hostConfig;
        }