public ConfigurationSet GetConfiguration(string setName, string environment = null)
        {
            var faultedMemCache = validateMemCache();

            if (faultedMemCache)
            {
                Logging.DebugMessage("ConfigSet MemoryCache error.....");
            }
            ConfigurationSet item = null;

            if (!faultedMemCache)
            {
                item = (ConfigurationSet)MemoryCache.Default.Get(setName);
            }
            if (item.IsInstance())
            {
                return(item);
            }
            item = GetConfigurationSet(setName, environment);
            Logging.DebugMessage("[ConfigSet cache is not primed]");
            if (!faultedMemCache)
            {
                MemoryCache.Default.Set(setName, item, new CacheItemPolicy {
                    SlidingExpiration = new TimeSpan(0, 0, GetCacheExpirationTime())
                });
            }
            return(item);
        }
예제 #2
0
        private void ValidateUsernamePassword(ConfigurationSet configData, string token)
        {
            var cred = EncodingFactory.ReadFileText(Convert.FromBase64String(token));
            var separator = cred.IndexOf(':');
            var name = cred.Substring(0, separator);
            var password = cred.Substring(separator + 1);
            var nameParts = name.Split('\\');
            if (nameParts.Length == 1)
            {
                if (configData.SetName.Equals(nameParts[0], StringComparison.OrdinalIgnoreCase) && configData.ReaderKey.Decrypt(ConfigCacheHelper.Secret) == password)
                {
                    return;
                }
            }
            else if (nameParts.Length == 2)
            {
                if (configData.SetName.Equals(nameParts[0], StringComparison.OrdinalIgnoreCase))
                {
                    var env = configData.Environments.SingleOrDefault(e => e.EnvironmentName.Equals(nameParts[1], StringComparison.OrdinalIgnoreCase));
                    if (env != null && env.ReaderKey.Decrypt(ConfigCacheHelper.Secret) == password)
                    {

                        return;
                    }
                }
            }
            throw new UnauthorizedAccessException("Invalid credentials");
        }
예제 #3
0
 public static void UpdateCache(string configSet, ConfigurationSet newConfigSet, ConfigWrapper cs)
 {
     var config = new ConfigWrapper { Set = newConfigSet, Environment = cs.Environment, Id = cs.Id };
     ConfigWrapper oldConfig;
     if (!cache.TryGetValue(configSet, out oldConfig)) cache.TryAdd(configSet, config);
     else
     {
         cache.TryUpdate(configSet, config, oldConfig);
     }
     File.WriteAllText(configSet, JsonConvert.SerializeObject(config));
 }
 private static ConfigurationSet PrepareDataForTransmission(ConfigurationSet configData)
 {
     var returnData = JsonConvert.DeserializeObject<ConfigurationSet>(JsonConvert.SerializeObject(configData));
     returnData.ReaderKey = null;
     foreach (var environmentConfig in returnData.Environments)
     {
         environmentConfig.ReaderKey = null;
     }
     returnData.RequestedBy = null;
     return returnData;
 }
 private static ConnectionMultiplexer GetMultiplexer(ConfigurationSet item, string environment)
 {
     var itemKey = GetItemKey(item.SetName, environment);
     var env = item.Environments.Single(e => e.EnvironmentName == environment);
     ConnectionMultiplexer multiplexer;
     if (Multiplexers.TryGetValue(itemKey, out multiplexer)) return multiplexer;
     lock (triowing)
     {
         if (Multiplexers.TryGetValue(itemKey, out multiplexer)) return multiplexer;
         multiplexer = ConnectionMultiplexer.Connect(GetConnectionString(env.Cache));
         Multiplexers.TryAdd(itemKey, multiplexer);
         return multiplexer;
     }
 }
예제 #6
0
 internal void AddOrUpdate(string name, ConfigurationSet configuration)
 {
     configuration.SetName = name.Trim();
     var cs = GetConfigSet(name.Trim());
     if (cs.IsNull())
     {
         var first = ConfigSets.Select(c1 => c1.Id).Concat(new long[] { 0 }).Max();
         configuration.Id = first;
         ConfigSets.Add(configuration);
     }
     else
     {
         ConfigSets.Remove(cs);
         ConfigSets.Add(configuration);
     }
 }
예제 #7
0
        internal void AddOrUpdate(string name, ConfigurationSet configuration)
        {
            configuration.SetName = name.Trim();
            var cs = GetConfigSet(name.Trim());

            if (cs.IsNull())
            {
                var first = ConfigSets.Select(c1 => c1.Id).Concat(new long[] { 0 }).Max();
                configuration.Id = first;
                ConfigSets.Add(configuration);
            }
            else
            {
                ConfigSets.Remove(cs);
                ConfigSets.Add(configuration);
            }
        }
예제 #8
0
 protected void ValidateAccess(ConfigurationSet configData, string environment)
 {
     var auth = Request.Headers["Authorization"];
     if (auth.IsNullOrWhiteSpace()) throw new UnauthorizedAccessException("No credentials provided");
     var token = auth.Split(' ').Last();
     if (auth.StartsWith("token", StringComparison.OrdinalIgnoreCase))
     {
         ValidateToken(configData, environment, token);
     }
     else
         ValidateUsernamePassword(configData, token);
     var userName = Request.Headers["key"];
     if (userName.IsNullOrWhiteSpace())
         userName = string.Format("{0}-{1}", configData.SetName, environment);
     this.HttpContext.User = new CustomPrincipal(new CustomIdentity(userName, "Form"));
     Thread.CurrentPrincipal = HttpContext.User;
     FormsAuthentication.SetAuthCookie(userName, false);
 }
 public bool UpdateCache(IEnvironment environmentSettings, ConfigurationSet raw)
 {
     try
     {
         var itemKey = GetItemKey(environmentSettings.ConfigSet.Id, environmentSettings.Name);
         Logging.DebugMessage("Itemkey: {0}",itemKey);
         if(!GetDataStore(raw, environmentSettings.Name).StringSet(itemKey, JsonConvert.SerializeObject(raw),new TimeSpan(1,0,0,0),When.Always, CommandFlags.HighPriority))
             Logging.DebugMessage("Update cache item {0} failed",itemKey );
         GetMultiplexer(raw, environmentSettings.Name)
             .GetSubscriber()
             .PublishAsync(itemKey, JsonConvert.SerializeObject(raw)).Wait();
     }
     catch (System.Exception ex)
     {
         Logging.Exception(ex, "[REDIS]");
         return false;
     }
     return true;
 }
        protected virtual void NotifyChange(string setName, string environmentName, ConfigurationSet configSet)
        {
            ConfigurationSet oldSet;

            if (StarterkitConfigurationReader.configCache.TryGetValue(StarterkitConfigurationReader.GetCacheKey(setName, environmentName), out oldSet))
            {
                if (oldSet.ETag == configSet.ETag)
                {
                    return;
                }
                ConfigurationSet cachedItem;
                StarterkitConfigurationReader.configCache.TryRemove(StarterkitConfigurationReader.GetCacheKey(setName, environmentName), out cachedItem);
                StarterkitConfigurationReader.configCache.TryAdd(StarterkitConfigurationReader.GetCacheKey(setName, environmentName), configSet);
            }
            else
            {
                StarterkitConfigurationReader.configCache.TryAdd(StarterkitConfigurationReader.GetCacheKey(setName, environmentName), configSet);
            }
            if (StarterkitConfigurationReader.changeHandler != null)
            {
                StarterkitConfigurationReader.changeHandler(configSet);
            }
        }
예제 #11
0
 private bool TryGetSetFromCache(string id, string environment, out ConfigurationSet set)
 {
     ConfigurationSet item;
     if (!ConfigSetCache.TryGetValue(GetCacheKey(id, environment), out item))
     {
         set = null;
         return false;
     }
     if (item.LastUpdated <= GetConfigSet(id).LastUpdate)
     {
         set = null;
         return false;
     }
     set = item;
     return true;
 }
예제 #12
0
 private void AddToCache(string id, string environment, ConfigurationSet set)
 {
     ConfigSetCache.AddOrUpdate(GetCacheKey(id, environment), set);
 }
예제 #13
0
        public void CreateFromTextConfigStoreFile(ConfigurationSet configSet)
        {
            var newSet = Repository.ConfigSets.Create();
            newSet.Administrators.Add(ConfigReaderFactory.CurrentUser);
            newSet.Name = configSet.SetName;
            newSet.System = configSet.SetName;
            newSet.Created = DateTime.UtcNow;
            foreach (var e in configSet.Environments)
            {
                var env = newSet.CreateEnvironment(Repository, e.EnvironmentName, true);
                foreach (var p in e.Parameters)
                {
                    var param = env.CreateParameters(Repository, p.Name, p.BinaryValue.ContainsElements());
                    param.ItemValue = p.Value;
                    if (p.BinaryValue.ContainsElements())
                    {
                        param.BinaryValue = p.BinaryValue;
                        param.SetValue(Convert.ToBase64String(p.BinaryValue));
                    }
                }
                env.AddIdentitySettingsToEnvironment(Repository,
                    (from s in configSet.Services where s.IdentitySettings != null select s.IdentitySettings)
                        .FirstOrDefault());
            }
            foreach (var s in configSet.Endpoints)
            {
                var service = newSet.CreateService(Repository, s.ServiceName);
                Repository.SaveChanges();
                foreach (var ep in s.Endpoints)
                {
                    var endpoint = service.CreateEndpoint(Repository, ep.BindingType, true);
                    endpoint.SetFromRawData(ep, Repository);
                }
                service.ClientEndpointValue = s.ActiveEndpoint;
            }
            if (configSet.Services.IsInstance())
            {
                foreach (var host in configSet.Services)
                {
                    try
                    {
                        var newHost = newSet.CreateServiceHost(Repository, host.ServiceName);
                        foreach (var configParameter in host.Parameters)
                        {
                            var param = newHost.CreateParameter(Repository, configParameter.Name,
                                configParameter.BinaryValue.ContainsElements(), false);
                            param.ItemValue = configParameter.BinaryValue.ContainsElements()
                                ? Convert.ToBase64String(configParameter.BinaryValue)
                                : configParameter.Value;
                            param.BinaryValue = configParameter.BinaryValue;
                        }
                    }
                    catch (Exception ex)
                    {

                        throw new InvalidDataException(
                            string.Format("Unable to create {0}: {1}", host.ServiceName, ex.Message), ex);
                    }
                }
            }
            newSet.LastUpdate = DateTime.UtcNow;
            Repository.SaveChanges();
        }
예제 #14
0
 public static void UpdateCache(string localFile, ConfigurationSet newConfigSet, ConfigWrapper cs)
 {
     if (UseDiscreteFiles)
     {
         localFile = localFile.Replace("\\\\", "\\").ToLowerInvariant();
         var config = new ConfigWrapper { Set = newConfigSet, Environment = cs.Environment, Id = cs.Id };
         ConfigWrapper oldConfig;
         if (!cache.TryGetValue(localFile, out oldConfig)) cache.TryAdd(localFile, config);
         else
         {
             if (long.Parse(oldConfig.Set.ETag) <= long.Parse(newConfigSet.ETag)) cache.TryUpdate(localFile, config, oldConfig);
         }
         File.WriteAllText(localFile, GetFileContent(config));
     }
     else
     {
         lock (triowing)
         {
             GetOrCreateConsolidatedFile();
             var config = new ConfigWrapper { Set = newConfigSet, Environment = cs.Environment, Id = cs.Id };
             if (consolidatedWrapper.ConfigWrappers.ContainsKey(GetSetId(cs))) consolidatedWrapper.ConfigWrappers.Remove(GetSetId(cs));
             consolidatedWrapper.ConfigWrappers.Add(GetSetId(cs), config);
             
         }
         SaveConsolidatedFile();
     }
 }
예제 #15
0
 private static bool ValidateMasterToken(ConfigurationSet configData, string environment, string token, string keyName)
 {
     if (configData.AllowMasterKeyAccess)
     {
         Logging.DebugMessage("Validating master token");
         try
         {
             if (token == configData.ReaderKey.Decrypt(Secret) && string.Equals(keyName, configData.SetName, StringComparison.OrdinalIgnoreCase))
             {
                 Logging.DebugMessage("Access to {0}-{1} was granted by master token validation", EventLogEntryType.SuccessAudit, configData.SetName, environment);
                 return true;
             }
         }
         catch (Exception ex)
         {
             ex.Log("unable to validate token");
         }
     }
     else if (string.Equals(keyName, configData.SetName, StringComparison.OrdinalIgnoreCase))
     {
         throw new InvalidDataException("Invalid access token");
     }
     return false;
 }
        private static IDatabase GetDataStore(ConfigurationSet item, string environment)
        {

            return GetMultiplexer(item, environment).GetDatabase();
        }
 public void WriteConfigurationSet(ConfigurationSet configuration, string setName)
 {
     throw new NotImplementedException();
 }
 public void WriteConfigurationSet(ConfigurationSet configuration, string setName)
 {
     configuration.LastUpdated = DateTime.Now;
     ConfigurationData.AddOrUpdate(setName, configuration);
     Write();
 }
 private HttpResponseMessage CreateResponse(ConfigurationSet configData)
 {
     return Request.CreateResponse(HttpStatusCode.OK, PrepareDataForTransmission(configData));
 }
 public bool UpdateCache(IEnvironment environmentSettings, ConfigurationSet raw)
 {
     return true;
 }
예제 #21
0
 public void ValidateToken(ConfigurationSet configData, string environment, string tokenString)
 {
     var token = EncodingFactory.ReadFileText(Convert.FromBase64String(tokenString));
     var keyName = Request.Headers["key"];
     if (keyName.IsNullOrWhiteSpace()) keyName = configData.SetName + "-" + environment;
     configData.ValidateToken(environment, token, keyName);
 }
 /// <summary>
 /// Saves a configSet to the cache
 /// </summary>
 /// <param name="setName">the set name</param>
 /// <param name="environment">the current environment</param>
 /// <param name="faultedMemCache">the state of the cache </param>
 /// <param name="item">the configSet to cache</param>
 protected virtual void SaveConfigSetToCache(string setName, string environment, bool faultedMemCache, ConfigurationSet item)
 {
     configCache.TryAdd(GetCacheKey(setName, environment), item);
 }
 /// <summary>
 /// Retreives the configSet from the cache, returns null if not found
 /// </summary>
 /// <param name="setName">the set name</param>
 /// <param name="environment">the current environment</param>
 /// <param name="item">the config set to return</param>
 /// <returns>The state of the cache.</returns>
 protected internal virtual bool GetSettingsFromCache(string setName, string environment, out ConfigurationSet item)
 {
     return(configCache.TryGetValue(GetCacheKey(setName, environment), out item));
 }