예제 #1
0
        public void EnvironmentVars_Expand_Recursive()
        {
            string cfg1;

            // Old style

            cfg1 =
                @"
var1=HELLO
var2=%var1%
var3=WORLD
var4=%var2% %var3%
";
            EnvironmentVars.Load(cfg1);
            Assert.AreEqual("HELLO", EnvironmentVars.Expand("%var2%"));
            Assert.AreEqual("prefix HELLO suffix", EnvironmentVars.Expand("prefix %var2% suffix"));
            Assert.AreEqual("HELLO WORLD", EnvironmentVars.Expand("%var4%"));

            // New style

            cfg1 =
                @"
var1=HELLO
var2=$(var1)
var3=WORLD
var4=$(var2) $(var3)
";
            EnvironmentVars.Load(cfg1);
            Assert.AreEqual("HELLO", EnvironmentVars.Expand("$(var2)"));
            Assert.AreEqual("prefix HELLO suffix", EnvironmentVars.Expand("prefix $(var2) suffix"));
            Assert.AreEqual("HELLO WORLD", EnvironmentVars.Expand("$(var4)"));
        }
예제 #2
0
        private static string conString;   // The default test database connection string

        /// <summary>
        /// Static constructor.
        /// </summary>
        static SqlTestDatabase()
        {
            conString = EnvironmentVars.Get("LT_TEST_DB");
            if (conString == null)
            {
                conString = "server=.\\SQLEXPRESS;Integrated Security=SSPI";
            }
        }
예제 #3
0
 public void EnvironmentVars_System()
 {
     EnvironmentVars.Load("");
     Assert.AreEqual(Environment.GetEnvironmentVariable("path"), EnvironmentVars.Get("path"));
     Assert.AreEqual(Environment.GetEnvironmentVariable("systemdrive"), EnvironmentVars.Get("systemdrive"));
     Assert.AreEqual(Environment.GetEnvironmentVariable("windir"), EnvironmentVars.Get("windir"));
     Assert.AreEqual(Environment.GetEnvironmentVariable("comspec"), EnvironmentVars.Get("comspec"));
 }
예제 #4
0
        /// <summary>
        /// Static constructor.
        /// </summary>
        static CoreApp()
        {
            // Initialize this to something reasonable so unit tests will work.
#if DEBUG
            CoreApp.InstallPath = EnvironmentVars.Expand(@"$(LT_ROOT)\Main\Platform\Telephony\NeonSwitchCore\bin\x64\Debug");
#else
            CoreApp.InstallPath = EnvironmentVars.Expand(@"$(LT_ROOT)\Main\Platform\Telephony\NeonSwitchCore\bin\x64\Release");
#endif
        }
 public DigitalOceanWorker(
     BotCommandResolver botCommandResolver,
     ITelegramBotClient telegramBotClient,
     ILogger <DigitalOceanWorker> logger)
 {
     _botCommandResolver = botCommandResolver;
     _logger             = logger;
     _telegramBotClient  = telegramBotClient;
     _userId             = EnvironmentVars.GetUserId();
 }
예제 #6
0
        /// <summary>
        /// Handles initialization for processes launched by Azure roles.
        /// </summary>
        /// <param name="processName">Identifies the process.</param>
        private static void ProcessInitialize(string processName)
        {
            // Load the known Azure related settings from environment variables set
            // by the parent Azure role.

            AzureHelper.RoleName       = GetVar("AZURE_ROLENAME") ?? string.Empty;
            AzureHelper.RoleType       = Serialize.Parse <AzureRoleType>(GetVar("AZURE_ROLETYPE"), AzureRoleType.Process);
            AzureHelper.Datacenter     = GetVar("AZURE_DATACENTER") ?? "EMULATOR";
            AzureHelper.Deployment     = GetVar("AZURE_DEPLOYMENT") ?? "<unknown>";
            AzureHelper.Environment    = Serialize.Parse <AzureEnvironment>(GetVar("AZURE_ENVIRONMENT"), AzureEnvironment.Dev);
            AzureHelper.RoleInstanceID = GetVar("AZURE_ROLEINSTANCEID") ?? string.Empty;
            AzureHelper.RoleIndex      = Serialize.Parse(GetVar("AZURE_ROLEINDEX"), -1);
            AzureHelper.RoleDataPath   = GetVar("AZURE_ROLEDATAPATH") ?? string.Empty;

            if (string.IsNullOrWhiteSpace(AzureHelper.RoleName))
            {
                AzureHelper.RoleName = processName;
            }

            // Make sure the role data path points somewhere real in case the
            // process is running outside the context of an Azure role
            // (e.g. during development or test).

            if (string.IsNullOrWhiteSpace(AzureHelper.RoleDataPath) || !Directory.Exists(AzureHelper.RoleDataPath))
            {
                AzureHelper.RoleDataPath = Path.GetTempPath();
            }

            // Make sure that the known Azure settings are persisted to environment variables.
            // We need to do this to ensure that the configuration settings are loaded properly.

            System.Environment.SetEnvironmentVariable("AZURE_ROLENAME", AzureHelper.RoleName);
            System.Environment.SetEnvironmentVariable("AZURE_ROLETYPE", AzureHelper.RoleType.ToString());
            System.Environment.SetEnvironmentVariable("AZURE_DATACENTER", AzureHelper.Datacenter);
            System.Environment.SetEnvironmentVariable("AZURE_DEPLOYMENT", AzureHelper.Deployment);
            System.Environment.SetEnvironmentVariable("AZURE_ENVIRONMENT", AzureHelper.Environment.ToString().ToUpper());
            System.Environment.SetEnvironmentVariable("AZURE_ROLEINSTANCEID", AzureHelper.RoleInstanceID);
            System.Environment.SetEnvironmentVariable("AZURE_ROLEINDEX", AzureHelper.RoleIndex.ToString());
            System.Environment.SetEnvironmentVariable("AZURE_ROLEDATAPATH", AzureHelper.RoleDataPath);

            // This indicates to the Config class how it can retrieve Windows Azure configuration settings.

            Config.SetAzureGetSettingMethod(typeof(AzureHelper).GetMethod("GetProcessAzureSetting"));

            // We need to reload the environment and configuration settings so that they will be processed
            // in the context of the Azure related settings.

            if (Helper.EntryAssemblyFile != null)
            {
                Config.SetConfigPath(Path.Combine(Helper.AppFolder, Path.GetFileNameWithoutExtension(Helper.EntryAssemblyFile) + ".ini"));
                EnvironmentVars.Reload();
                Config.Load();
            }
        }
예제 #7
0
        public void EnvironmentVars_IsVariable()
        {
            // Actual environment vairabl;es

            Assert.IsTrue(EnvironmentVars.IsVariable("path"));
            Assert.IsTrue(EnvironmentVars.IsVariable("temp"));
            Assert.IsTrue(EnvironmentVars.IsVariable("tmp"));

            // Handle LillTek built-in variables.

            Assert.IsTrue(EnvironmentVars.IsVariable("os"));
            Assert.IsTrue(EnvironmentVars.IsVariable("appversion"));
        }
예제 #8
0
        /// <summary>
        /// Starts the RADIUS server, intializing the user and client
        /// databases.
        /// </summary>
        /// <param name="users">The user database file contents.</param>
        /// <param name="clients">The client database file contents.</param>
        /// <remarks>
        /// See the <b>users.example</b> and <b>clients.example</b> files
        /// in the <b>raddb</b> folder for a description of how these
        /// files must be formatted.
        /// </remarks>
        /// <exception cref="NotAvailableException">Thrown if the RADIUS server application is not installed.</exception>
        public void Start(string users, string clients)
        {
            StreamWriter writer = null;
            string       testBinPath;
            string       exePath;

            testBinPath = EnvironmentVars.Get("LT_TESTBIN");
            if (testBinPath == null)
            {
                throw new ArgumentException("[LT_TESTBIN] environment variable does not exist.");
            }

            testBinPath = Helper.AddTrailingSlash(testBinPath) + @"RadiusServer\";
            exePath     = testBinPath + "Radl.exe";
            usersPath   = testBinPath + @"raddb\users";
            clientsPath = testBinPath + @"raddb\clients";

            if (!File.Exists(exePath))
            {
                throw new NotAvailableException("RADIUS Server not found at: " + exePath);
            }

            orgDir = Environment.CurrentDirectory;
            Environment.CurrentDirectory = testBinPath.Substring(0, testBinPath.Length - 1);

            try
            {
                writer = new StreamWriter(usersPath, false, Helper.AnsiEncoding);
                writer.Write(users);
                writer.Close();
                writer = null;

                writer = new StreamWriter(clientsPath, false, Helper.AnsiEncoding);
                writer.Write(clients);
                writer.Close();
                writer = null;

                serverProcess = Process.Start(exePath, string.Empty);
                serverProcess.EnableRaisingEvents = true;

                Thread.Sleep(5000);    // Give the server a chance to initialize
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
예제 #9
0
        public void EnvironmentVars_Expand_InfiniteRecursion()
        {
            string cfg1;

            // Old style

            cfg1 =
                @"
var1=%var2%
var2=%var1%
";
            EnvironmentVars.Load(cfg1);

            try
            {
                EnvironmentVars.Expand("%var2%");
                Assert.Fail();  // Expected a StackOverflowException
            }
            catch (StackOverflowException)
            {
            }
            catch
            {
                Assert.Fail();  // Expected a StackOverflowException
            }

            // New style

            cfg1 =
                @"
var1=$(var2)
var2=$(var1)
";
            EnvironmentVars.Load(cfg1);

            try
            {
                EnvironmentVars.Expand("$(var2)");
                Assert.Fail();  // Expected a StackOverflowException
            }
            catch (StackOverflowException)
            {
            }
            catch
            {
                Assert.Fail();  // Expected a StackOverflowException
            }
        }
예제 #10
0
 public BuildProjectCode(WIXSharpProject project)
 {
     Options = project.GetOptions();
     GlobalFileAssociations = project.GetGlobalFileAssociations();
     Registryvalues         = project.GetRegistryValues();
     FireExcept             = project.GetFirewallExceptions();
     Sourcefiles            = project.GetSourceFiles();
     Certs = project.GetCerts();
     EnvironmentVariables = project.GetEnvironmentVars();
     application          = project.GetApplication();
     users      = project.GetUsers();
     WElements  = project.GetElements();
     installdir = project.GetInstallDir();
     progfiles  = project.GetProgFiles();
     progmenu   = project.GetProgMenu();
 }
예제 #11
0
        public void EnvironmentVars_IPAddressing()
        {
            string output;

            // This test exercises the IP address macros without actually checking
            // their values (since they'll differ from machine to machine).  This
            // will test for crashes and also provide a place where these values
            // can be manually verified.

            output = EnvironmentVars.Expand(@"

ip-address = $(ip-address)
ip-mask    = $(ip-mask)
ip-subnet  = $(ip-subnet)
");
        }
예제 #12
0
        public void RadiusClient_Interop_AD_IAS()
        {
            if (EnvironmentVars.Get("LT_TESTBIN") == null)
            {
                Assert.Inconclusive("[LT_TESTBIN] environment variable does not exist.");
            }

            if (EnvironmentVars.Get("LT_TEST_AD") == null)
            {
                Assert.Inconclusive("[LT_TEST_AD] environment variable does not exist.");
            }

            var ad = new ADTestSettings();

            if (ad.NasSecret == string.Empty)
            {
                Assert.Inconclusive("AD/IAS Testing is disabled");
                return;
            }

            // Verify that RADIUS client works against AD/IAS.  This requires that
            // the LT_TEST_AD environment variable be set properly as described
            // in the LillTek DevInstall.doc document.  The IAS server must also
            // be manually configured with the NAS shared secret for this client.

            RadiusClient         client         = new RadiusClient();
            NetworkBinding       serverEP       = new NetworkBinding(EnhancedDns.GetHostByName(ad.Servers[0]).AddressList.IPv4Only()[0], NetworkPort.RADIUS);
            RadiusClientSettings clientSettings = new RadiusClientSettings(serverEP, ad.NasSecret);

            clientSettings.RealmFormat = RealmFormat.Email;
            clientSettings.PortCount   = 1;

            try
            {
                client.Open(clientSettings);

                Assert.IsTrue(client.Authenticate(ad.Domain, ad.Account, ad.Password));

                Assert.IsFalse(client.Authenticate(ad.Domain + "x", ad.Account, ad.Password));
                Assert.IsFalse(client.Authenticate(ad.Domain, ad.Account + "x", ad.Password));
                Assert.IsFalse(client.Authenticate(ad.Domain, ad.Account, ad.Password + "x"));
            }
            finally
            {
                client.Close();
            }
        }
예제 #13
0
        public void EnvironmentVars_BuiltIn()
        {
            EnvironmentVars.Load("");

            Assert.AreEqual(Environment.GetEnvironmentVariable("temp"), EnvironmentVars.Get("temp"));
            Assert.AreEqual(Environment.GetEnvironmentVariable("tmp"), EnvironmentVars.Get("tmp"));
            Assert.AreEqual(Environment.GetEnvironmentVariable("SystemRoot"), EnvironmentVars.Get("SystemRoot"));
            Assert.AreEqual((Environment.GetEnvironmentVariable("SystemRoot") + @"\system32").ToLowerInvariant(), EnvironmentVars.Get("SystemDirectory").ToLowerInvariant());
            Assert.AreEqual(Helper.EntryAssemblyFolder, EnvironmentVars.Get("AppPath"));
            Assert.IsNotNull(EnvironmentVars.Get("OS"));
            Assert.IsNotNull(EnvironmentVars.Get("WINFULL"));
            Assert.IsNull(EnvironmentVars.Get("WINCE"));
            Assert.AreEqual(Helper.GetVersionString(Assembly.GetExecutingAssembly()), EnvironmentVars.Get("appversion"));
            Assert.AreEqual(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), EnvironmentVars.ProgramDataPath);
            Assert.IsTrue(!EnvironmentVars.ProgramDataPath.EndsWith("/"));
            Assert.IsTrue(!EnvironmentVars.ProgramDataPath.EndsWith("\\"));
            Assert.AreNotEqual(EnvironmentVars.Get("guid"), EnvironmentVars.Get("Guid"));
            Assert.AreEqual(Helper.MachineName, EnvironmentVars.Get("MachineName"));
            Assert.AreEqual(Dns.GetHostName(), EnvironmentVars.Get("HostName"));
            Assert.AreEqual(EnvironmentVars.ServerID, EnvironmentVars.Get("ServerID"));

            Assert.AreEqual(Environment.GetEnvironmentVariable("temp"), EnvironmentVars.Expand("$(temp)"));
            Assert.AreEqual(Environment.GetEnvironmentVariable("tmp"), EnvironmentVars.Expand("$(tmp)"));
            Assert.AreEqual(Environment.GetEnvironmentVariable("SystemRoot"), EnvironmentVars.Expand("$(SystemRoot)"));
            Assert.AreEqual((Environment.GetEnvironmentVariable("SystemRoot") + @"\system32").ToLowerInvariant(), EnvironmentVars.Expand("$(SystemDirectory)").ToLowerInvariant());
            Assert.AreEqual(Helper.EntryAssemblyFolder, EnvironmentVars.Expand("$(AppPath)"));
            Assert.IsNotNull(EnvironmentVars.Expand("$(OS)"));
            Assert.IsNotNull(EnvironmentVars.Expand("$(WINFULL)"));
            Assert.AreEqual("$(WINCE)", EnvironmentVars.Expand("$(WINCE)"));
            Assert.AreNotEqual(EnvironmentVars.Expand("$(guid)"), EnvironmentVars.Expand("$(Guid)"));
            Assert.AreEqual(Helper.MachineName, EnvironmentVars.Expand("$(MachineName)"));
            Assert.AreEqual(Environment.ProcessorCount.ToString(), EnvironmentVars.Expand("$(ProcessorCount)"));

            Assert.AreEqual(Const.DCCloudEP.ToString(), EnvironmentVars.Expand("$(LillTek.DC.CloudEP)"));
            Assert.AreEqual(Const.DCCloudGroup.ToString(), EnvironmentVars.Expand("$(LillTek.DC.CloudGroup)"));
            Assert.AreEqual(Const.DCCloudPort.ToString(), EnvironmentVars.Expand("$(LillTek.DC.CloudPort)"));
            Assert.AreEqual(Const.DCRootPort.ToString(), EnvironmentVars.Expand("$(LillTek.DC.RootPort)"));
            Assert.AreEqual(Const.DCDefHubName, EnvironmentVars.Expand("$(LillTek.DC.DefHubName)"));
#if DEBUG
            Assert.AreEqual("true", EnvironmentVars.Expand("$(IsDebug)"));
            Assert.AreEqual("false", EnvironmentVars.Expand("$(IsRelease)"));
#else
            Assert.AreEqual("false", EnvironmentVars.Expand("$(IsDebug)"));
            Assert.AreEqual("true", EnvironmentVars.Expand("$(IsRelease)"));
#endif
        }
예제 #14
0
        /// <summary>
        /// Queries the realm map provider for the current set of realm mappings.
        /// </summary>
        /// <returns>The list of realm mappings.</returns>
        /// <exception cref="AuthenticationException">Thrown if there's an error getting the map.</exception>
        public List <RealmMapping> GetMap()
        {
            OdbcConnection      dbCon  = null;
            OdbcDataReader      reader = null;
            List <RealmMapping> map    = new List <RealmMapping>();
            OdbcCommand         cmd;

            using (TimedLock.Lock(this))
            {
                if (!IsOpen)
                {
                    throw new AuthenticationException("Provider is closed.");
                }

                dbCon = new OdbcConnection(conString);
                dbCon.Open();

                try
                {
                    cmd             = dbCon.CreateCommand();
                    cmd.CommandText = query;
                    cmd.CommandType = CommandType.Text;

                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        map.Add(new RealmMapping(engineSettings,
                                                 SqlHelper.AsString(reader["Realm"]),
                                                 Config.Parse(SqlHelper.AsString(reader["ProviderType"]), (System.Type)null),
                                                 ArgCollection.Parse(EnvironmentVars.Expand(SqlHelper.AsString(reader["Args"]))),
                                                 SqlHelper.AsString(reader["Query"])));
                    }
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }

                    dbCon.Close();
                }

                return(map);
            }
        }
예제 #15
0
 public BuildProjectCode(SetupOptions options, FileAssociations fileassoc, RegistryValues registryvalues, FirewallExceptions firewallexceptions, SourceFiles sourcefiles,
                         Certificates certs, EnvironmentVars envirvars, ApplicationInfo app, Users user, Elements elements, string dir, string files, string menu)
 {
     Options = options;
     GlobalFileAssociations = fileassoc;
     Registryvalues         = registryvalues;
     FireExcept             = firewallexceptions;
     Sourcefiles            = sourcefiles;
     Certs = certs;
     EnvironmentVariables = envirvars;
     application          = app;
     users      = user;
     WElements  = elements;
     installdir = dir;
     progfiles  = files;
     progmenu   = menu;
     addglobalfileassociations();
 }
예제 #16
0
        public void RadiusClient_Interop()
        {
            if (EnvironmentVars.Get("LT_TESTBIN") == null)
            {
                Assert.Inconclusive("[LT_TESTBIN] environment variable does not exist.");
            }

            // Verify that my RADIUS client code can work against a server from
            // another vendor.

            RadiusTestServer               server = new RadiusTestServer();
            Dictionary <string, string>    users;
            Dictionary <IPAddress, string> devices;
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_AAA, "secret");

            clientSettings.RealmFormat = RealmFormat.Email;
            clientSettings.PortCount   = 1;

            users = new Dictionary <string, string>();
            users.Add("jeff", "password1");
            users.Add("joe", "password2");

            devices = new Dictionary <IPAddress, string>();
            devices.Add(IPAddress.Loopback, "secret");
            devices.Add(NetHelper.GetActiveAdapter(), "secret");

            try
            {
                server.Start(users, devices);
                client.Open(clientSettings);

                Assert.IsTrue(client.Authenticate("", "jeff", "password1"));
                Assert.IsTrue(client.Authenticate("", "joe", "password2"));

                Assert.IsFalse(client.Authenticate("", "jeff", "passwordX"));
                Assert.IsFalse(client.Authenticate("", "billy", "x"));
            }
            finally
            {
                client.Close();
                server.Stop();
            }
        }
예제 #17
0
        /// <summary>
        /// Establishes a session with the authentication extension.
        /// </summary>
        /// <param name="args">The extension specific arguments (see the remarks).</param>
        /// <param name="query">Ignored for this extension.</param>
        /// <param name="perfCounters">The application's performance counter set (or <c>null</c>).</param>
        /// <param name="perfPrefix">The string to prefix any performance counter names (or <c>null</c>).</param>
        /// <remarks>
        /// <para>
        /// This extension recognises the following arguments:
        /// </para>
        /// <list type="table">
        ///     <item>
        ///         <term>Path</term>
        ///         <description>
        ///         The fully qualified path to the credential file.  This argument is required.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>Reload</term>
        ///         <description>
        ///         Indicates whether the credentials file should be reloaded before every authentication
        ///         attempt.  This can have values such as "yes"/"no" or "true"/"false".  This argument
        ///         defaults to "true".
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>MaxCacheTime</term>
        ///         <description>
        ///         Specifies the maximum time clients should retain authentication information.
        ///         This is expressed in the same format as timespans parsed by <see cref="Config.Parse(string,TimeSpan)" />.
        ///         This argument defaults to "5m".
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>LockoutCount</term>
        ///         <description>
        ///         Specifies the limiting failed authentication count.  Accounts
        ///         will be locked when the fail count reaches this number.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>LockoutThreshold</term>
        ///         <description>
        ///         The period of time that can elapse between failed authentication
        ///         attempts where the failed attempts will <b>not</b> be counted against the
        ///         <b>LockoutCount</b>.  Set this to <see cref="TimeSpan.Zero" />
        ///         to disable account lockout for the realm.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>LockoutTime</term>
        ///         <description>
        ///         The period of time an account will remain locked after being locked
        ///         out due to too many failed authentication attempts.
        ///         </description>
        ///     </item>
        /// </list>
        /// <note>
        /// All calls to <see cref="Open" /> must be matched with a call
        /// to <see cref="Close" /> or <see cref="Dispose" />.
        /// </note>
        /// </remarks>
        public void Open(ArgCollection args, string query, PerfCounterSet perfCounters, string perfPrefix)
        {
            using (TimedLock.Lock(this))
            {
                if (IsOpen)
                {
                    throw new AuthenticationException("Authentication extension is already open.");
                }

                perf         = new Perf(perfCounters, perfPrefix);
                path         = EnvironmentVars.Expand(args["Path"]);
                reload       = args.Get("Reload", true);
                maxCacheTime = args.Get("MaxCacheTime", TimeSpan.FromMinutes(5));

                if (!reload)
                {
                    credentials = LoadCredentials();
                }
            }
        }
예제 #18
0
        public void EnvironmentVars_Basic()
        {
            string cfg1 =
                @"
var1=10
// This is a comment  
   var2  =  20   

VAR3=30

path=$(ProgramDataPath)\Foo
";

            EnvironmentVars.Load(cfg1);
            Assert.AreEqual("10", EnvironmentVars.Get("var1"));
            Assert.AreEqual("20", EnvironmentVars.Get("VAR2"));
            Assert.AreEqual("30", EnvironmentVars.Get("var3"));
            Assert.IsNull(EnvironmentVars.Get("var4"));
            Assert.AreEqual(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Foo"), EnvironmentVars.Expand(EnvironmentVars.Get("path")));
        }
예제 #19
0
        public void EnvironmentVars_Expand()
        {
            string cfg1 =
                @"
var1=INSERT
";

            EnvironmentVars.Load(cfg1);

            // Old style

            Assert.AreEqual("", EnvironmentVars.Expand(""));
            Assert.AreEqual("INSERT", EnvironmentVars.Expand("INSERT"));
            Assert.AreEqual("INSERT", EnvironmentVars.Expand("%var1%"));
            Assert.AreEqual("prefix INSERT suffix", EnvironmentVars.Expand("prefix %VAR1% suffix"));
            Assert.AreEqual("%none%", EnvironmentVars.Expand("%none%"));
            Assert.AreEqual("prefix %none% suffix", EnvironmentVars.Expand("prefix %none% suffix"));
            Assert.AreEqual("%", EnvironmentVars.Expand("%"));
            Assert.AreEqual("%hello", EnvironmentVars.Expand("%hello"));
            Assert.AreEqual("hello%", EnvironmentVars.Expand("hello%"));
            Assert.AreEqual("hello%world", EnvironmentVars.Expand("hello%world"));

            // New style

            Assert.AreEqual("", EnvironmentVars.Expand(""));
            Assert.AreEqual("INSERT", EnvironmentVars.Expand("INSERT"));
            Assert.AreEqual("INSERT", EnvironmentVars.Expand("$(var1)"));
            Assert.AreEqual("prefix INSERT suffix", EnvironmentVars.Expand("prefix $(VAR1) suffix"));
            Assert.AreEqual("$(none)", EnvironmentVars.Expand("$(none)"));
            Assert.AreEqual("prefix $(none) suffix", EnvironmentVars.Expand("prefix $(none) suffix"));
            Assert.AreEqual("$", EnvironmentVars.Expand("$"));
            Assert.AreEqual("$(", EnvironmentVars.Expand("$("));
            Assert.AreEqual("$hello", EnvironmentVars.Expand("$hello"));
            Assert.AreEqual("$(hello", EnvironmentVars.Expand("$(hello"));
            Assert.AreEqual("$(hello)", EnvironmentVars.Expand("$(hello)"));
            Assert.AreEqual("hello)", EnvironmentVars.Expand("hello)"));
            Assert.AreEqual("hello)world", EnvironmentVars.Expand("hello)world"));
        }
예제 #20
0
        public void EnvironmentVars_ServerID()
        {
            string orgServerID;

            orgServerID = EnvironmentVars.ServerID;
            if (String.Compare(orgServerID, Dns.GetHostName(), true) == 0)
            {
                orgServerID = null;
            }

            try
            {
                EnvironmentVars.ServerID = "www.lilltek.com";
                Assert.AreEqual("www.lilltek.com", EnvironmentVars.Expand("$(ServerID)"));

                EnvironmentVars.ServerID = null;
                Assert.AreEqual(Dns.GetHostName(), EnvironmentVars.Expand("$(ServerID)"));
            }
            finally
            {
                EnvironmentVars.ServerID = orgServerID;
            }
        }
예제 #21
0
 public static IHostBuilder ConfigureTelegram(this IHostBuilder hostBuilder)
 {
     return(hostBuilder.ConfigureServices((_, collection) =>
     {
         collection.AddSingleton <ITelegramBotClient>(_ => new TelegramBotClient(EnvironmentVars.GetTelegramToken()));
     }));
 }
예제 #22
0
 /// <summary>
 /// Constructs the default router settings.
 /// </summary>
 public RouterSettings()
 {
     this.RouterEP = EnvironmentVars.Expand("physical://DETACHED/$(LillTek.DC.DefHubName)/$(Guid)");
 }
예제 #23
0
 private static string GetEnvVar(EnvironmentVars var)
 {
     return(Environment.GetEnvironmentVariable(var.ToString()) != null?
            Environment.GetEnvironmentVariable(var.ToString()) :
                new DefaultEnvVars().GetType().GetProperty(var.ToString())?.GetValue(null)?.ToString());
 }
예제 #24
0
        public void SentinelServiceDB_DeployDB()
        {
            SqlTestDatabase    dbTest;
            Package            dbPackage = null;
            DBPackageInstaller dbInstaller;
            DBInstallParams    dbParams;
            DBInstallResult    result;

            using (dbTest = SqlTestDatabase.Create())
            {
                SqlConnectionInfo conInfo;
                SqlContext        ctx = null;
                SqlCommand        cmd;
                DataTable         dt;

                try
                {
                    // Deploy to a non-existent database

                    dbPackage   = new Package(EnvironmentVars.Expand("$(LT_BUILD)\\LillTek.SentinelService.dbpack"));
                    dbParams    = new DBInstallParams("SentinelService", dbTest.ConnectionInfo.Database);
                    dbInstaller = new DBPackageInstaller(dbPackage);

                    result = dbInstaller.Install(dbParams);
                    Assert.AreEqual(DBInstallResult.Installed, result);

                    conInfo = SqlConnectionInfo.Parse(dbInstaller.ConnectionString);
                    ctx     = new SqlContext(conInfo);
                    ctx.Open();

                    cmd = ctx.CreateSPCall("GetProductInfo");
                    dt  = ctx.ExecuteTable(cmd);
                    Assert.AreEqual(1, dt.Rows.Count);

                    cmd = ctx.CreateSPCall("Ping");
                    dt  = ctx.ExecuteTable(cmd);
                    Assert.AreEqual(1, dt.Rows.Count);
                    Assert.AreEqual("OK", SqlHelper.AsString(dt.Rows[0]["STATUS"]));

                    ctx.Close();
                    ctx = null;

                    // Deploy again and we should see that the database is up-to-date.

                    SqlConnection.ClearAllPools();
                    result = dbInstaller.Install(dbParams);
                    Assert.AreEqual(DBInstallResult.UpToDate, result);
                }
                finally
                {
                    if (dbPackage != null)
                    {
                        dbPackage.Close();
                    }

                    if (ctx != null)
                    {
                        ctx.Close();
                    }
                }
            }
        }
예제 #25
0
        /// <summary>
        /// Starts the router, reading configuration parameters from the
        /// application's configuration settings.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This method will gather the instance settings from the application's
        /// configuration settings, as described below.  Multiple router instances
        /// can be specified in a single configuration file.  The router name
        /// parameter is used to distinguish between the settings for each router
        /// instance.  The method will look for configuration keys prefixed by
        /// </para>
        /// <code language="none">
        /// "MsgRouter." + name + "."
        /// </code>
        /// <para>
        /// So, when loading the TcpEP setting, Start("Foo") will query for
        /// "Router.Foo.TcpEP".
        /// </para>
        /// <para>
        /// Here are the configuration settings LeafRouter expects: (note
        /// that all settings are prefixed by "MsgRouter." as in "MsgRouter.RouterEP".
        /// </para>
        /// <div class="tablediv">
        /// <table class="dtTABLE" cellspacing="0" ID="Table1">
        /// <tr valign="top">
        /// <th width="1">Setting</th>
        /// <th width="1">Default</th>
        /// <th width="90%">Description</th>
        /// </tr>
        /// <tr valign="top"><td>AppName</td><td>EXE file name</td><td>Name of the application hosting the router</td></tr>
        /// <tr valign="top"><td>AppDescription</td><td>(none)</td><td>Description of the application hosting thr router</td></tr>
        /// <tr valign="top">
        ///     <td>RouterEP</td>
        ///     <td>physical://DETACHED/$(LillTek.DC.DefHubName)/$(Guid)</td>
        ///     <td>
        ///         Physical MsgEP for this instance.  The endpoint should be three levels deep
        ///         such as physical://root.com:40/hub/leaf and the leaf name should be unique across
        ///         all leaf routers beneath the hub.  One way to guarantee uniquness is to use the $(guid)
        ///         environment variable in the endpoint, as in physical://root.com:40/hub/$(MachineName)-$(Guid).
        ///         This will be replaced with a newly generated GUID when the configuration variable
        ///         is processed.
        ///     </td>
        /// </tr>
        /// <tr valign="top">
        ///     <td>DiscoveryMode</td>
        ///     <td>MULTICAST</td>
        ///     <td>
        ///     <para>
        ///     Specifies how the router will go about discovering other routers on the
        ///     network.  The possible values are <b>MULTICAST</b> (the default) and
        ///     <b>UDPBROADCAST</b>.
        ///     </para>
        ///     <para>
        ///     If <b>MULTICAST</b> is specified then the router will broadcast and listen
        ///     for presence packets on the specified <see cref="RouterSettings.CloudAdapter"/> for the
        ///     <see cref="RouterSettings.CloudEP" /> multicast endpoint.
        ///     </para>
        ///     <para>
        ///     If <b>UDPBROADCAST</b> is specified then the router will use the LillTek
        ///     Broadcast Server to handle the transmission and reception presence packets
        ///     on networks that don't support multicast.  The <see cref="RouterSettings.BroadcastSettings" />
        ///     property can be used to configure the internal <see cref="UdpBroadcastClient" />
        ///     used to manage these broadcasts.
        ///     </para>
        ///     </td>
        /// </tr>
        /// <tr valign="top"><td>CloudEP</td><td><see cref="Const.DCCloudEP" /></td><td>The discovery UDP multicast network group and port</td></tr>
        /// <tr valign="top"><td>CloudAdapter</td><td>ANY</td><td>The discovery UDP multicast network adapter address</td></tr>
        /// <tr valign="top"><td>MulticastSendBufferSize</td><td>64K</td><td>UDP multicast socket send buffer size</td></tr>
        /// <tr valign="top"><td>MulticastReceiveBufferSize</td><td>64K</td><td>Multicast socket receive buffer size</td></tr>
        /// <tr valign="top">
        ///     <td>BroadcastSettings</td>
        ///     <td>(see note)</td>
        ///     <td>
        ///     Settings for the <see cref="UdpBroadcastClient" /> used to manage the precence
        ///     packets used for router discovery when operating in <see cref="DiscoveryMode.UdpBroadcast "/>
        ///     discovery mode.  This is initialized with reasonable default values.
        ///     </td>
        /// </tr>
        /// <tr valign="top"><td>UdpEP</td><td>ANY:0</td><td>UDP network endpoint</td></tr>
        /// <tr valign="top"><td>UdpMsgQueueCountMax</td><td>1000</td><td>Max queued outbound UDP normal priority messages.</td></tr>
        /// <tr valign="top"><td>UdpMsgQueueSizeMax</td><td>10MB</td><td>Max bytes of serialized queued outbound UDP normal priority messages.</td></tr>
        /// <tr valign="top"><td>UdpSendBufferSize</td><td>64K</td><td>UDP unicast socket send buffer size</td></tr>
        /// <tr valign="top"><td>UdpReceiveBufferSize</td><td>64K</td><td>UDP unicast socket receive buffer size</td></tr>
        /// <tr valign="top"><td>TcpEP</td><td>ANY:0</td><td>TCP listening network endpoint</td></tr>
        /// <tr valign="top"><td>TcpMsgQueueCountMax</td><td>1000</td><td>Max queued outbound TCP normal priority messages.</td></tr>
        /// <tr valign="top"><td>TcpMsgQueueSizeMax</td><td>10MB</td><td>Max bytes of serialized queued outbound TCP normal priority messages.</td></tr>
        /// <tr valign="top"><td>TcpBacklog</td><td>100</td><td>Max pending connecting TCP sockets</td></tr>
        /// <tr valign="top"><td>TcpDelay</td><td>off</td><td>Enables Nagle on TCP channels</td></tr>
        /// <tr valign="top"><td>TcpSendBufferSize</td><td>64K</td><td>TCP socket send buffer size</td></tr>
        /// <tr valign="top"><td>TcpReceiveBufferSize</td><td>64K</td><td>TCP socket receive buffer size</td></tr>
        /// <tr valign="top"><td>BkInterval</td><td>1s</td><td>Background task interval</td></tr>
        /// <tr valign="top"><td>MaxIdle</td><td>5m</td><td>Maximum time a TCP socket should idle before being closed automatically</td></tr>
        /// <tr valign="top"><td>EnableP2P</td><td>true</td><td>Enables peer-to-peer routing between routers on the same subnet</td></tr>
        /// <tr valign="top"><td>AdvertiseTime</td><td>1m</td><td>RouterAdvertiseMsg multicast interval</td></tr>
        /// <tr valign="top"><td>PhysicalRouteTTL</td><td>3m</td><td>Maximum time a physical route will be maintained without being refreshed with a RouterAdvertiseMsg</td></tr>
        /// <tr valign="top"><td>DefMsgTTL</td><td>5</td><td>Default message time-to-live (max hops)</td></tr>
        /// <tr valign="top"><td>SharedKey</td><td>PLAINTEXT</td><td>The shared encryption key used to encrypt all message traffic.</td></tr>
        /// <tr valign="top"><td>SessionCacheTime</td><td>2m</td><td>Default time the router's session manager will cache idempotent replies.</td></tr>
        /// <tr valign="top"><td>SessionRetries</td><td>3</td><td>Maximum session initiation retries.</td></tr>
        /// <tr valign="top"><td>SessionTimeout</td><td>10s</td><td>Default session timeout</td></tr>
        /// <tr valign="top"><td>MaxLogicalAdvertiseEPs</td><td>256</td><td>Maximum number of logical endpoints to be included in a single LogicalAdvertiseMsg</td></tr>
        /// <tr valign="top"><td>DeadRouterTTL</td><td>0s</td><td>Maximum time to wait for a <see cref="ReceiptMsg" /> before declaring a dead router.  Use 0 to disable dead router detection.</td></tr>
        /// <tr valign="top">
        ///     <td>RouteLocal</td>
        ///     <td>(none)</td>
        ///     <td>
        ///     <para>
        ///     An array of zero or more logical routes for which messages should favor
        ///     local destinations.  These routes may include wildcards.  Here's an example
        ///     configuration fragment:
        ///     </para>
        ///     <code lang="none">
        ///     #section MsgRouter
        ///
        ///         RouteLocal[0] = abstract://Test/Local
        ///         RouteLocal[1] = abstract://MyApps/*
        ///
        ///     #endsection
        ///     </code>
        ///     </td>
        /// </tr>
        /// </table>
        /// </div>
        /// </remarks>
        public void Start()
        {
            RouterSettings settings;
            MsgEP          routerEP;
            Config         config;
            string         v;

            // Load the configuration settings

            config = new Config(MsgHelper.ConfigPrefix);

            v = config.Get("RouterEP", EnvironmentVars.Expand("physical://DETACHED/$(LillTek.DC.DefHubName)/$(Guid)"));

            try
            {
                routerEP = MsgEP.Parse(v);
            }
            catch
            {
                throw new MsgException("[MsgRouter.RouterEP] configuration setting is invalid.");
            }

            if (routerEP.Segments.Length != 2)
            {
                throw new MsgException("[MsgRouter.RouterEP] must specify a valid two segment leaf endpoint (eg: physical://root/hub/leaf).");
            }

            settings                            = new RouterSettings(routerEP);
            settings.AppName                    = config.Get("AppName", settings.AppName);
            settings.AppDescription             = config.Get("AppDescription", settings.AppDescription);
            settings.DiscoveryMode              = config.Get <DiscoveryMode>("DiscoveryMode", settings.DiscoveryMode);
            settings.CloudAdapter               = config.Get("CloudAdapter", settings.CloudAdapter);
            settings.CloudEP                    = config.Get("CloudEP", settings.CloudEP);
            settings.BroadcastSettings          = new UdpBroadcastClientSettings(Config.CombineKeys(MsgHelper.ConfigPrefix, "BroadcastSettings"));
            settings.UdpEP                      = config.Get("UdpEP", settings.UdpEP);
            settings.UdpMsgQueueCountMax        = config.Get("UdpMsgQueueCountMax", settings.UdpMsgQueueCountMax);
            settings.UdpMsgQueueSizeMax         = config.Get("UdpMsgQueueSizeMax", settings.UdpMsgQueueSizeMax);
            settings.TcpEP                      = config.Get("TcpEP", settings.TcpEP);
            settings.TcpMsgQueueCountMax        = config.Get("TcpMsgQueueCountMax", settings.TcpMsgQueueCountMax);
            settings.TcpMsgQueueSizeMax         = config.Get("TcpMsgQueueSizeMax", settings.TcpMsgQueueSizeMax);
            settings.TcpBacklog                 = config.Get("TcpBacklog", settings.TcpBacklog);
            settings.MaxIdle                    = config.Get("MaxIdle", settings.MaxIdle);
            settings.EnableP2P                  = config.Get("EnableP2P", settings.EnableP2P);
            settings.SessionCacheTime           = config.Get("SessionCacheTime", settings.SessionCacheTime);
            settings.SessionRetries             = config.Get("SessionRetries", settings.SessionRetries);
            settings.SessionTimeout             = config.Get("SessionTimeout", settings.SessionTimeout);
            settings.TcpDelay                   = config.Get("TcpDelay", settings.TcpDelay);
            settings.BkInterval                 = config.Get("BkInterval", settings.BkInterval);
            settings.DefMsgTTL                  = config.Get("DefMsgTTL", settings.DefMsgTTL);
            settings.PhysicalRouteTTL           = config.Get("PhysicalRouteTTL", settings.PhysicalRouteTTL);
            settings.MaxLogicalAdvertiseEPs     = config.Get("MaxLogicalAdvertiseEPs", settings.MaxLogicalAdvertiseEPs);
            settings.DeadRouterTTL              = config.Get("DeadRouterTTL", settings.DeadRouterTTL);
            settings.MulticastSendBufferSize    = config.Get("MulticastSendBufferSize", settings.MulticastSendBufferSize);
            settings.MulticastReceiveBufferSize = config.Get("MulticastReceiveBufferSize", settings.MulticastReceiveBufferSize);
            settings.UdpSendBufferSize          = config.Get("UdpSendBufferSize", settings.UdpSendBufferSize);
            settings.UdpReceiveBufferSize       = config.Get("UdpReceiveBufferSize", settings.UdpReceiveBufferSize);
            settings.TcpSendBufferSize          = config.Get("TcpSendBufferSize", settings.TcpSendBufferSize);
            settings.TcpReceiveBufferSize       = config.Get("TcpReceiveBufferSize", settings.TcpReceiveBufferSize);
            settings.AdvertiseTime              = config.Get("AdvertiseTime", settings.AdvertiseTime);

            v = config.Get("SharedKey");
            if (!string.IsNullOrWhiteSpace(v))
            {
                try
                {
                    settings.SharedKey = new SymmetricKey(v);
                }
                catch
                {
                    // Ignoring
                }
            }

            // Get the local route endpoints

            foreach (string ep in config.GetArray("RouteLocal"))
            {
                settings.LocalityMap.Add(ep);
            }

            Start(settings);
        }
예제 #26
0
        /// <summary>
        /// Establishes a session with the realm map provider.
        /// </summary>
        /// <param name="engineSettings">The associated authentication engine's settings.</param>
        /// <param name="key">
        /// This is simply the name of the configuration array that holds the
        /// static realm mappings.
        /// </param>
        /// <remarks>
        /// <para>
        /// This provider simply loads a static list of provider mappings from the
        /// application's configuration settings.  The mappings are loaded from
        /// the configuration key array specified by the <b>key</b> parameter.
        /// Each element in the array specifies a single realm mapping.  The format
        /// of each is mapping is:
        /// </para>
        /// <code language="none">
        ///     &lt;realm&gt;$$&lt;extension typeref&gt;$$&lt;args&gt;$$&lt;query&gt;
        /// </code>
        /// <para>
        /// where <b>realm</b> identifies the authentication realm, <b>extension typeref</b>
        /// specifies the type implementing <see cref="IAuthenticationExtension" /> formatted as
        /// specified for <see cref="Config.Parse(string,System.Type)" />, <b>key</b>
        /// are the provider arguments and <b>query</b> is the optional provider query
        /// string.  Note the use of <b>$$</b> as field separators.  Here's an example
        /// configuration:
        /// </para>
        /// <code language="none">
        /// realm-map[0] = lilltek.com$$LillTek.Datacenter.Server.FileAuthenticationExtension:LillTek.Datacenter.Server.dll$$path=c:\lilltek.txt$$
        /// realm-map[1] = test.com$$LillTek.Datacenter..Server.FileAuthenticationExtension:LillTek.Datacenter.Server.dll$$path=c:\test.txt$$
        /// </code>
        /// <note>
        /// Every call to <see cref="Open" /> should be matched by a call to
        /// <see cref="Close" /> or <see cref="Dispose" />.
        /// </note>
        /// </remarks>
        /// <exception cref="AuthenticationException">Thrown if there's an error loading the map.</exception>
        public void Open(AuthenticationEngineSettings engineSettings, string key)
        {
            string[] configMap;

            using (TimedLock.Lock(this))
            {
                if (IsOpen)
                {
                    throw new AuthenticationException("Provider is already open.");
                }

                this.engineSettings = engineSettings;

                configMap = Config.Global.GetArray(key);
                if (configMap == null)
                {
                    throw new AuthenticationException("Configuration key [{0}] not found.", key);
                }

                realmMap = new List <RealmMapping>();
                foreach (string map in configMap)
                {
                    string[]    fields;
                    string      realm;
                    System.Type providerType;
                    string      args;
                    string      query;

                    fields = map.Split(new string[] { "$$" }, StringSplitOptions.None);
                    if (fields.Length != 4)
                    {
                        throw new AuthenticationException("Four realm map fields expected: [{0}]", map);
                    }

                    realm = fields[0].Trim();
                    args  = fields[2].Trim();
                    query = fields[3].Trim();

                    if (realm.Length == 0)
                    {
                        throw new AuthenticationException("<realm> field cannot be empty.");
                    }

                    providerType = Config.Parse(fields[1], (System.Type)null);
                    if (providerType == null)
                    {
                        throw new AuthenticationException("Unable to instantiate provider class: [{0}]", fields[1]);
                    }

                    for (int i = 0; i < realmMap.Count; i++)
                    {
                        if (String.Compare(realmMap[i].Realm, realm, true) == 0)
                        {
                            throw new AuthenticationException("Duplicate realm: {0}", realm);
                        }
                    }

                    realmMap.Add(new RealmMapping(engineSettings, realm, providerType, new ArgCollection(EnvironmentVars.Expand(args)), query));
                }
            }
        }
예제 #27
0
        public static IHostBuilder ConfigureServices(this IHostBuilder hostBuilder)
        {
            return(hostBuilder.ConfigureServices((_, collection) =>
            {
                collection.Scan(scan =>
                {
                    scan.FromAssemblyOf <IPaginator>()
                    .AddClasses()
                    .AsSelf()
                    .WithSingletonLifetime();

                    scan.FromAssemblyOf <IBotCommand>()
                    .AddClasses(x => x.AssignableTo <IBotCommand>())
                    .As <IBotCommand>()
                    .WithSingletonLifetime();

                    scan.FromAssemblyOf <IBotStateHandler>()
                    .AddClasses(x => x.AssignableTo <IBotStateHandler>())
                    .As <IBotStateHandler>()
                    .WithSingletonLifetime();

                    scan.FromAssemblyOf <IBotCallbackQuery>()
                    .AddClasses(x => x.AssignableTo <IBotCallbackQuery>())
                    .As <IBotCallbackQuery>()
                    .WithSingletonLifetime();
                });

                collection.AddSingleton <IDigitalOceanClient>(_ => new DigitalOceanClient(EnvironmentVars.GetDigitalOceanToken()));
                collection.AddSingleton <StorageService>();
                collection.AddSingleton <BotCommandResolver>();
            }));
        }
예제 #28
0
        /// <summary>
        /// Attempts to load the realm map from the text file.
        /// </summary>
        /// <returns>The new realm map.</returns>
        private List <RealmMapping> LoadMap()
        {
            StreamReader        reader;
            List <RealmMapping> realmMap;
            int lineNum;

            reader = new StreamReader(path, Helper.AnsiEncoding);

            try
            {
                lineNum  = 0;
                realmMap = new List <RealmMapping>();

                while (true)
                {
                    string      map;
                    string[]    fields;
                    string      realm;
                    System.Type providerType;
                    string      args;
                    string      query;

                    map = reader.ReadLine();
                    if (map == null)
                    {
                        break;
                    }

                    lineNum++;

                    map = map.Trim();
                    if (map.Length == 0 || map.StartsWith("//"))
                    {
                        continue;
                    }

                    map = EnvironmentVars.Expand(map);

                    fields = map.Split(new string[] { "$$" }, StringSplitOptions.None);
                    if (fields.Length != 4)
                    {
                        throw new AuthenticationException("{0}({1}): Four realm map fields expected: [{2}]", Path.GetFileName(path), lineNum, map);
                    }

                    realm = fields[0].Trim();
                    args  = fields[2].Trim();
                    query = fields[3].Trim();

                    providerType = Config.Parse(fields[1], (System.Type)null);
                    if (providerType == null)
                    {
                        throw new AuthenticationException("{0}({1}): Unable to instantiate provider class: [{2}]", Path.GetFileName(path), lineNum, fields[1]);
                    }

                    for (int i = 0; i < realmMap.Count; i++)
                    {
                        if (String.Compare(realmMap[i].Realm, realm, true) == 0)
                        {
                            throw new AuthenticationException("{0}({1}): Duplicate realm: {2}", Path.GetFileName(path), realm);
                        }
                    }

                    realmMap.Add(new RealmMapping(engineSettings, realm, providerType, new ArgCollection(args), query));
                }
            }
            finally
            {
                reader.Close();
            }

            return(realmMap);
        }
예제 #29
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="appName">The application name.</param>
        /// <param name="database">The database name.</param>
        /// <remarks>
        /// <note>
        /// The application name must be no longer than 32 characters
        /// and can include only letters or digit characters.
        /// The application name is used to generate a unique database
        /// user account and password to be used by the application to gain
        /// gain access to the database.
        /// </note>
        /// </remarks>
        public DBInstallParams(string appName, string database)
        {
            SqlConnectionInfo conInfo;
            string            conString;
            string            path;
            int pos;

            if (string.IsNullOrWhiteSpace(appName))
            {
                throw new ArgumentException("Invalid application name.");
            }
            else if (appName.Length > 32)
            {
                throw new ArgumentException("Application name exceeds 32 characters.");
            }
            else
            {
                foreach (char ch in appName)
                {
                    if (Char.IsLetterOrDigit(ch))
                    {
                        continue;
                    }
                    else
                    {
                        throw new ArgumentException("Application name may include only letters or digits characters.");
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(database))
            {
                throw new ArgumentException("Invalid database path.");
            }

            conString = EnvironmentVars.Get("LT_TEST_DB");
            if (conString != null)
            {
                conInfo = new SqlConnectionInfo(conString);
            }
            else
            {
                conInfo = new SqlConnectionInfo("server=.\\SQLEXPRESS;Integrated Security=SSPI");
            }

            this.appName       = appName;
            this.server        = conInfo.Server;
            this.database      = database;
            this.adminSecurity = string.IsNullOrWhiteSpace(conInfo.Security) ? "" : "Integrated Security=" + conInfo.Security;
            this.appSecurity   = string.Format("uid={0}User;pwd={1}", appName, Crypto.GeneratePassword(8, true));
            this.dbPath        = null;
            this.logPath       = null;

            path = Environment.SystemDirectory;
            pos  = path.IndexOf(':');
            if (pos == -1)
            {
                throw new InvalidOperationException("Unexpected system directory path.");
            }

            this.defDBFolder = path.Substring(0, pos + 1) + @"\LillTek\Data";
        }
예제 #30
0
        /// <summary>
        /// Called by Azure roles early in their boot process to intialize global state.  Note that
        /// this method may also be safely called by processes launched by an Azure role.
        /// </summary>
        /// <param name="roleName">The role or process name.</param>
        /// <param name="roleType">The type of Azure role being hosted.</param>
        /// <exception cref="AzureHelperException">Thrown if initialization failed.</exception>
        /// <remarks>
        /// <para>
        /// This method should be called after <see cref="Helper.InitializeApp"/> or <b>WebHelper.PlatformInitialize()</b> is
        /// called to perform basic LillTek initalization.
        /// </para>
        /// <para>
        /// This method will set the <b>AZURE_ROLENAME</b>, <b>AZURE_ROLETYPE</b>, <b>AZURE_DATACENTER</b>,
        /// <b>AZURE_DEPLOYMENT</b>, <b>AZURE_ENVIRONMENT</b>, <b>AZURE_ROLEINDEX</b>, <b>AZURE_ROLEINSTANCEID</b>,
        /// and <b>AZURE_ROLEDATAPATH</b> environment variables so that child processes can have
        /// access to this information.
        /// </para>
        /// <para>
        /// Applications can also specify that other Azure configuration settings be persisted
        /// to the environment by specifying the names of these settings as a comma separated list
        /// in the <b>EnvironmentSettings</b> Azure configuration setting.
        /// </para>
        /// <para>
        /// This method also requires that the role define the <b>RoleData</b> local folder
        /// resource in its Azure configuration file.  The path to this folder can be obtained
        /// globally via <see cref="RoleDataPath"/>.
        /// </para>
        /// </remarks>
        public static void RoleInitialize(string roleName, AzureRoleType roleType)
        {
            LocalResource resource;

            // Handle non-Azure role initialization separately.

            if (roleType == AzureRoleType.Process)
            {
                ProcessInitialize(roleName);
                return;
            }

            // Initialize the role type and role data path globals.  Note that the data path is required.

            AzureHelper.RoleName     = roleName;
            AzureHelper.RoleType     = roleType;
            AzureHelper.RoleDataPath = null;

            try
            {
                resource = RoleEnvironment.GetLocalResource("RoleData");
            }
            catch
            {
                resource = null;
            }

            if (resource != null)
            {
                AzureHelper.RoleDataPath = resource.RootPath;
            }

            if (AzureHelper.RoleDataPath == null)
            {
                throw new AzureHelperException("Could not obtain the [RoleData] local resource. This resource must be specified in the Windows Azure role configuration settings.");
            }

            // This indicates to the Config class how it can retrieve Windows Azure configuration settings.

            Config.SetAzureGetSettingMethod(typeof(Microsoft.WindowsAzure.CloudConfigurationManager).GetMethod("GetSetting"));

            // $hack:
            //
            // I'm going to parse the role deployment index out of the RoleInstance.Id property.
            // The code below should be robust enough not to crash if the format changes, and
            // will set RoleInstance=-1 in this case.
            //
            // The code below assumes that the ID property looks someything like:
            //
            //      "deployment17(273).MyService.MyRole_IN_0"
            //
            // where the role instance number is the integer at the end.

            AzureHelper.RoleIndex = -1;

            try
            {
                var fields = RoleEnvironment.CurrentRoleInstance.Id.Split('_');
                int v;

                if (!int.TryParse(fields.Last(), out v) || v < 0)
                {
                    throw new FormatException("RoleIndex: Last role instance ID field is not a valid instance number.");
                }

                AzureHelper.RoleIndex = v;
            }
            catch (Exception e)
            {
                SysLog.LogException(e, "Unable to extract the role index from the Azure role ID [{0}].", RoleEnvironment.CurrentRoleInstance.Id);
            }

            // Load Azure deployment related settings.

            AzureHelper.Datacenter     = Config.Global.Get("Azure.Datacenter", "UNKNOWN");
            AzureHelper.Deployment     = Config.Global.Get("Azure.Deployment", "UNKNOWN");
            AzureHelper.Environment    = Config.Global.Get <AzureEnvironment>("Azure.Environment", AzureEnvironment.Unknown);
            AzureHelper.RoleInstanceID = string.Format("{0}[{1}]", AzureHelper.RoleName, AzureHelper.RoleIndex);

            if (AzureHelper.Environment == AzureEnvironment.Dev)
            {
                var machineName = Helper.MachineName;

                if (!string.IsNullOrWhiteSpace(machineName))
                {
                    AzureHelper.RoleInstanceID = machineName + "." + AzureHelper.RoleInstanceID;
                }
            }

            // Persist Azure deployment related settings to environment variables so
            // external child processes can pick these up.

            System.Environment.SetEnvironmentVariable("AZURE_ROLENAME", AzureHelper.RoleName);
            System.Environment.SetEnvironmentVariable("AZURE_ROLETYPE", AzureHelper.RoleType.ToString());
            System.Environment.SetEnvironmentVariable("AZURE_DATACENTER", AzureHelper.Datacenter);
            System.Environment.SetEnvironmentVariable("AZURE_DEPLOYMENT", AzureHelper.Deployment.ToUpper());
            System.Environment.SetEnvironmentVariable("AZURE_ENVIRONMENT", AzureHelper.Environment.ToString().ToUpper());
            System.Environment.SetEnvironmentVariable("AZURE_ROLEINSTANCEID", AzureHelper.RoleInstanceID);
            System.Environment.SetEnvironmentVariable("AZURE_ROLEINDEX", AzureHelper.RoleIndex.ToString());
            System.Environment.SetEnvironmentVariable("AZURE_ROLEDATAPATH", AzureHelper.RoleDataPath);

            // The [Azure.EnvironmentSettings] configuration setting can be used to specify
            // the names of all the settings to be saved to environment variables to be accessable
            // by processes launched by the role.  Handle this here.

            var environmentSettings = Config.Global.Get("Azure.EnvironmentSettings", string.Empty).Split(',');

            foreach (var envSetting in environmentSettings)
            {
                var name  = envSetting.Trim().ToUpper();
                var value = System.Environment.GetEnvironmentVariable(name);

                if (name == string.Empty || value == null)
                {
                    continue;
                }

                name = "AZURE " + name;

                if (System.Environment.GetEnvironmentVariable(name) != null)
                {
                    continue;   // Don't overwrite a setting that was saved above.
                }
                System.Environment.SetEnvironmentVariable(name, value);
            }

            // Load/reload the LillTek environment variables and configuration here.

            if (roleType == AzureRoleType.Web)
            {
                Config.SetConfigPath(Path.Combine(Helper.AppFolder, "Web.ini"));
            }
            else
            {
                Config.SetConfigPath(Path.Combine(Helper.AppFolder, Path.GetFileNameWithoutExtension(Helper.EntryAssemblyFile) + ".ini"));
            }

            EnvironmentVars.Reload();
            Config.Load();
        }