Exemplo n.º 1
0
        private static void Setup(out string startDirectory, out FileInfo[] files)
        {
            string resultDirectory = Arguments.Contains("data") ? Arguments["data"] : ".";
            string filePrefix      = Arguments["dataPrefix"].Or("BamTests");
            List <ITestRunListener <UnitTestMethod> > testRunListeners = new List <ITestRunListener <UnitTestMethod> > {
                new UnitTestRunListener(resultDirectory, $"{filePrefix}_{DateTime.Now.Date.ToString("MM_dd_yyyy")}")
            };

            string reportHost = Arguments["testReportHost"];

            if (string.IsNullOrEmpty(reportHost))
            {
                reportHost = DefaultConfiguration.GetAppSetting("TestReportHost", string.Empty);
            }
            if (!string.IsNullOrEmpty(reportHost))
            {
                testRunListeners.Add(new UnitTestRunReportingListener(reportHost));
            }

            GetUnitTestRunListeners = () => testRunListeners;
            startDirectory          = Environment.CurrentDirectory;
            DirectoryInfo testDir = GetTestDirectory();

            Environment.CurrentDirectory = testDir.FullName;

            files = GetTestFiles(testDir);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initialize roles from the config file.  This will look for the
        /// appSetting with the key "Roles" and assume that it is a
        /// semi-colon (;) separated list of key value pairs delimited by colons (:)
        /// where the key is the name of a role to initialize and the
        /// value is a comma separated list of users to create and add to
        /// the role.
        /// </summary>
        public static void InitializeFromConfig()
        {
            string[]        roleNameToUserNames = DefaultConfiguration.GetAppSetting("Roles", "").DelimitSplit(";", true);
            DaoRoleProvider provider            = new DaoRoleProvider();

            roleNameToUserNames.Each(keyValues =>
            {
                string[] split = keyValues.DelimitSplit(":", true);
                Expect.IsTrue(split.Length <= 2, "Unrecognized Role config value.");
                string role        = split[0];
                string[] userNames = split.Length == 2 ? split[1].DelimitSplit(",", true) : new string[] { };
                provider.CreateRole(role);

                if (userNames.Length > 0)
                {
                    List <string> usersToAddToRole = new List <string>();
                    userNames.Each(userName =>
                    {
                        User.Ensure(userName);
                        usersToAddToRole.Add(userName);
                    });
                    if (usersToAddToRole.Count > 0)
                    {
                        provider.AddUsersToRoles(usersToAddToRole.ToArray(), new string[] { role });
                    }
                }
            });
        }
Exemplo n.º 3
0
 /// <summary>
 /// Reads all keys in the appSettings section of the default configuration
 /// file and adds them all as valid arguments so that they may be
 /// specified on the command line.
 /// </summary>
 protected static void AddConfigurationSwitches()
 {
     DefaultConfiguration.GetAppSettings().AllKeys.Each(key =>
     {
         AddValidArgument(key, $"Override value from config: {DefaultConfiguration.GetAppSetting(key)}");
     });
 }
Exemplo n.º 4
0
        /// <summary>
        /// Gets the path to the current user's AppData folder. If
        /// this is run in a Web app (HttpContext.Current isn't null)
        /// then the full path to ~/AppData/ is returned.
        /// </summary>
        /// <param name="webSession">If true, domain_userName is appended to the path.  The default value is false.</param>
        /// <returns></returns>
        public static string GetCurrentUserAppDataFolder(bool webSession)
        {
            string path = "";

            if (HttpContext.Current == null)
            {
                path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                if (!path.EndsWith("\\"))
                {
                    path += "\\";
                }

                path += FsUtil.CompanyName + "\\" + DefaultConfiguration.GetAppSetting("ApplicationName", "UNKNOWN") + "\\";
                FileInfo fileInfo = new FileInfo(path);
                if (!Directory.Exists(fileInfo.Directory.FullName))
                {
                    Directory.CreateDirectory(fileInfo.Directory.FullName);
                }
            }
            else
            {
                path = HttpContext.Current.Server.MapPath("~/App_Data/");
                string webUser = UserUtil.GetCurrentWebUserName(true).Replace("\\", "_");
                if (webSession && !string.IsNullOrEmpty(webUser))
                {
                    path += webUser + "\\";
                }
            }

            return(path);
        }
Exemplo n.º 5
0
        private string GetAppNameFromRequest()
        {
            string hostName = Request.Url.Host;
            string result   = hostName;

            string[] splitHost = hostName.DelimitSplit(".");

            if (splitHost[0].ToLowerInvariant().Equals("www"))
            {
                result = splitHost[1];
            }
            else if (splitHost.Length == 2)
            {
                result = splitHost[0];
            }

            if (!AppPathExists(hostName))
            {
                hostName = DefaultConfiguration.GetAppSetting("ApplicationName", "main");
                if (!hostName.Equals("main") && !AppPathExists(hostName))
                {
                    Log.AddEntry("ApplicationName {0} was specified in the config but no bam app was found by that name", LogEventType.Warning, hostName);
                    hostName = "main";
                }
                result = hostName;
                Log.AddEntry("Unable to determine appName from hostName {0}, directing to 'main' instead.", LogEventType.Warning, hostName);
            }

            return(result);
        }
Exemplo n.º 6
0
 static Dust()
 {
     ResourceScripts.LoadScripts(typeof(Dust));
     _compiledTemplates = new Dictionary <string, string>();
     _templates         = new Dictionary <string, DustTemplate>();
     _dustRoot          = DefaultConfiguration.GetAppSetting("DustRoot", _dustRoot);
 }
Exemplo n.º 7
0
        /// <summary>
        /// Gets the path to the current user's AppData folder. If
        /// this is run in a Web app (HttpContext.Current isn't null)
        /// then the full path to ~/AppData/ is returned.
        /// </summary>
        protected static string GetAppDataFolder()
        {
            StringBuilder path = new StringBuilder();

            if (HttpContext.Current == null)
            {
                path.Append(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
                if (!path.ToString().EndsWith("\\"))
                {
                    path.Append("\\");
                }

                path.Append("KLGates\\Logs\\" + DefaultConfiguration.GetAppSetting("ApplicationName", unknownAppName) + "\\");
                FileInfo fileInfo = new FileInfo(path.ToString());
                if (!Directory.Exists(fileInfo.Directory.FullName))
                {
                    Directory.CreateDirectory(fileInfo.Directory.FullName);
                }
            }
            else
            {
                path.Append(HttpContext.Current.Server.MapPath("~/App_Data/"));
            }

            return(path.ToString());
        }
Exemplo n.º 8
0
        /// <summary>
        /// Encrypts the appsetting values specified by the appsetting with the key EncryptAppSettings.
        /// Encrypts the connection strings specified by the appsetting with the key EncryptConnStrings.
        /// Values are expected to be comma and/or semi colon separated lists of keys or names.
        /// Saves the specified values to and injects values from Profiguration.Default
        /// </summary>
        public static void Initialize()
        {
            string appKeysString        = DefaultConfiguration.GetAppSetting(EncryptAppSettingsKey);
            string connStringKeysString = DefaultConfiguration.GetAppSetting(EncryptConnStringsKey);

            Profiguration prof = Profiguration.Default;

            if (!string.IsNullOrEmpty(appKeysString))
            {
                string[] appSettingKeys = appKeysString.DelimitSplit(",", ";");
                foreach (string key in appSettingKeys)
                {
                    prof.CopyAppSetting(key);
                }
            }

            if (!string.IsNullOrEmpty(connStringKeysString))
            {
                string[] connStringNames = connStringKeysString.DelimitSplit(",", ";");
                foreach (string name in connStringNames)
                {
                    prof.CopyConnectionString(name);
                }
            }

            prof.Save();
            prof.Inject();
        }
Exemplo n.º 9
0
        protected Task ScanForContentHandlers()
        {
            Task scan = Task.Run(() =>
            {
                try
                {
                    string[] assemblySearchPatterns = DefaultConfiguration.GetAppSetting("AssemblySearchPattern", "*ContentHandlers.dll").DelimitSplit(",", true);
                    DirectoryInfo entryDir          = Assembly.GetEntryAssembly().GetFileInfo().Directory;
                    DirectoryInfo sysAssemblies     = DataSettings.GetSysAssemblyDirectory();
                    List <FileInfo> files           = new List <FileInfo>();
                    foreach (string assemblySearchPattern in assemblySearchPatterns)
                    {
                        files.AddRange(entryDir.GetFiles(assemblySearchPattern));
                        if (sysAssemblies.Exists)
                        {
                            files.AddRange(sysAssemblies.GetFiles(assemblySearchPattern));
                        }
                    }
                    Parallel.ForEach(files, LoadCustomHandlers);
                }
                catch (Exception ex)
                {
                    Logger.AddEntry("Exception occurred scanning for custom content handlers: {0}", ex, ex.Message);
                }
            });

            return(scan);
        }
Exemplo n.º 10
0
        public static void Install(string serviceName, string displayName, string description, string credentialKey, bool allowDesktopInteract)
        {
            OnStartInstall();
            try
            {
                bool   withIssues    = false;
                string startName     = string.IsNullOrEmpty(credentialKey) ? null : DefaultConfiguration.GetAppSetting(credentialKey);
                string startPassword = string.IsNullOrEmpty(credentialKey) ? null : DefaultConfiguration.GetAppSetting(credentialKey + "Password");
                startName     = string.IsNullOrEmpty(startName) ? null : startName;
                startPassword = string.IsNullOrEmpty(startPassword) ? null : startPassword;
                Assembly cur = Assembly.GetEntryAssembly();
                Console.WriteLine("INFO:: Creating service from " + cur.Location);
                ManagementClass win32Service = new ManagementClass(@"\\.\root\cimv2:Win32_Service");

                Console.WriteLine("INFO:: ServiceName={0},DisplayName={1},Description={2}",
                                  serviceName, displayName, description);

                object ret = win32Service.InvokeMethod("Create", new object[] { serviceName, displayName, cur.Location, 16, 0, "Automatic", allowDesktopInteract, startName, startPassword, null, null, null });
                if (ret.ToString().Equals("0"))
                {
                    Console.WriteLine("INFO:: Service was created successfully");
                }
                else
                {
                    Console.WriteLine("WARN:: Return code was: {0}", ret.ToString());
                    withIssues = true;
                }

                if (!string.IsNullOrEmpty(description))
                {
                    Console.WriteLine("INFO:: Setting description for '{0}' to '{1}'", displayName, description);

                    RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\" + serviceName, true);
                    if (key == null)
                    {
                        withIssues = true;
                    }
                    else
                    {
                        key.SetValue("Description", description, RegistryValueKind.String);
                    }
                }

                if (!withIssues)
                {
                    Console.WriteLine("INFO:: Operation complete");
                }
                else
                {
                    Console.WriteLine("WARN:: Operation completed with some issues");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR:: Unable to create service: " + ex.Message);
            }

            OnEndInstall();
        }
Exemplo n.º 11
0
        private static Encryption.Vault LoadVault()
        {
            string    vaultPath = DefaultConfiguration.GetAppSetting("vaultPath");
            VaultInfo vaultInfo = new VaultInfo(new FileInfo(vaultPath));
            Vault     vault     = vaultInfo.Load();

            return(vault);
        }
Exemplo n.º 12
0
        public void CopyAppSetting(string key)
        {
            string value = DefaultConfiguration.GetAppSetting(key);

            if (!string.IsNullOrEmpty(value))
            {
                AppSettings[key] = value;
            }
        }
Exemplo n.º 13
0
        public static HostPrefix GetConfiguredHostPrefix()
        {
            HostPrefix hostPrefix = new HostPrefix();

            hostPrefix.HostName = DefaultConfiguration.GetAppSetting("HostName").Or("localhost");
            hostPrefix.Port     = int.Parse(DefaultConfiguration.GetAppSetting("Port"));
            hostPrefix.Ssl      = bool.Parse(DefaultConfiguration.GetAppSetting("Ssl"));
            return(hostPrefix);
        }
Exemplo n.º 14
0
        public static void Install(string serviceName, string displayName, string description, string credentialKey, bool allowDesktopInteract)
        {
            string userName = string.IsNullOrEmpty(credentialKey) ? null : DefaultConfiguration.GetAppSetting(credentialKey);
            string password = string.IsNullOrEmpty(credentialKey) ? null : DefaultConfiguration.GetAppSetting(credentialKey + "Password");

            userName = string.IsNullOrEmpty(userName) ? null : userName;
            password = string.IsNullOrEmpty(password) ? null : password;

            Install(serviceName, displayName, description, allowDesktopInteract, userName, password);
        }
Exemplo n.º 15
0
        public void Configure(IConfigurable configurable)
        {
            foreach (string requiredProp in configurable.RequiredProperties)
            {
                string value = Arguments[requiredProp].Or(DefaultConfiguration.GetAppSetting(requiredProp));
                configurable.Property(requiredProp, value);
            }

            configurable.CheckRequiredProperties();
        }
Exemplo n.º 16
0
        private static ILogger GetDefaultLogger()
        {
            if (_currentLogger == null)
            {
                // create a logger of the type specified by the config
                // if no value is in the config create a null logger
                _currentLogger = CreateLogger(DefaultConfiguration.GetAppSetting("LogType", "Null"));
            }

            return(_currentLogger);
        }
Exemplo n.º 17
0
        public static void StartGlooServer(ConsoleLogger logger)
        {
            BamConf conf = BamConf.Load(DefaultConfiguration.GetAppSetting(contentRootConfigKey).Or(defaultContentRoot));

            glooServer = new GlooServer(conf, logger, GetArgument("verbose", "Log responses to the console?").IsAffirmative())
            {
                HostPrefixes       = new HashSet <HostPrefix>(HostPrefix.FromDefaultConfiguration("localhost", 9100)),
                MonitorDirectories = DefaultConfiguration.GetAppSetting("MonitorDirectories").DelimitSplit(",", ";")
            };
            glooServer.Start();
        }
Exemplo n.º 18
0
        public static void StartTrooServer(ConsoleLogger logger, IRepository repo)
        {
            BamConf conf = BamConf.Load(DefaultConfiguration.GetAppSetting(contentRootConfigKey).Or(defaultContentRoot));

            trooServer = new TrooServer(conf, logger, repo)
            {
                HostPrefixes       = new HashSet <HostPrefix>(HostPrefix.FromDefaultConfiguration()),
                MonitorDirectories = DefaultConfiguration.GetAppSetting("MonitorDirectories").DelimitSplit(",", ";")
            };
            trooServer.Start();
        }
Exemplo n.º 19
0
        /// <summary>
        /// Get the value specified for the argument with the
        /// specified name either from the command line or
        /// from the default configuration file or prompt for
        /// it if the value was not found
        /// </summary>
        /// <param name="name"></param>
        /// <param name="promptMessage"></param>
        /// <returns></returns>
        public static string GetArgument(string name, string promptMessage = null, Func <string, string> prompter = null)
        {
            prompter = prompter ?? ((p) => Prompt(p ?? $"Please enter a value for {name}"));
            string acronym    = name.CaseAcronym().ToLowerInvariant();
            string fromConfig = DefaultConfiguration.GetAppSetting(name, "").Or(DefaultConfiguration.GetAppSetting(acronym, ""));

            return(Arguments.Contains(name) ? Arguments[name] :
                   Arguments.Contains(acronym) ? Arguments[acronym] :
                   !string.IsNullOrEmpty(fromConfig) ? fromConfig :
                   prompter(promptMessage));
        }
Exemplo n.º 20
0
 public ContentResponder(BamConf conf, ILogger logger, ITemplateManager commonTemplateManager = null)
     : base(conf, logger)
 {
     ContentRoot            = conf?.ContentRoot ?? DefaultConfiguration.GetAppSetting(contentRootConfigKey, defaultRoot);
     ServerRoot             = new Fs(ContentRoot);
     TemplateDirectoryNames = new List <string>(new string[] { "views", "templates" });
     CommonTemplateManager  = commonTemplateManager ?? new CommonDustRenderer(this);
     FileCachesByExtension  = new Dictionary <string, FileCache>();
     HostAppMappings        = new Dictionary <string, HostAppMap>();
     InitializeFileExtensions();
     InitializeCaches();
 }
Exemplo n.º 21
0
        public static Database GetConfiguredDatabase()
        {
            string dialect          = DefaultConfiguration.GetAppSetting("SqlDialect");
            string connectionString = DefaultConfiguration.GetAppSetting("SqlConnectionString");

            if (!Enum.TryParse <SqlDialect>(dialect, out SqlDialect sqlDialect))
            {
                sqlDialect       = SqlDialect.SQLite;
                connectionString = "Default";
            }

            return(DatabaseFactory.Instance.GetDatabase(sqlDialect, connectionString));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Increments the file number if the current file number already exists.
        /// </summary>
        protected void SetNextFileInfo()
        {
            string appName  = DefaultConfiguration.GetAppSetting("ApplicationName", unknownAppName);
            string fileName = string.Format("{0}_{1}.{2}", appName, _fileNumber, FileExtension);

            _file = new FileInfo(Folder.FullName + fileName);
            while (_file.Exists)
            {
                _fileNumber += 1;
                fileName     = string.Format("{0}_{1}.{2}", appName, _fileNumber, FileExtension);
                _file        = new FileInfo(Folder.FullName + fileName);
            }
        }
Exemplo n.º 23
0
 public ServiceRegistryService(
     IFileService fileservice,
     IAssemblyService assemblyService,
     ServiceRegistryRepository repo,
     DaoRepository daoRepo,
     AppConf appConf,
     DataSettings dataSettings = null) : base(daoRepo, appConf)
 {
     FileService = fileservice;
     ServiceRegistryRepository = repo;
     AssemblyService           = assemblyService;
     DataSettings          = dataSettings ?? DataSettings.Current;
     AssemblySearchPattern = DefaultConfiguration.GetAppSetting("AssemblySearchPattern", "*.dll");
     _scanResults          = new Dictionary <Type, List <ServiceRegistryContainerRegistrationResult> >();
 }
Exemplo n.º 24
0
        public static ICrawler CreateMine(string url)
        {
            ICrawler result = null;
            string   name   = "{0}"._Format(DefaultConfiguration.GetAppSetting("ApplicationName", "UNKNOWN"));

            if (Instances.ContainsKey(name))
            {
                result = Instances[name];
            }
            else
            {
                result = Create(name, url);
            }

            return(result);
        }
Exemplo n.º 25
0
        public void FillLanguageTable()
        {
            Action <dynamic> ouput = (args) =>
            {
                OutLineFormat(args.Message, args.Color, args.Parameters);
            };

            string languageDatabasePath = DefaultConfiguration.GetAppSetting("languageDatabasePath");

            FileInfo       languageFile  = new FileInfo(languageDatabasePath);
            DirectoryInfo  directory     = languageFile.Directory;
            SQLiteDatabase translationDb = new SQLiteDatabase(directory.FullName, Path.GetFileNameWithoutExtension(languageFile.FullName));

            translationDb.TryEnsureSchema(typeof(Language));
            TranslationProvider.EnsureLanguages(translationDb);
        }
Exemplo n.º 26
0
        private static Type[] GetTestMethodAttributeTypes()
        {
            List <Type> returnValues = new List <Type>();

            returnValues.Add(typeof(UnitTest));

            string attrName   = DefaultConfiguration.GetAppSetting(UnitTestAttribute);
            Type   fromConfig = Type.GetType(attrName);

            if (fromConfig != null)
            {
                returnValues.Add(fromConfig);
            }

            return(returnValues.ToArray());
        }
Exemplo n.º 27
0
        protected void SaveDefaultConfiguration()
        {
            string appNameKey = "ApplicationName";
            NameValueCollection defaultConfig = DefaultConfiguration.GetAppSettings();
            string appName = DefaultConfiguration.GetAppSetting(appNameKey, "UNKNOWN");
            Dictionary <string, string> settings = new Dictionary <string, string>();

            foreach (string key in defaultConfig.AllKeys)
            {
                if (!key.Equals(appNameKey))
                {
                    settings.Add(key, defaultConfig[key]);
                }
            }
            SetApplicationConfiguration(appName, settings, "Default");
        }
Exemplo n.º 28
0
        private void TryReloadServices(DirectoryInfo directory)
        {
            try
            {
                List <string> excludeNamespaces = new List <string>();
                excludeNamespaces.AddRange(DefaultConfiguration.GetAppSetting("ExcludeNamespaces").DelimitSplit(",", "|"));
                List <string> excludeClasses = new List <string>();
                excludeClasses.AddRange(DefaultConfiguration.GetAppSetting("ExcludeClasses").DelimitSplit(",", "|"));

                lock (_serviceTypeLock)
                {
                    DefaultConfiguration
                    .GetAppSetting("AssemblySearchPattern")
                    .Or("*Services.dll,*Proxyables.dll,*Gloo.dll")
                    .DelimitSplit(",", "|")
                    .Each(new { Directory = directory, ExcludeNamespaces = excludeNamespaces, ExcludeClasses = excludeClasses },
                          (ctx, searchPattern) =>
                    {
                        FileInfo[] files = ctx.Directory.GetFiles(searchPattern, SearchOption.AllDirectories);
                        foreach (FileInfo file in files)
                        {
                            try
                            {
                                Assembly toLoad = Assembly.LoadFrom(file.FullName);
                                Type[] types    = toLoad.GetTypes().Where(type => !ctx.ExcludeNamespaces.Contains(type.Namespace) &&
                                                                          !ctx.ExcludeClasses.Contains(type.Name) &&
                                                                          type.HasCustomAttributeOfType <ProxyAttribute>()).ToArray();
                                foreach (Type t in types)
                                {
                                    ServiceTypes.Add(t);
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.AddEntry("An exception occurred loading services from file {0}: {1}", LogEventType.Warning, ex, file.FullName, ex.Message);
                            }
                        }
                    });
                }
                RegisterServiceTypes();
            }
            catch (Exception ex)
            {
                Logger.AddEntry("An exception occurred loading services: {0}", ex, ex.Message);
            }
        }
Exemplo n.º 29
0
        private static ServiceRegistry GetServiceRegistry(CoreClient coreClient)
        {
            string contentRoot        = DefaultConfiguration.GetAppSetting("ContentRoot", "c:\\bam\\content");
            string organization       = DefaultConfiguration.GetAppSetting("Organization", "PUBLIC");
            string applicationName    = DefaultConfiguration.GetAppSetting("ApplicationName", "UNKNOWN");
            string databasesPath      = Path.Combine(contentRoot, "Databases");
            string workspaceDirectory = Path.Combine(contentRoot, "Workspace");

            ApplicationLogDatabase logDb = new ApplicationLogDatabase(workspaceDirectory);

            return((ServiceRegistry)(new ServiceRegistry())
                   .For <CoreClient>().Use(coreClient)
                   .For <ApplicationLogDatabase>().Use(logDb)
                   .For <ILogger>().Use <ApplicationLogger>()
                   .For <ILog>().Use <ApplicationLogger>()
                   .For <IConfigurationService>().Use <ApplicationConfigurationProvider>()
                   .For <IUserManager>().Use(coreClient.UserRegistryService));
        }
Exemplo n.º 30
0
        public static HostPrefix[] GetConfiguredHostPrefixes()
        {
            int  port = int.Parse(DefaultConfiguration.GetAppSetting("Port", "80"));
            bool ssl  = DefaultConfiguration.GetAppSetting("Ssl").IsAffirmative();
            List <HostPrefix> results = new List <HostPrefix>();

            foreach (string hostName in DefaultConfiguration.GetAppSetting("HostNames").Or("localhost").DelimitSplit(",", true))
            {
                HostPrefix hostPrefix = new HostPrefix()
                {
                    HostName = hostName,
                    Port     = port,
                    Ssl      = ssl
                };
                results.Add(hostPrefix);
            }
            return(results.ToArray());
        }